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 1731 2012-04-08 15:10:35Z sakamocchi $
\r
28 * Cached ITEM, BLOG, PLUGIN, KARMA and MEMBER objects. When these objects are requested
\r
29 * through the global $manager object (getItem, getBlog, ...), only the first call
\r
30 * will create an object. Subsequent calls will return the same object.
\r
32 * The $items, $blogs, ... arrays map an id to an object (for plugins, the name is used
\r
33 * rather than an ID)
\r
43 * cachedInfo to avoid repeated SQL queries (see pidInstalled/pluginInstalled/getPidFromName)
\r
44 * e.g. which plugins exists?
\r
46 * $cachedInfo['installedPlugins'] = array($pid -> $name)
\r
48 private $cachedInfo;
\r
51 * The plugin subscriptionlist
\r
53 * The subcription array has the following structure
\r
54 * $subscriptions[$EventName] = array containing names of plugin classes to be
\r
55 * notified when that event happens
\r
57 * NOTE: this is referred by Comments::addComment() for spamcheck API
\r
58 * TODO: we should add new methods to get this
\r
60 public $subscriptions;
\r
63 * Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
\r
64 * requests. tickets are user specific
\r
66 private $currentRequestTicket = '';
\r
69 * Returns the only instance of this class. Creates the instance if it
\r
70 * does not yet exists. Users should use this function as
\r
71 * $manager =& Manager::instance(); to get a reference to the object
\r
74 public function &instance()
\r
76 static $instance = array();
\r
77 if ( empty($instance) )
\r
79 $instance[0] = new Manager();
\r
81 return $instance[0];
\r
85 * The constructor of this class initializes the object caches
\r
87 public function __construct()
\r
89 $this->items = array();
\r
90 $this->blogs = array();
\r
91 $this->plugins = array();
\r
92 $this->karma = array();
\r
93 $this->parserPrefs = array();
\r
94 $this->cachedInfo = array();
\r
99 * Returns the requested item object. If it is not in the cache, it will
\r
100 * first be loaded and then placed in the cache.
\r
101 * Intended use: $item =& $manager->getItem(1234, 0, 0)
\r
103 public function &getItem($itemid, $allowdraft, $allowfuture)
\r
105 $item =& $this->items[$itemid];
\r
107 /* confirm to cached */
\r
108 if ( !array_key_exists($itemid, $this->items) )
\r
110 $this->loadClass('ITEM');
\r
111 $item = Item::getitem($itemid, $allowdraft, $allowfuture);
\r
112 $this->items[$itemid] = $item;
\r
115 $item =& $this->items[$itemid];
\r
116 if ( !$allowdraft && ($item['draft']) )
\r
121 $blog =& $this->getBlog($item['blogid']);
\r
122 if ( !$allowfuture && ($item['timestamp'] > $blog->getCorrectTime()) )
\r
131 * Loads a class if it has not yet been loaded
\r
133 public function loadClass($name)
\r
135 $this->_loadClass($name, $name . '.php');
\r
140 * Checks if an item exists
\r
142 public function existsItem($id,$future,$draft)
\r
144 $this->_loadClass('ITEM','ITEM.php');
\r
145 return Item::exists($id,$future,$draft);
\r
149 * Checks if a category exists
\r
151 public function existsCategory($id)
\r
153 return (DB::getValue('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
\r
157 * Returns the blog object for a given blogid
\r
159 public function &getBlog($blogid)
\r
161 $blog =& $this->blogs[$blogid];
\r
165 // load class if needed
\r
166 $this->_loadClass('BLOG','BLOG.php');
\r
167 // load blog object
\r
168 $blog = new Blog($blogid);
\r
169 $this->blogs[$blogid] =& $blog;
\r
175 * Checks if a blog exists
\r
177 public function existsBlog($name)
\r
179 $this->_loadClass('BLOG','BLOG.php');
\r
180 return Blog::exists($name);
\r
184 * Checks if a blog id exists
\r
186 public function existsBlogID($id)
\r
188 $this->_loadClass('BLOG','BLOG.php');
\r
189 return Blog::existsID($id);
\r
193 * Returns a previously read template
\r
195 public function &getTemplate($templateName)
\r
197 $template =& $this->templates[$templateName];
\r
201 $template = Template::read($templateName);
\r
202 $this->templates[$templateName] =& $template;
\r
208 * Returns a KARMA object (karma votes)
\r
210 public function &getKarma($itemid)
\r
212 $karma =& $this->karma[$itemid];
\r
216 // load class if needed
\r
217 $this->_loadClass('KARMA','KARMA.php');
\r
218 // create KARMA object
\r
219 $karma = new Karma($itemid);
\r
220 $this->karma[$itemid] =& $karma;
\r
226 * Returns a MEMBER object
\r
228 public function &getMember($memberid)
\r
230 $mem =& $this->members[$memberid];
\r
234 // load class if needed
\r
235 $this->_loadClass('MEMBER','MEMBER.php');
\r
236 // create MEMBER object
\r
237 $mem =& Member::createFromID($memberid);
\r
238 $this->members[$memberid] =& $mem;
\r
244 * Set the global parser preferences
\r
246 public function setParserProperty($name, $value)
\r
248 $this->parserPrefs[$name] = $value;
\r
253 * Get the global parser preferences
\r
255 public function getParserProperty($name)
\r
257 return $this->parserPrefs[$name];
\r
261 * A helper function to load a class
\r
265 private function _loadClass($name, $filename)
\r
267 if ( !class_exists($name) )
\r
270 include($DIR_LIBS . $filename);
\r
276 * Manager::_loadPlugin()
\r
277 * loading a certain plugin
\r
279 * @param string $name plugin name
\r
282 private function _loadPlugin($name)
\r
284 global $DIR_PLUGINS, $MYSQL_HANDLER, $MYSQL_PREFIX;
\r
286 if ( class_exists($name) )
\r
291 $fileName = "{$DIR_PLUGINS}{$name}.php";
\r
293 if ( !file_exists($fileName) )
\r
295 if ( !defined('_MANAGER_PLUGINFILE_NOTFOUND') )
\r
297 define('_MANAGER_PLUGINFILE_NOTFOUND', 'Plugin %s was not loaded (File not found)');
\r
299 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name));
\r
304 include($fileName);
\r
306 // check if class exists (avoid errors in eval'd code)
\r
307 if ( !class_exists($name) )
\r
309 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
\r
313 // add to plugin array
\r
314 $this->plugins[$name] = new $name();
\r
317 $this->plugins[$name]->setID($this->getPidFromName($name));
\r
319 // unload plugin if a prefix is used and the plugin cannot handle this
\r
320 if ( ($MYSQL_PREFIX != '')
\r
321 && !$this->plugins[$name]->supportsFeature('SqlTablePrefix') )
\r
323 unset($this->plugins[$name]);
\r
324 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
\r
328 // unload plugin if using non-mysql handler and plugin does not support it
\r
329 if ( (!in_array('mysql',$MYSQL_HANDLER))
\r
330 && !$this->plugins[$name]->supportsFeature('SqlApi') )
\r
332 unset($this->plugins[$name]);
\r
333 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINSQLAPI_NOTSUPPORT, $name));
\r
337 // call init method
\r
338 $this->plugins[$name]->init();
\r
344 * Manager:getPlugin()
\r
345 * Returns a PLUGIN object
\r
347 * @param string $name name of plugin
\r
348 * @return object plugin object
\r
350 public function &getPlugin($name)
\r
352 // retrieve the name of the plugin in the right capitalisation
\r
353 $name = $this->getUpperCaseName ($name);
\r
356 $plugin =& $this->plugins[$name];
\r
360 // load class if needed
\r
361 $this->_loadPlugin($name);
\r
362 $plugin =& $this->plugins[$name];
\r
368 * Manager::pluginLoaded()
\r
369 * Checks if the given plugin IS loaded or not
\r
371 * @param string $name name of plugin
\r
372 * @return object plugin object
\r
374 public function &pluginLoaded($name)
\r
376 $plugin =& $this->plugins[$name];
\r
381 * Manager::pidLoaded()
\r
383 * @param integer $pid id for plugin
\r
384 * @return object plugin object
\r
386 public function &pidLoaded($pid)
\r
389 reset($this->plugins);
\r
390 while ( list($name) = each($this->plugins) )
\r
392 if ( $pid!=$this->plugins[$name]->getId() )
\r
396 $plugin= & $this->plugins[$name];
\r
403 * Manager::pluginInstalled()
\r
404 * checks if the given plugin IS installed or not
\r
406 * @param string $name name of plugin
\r
407 * @return boolean exists or not
\r
409 public function pluginInstalled($name)
\r
411 $this->_initCacheInfo('installedPlugins');
\r
412 return ($this->getPidFromName($name) != -1);
\r
416 * Manager::pidInstalled()
\r
417 * checks if the given plugin IS installed or not
\r
419 * @param integer $pid id of plugin
\r
420 * @return boolean exists or not
\r
422 public function pidInstalled($pid)
\r
424 $this->_initCacheInfo('installedPlugins');
\r
425 return ($this->cachedInfo['installedPlugins'][$pid] != '');
\r
429 * Manager::getPidFromName()
\r
431 * @param string $name name of plugin
\r
432 * @return mixed id for plugin or -1 if not exists
\r
434 public function getPidFromName($name)
\r
436 $this->_initCacheInfo('installedPlugins');
\r
437 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
\r
439 if (strtolower($pfile) == strtolower($name))
\r
448 * Manager::getPluginNameFromPid()
\r
450 * @param string $pid ID for plugin
\r
451 * @return string name of plugin
\r
453 public function getPluginNameFromPid($pid)
\r
455 if ( !array_key_exists($pid, $this->cachedInfo['installedPlugins']) )
\r
457 $query = 'SELECT pfile FROM %s WHERE pid=%d;';
\r
458 $query = sprintf($query, sql_table('plugin'), (integer) $pid);
\r
459 return DB::getValue($query);
\r
461 return $this->cachedInfo['installedPlugins'][$pid];
\r
465 * Manager::getUpperCaseName()
\r
466 * Retrieve the name of a plugin in the right capitalisation
\r
468 * @param string $name name of plugin
\r
469 * @return string name according to UpperCamelCase
\r
471 public function getUpperCaseName ($name)
\r
473 $this->_initCacheInfo('installedPlugins');
\r
474 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
\r
476 if ( strtolower($pfile) == strtolower($name) )
\r
485 * Manager::clearCachedInfo()
\r
487 * @param string $what
\r
490 public function clearCachedInfo($what)
\r
492 unset($this->cachedInfo[$what]);
\r
497 * Manager::_initCacheInfo()
\r
498 * Loads some info on the first call only
\r
500 * @param string $what 'installedPlugins'
\r
503 private function _initCacheInfo($what)
\r
505 if ( array_key_exists($what, $this->cachedInfo)
\r
506 && is_array($this->cachedInfo[$what]) )
\r
513 // 'installedPlugins' = array ($pid => $name)
\r
514 case 'installedPlugins':
\r
515 $this->cachedInfo['installedPlugins'] = array();
\r
516 $res = DB::getResult('SELECT pid, pfile FROM ' . sql_table('plugin'));
\r
517 foreach ( $res as $row )
\r
519 $this->cachedInfo['installedPlugins'][$row['pid']] = $row['pfile'];
\r
527 * Manager::notify()
\r
528 * A function to notify plugins that something has happened. Only the plugins
\r
529 * that are subscribed to the event will get notified.
\r
530 * Upon the first call, the list of subscriptions will be fetched from the
\r
531 * database. The plugins itsself will only get loaded when they are first needed
\r
533 * @param string $eventName Name of the event (method to be called on plugins)
\r
534 * @param string $data Can contain any type of data,
\r
535 * depending on the event type. Usually this is an itemid, blogid, ...
\r
536 * but it can also be an array containing multiple values
\r
539 public function notify($eventName, $data)
\r
541 // load subscription list if needed
\r
542 if ( !is_array($this->subscriptions) )
\r
544 $this->_loadSubscriptions();
\r
547 // get listening objects
\r
548 $listeners = false;
\r
549 if ( array_key_exists($eventName, $this->subscriptions)
\r
550 && !empty($this->subscriptions[$eventName]) )
\r
552 $listeners = $this->subscriptions[$eventName];
\r
555 // notify all of them
\r
556 if ( is_array($listeners) )
\r
558 foreach( $listeners as $listener )
\r
560 // load class if needed
\r
561 $this->_loadPlugin($listener);
\r
563 // do notify (if method exists)
\r
564 if ( array_key_exists($listener, $this->plugins)
\r
565 && !empty($this->plugins[$listener])
\r
566 && method_exists($this->plugins[$listener], 'event_' . $eventName) )
\r
568 call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), $data);
\r
576 * Manager::_loadSubscriptions()
\r
577 * Loads plugin subscriptions
\r
582 private function _loadSubscriptions()
\r
584 // initialize as array
\r
585 $this->subscriptions = array();
\r
587 $query = "SELECT p.pfile as pfile, e.event as event"
\r
588 . " FROM %s as e, %s as p"
\r
589 . " WHERE e.pid=p.pid ORDER BY p.porder ASC";
\r
590 $query = sprintf($query, sql_table('plugin_event'), sql_table('plugin'));
\r
591 $res = DB::getResult($query);
\r
593 foreach ( $res as $row )
\r
595 $pluginName = $row['pfile'];
\r
596 $eventName = $row['event'];
\r
597 $this->subscriptions[$eventName][] = $pluginName;
\r
603 * Manager::getNumberOfSubscribers()
\r
605 * @param string $event name of events
\r
606 * @return integer number of event subscriber
\r
608 public function getNumberOfSubscribers($event)
\r
610 $query = 'SELECT COUNT(*) as count FROM %s WHERE event=%s;';
\r
611 $query = sprintf($query, sql_table('plugin_event'), DB::quoteValue($event));
\r
612 return (integer) DB::getValue($query);
\r
616 * Manager::addTicketToUrl()
\r
617 * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
\r
619 * @param string url string for URI
\r
622 public function addTicketToUrl($url)
\r
624 $ticketCode = 'ticket=' . $this->_generateTicket();
\r
625 if ( i18n::strpos($url, '?') === FALSE )
\r
627 $ticketCode = "{$url}?{$ticketCode}";
\r
631 $ticketCode = "{$url}&{$ticketCode}";
\r
633 return $ticketCode;
\r
637 * Manager::addTicketHidden()
\r
638 * POST requests: Adds ticket as hidden formvar
\r
643 public function addTicketHidden()
\r
645 $ticket = $this->_generateTicket();
\r
646 echo '<input type="hidden" name="ticket" value="', Entity::hsc($ticket), '" />';
\r
651 * Manager::getNewTicket()
\r
653 * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
\r
656 * @return string string of ticket
\r
658 public function getNewTicket()
\r
660 $this->currentRequestTicket = '';
\r
661 return $this->_generateTicket();
\r
665 * Manager::checkTicket()
\r
666 * Checks the ticket that was passed along with the current request
\r
669 * @return boolean correct or not
\r
671 public function checkTicket()
\r
675 // get ticket from request
\r
676 $ticket = requestVar('ticket');
\r
678 // no ticket -> don't allow
\r
679 if ( $ticket == '' )
\r
684 // remove expired tickets first
\r
685 $this->_cleanUpExpiredTickets();
\r
688 if (!$member->isLoggedIn())
\r
694 $memberId = $member->getID();
\r
697 // check if ticket is a valid one
\r
698 $query = sprintf('SELECT COUNT(*) as result FROM %s WHERE member=%d and ticket=%s',
\r
699 sql_table('tickets'),
\r
701 DB::quoteValue($ticket)
\r
706 * [in the original implementation, the checked ticket was deleted. This would lead to invalid
\r
707 * tickets when using the browsers back button and clicking another link/form
\r
708 * leaving the keys in the database is not a real problem, since they're member-specific and
\r
709 * only valid for a period of one hour]
\r
711 if ( DB::getValue($query) != 1 )
\r
720 * Manager::_cleanUpExpiredTickets()
\r
721 * Removes the expired tickets
\r
726 private function _cleanUpExpiredTickets()
\r
728 // remove tickets older than 1 hour
\r
729 $oldTime = time() - 60 * 60;
\r
730 $query = 'DELETE FROM %s WHERE ctime < %s';
\r
731 $query = sprintf($query, sql_table('tickets'), DB::formatDateTime($oldTime));
\r
732 DB::execute($query);
\r
737 * Manager::_generateTicket()
\r
738 * Generates/returns a ticket (one ticket per page request)
\r
743 private function _generateTicket()
\r
745 if ( $this->currentRequestTicket == '' )
\r
747 // generate new ticket (only one ticket will be generated per page request)
\r
748 // and store in database
\r
751 if ( !$member->isLoggedIn() )
\r
757 $memberId = $member->getID();
\r
763 // generate a random token
\r
764 srand((double)microtime()*1000000);
\r
765 $ticket = md5(uniqid(rand(), true));
\r
767 // add in database as non-active
\r
768 $query = 'INSERT INTO %s (ticket, member, ctime) VALUES (%s, %d, %s)';
\r
769 $query = sprintf($query, sql_table('tickets'), DB::quoteValue($ticket), (integer) $memberId, DB::formatDateTime());
\r
771 if ( DB::execute($query) !== FALSE )
\r
776 $this->currentRequestTicket = $ticket;
\r
778 return $this->currentRequestTicket;
\r