3 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
4 * Copyright (C) 2002-2009 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-2009 The Nucleus Group
24 * $NucleusJP: MANAGER.php,v 1.8.2.1 2007/09/05 07:00:18 kimitake Exp $
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
67 static $instance = array();
\r
68 if (empty($instance)) {
\r
69 $instance[0] =& new MANAGER();
\r
71 return $instance[0];
\r
75 * The constructor of this class initializes the object caches
\r
77 function MANAGER() {
\r
78 $this->items = array();
\r
79 $this->blogs = array();
\r
80 $this->plugins = array();
\r
81 $this->karma = array();
\r
82 $this->parserPrefs = array();
\r
83 $this->cachedInfo = array();
\r
87 * Returns the requested item object. If it is not in the cache, it will
\r
88 * first be loaded and then placed in the cache.
\r
89 * Intended use: $item =& $manager->getItem(1234)
\r
91 function &getItem($itemid, $allowdraft, $allowfuture) {
\r
92 $item =& $this->items[$itemid];
\r
94 // check the draft and future rules if the item was already cached
\r
96 if ((!$allowdraft) && ($item['draft']))
\r
99 $blog =& $this->getBlog(getBlogIDFromItemID($itemid));
\r
100 if ((!$allowfuture) && ($item['timestamp'] > $blog->getCorrectTime()))
\r
104 // load class if needed
\r
105 $this->loadClass('ITEM');
\r
106 // load item object
\r
107 $item = ITEM::getitem($itemid, $allowdraft, $allowfuture);
\r
108 $this->items[$itemid] = $item;
\r
114 * Loads a class if it has not yet been loaded
\r
116 function loadClass($name) {
\r
117 $this->_loadClass($name, $name . '.php');
\r
121 * Checks if an item exists
\r
123 function existsItem($id,$future,$draft) {
\r
124 $this->_loadClass('ITEM','ITEM.php');
\r
125 return ITEM::exists($id,$future,$draft);
\r
129 * Checks if a category exists
\r
131 function existsCategory($id) {
\r
132 return (quickQuery('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
\r
136 * Returns the blog object for a given blogid
\r
138 function &getBlog($blogid) {
\r
139 $blog =& $this->blogs[$blogid];
\r
142 // load class if needed
\r
143 $this->_loadClass('BLOG','BLOG.php');
\r
144 // load blog object
\r
145 $blog =& new BLOG($blogid);
\r
146 $this->blogs[$blogid] =& $blog;
\r
152 * Checks if a blog exists
\r
154 function existsBlog($name) {
\r
155 $this->_loadClass('BLOG','BLOG.php');
\r
156 return BLOG::exists($name);
\r
160 * Checks if a blog id exists
\r
162 function existsBlogID($id) {
\r
163 $this->_loadClass('BLOG','BLOG.php');
\r
164 return BLOG::existsID($id);
\r
168 * Returns a previously read template
\r
170 function &getTemplate($templateName) {
\r
171 $template =& $this->templates[$templateName];
\r
174 $template = TEMPLATE::read($templateName);
\r
175 $this->templates[$templateName] =& $template;
\r
181 * Returns a KARMA object (karma votes)
\r
183 function &getKarma($itemid) {
\r
184 $karma =& $this->karma[$itemid];
\r
187 // load class if needed
\r
188 $this->_loadClass('KARMA','KARMA.php');
\r
189 // create KARMA object
\r
190 $karma =& new KARMA($itemid);
\r
191 $this->karma[$itemid] =& $karma;
\r
197 * Returns a MEMBER object
\r
199 function &getMember($memberid) {
\r
200 $mem =& $this->members[$memberid];
\r
203 // load class if needed
\r
204 $this->_loadClass('MEMBER','MEMBER.php');
\r
205 // create MEMBER object
\r
206 $mem =& MEMBER::createFromID($memberid);
\r
207 $this->members[$memberid] =& $mem;
\r
213 * Set the global parser preferences
\r
215 function setParserProperty($name, $value) {
\r
216 $this->parserPrefs[$name] = $value;
\r
220 * Get the global parser preferences
\r
222 function getParserProperty($name) {
\r
223 return $this->parserPrefs[$name];
\r
227 * A helper function to load a class
\r
231 function _loadClass($name, $filename) {
\r
232 if (!class_exists($name)) {
\r
234 include($DIR_LIBS . $filename);
\r
239 * A helper function to load a plugin
\r
243 function _loadPlugin($name) {
\r
244 if (!class_exists($name)) {
\r
245 global $DIR_PLUGINS;
\r
247 $fileName = $DIR_PLUGINS . $name . '.php';
\r
249 if (!file_exists($fileName))
\r
251 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name));
\r
256 include($fileName);
\r
258 // check if class exists (avoid errors in eval'd code)
\r
259 if (!class_exists($name))
\r
261 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
\r
265 // add to plugin array
\r
266 eval('$this->plugins[$name] =& new ' . $name . '();');
\r
269 $this->plugins[$name]->plugid = $this->getPidFromName($name);
\r
271 // unload plugin if a prefix is used and the plugin cannot handle this^
\r
272 global $MYSQL_PREFIX;
\r
273 if (($MYSQL_PREFIX != '') && !$this->plugins[$name]->supportsFeature('SqlTablePrefix'))
\r
275 unset($this->plugins[$name]);
\r
276 ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
\r
280 // call init method
\r
281 $this->plugins[$name]->init();
\r
287 * Returns a PLUGIN object
\r
289 function &getPlugin($name) {
\r
290 // retrieve the name of the plugin in the right capitalisation
\r
291 $name = $this->getUpperCaseName ($name);
\r
293 $plugin =& $this->plugins[$name];
\r
296 // load class if needed
\r
297 $this->_loadPlugin($name);
\r
298 $plugin =& $this->plugins[$name];
\r
304 * Checks if the given plugin IS loaded or not
\r
306 function &pluginLoaded($name) {
\r
307 $plugin =& $this->plugins[$name];
\r
311 function &pidLoaded($pid) {
\r
313 reset($this->plugins);
\r
314 while (list($name) = each($this->plugins)) {
\r
315 if ($pid!=$this->plugins[$name]->getId()) continue;
\r
316 $plugin= & $this->plugins[$name];
\r
323 * checks if the given plugin IS installed or not
\r
325 function pluginInstalled($name) {
\r
326 $this->_initCacheInfo('installedPlugins');
\r
327 return ($this->getPidFromName($name) != -1);
\r
330 function pidInstalled($pid) {
\r
331 $this->_initCacheInfo('installedPlugins');
\r
332 return ($this->cachedInfo['installedPlugins'][$pid] != '');
\r
335 function getPidFromName($name) {
\r
336 $this->_initCacheInfo('installedPlugins');
\r
337 foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
\r
339 if (strtolower($pfile) == strtolower($name))
\r
346 * Retrieve the name of a plugin in the right capitalisation
\r
348 function getUpperCaseName ($name) {
\r
349 $this->_initCacheInfo('installedPlugins');
\r
350 foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
\r
352 if (strtolower($pfile) == strtolower($name))
\r
358 function clearCachedInfo($what) {
\r
359 unset($this->cachedInfo[$what]);
\r
363 * Loads some info on the first call only
\r
365 function _initCacheInfo($what)
\r
367 if (isset($this->cachedInfo[$what]) && is_array($this->cachedInfo[$what]))
\r
371 // 'installedPlugins' = array ($pid => $name)
\r
372 case 'installedPlugins':
\r
373 $this->cachedInfo['installedPlugins'] = array();
\r
374 $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
\r
375 while ($o = mysql_fetch_object($res))
\r
377 $this->cachedInfo['installedPlugins'][$o->pid] = $o->pfile;
\r
384 * A function to notify plugins that something has happened. Only the plugins
\r
385 * that are subscribed to the event will get notified.
\r
386 * Upon the first call, the list of subscriptions will be fetched from the
\r
387 * database. The plugins itsself will only get loaded when they are first needed
\r
389 * @param $eventName
\r
390 * Name of the event (method to be called on plugins)
\r
392 * Can contain any type of data, depending on the event type. Usually this is
\r
393 * an itemid, blogid, ... but it can also be an array containing multiple values
\r
395 function notify($eventName, $data) {
\r
396 // load subscription list if needed
\r
397 if (!is_array($this->subscriptions))
\r
398 $this->_loadSubscriptions();
\r
401 // get listening objects
\r
402 $listeners = false;
\r
403 if (isset($this->subscriptions[$eventName])) {
\r
404 $listeners = $this->subscriptions[$eventName];
\r
407 // notify all of them
\r
408 if (is_array($listeners)) {
\r
409 foreach($listeners as $listener) {
\r
410 // load class if needed
\r
411 $this->_loadPlugin($listener);
\r
412 // do notify (if method exists)
\r
413 if (method_exists($this->plugins[$listener], 'event_' . $eventName))
\r
414 call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), $data);
\r
421 * Loads plugin subscriptions
\r
423 function _loadSubscriptions() {
\r
424 // initialize as array
\r
425 $this->subscriptions = array();
\r
427 $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
428 while ($o = mysql_fetch_object($res)) {
\r
429 $pluginName = $o->pfile;
\r
430 $eventName = $o->event;
\r
431 $this->subscriptions[$eventName][] = $pluginName;
\r
437 Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
\r
438 requests. tickets are user specific
\r
441 var $currentRequestTicket = '';
\r
444 * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
\r
446 function addTicketToUrl($url)
\r
448 $ticketCode = 'ticket=' . $this->_generateTicket();
\r
449 if (strstr($url, '?'))
\r
450 return $url . '&' . $ticketCode;
\r
452 return $url . '?' . $ticketCode;
\r
456 * POST requests: Adds ticket as hidden formvar
\r
458 function addTicketHidden()
\r
460 $ticket = $this->_generateTicket();
\r
462 echo '<input type="hidden" name="ticket" value="', htmlspecialchars($ticket), '" />';
\r
467 * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
\r
469 function getNewTicket()
\r
471 $this->currentRequestTicket = '';
\r
472 return $this->_generateTicket();
\r
476 * Checks the ticket that was passed along with the current request
\r
478 function checkTicket()
\r
482 // get ticket from request
\r
483 $ticket = requestVar('ticket');
\r
485 // no ticket -> don't allow
\r
489 // remove expired tickets first
\r
490 $this->_cleanUpExpiredTickets();
\r
493 if (!$member->isLoggedIn())
\r
496 $memberId = $member->getID();
\r
498 // check if ticket is a valid one
\r
499 $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'';
\r
500 if (quickQuery($query) == 1)
\r
502 // [in the original implementation, the checked ticket was deleted. This would lead to invalid
\r
503 // tickets when using the browsers back button and clicking another link/form
\r
504 // leaving the keys in the database is not a real problem, since they're member-specific and
\r
505 // only valid for a period of one hour
\r
507 // sql_query('DELETE FROM '.sql_table('tickets').' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'');
\r
510 // not a valid ticket
\r
517 * (internal method) Removes the expired tickets
\r
519 function _cleanUpExpiredTickets()
\r
521 // remove tickets older than 1 hour
\r
522 $oldTime = time() - 60 * 60;
\r
523 $query = 'DELETE FROM ' . sql_table('tickets'). ' WHERE ctime < \'' . date('Y-m-d H:i:s',$oldTime) .'\'';
\r
528 * (internal method) Generates/returns a ticket (one ticket per page request)
\r
530 function _generateTicket()
\r
532 if ($this->currentRequestTicket == '')
\r
534 // generate new ticket (only one ticket will be generated per page request)
\r
535 // and store in database
\r
538 if (!$member->isLoggedIn())
\r
541 $memberId = $member->getID();
\r
546 // generate a random token
\r
547 srand((double)microtime()*1000000);
\r
548 $ticket = md5(uniqid(rand(), true));
\r
550 // add in database as non-active
\r
551 $query = 'INSERT INTO ' . sql_table('tickets') . ' (ticket, member, ctime) ';
\r
552 $query .= 'VALUES (\'' . addslashes($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
\r
553 if (sql_query($query))
\r
557 $this->currentRequestTicket = $ticket;
\r
559 return $this->currentRequestTicket;
\r