3 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
\r
4 * Copyright (C) 2002-2009 The Nucleus Group
\r
6 * This program is free software; you can redistribute it and/or
\r
7 * modify it under the terms of the GNU General Public License
\r
8 * as published by the Free Software Foundation; either version 2
\r
9 * of the License, or (at your option) any later version.
\r
10 * (see nucleus/documentation/index.html#license for more info)
\r
13 * This class makes sure each item/weblog/comment object gets requested from
\r
14 * the database only once, by keeping them in a cache. The class also acts as
\r
15 * a dynamic classloader, loading classes _only_ when they are first needed,
\r
16 * hoping to diminish execution time
\r
18 * The class is a singleton, meaning that there will be only one object of it
\r
19 * active at all times. The object can be requested using MANAGER::instance()
\r
21 * @license http://nucleuscms.org/license.txt GNU General Public License
\r
22 * @copyright Copyright (C) 2002-2009 The Nucleus Group
\r
23 * @version $Id: MANAGER.php 1624 2012-01-09 11:36:20Z sakamocchi $
\r
29 * Cached ITEM, BLOG, PLUGIN, KARMA and MEMBER objects. When these objects are requested
\r
30 * through the global $manager object (getItem, getBlog, ...), only the first call
\r
31 * will create an object. Subsequent calls will return the same object.
\r
33 * The $items, $blogs, ... arrays map an id to an object (for plugins, the name is used
\r
34 * rather than an ID)
\r
44 * cachedInfo to avoid repeated SQL queries (see pidInstalled/pluginInstalled/getPidFromName)
\r
45 * e.g. which plugins exists?
\r
47 * $cachedInfo['installedPlugins'] = array($pid -> $name)
\r
52 * The plugin subscriptionlist
\r
54 * The subcription array has the following structure
\r
55 * $subscriptions[$EventName] = array containing names of plugin classes to be
\r
56 * notified when that event happens
\r
61 * Returns the only instance of this class. Creates the instance if it
\r
62 * does not yet exists. Users should use this function as
\r
63 * $manager =& MANAGER::instance(); to get a reference to the object
\r
66 function &instance()
\r
68 static $instance = array();
\r
69 if ( empty($instance) )
\r
71 $instance[0] = new MANAGER();
\r
73 return $instance[0];
\r
77 * The constructor of this class initializes the object caches
\r
81 $this->items = array();
\r
82 $this->blogs = array();
\r
83 $this->plugins = array();
\r
84 $this->karma = array();
\r
85 $this->parserPrefs = array();
\r
86 $this->cachedInfo = array();
\r
91 * Returns the requested item object. If it is not in the cache, it will
\r
92 * first be loaded and then placed in the cache.
\r
93 * Intended use: $item =& $manager->getItem(1234)
\r
95 function &getItem($itemid, $allowdraft, $allowfuture)
\r
97 $item =& $this->items[$itemid];
\r
99 // check the draft and future rules if the item was already cached
\r
102 if ((!$allowdraft) && ($item['draft']))
\r
105 $blog =& $this->getBlog(getBlogIDFromItemID($itemid));
\r
106 if ( (!$allowfuture) && ($item['timestamp'] > $blog->getCorrectTime()) )
\r
113 // load class if needed
\r
114 $this->loadClass('ITEM');
\r
115 // load item object
\r
116 $item = ITEM::getitem($itemid, $allowdraft, $allowfuture);
\r
117 $this->items[$itemid] = $item;
\r
123 * Loads a class if it has not yet been loaded
\r
125 function loadClass($name)
\r
127 $this->_loadClass($name, $name . '.php');
\r
132 * Checks if an item exists
\r
134 function existsItem($id,$future,$draft)
\r
136 $this->_loadClass('ITEM','ITEM.php');
\r
137 return ITEM::exists($id,$future,$draft);
\r
141 * Checks if a category exists
\r
143 function existsCategory($id)
\r
145 return (quickQuery('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
\r
149 * Returns the blog object for a given blogid
\r
151 function &getBlog($blogid)
\r
153 $blog =& $this->blogs[$blogid];
\r
157 // load class if needed
\r
158 $this->_loadClass('BLOG','BLOG.php');
\r
159 // load blog object
\r
160 $blog = new BLOG($blogid);
\r
161 $this->blogs[$blogid] =& $blog;
\r
167 * Checks if a blog exists
\r
169 function existsBlog($name)
\r
171 $this->_loadClass('BLOG','BLOG.php');
\r
172 return BLOG::exists($name);
\r
176 * Checks if a blog id exists
\r
178 function existsBlogID($id)
\r
180 $this->_loadClass('BLOG','BLOG.php');
\r
181 return BLOG::existsID($id);
\r
185 * Returns a previously read template
\r
187 function &getTemplate($templateName)
\r
189 $template =& $this->templates[$templateName];
\r
193 $template = TEMPLATE::read($templateName);
\r
194 $this->templates[$templateName] =& $template;
\r
200 * Returns a KARMA object (karma votes)
\r
202 function &getKarma($itemid)
\r
204 $karma =& $this->karma[$itemid];
\r
207 // load class if needed
\r
208 $this->_loadClass('KARMA','KARMA.php');
\r
209 // create KARMA object
\r
210 $karma = new KARMA($itemid);
\r
211 $this->karma[$itemid] =& $karma;
\r
217 * Returns a MEMBER object
\r
219 function &getMember($memberid)
\r
221 $mem =& $this->members[$memberid];
\r
225 // load class if needed
\r
226 $this->_loadClass('MEMBER','MEMBER.php');
\r
227 // create MEMBER object
\r
228 $mem =& MEMBER::createFromID($memberid);
\r
229 $this->members[$memberid] =& $mem;
\r
235 * Set the global parser preferences
\r
237 function setParserProperty($name, $value)
\r
239 $this->parserPrefs[$name] = $value;
\r
244 * Get the global parser preferences
\r
246 function getParserProperty($name)
\r
248 return $this->parserPrefs[$name];
\r
252 * A helper function to load a class
\r
256 function _loadClass($name, $filename)
\r
258 if ( !class_exists($name) )
\r
261 include($DIR_LIBS . $filename);
\r
267 * MANAGER::_loadPlugin()
\r
268 * loading a certain plugin
\r
270 * @param string $name plugin name
\r
273 function _loadPlugin($name)
\r
275 if ( !class_exists($name) )
\r
277 global $DIR_PLUGINS;
\r
279 $fileName = $DIR_PLUGINS . $name . '.php';
\r
281 if ( !file_exists($fileName) )
\r
283 if ( !defined('_MANAGER_PLUGINFILE_NOTFOUND') )
\r
285 define('_MANAGER_PLUGINFILE_NOTFOUND', 'Plugin %s was not loaded (File not found)');
\r
287 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name));
\r
292 include($fileName);
\r
294 // check if class exists (avoid errors in eval'd code)
\r
295 if ( !class_exists($name) )
\r
297 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
\r
301 // add to plugin array
\r
302 eval('$this->plugins[$name] = new ' . $name . '();');
\r
305 $this->plugins[$name]->setID($this->getPidFromName($name));
\r
307 // unload plugin if a prefix is used and the plugin cannot handle this^
\r
308 global $MYSQL_PREFIX;
\r
309 if ( ($MYSQL_PREFIX != '')
\r
310 && !$this->plugins[$name]->supportsFeature('SqlTablePrefix') )
\r
312 unset($this->plugins[$name]);
\r
313 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
\r
317 // unload plugin if using non-mysql handler and plugin does not support it
\r
318 global $MYSQL_HANDLER;
\r
319 if ( (!in_array('mysql',$MYSQL_HANDLER))
\r
320 && !$this->plugins[$name]->supportsFeature('SqlApi') )
\r
322 unset($this->plugins[$name]);
\r
323 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINSQLAPI_NOTSUPPORT, $name));
\r
327 // call init method
\r
328 $this->plugins[$name]->init();
\r
334 * Returns a PLUGIN object
\r
336 function &getPlugin($name)
\r
338 // retrieve the name of the plugin in the right capitalisation
\r
339 $name = $this->getUpperCaseName ($name);
\r
341 $plugin =& $this->plugins[$name];
\r
345 // load class if needed
\r
346 $this->_loadPlugin($name);
\r
347 $plugin =& $this->plugins[$name];
\r
353 * Checks if the given plugin IS loaded or not
\r
355 function &pluginLoaded($name)
\r
357 $plugin =& $this->plugins[$name];
\r
361 function &pidLoaded($pid)
\r
364 reset($this->plugins);
\r
365 while ( list($name) = each($this->plugins) )
\r
367 if ( $pid!=$this->plugins[$name]->getId() )
\r
371 $plugin= & $this->plugins[$name];
\r
378 * checks if the given plugin IS installed or not
\r
380 function pluginInstalled($name)
\r
382 $this->_initCacheInfo('installedPlugins');
\r
383 return ($this->getPidFromName($name) != -1);
\r
386 function pidInstalled($pid)
\r
388 $this->_initCacheInfo('installedPlugins');
\r
389 return ($this->cachedInfo['installedPlugins'][$pid] != '');
\r
392 function getPidFromName($name)
\r
394 $this->_initCacheInfo('installedPlugins');
\r
395 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
\r
397 if (strtolower($pfile) == strtolower($name))
\r
406 * Retrieve the name of a plugin in the right capitalisation
\r
408 function getUpperCaseName ($name)
\r
410 $this->_initCacheInfo('installedPlugins');
\r
411 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
\r
413 if ( strtolower($pfile) == strtolower($name) )
\r
421 function clearCachedInfo($what)
\r
423 unset($this->cachedInfo[$what]);
\r
428 * Loads some info on the first call only
\r
430 function _initCacheInfo($what)
\r
432 if ( isset($this->cachedInfo[$what]) && is_array($this->cachedInfo[$what]) )
\r
438 // 'installedPlugins' = array ($pid => $name)
\r
439 case 'installedPlugins':
\r
440 $this->cachedInfo['installedPlugins'] = array();
\r
441 $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
\r
442 while ( $o = sql_fetch_object($res) )
\r
444 $this->cachedInfo['installedPlugins'][$o->pid] = $o->pfile;
\r
452 * A function to notify plugins that something has happened. Only the plugins
\r
453 * that are subscribed to the event will get notified.
\r
454 * Upon the first call, the list of subscriptions will be fetched from the
\r
455 * database. The plugins itsself will only get loaded when they are first needed
\r
457 * @param $eventName
\r
458 * Name of the event (method to be called on plugins)
\r
460 * Can contain any type of data, depending on the event type. Usually this is
\r
461 * an itemid, blogid, ... but it can also be an array containing multiple values
\r
463 function notify($eventName, $data)
\r
465 // load subscription list if needed
\r
466 if ( !is_array($this->subscriptions) )
\r
468 $this->_loadSubscriptions();
\r
471 // get listening objects
\r
472 $listeners = false;
\r
473 if ( isset($this->subscriptions[$eventName]) )
\r
475 $listeners = $this->subscriptions[$eventName];
\r
478 // notify all of them
\r
479 if ( is_array($listeners) )
\r
481 foreach( $listeners as $listener )
\r
483 // load class if needed
\r
484 $this->_loadPlugin($listener);
\r
485 // do notify (if method exists)
\r
486 if ( isset($this->plugins[$listener])
\r
487 && method_exists($this->plugins[$listener], 'event_' . $eventName))
\r
489 call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), $data);
\r
497 * Loads plugin subscriptions
\r
499 function _loadSubscriptions()
\r
501 // initialize as array
\r
502 $this->subscriptions = array();
\r
504 $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');
\r
505 while ( $o = sql_fetch_object($res) )
\r
507 $pluginName = $o->pfile;
\r
508 $eventName = $o->event;
\r
509 $this->subscriptions[$eventName][] = $pluginName;
\r
515 Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
\r
516 requests. tickets are user specific
\r
519 var $currentRequestTicket = '';
\r
522 * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
\r
524 function addTicketToUrl($url)
\r
526 $ticketCode = 'ticket=' . $this->_generateTicket();
\r
527 if ( strstr($url, '?') )
\r
529 $ticketCode = "{$url}&{$ticketCode}";
\r
533 $ticketCode = "{$url}?{$ticketCode}";
\r
535 return $ticketCode;
\r
539 * POST requests: Adds ticket as hidden formvar
\r
541 function addTicketHidden()
\r
543 $ticket = $this->_generateTicket();
\r
544 echo '<input type="hidden" name="ticket" value="', ENTITY::hsc($ticket), '" />';
\r
550 * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
\r
552 function getNewTicket()
\r
554 $this->currentRequestTicket = '';
\r
555 return $this->_generateTicket();
\r
559 * Checks the ticket that was passed along with the current request
\r
561 function checkTicket()
\r
565 // get ticket from request
\r
566 $ticket = requestVar('ticket');
\r
568 // no ticket -> don't allow
\r
569 if ( $ticket == '' )
\r
574 // remove expired tickets first
\r
575 $this->_cleanUpExpiredTickets();
\r
578 if (!$member->isLoggedIn())
\r
584 $memberId = $member->getID();
\r
587 // check if ticket is a valid one
\r
588 $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.sql_real_escape_string($ticket).'\'';
\r
592 * [in the original implementation, the checked ticket was deleted. This would lead to invalid
\r
593 * tickets when using the browsers back button and clicking another link/form
\r
594 * leaving the keys in the database is not a real problem, since they're member-specific and
\r
595 * only valid for a period of one hour]
\r
597 if ( quickQuery($query) == 1 )
\r
601 // not a valid ticket
\r
609 * (internal method) Removes the expired tickets
\r
611 function _cleanUpExpiredTickets()
\r
613 // remove tickets older than 1 hour
\r
614 $oldTime = time() - 60 * 60;
\r
615 $query = 'DELETE FROM ' . sql_table('tickets'). ' WHERE ctime < \'' . date('Y-m-d H:i:s',$oldTime) .'\'';
\r
621 * (internal method) Generates/returns a ticket (one ticket per page request)
\r
623 function _generateTicket()
\r
625 if ( $this->currentRequestTicket == '' )
\r
627 // generate new ticket (only one ticket will be generated per page request)
\r
628 // and store in database
\r
631 if ( !$member->isLoggedIn() )
\r
637 $memberId = $member->getID();
\r
643 // generate a random token
\r
644 srand((double)microtime()*1000000);
\r
645 $ticket = md5(uniqid(rand(), true));
\r
647 // add in database as non-active
\r
648 $query = 'INSERT INTO ' . sql_table('tickets') . ' (ticket, member, ctime) ';
\r
649 $query .= 'VALUES (\'' . sql_real_escape_string($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
\r
650 if ( sql_query($query) )
\r
655 $this->currentRequestTicket = $ticket;
\r
657 return $this->currentRequestTicket;
\r