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
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
49 private $cachedInfo;
\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
58 * NOTE: this is referred by Comments::addComment() for spamcheck API
\r
59 * TODO: we should add new methods to get this
\r
61 public $subscriptions;
\r
64 * Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
\r
65 * requests. tickets are user specific
\r
67 private $currentRequestTicket = '';
\r
70 * Returns the only instance of this class. Creates the instance if it
\r
71 * does not yet exists. Users should use this function as
\r
72 * $manager =& Manager::instance(); to get a reference to the object
\r
75 public function &instance()
\r
77 static $instance = array();
\r
78 if ( empty($instance) )
\r
80 $instance[0] = new Manager();
\r
82 return $instance[0];
\r
86 * The constructor of this class initializes the object caches
\r
88 public function __construct()
\r
90 $this->items = array();
\r
91 $this->blogs = array();
\r
92 $this->plugins = array();
\r
93 $this->karma = array();
\r
94 $this->templates = array();
\r
95 $this->skins = array();
\r
96 $this->parserPrefs = array();
\r
97 $this->cachedInfo = array();
\r
98 $this->members = array();
\r
103 * Returns the requested item object. If it is not in the cache, it will
\r
104 * first be loaded and then placed in the cache.
\r
105 * Intended use: $item =& $manager->getItem(1234, 0, 0)
\r
107 public function &getItem($itemid, $allowdraft, $allowfuture)
\r
109 /* confirm to cached */
\r
110 if ( !array_key_exists($itemid, $this->items) )
\r
112 $this->loadClass('ITEM');
\r
113 $item = Item::getitem($itemid, $allowdraft, $allowfuture);
\r
114 $this->items[$itemid] = $item;
\r
117 $item =& $this->items[$itemid];
\r
118 if ( !$allowdraft && ($item['draft']) )
\r
123 $blog =& $this->getBlog($item['blogid']);
\r
124 if ( !$allowfuture && ($item['timestamp'] > $blog->getCorrectTime()) )
\r
133 * Loads a class if it has not yet been loaded
\r
135 public function loadClass($name)
\r
137 $this->_loadClass($name, $name . '.php');
\r
142 * Checks if an item exists
\r
144 public function existsItem($id,$future,$draft)
\r
146 $this->_loadClass('ITEM','ITEM.php');
\r
147 return Item::exists($id,$future,$draft);
\r
151 * Checks if a category exists
\r
153 public function existsCategory($id)
\r
155 return (DB::getValue('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
\r
159 * Returns the blog object for a given blogid
\r
161 public function &getBlog($blogid)
\r
163 if ( !array_key_exists($blogid, $this->blogs) )
\r
165 $this->_loadClass('BLOG','BLOG.php');
\r
166 $this->blogs[$blogid] = new Blog($blogid);
\r
168 return $this->blogs[$blogid];
\r
172 * Checks if a blog exists
\r
174 public function existsBlog($name)
\r
176 $this->_loadClass('BLOG','BLOG.php');
\r
177 return Blog::exists($name);
\r
181 * Checks if a blog id exists
\r
183 public function existsBlogID($id)
\r
185 $this->_loadClass('BLOG','BLOG.php');
\r
186 return Blog::existsID($id);
\r
190 * Returns a previously read template
\r
192 public function &getTemplate($templateName)
\r
194 if ( !array_key_exists($templateName, $this->templates) )
\r
196 $this->_loadClass('Template','TEMPLATE.php');
\r
197 $this->templates[$templateName] =& Template::read($templateName);
\r
199 return $this->templates[$templateName];
\r
203 * Returns a KARMA object (karma votes)
\r
205 public function &getKarma($itemid)
\r
207 if ( !array_key_exists($itemid, $this->karma) )
\r
209 $this->_loadClass('Karma','KARMA.php');
\r
210 $this->karma[$itemid] = new Karma($itemid);
\r
212 return $this->karma[$itemid];
\r
216 * Returns a MEMBER object
\r
218 public function &getMember($memberid)
\r
220 if ( !array_key_exists($memberid, $this->members) )
\r
222 $this->_loadClass('Member','MEMBER.php');
\r
223 $this->members[$memberid] =& Member::createFromID($memberid);;
\r
225 return $this->members[$memberid];
\r
229 * Manager::getSkin()
\r
231 * @param integer $skinid ID for skin
\r
232 * @param string $action_class action class for handling skin variables
\r
233 * @param string $event_identifier identifier for event name
\r
234 * @return object instance of Skin class
\r
236 public function &getSkin($skinid, $action_class='Actions', $event_identifier='Skin')
\r
238 if ( !array_key_exists($skinid, $this->skins) )
\r
240 $this->_loadClass('Skin', 'SKIN.php');
\r
241 $this->skins[$skinid] = new Skin($skinid, $action_class, $event_identifier);
\r
244 return $this->skins[$skinid];
\r
248 * Set the global parser preferences
\r
250 public function setParserProperty($name, $value)
\r
252 $this->parserPrefs[$name] = $value;
\r
257 * Get the global parser preferences
\r
259 public function getParserProperty($name)
\r
261 return $this->parserPrefs[$name];
\r
265 * A helper function to load a class
\r
269 private function _loadClass($name, $filename)
\r
273 if ( !class_exists($name) )
\r
275 include($DIR_LIBS . $filename);
\r
281 * Manager::_loadPlugin()
\r
282 * loading a certain plugin
\r
284 * @param string $name plugin name
\r
287 private function _loadPlugin($name)
\r
289 global $DIR_PLUGINS, $MYSQL_HANDLER, $MYSQL_PREFIX;
\r
291 if ( class_exists($name) )
\r
296 $fileName = "{$DIR_PLUGINS}{$name}.php";
\r
298 if ( !file_exists($fileName) )
\r
300 if ( !defined('_MANAGER_PLUGINFILE_NOTFOUND') )
\r
302 define('_MANAGER_PLUGINFILE_NOTFOUND', 'Plugin %s was not loaded (File not found)');
\r
304 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name));
\r
309 include($fileName);
\r
311 // check if class exists (avoid errors in eval'd code)
\r
312 if ( !class_exists($name) )
\r
314 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
\r
318 // add to plugin array
\r
319 $this->plugins[$name] = new $name();
\r
322 $this->plugins[$name]->setID($this->getPidFromName($name));
\r
324 // unload plugin if a prefix is used and the plugin cannot handle this
\r
325 if ( ($MYSQL_PREFIX != '')
\r
326 && !$this->plugins[$name]->supportsFeature('SqlTablePrefix') )
\r
328 unset($this->plugins[$name]);
\r
329 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
\r
333 // unload plugin if using non-mysql handler and plugin does not support it
\r
334 if ( (!in_array('mysql',$MYSQL_HANDLER))
\r
335 && !$this->plugins[$name]->supportsFeature('SqlApi') )
\r
337 unset($this->plugins[$name]);
\r
338 ActionLog::add(WARNING, sprintf(_MANAGER_PLUGINSQLAPI_NOTSUPPORT, $name));
\r
342 // call init method
\r
343 $this->plugins[$name]->init();
\r
349 * Manager:getPlugin()
\r
350 * Returns a PLUGIN object
\r
352 * @param string $name name of plugin
\r
353 * @return object plugin object
\r
355 public function &getPlugin($name)
\r
357 // retrieve the name of the plugin in the right capitalisation
\r
358 $name = $this->getUpperCaseName ($name);
\r
361 $plugin =& $this->plugins[$name];
\r
365 // load class if needed
\r
366 $this->_loadPlugin($name);
\r
367 $plugin =& $this->plugins[$name];
\r
373 * Manager::pluginLoaded()
\r
374 * Checks if the given plugin IS loaded or not
\r
376 * @param string $name name of plugin
\r
377 * @return object plugin object
\r
379 public function &pluginLoaded($name)
\r
381 $plugin =& $this->plugins[$name];
\r
386 * Manager::pidLoaded()
\r
388 * @param integer $pid id for plugin
\r
389 * @return object plugin object
\r
391 public function &pidLoaded($pid)
\r
394 reset($this->plugins);
\r
395 while ( list($name) = each($this->plugins) )
\r
397 if ( $pid!=$this->plugins[$name]->getId() )
\r
401 $plugin= & $this->plugins[$name];
\r
408 * Manager::pluginInstalled()
\r
409 * checks if the given plugin IS installed or not
\r
411 * @param string $name name of plugin
\r
412 * @return boolean exists or not
\r
414 public function pluginInstalled($name)
\r
416 $this->_initCacheInfo('installedPlugins');
\r
417 return ($this->getPidFromName($name) != -1);
\r
421 * Manager::pidInstalled()
\r
422 * checks if the given plugin IS installed or not
\r
424 * @param integer $pid id of plugin
\r
425 * @return boolean exists or not
\r
427 public function pidInstalled($pid)
\r
429 $this->_initCacheInfo('installedPlugins');
\r
430 return ($this->cachedInfo['installedPlugins'][$pid] != '');
\r
434 * Manager::getPidFromName()
\r
436 * @param string $name name of plugin
\r
437 * @return mixed id for plugin or -1 if not exists
\r
439 public function getPidFromName($name)
\r
441 $this->_initCacheInfo('installedPlugins');
\r
442 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
\r
444 if (strtolower($pfile) == strtolower($name))
\r
453 * Manager::getPluginNameFromPid()
\r
455 * @param string $pid ID for plugin
\r
456 * @return string name of plugin
\r
458 public function getPluginNameFromPid($pid)
\r
460 if ( !array_key_exists($pid, $this->cachedInfo['installedPlugins']) )
\r
462 $query = 'SELECT pfile FROM %s WHERE pid=%d;';
\r
463 $query = sprintf($query, sql_table('plugin'), (integer) $pid);
\r
464 return DB::getValue($query);
\r
466 return $this->cachedInfo['installedPlugins'][$pid];
\r
470 * Manager::getUpperCaseName()
\r
471 * Retrieve the name of a plugin in the right capitalisation
\r
473 * @param string $name name of plugin
\r
474 * @return string name according to UpperCamelCase
\r
476 public function getUpperCaseName ($name)
\r
478 $this->_initCacheInfo('installedPlugins');
\r
479 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
\r
481 if ( strtolower($pfile) == strtolower($name) )
\r
490 * Manager::clearCachedInfo()
\r
492 * @param string $what
\r
495 public function clearCachedInfo($what)
\r
497 unset($this->cachedInfo[$what]);
\r
502 * Manager::_initCacheInfo()
\r
503 * Loads some info on the first call only
\r
505 * @param string $what 'installedPlugins'
\r
508 private function _initCacheInfo($what)
\r
510 if ( array_key_exists($what, $this->cachedInfo)
\r
511 && is_array($this->cachedInfo[$what]) )
\r
518 // 'installedPlugins' = array ($pid => $name)
\r
519 case 'installedPlugins':
\r
520 $this->cachedInfo['installedPlugins'] = array();
\r
521 $res = DB::getResult('SELECT pid, pfile FROM ' . sql_table('plugin'));
\r
522 foreach ( $res as $row )
\r
524 $this->cachedInfo['installedPlugins'][$row['pid']] = $row['pfile'];
\r
532 * Manager::notify()
\r
533 * A function to notify plugins that something has happened. Only the plugins
\r
534 * that are subscribed to the event will get notified.
\r
535 * Upon the first call, the list of subscriptions will be fetched from the
\r
536 * database. The plugins itsself will only get loaded when they are first needed
\r
538 * @param string $eventName Name of the event (method to be called on plugins)
\r
539 * @param string $data Can contain any type of data,
\r
540 * depending on the event type. Usually this is an itemid, blogid, ...
\r
541 * but it can also be an array containing multiple values
\r
544 public function notify($eventName, $data)
\r
546 // load subscription list if needed
\r
547 if ( !is_array($this->subscriptions) )
\r
549 $this->_loadSubscriptions();
\r
552 // get listening objects
\r
553 $listeners = false;
\r
554 if ( array_key_exists($eventName, $this->subscriptions)
\r
555 && !empty($this->subscriptions[$eventName]) )
\r
557 $listeners = $this->subscriptions[$eventName];
\r
560 // notify all of them
\r
561 if ( is_array($listeners) )
\r
563 foreach( $listeners as $listener )
\r
565 // load class if needed
\r
566 $this->_loadPlugin($listener);
\r
568 // do notify (if method exists)
\r
569 if ( array_key_exists($listener, $this->plugins)
\r
570 && !empty($this->plugins[$listener])
\r
571 && method_exists($this->plugins[$listener], 'event_' . $eventName) )
\r
573 call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), $data);
\r
581 * Manager::_loadSubscriptions()
\r
582 * Loads plugin subscriptions
\r
587 private function _loadSubscriptions()
\r
589 // initialize as array
\r
590 $this->subscriptions = array();
\r
592 $query = "SELECT p.pfile as pfile, e.event as event"
\r
593 . " FROM %s as e, %s as p"
\r
594 . " WHERE e.pid=p.pid ORDER BY p.porder ASC";
\r
595 $query = sprintf($query, sql_table('plugin_event'), sql_table('plugin'));
\r
596 $res = DB::getResult($query);
\r
598 foreach ( $res as $row )
\r
600 $pluginName = $row['pfile'];
\r
601 $eventName = $row['event'];
\r
602 $this->subscriptions[$eventName][] = $pluginName;
\r
608 * Manager::getNumberOfSubscribers()
\r
610 * @param string $event name of events
\r
611 * @return integer number of event subscriber
\r
613 public function getNumberOfSubscribers($event)
\r
615 $query = 'SELECT COUNT(*) as count FROM %s WHERE event=%s;';
\r
616 $query = sprintf($query, sql_table('plugin_event'), DB::quoteValue($event));
\r
617 return (integer) DB::getValue($query);
\r
621 * Manager::addTicketToUrl()
\r
622 * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
\r
624 * @param string url string for URI
\r
627 public function addTicketToUrl($url)
\r
629 $ticketCode = 'ticket=' . $this->_generateTicket();
\r
630 if ( i18n::strpos($url, '?') === FALSE )
\r
632 $ticketCode = "{$url}?{$ticketCode}";
\r
636 $ticketCode = "{$url}&{$ticketCode}";
\r
638 return $ticketCode;
\r
642 * Manager::addTicketHidden()
\r
643 * POST requests: Adds ticket as hidden formvar
\r
648 public function addTicketHidden()
\r
650 $ticket = $this->_generateTicket();
\r
651 echo '<input type="hidden" name="ticket" value="', Entity::hsc($ticket), '" />';
\r
656 * Manager::getNewTicket()
\r
658 * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
\r
661 * @return string string of ticket
\r
663 public function getNewTicket()
\r
665 $this->currentRequestTicket = '';
\r
666 return $this->_generateTicket();
\r
670 * Manager::checkTicket()
\r
671 * Checks the ticket that was passed along with the current request
\r
674 * @return boolean correct or not
\r
676 public function checkTicket()
\r
680 // get ticket from request
\r
681 $ticket = requestVar('ticket');
\r
683 // no ticket -> don't allow
\r
684 if ( $ticket == '' )
\r
689 // remove expired tickets first
\r
690 $this->_cleanUpExpiredTickets();
\r
693 if (!$member->isLoggedIn())
\r
699 $memberId = $member->getID();
\r
702 // check if ticket is a valid one
\r
703 $query = sprintf('SELECT COUNT(*) as result FROM %s WHERE member=%d and ticket=%s',
\r
704 sql_table('tickets'),
\r
706 DB::quoteValue($ticket)
\r
711 * [in the original implementation, the checked ticket was deleted. This would lead to invalid
\r
712 * tickets when using the browsers back button and clicking another link/form
\r
713 * leaving the keys in the database is not a real problem, since they're member-specific and
\r
714 * only valid for a period of one hour]
\r
716 if ( DB::getValue($query) != 1 )
\r
725 * Manager::_cleanUpExpiredTickets()
\r
726 * Removes the expired tickets
\r
731 private function _cleanUpExpiredTickets()
\r
733 // remove tickets older than 1 hour
\r
734 $oldTime = time() - 60 * 60;
\r
735 $query = 'DELETE FROM %s WHERE ctime < %s';
\r
736 $query = sprintf($query, sql_table('tickets'), DB::formatDateTime($oldTime));
\r
737 DB::execute($query);
\r
742 * Manager::_generateTicket()
\r
743 * Generates/returns a ticket (one ticket per page request)
\r
748 private function _generateTicket()
\r
750 if ( $this->currentRequestTicket == '' )
\r
752 // generate new ticket (only one ticket will be generated per page request)
\r
753 // and store in database
\r
756 if ( !$member->isLoggedIn() )
\r
762 $memberId = $member->getID();
\r
768 // generate a random token
\r
769 srand((double)microtime()*1000000);
\r
770 $ticket = md5(uniqid(rand(), true));
\r
772 // add in database as non-active
\r
773 $query = 'INSERT INTO %s (ticket, member, ctime) VALUES (%s, %d, %s)';
\r
774 $query = sprintf($query, sql_table('tickets'), DB::quoteValue($ticket), (integer) $memberId, DB::formatDateTime());
\r
776 if ( DB::execute($query) !== FALSE )
\r
781 $this->currentRequestTicket = $ticket;
\r
783 return $this->currentRequestTicket;
\r