3 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
4 * Copyright (C) 2002-2006 The Nucleus Group
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 * (see nucleus/documentation/index.html#license for more info)
13 * This class makes sure each item/weblog/comment object gets requested from
14 * the database only once, by keeping them in a cache. The class also acts as
15 * a dynamic classloader, loading classes _only_ when they are first needed,
16 * hoping to diminish execution time
18 * The class is a singleton, meaning that there will be only one object of it
19 * active at all times. The object can be requested using MANAGER::instance()
21 * @license http://nucleuscms.org/license.txt GNU General Public License
22 * @copyright Copyright (C) 2002-2006 The Nucleus Group
23 * @version $Id: MANAGER.php,v 1.5 2006-07-17 20:03:44 kimitake Exp $
24 * $NucleusJP: MANAGER.php,v 1.4 2005/08/13 07:33:02 kimitake Exp $
29 * Cached ITEM, BLOG, PLUGIN, KARMA and MEMBER objects. When these objects are requested
30 * through the global $manager object (getItem, getBlog, ...), only the first call
31 * will create an object. Subsequent calls will return the same object.
33 * The $items, $blogs, ... arrays map an id to an object (for plugins, the name is used
44 * cachedInfo to avoid repeated SQL queries (see pidInstalled/pluginInstalled/getPidFromName)
45 * e.g. which plugins exists?
47 * $cachedInfo['installedPlugins'] = array($pid -> $name)
52 * The plugin subscriptionlist
54 * The subcription array has the following structure
55 * $subscriptions[$EventName] = array containing names of plugin classes to be
56 * notified when that event happens
61 * Returns the only instance of this class. Creates the instance if it
62 * does not yet exists. Users should use this function as
63 * $manager =& MANAGER::instance(); to get a reference to the object
66 function &instance() {
67 static $instance = array();
68 if (empty($instance)) {
69 $instance[0] =& new MANAGER();
75 * The constructor of this class initializes the object caches
78 $this->items = array();
79 $this->blogs = array();
80 $this->plugins = array();
81 $this->karma = array();
82 $this->parserPrefs = array();
83 $this->cachedInfo = array();
87 * Returns the requested item object. If it is not in the cache, it will
88 * first be loaded and then placed in the cache.
89 * Intended use: $item =& $manager->getItem(1234)
91 function &getItem($itemid, $allowdraft, $allowfuture) {
92 $item =& $this->items[$itemid];
94 // check the draft and future rules if the item was already cached
96 if ((!$allowdraft) && ($item['draft']))
99 $blog =& $this->getBlog(getBlogIDFromItemID($itemid));
100 if ((!$allowfuture) && ($item['timestamp'] > $blog->getCorrectTime()))
104 // load class if needed
105 $this->loadClass('ITEM');
107 $item = ITEM::getitem($itemid, $allowdraft, $allowfuture);
108 $this->items[$itemid] = $item;
114 * Loads a class if it has not yet been loaded
116 function loadClass($name) {
117 $this->_loadClass($name, $name . '.php');
121 * Checks if an item exists
123 function existsItem($id,$future,$draft) {
124 $this->_loadClass('ITEM','ITEM.php');
125 return ITEM::exists($id,$future,$draft);
129 * Checks if a category exists
131 function existsCategory($id) {
132 return (quickQuery('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
135 function &getBlog($blogid) {
136 $blog =& $this->blogs[$blogid];
139 // load class if needed
140 $this->_loadClass('BLOG','BLOG.php');
142 $blog =& new BLOG($blogid);
143 $this->blogs[$blogid] =& $blog;
148 function existsBlog($name) {
149 $this->_loadClass('BLOG','BLOG.php');
150 return BLOG::exists($name);
153 function existsBlogID($id) {
154 $this->_loadClass('BLOG','BLOG.php');
155 return BLOG::existsID($id);
159 * Returns a previously read template
161 function &getTemplate($templateName) {
162 $template =& $this->templates[$templateName];
165 $template = TEMPLATE::read($templateName);
166 $this->templates[$templateName] =& $template;
172 * Returns a KARMA object (karma votes)
174 function &getKarma($itemid) {
175 $karma =& $this->karma[$itemid];
178 // load class if needed
179 $this->_loadClass('KARMA','KARMA.php');
180 // create KARMA object
181 $karma =& new KARMA($itemid);
182 $this->karma[$itemid] =& $karma;
188 * Returns a MEMBER object
190 function &getMember($memberid) {
191 $mem =& $this->members[$memberid];
194 // load class if needed
195 $this->_loadClass('MEMBER','MEMBER.php');
196 // create MEMBER object
197 $mem =& MEMBER::createFromID($memberid);
198 $this->members[$memberid] =& $mem;
204 * Global parser preferences
206 function setParserProperty($name, $value) {
207 $this->parserPrefs[$name] = $value;
209 function getParserProperty($name) {
210 return $this->parserPrefs[$name];
214 * A private helper class to load classes
216 function _loadClass($name, $filename) {
217 if (!class_exists($name)) {
219 include($DIR_LIBS . $filename);
223 function _loadPlugin($name) {
224 if (!class_exists($name)) {
227 $fileName = $DIR_PLUGINS . $name . '.php';
229 if (!file_exists($fileName))
231 ACTIONLOG::add(WARNING, 'Plugin ' . $name . ' was not loaded (File not found)');
238 // check if class exists (avoid errors in eval'd code)
239 if (!class_exists($name))
241 ACTIONLOG::add(WARNING, 'Plugin ' . $name . ' was not loaded (Class not found in file, possible parse error)');
245 // add to plugin array
246 eval('$this->plugins[$name] =& new ' . $name . '();');
249 $this->plugins[$name]->plugid = $this->getPidFromName($name);
251 // unload plugin if a prefix is used and the plugin cannot handle this^
252 global $MYSQL_PREFIX;
253 if (($MYSQL_PREFIX != '') && !$this->plugins[$name]->supportsFeature('SqlTablePrefix'))
255 unset($this->plugins[$name]);
256 ACTIONLOG::add(WARNING, 'Plugin ' . $name . ' was not loaded (does not support SqlTablePrefix)');
261 $this->plugins[$name]->init();
266 function &getPlugin($name) {
267 $plugin =& $this->plugins[$name];
270 // load class if needed
271 $this->_loadPlugin($name);
272 $plugin =& $this->plugins[$name];
278 * checks if the given plugin IS installed or not
280 function pluginInstalled($name) {
281 $this->_initCacheInfo('installedPlugins');
282 return ($this->getPidFromName($name) != -1);
284 function pidInstalled($pid) {
285 $this->_initCacheInfo('installedPlugins');
286 return ($this->cachedInfo['installedPlugins'][$pid] != '');
288 function getPidFromName($name) {
289 $this->_initCacheInfo('installedPlugins');
290 foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
297 function clearCachedInfo($what) {
298 unset($this->cachedInfo[$what]);
302 * Loads some info on the first call only
304 function _initCacheInfo($what)
306 if (isset($this->cachedInfo[$what]) && is_array($this->cachedInfo[$what]))
310 // 'installedPlugins' = array ($pid => $name)
311 case 'installedPlugins':
312 $this->cachedInfo['installedPlugins'] = array();
313 $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
314 while ($o = mysql_fetch_object($res))
316 $this->cachedInfo['installedPlugins'][$o->pid] = $o->pfile;
323 * A function to notify plugins that something has happened. Only the plugins
324 * that are subscribed to the event will get notified.
325 * Upon the first call, the list of subscriptions will be fetched from the
326 * database. The plugins itsself will only get loaded when they are first needed
329 * Name of the event (method to be called on plugins)
331 * Can contain any type of data, depending on the event type. Usually this is
332 * an itemid, blogid, ... but it can also be an array containing multiple values
334 function notify($eventName, $data) {
335 // load subscription list if needed
336 if (!is_array($this->subscriptions))
337 $this->_loadSubscriptions();
340 // get listening objects
342 if (isset($this->subscriptions[$eventName])) {
343 $listeners = $this->subscriptions[$eventName];
346 // notify all of them
347 if (is_array($listeners)) {
348 foreach($listeners as $listener) {
349 // load class if needed
350 $this->_loadPlugin($listener);
351 // do notify (if method exists)
352 if (method_exists($this->plugins[$listener], 'event_' . $eventName))
353 call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), $data);
360 * Loads plugin subscriptions
362 function _loadSubscriptions() {
363 // initialize as array
364 $this->subscriptions = array();
366 $res = sql_query('SELECT p.pfile as pfile, e.event as event FROM '.sql_table('plugin_event').' as e, '.sql_table('plugin').' as p WHERE e.pid=p.pid ORDER BY p.porder ASC');
367 while ($o = mysql_fetch_object($res)) {
368 $pluginName = $o->pfile;
369 $eventName = $o->event;
370 $this->subscriptions[$eventName][] = $pluginName;
376 Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
377 requests. tickets are user specific
380 var $currentRequestTicket = '';
383 * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
385 function addTicketToUrl($url)
387 $ticketCode = 'ticket=' . $this->_generateTicket();
388 if (strstr($url, '?'))
389 return $url . '&' . $ticketCode;
391 return $url . '?' . $ticketCode;
395 * POST requests: Adds ticket as hidden formvar
397 function addTicketHidden()
399 $ticket = $this->_generateTicket();
401 echo '<input type="hidden" name="ticket" value="', htmlspecialchars($ticket), '" />';
406 * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
408 function getNewTicket()
410 $this->currentRequestTicket = '';
411 return $this->_generateTicket();
415 * Checks the ticket that was passed along with the current request
417 function checkTicket()
421 // get ticket from request
422 $ticket = requestVar('ticket');
424 // no ticket -> don't allow
428 // remove expired tickets first
429 $this->_cleanUpExpiredTickets();
432 if (!$member->isLoggedIn())
435 $memberId = $member->getID();
437 // check if ticket is a valid one
438 $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'';
439 if (quickQuery($query) == 1)
441 // [in the original implementation, the checked ticket was deleted. This would lead to invalid
442 // tickets when using the browsers back button and clicking another link/form
443 // leaving the keys in the database is not a real problem, since they're member-specific and
444 // only valid for a period of one hour
446 // sql_query('DELETE FROM '.sql_table('tickets').' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'');
449 // not a valid ticket
456 * (internal method) Removes the expired tickets
458 function _cleanUpExpiredTickets()
460 // remove tickets older than 1 hour
461 $oldTime = time() - 60 * 60;
462 $query = 'DELETE FROM ' . sql_table('tickets'). ' WHERE ctime < \'' . date('Y-m-d H:i:s',$oldTime) .'\'';
467 * (internal method) Generates/returns a ticket (one ticket per page request)
469 function _generateTicket()
471 if ($this->currentRequestTicket == '')
473 // generate new ticket (only one ticket will be generated per page request)
474 // and store in database
477 if (!$member->isLoggedIn())
480 $memberId = $member->getID();
485 // generate a random token
486 srand((double)microtime()*1000000);
487 $ticket = md5(uniqid(rand(), true));
489 // add in database as non-active
490 $query = 'INSERT INTO ' . sql_table('tickets') . ' (ticket, member, ctime) ';
491 $query .= 'VALUES (\'' . addslashes($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
492 if (sql_query($query))
496 $this->currentRequestTicket = $ticket;
498 return $this->currentRequestTicket;