OSDN Git Service

本家Nucleus CMSの開発を補助するためにコミット
[nucleus-jp/nucleus-next.git] / nucleus / libs / MANAGER.php
1 <?php
2 /*
3  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
4  * Copyright (C) 2002-2009 The Nucleus Group
5  *
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)
11  */
12 /**
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
17  *
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()
20  *
21  * @license http://nucleuscms.org/license.txt GNU General Public License
22  * @copyright Copyright (C) 2002-2009 The Nucleus Group
23  * @version $Id: MANAGER.php 1624 2012-01-09 11:36:20Z sakamocchi $
24  */
25 class MANAGER
26 {
27
28         /**
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.
32          *
33          * The $items, $blogs, ... arrays map an id to an object (for plugins, the name is used
34          * rather than an ID)
35          */
36         var $items;
37         var $blogs;
38         var $plugins;
39         var $karma;
40         var $templates;
41         var $members;
42
43         /**
44          * cachedInfo to avoid repeated SQL queries (see pidInstalled/pluginInstalled/getPidFromName)
45          * e.g. which plugins exists?
46          *
47          * $cachedInfo['installedPlugins'] = array($pid -> $name)
48          */
49         var $cachedInfo;
50
51         /**
52          * The plugin subscriptionlist
53          *
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
57          */
58         var $subscriptions;
59
60         /**
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
64          * instead of a copy
65          */
66         function &instance()
67         {
68                 static $instance = array();
69                 if ( empty($instance) )
70                 {
71                         $instance[0] = new MANAGER();
72                 }
73                 return $instance[0];
74         }
75
76         /**
77          * The constructor of this class initializes the object caches
78          */
79         function MANAGER()
80         {
81                 $this->items = array();
82                 $this->blogs = array();
83                 $this->plugins = array();
84                 $this->karma = array();
85                 $this->parserPrefs = array();
86                 $this->cachedInfo = array();
87                 return;
88         }
89
90         /**
91          * Returns the requested item object. If it is not in the cache, it will
92          * first be loaded and then placed in the cache.
93          * Intended use: $item =& $manager->getItem(1234)
94          */
95         function &getItem($itemid, $allowdraft, $allowfuture)
96         {
97                 $item =& $this->items[$itemid];
98
99                 // check the draft and future rules if the item was already cached
100                 if ( $item )
101                 {
102                         if ((!$allowdraft) && ($item['draft']))
103                                 return 0;
104
105                         $blog =& $this->getBlog(getBlogIDFromItemID($itemid));
106                         if ( (!$allowfuture) && ($item['timestamp'] > $blog->getCorrectTime()) )
107                         {
108                                 return 0;
109                         }
110                 }
111                 if ( !$item )
112                 {
113                         // load class if needed
114                         $this->loadClass('ITEM');
115                         // load item object
116                         $item = ITEM::getitem($itemid, $allowdraft, $allowfuture);
117                         $this->items[$itemid] = $item;
118                 }
119                 return $item;
120         }
121
122         /**
123          * Loads a class if it has not yet been loaded
124          */
125         function loadClass($name)
126         {
127                 $this->_loadClass($name, $name . '.php');
128                 return;
129         }
130
131         /**
132          * Checks if an item exists
133          */
134         function existsItem($id,$future,$draft)
135         {
136                 $this->_loadClass('ITEM','ITEM.php');
137                 return ITEM::exists($id,$future,$draft);
138         }
139
140         /**
141          * Checks if a category exists
142          */
143         function existsCategory($id)
144         {
145                 return (quickQuery('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
146         }
147
148         /**
149          * Returns the blog object for a given blogid
150          */
151         function &getBlog($blogid)
152         {
153                 $blog =& $this->blogs[$blogid];
154
155                 if ( !$blog )
156                 {
157                         // load class if needed
158                         $this->_loadClass('BLOG','BLOG.php');
159                         // load blog object
160                         $blog = new BLOG($blogid);
161                         $this->blogs[$blogid] =& $blog;
162                 }
163                 return $blog;
164         }
165
166         /**
167          * Checks if a blog exists
168          */
169         function existsBlog($name)
170         {
171                 $this->_loadClass('BLOG','BLOG.php');
172                 return BLOG::exists($name);
173         }
174
175         /**
176          * Checks if a blog id exists
177          */
178         function existsBlogID($id)
179         {
180                 $this->_loadClass('BLOG','BLOG.php');
181                 return BLOG::existsID($id);
182         }
183
184         /**
185          * Returns a previously read template
186          */
187         function &getTemplate($templateName)
188         {
189                 $template =& $this->templates[$templateName];
190
191                 if ( !$template )
192                 {
193                         $template = TEMPLATE::read($templateName);
194                         $this->templates[$templateName] =& $template;
195                 }
196                 return $template;
197         }
198
199         /**
200          * Returns a KARMA object (karma votes)
201          */
202         function &getKarma($itemid)
203         {
204                 $karma =& $this->karma[$itemid];
205
206                 if ( !$karma ) {
207                         // load class if needed
208                         $this->_loadClass('KARMA','KARMA.php');
209                         // create KARMA object
210                         $karma = new KARMA($itemid);
211                         $this->karma[$itemid] =& $karma;
212                 }
213                 return $karma;
214         }
215
216         /**
217          * Returns a MEMBER object
218          */
219         function &getMember($memberid)
220         {
221                 $mem =& $this->members[$memberid];
222
223                 if ( !$mem )
224                 {
225                         // load class if needed
226                         $this->_loadClass('MEMBER','MEMBER.php');
227                         // create MEMBER object
228                         $mem =& MEMBER::createFromID($memberid);
229                         $this->members[$memberid] =& $mem;
230                 }
231                 return $mem;
232         }
233
234         /**
235          * Set the global parser preferences
236          */
237         function setParserProperty($name, $value)
238         {
239                 $this->parserPrefs[$name] = $value;
240                 return;
241         }
242         
243         /**
244          * Get the global parser preferences
245          */
246         function getParserProperty($name)
247         {
248                 return $this->parserPrefs[$name];
249         }
250
251         /**
252           * A helper function to load a class
253           * 
254           *     private
255           */
256         function _loadClass($name, $filename)
257         {
258                 if ( !class_exists($name) )
259                 {
260                                 global $DIR_LIBS;
261                                 include($DIR_LIBS . $filename);
262                 }
263                 return;
264         }
265
266         /**
267           * A helper function to load a plugin
268           * 
269           *     private
270           */
271         function _loadPlugin($name)
272         {
273                 if ( !class_exists($name) )
274                 {
275                                 global $DIR_PLUGINS;
276
277                                 $fileName = $DIR_PLUGINS . $name . '.php';
278
279                                 if ( !file_exists($fileName) )
280                                 {
281                                         if ( !defined('_MANAGER_PLUGINFILE_NOTFOUND') )
282                                         {
283                                                 define('_MANAGER_PLUGINFILE_NOTFOUND', 'Plugin %s was not loaded (File not found)');
284                                         }
285                                         ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name)); 
286                                         return 0;
287                                 }
288
289                                 // load plugin
290                                 include($fileName);
291
292                                 // check if class exists (avoid errors in eval'd code)
293                                 if ( !class_exists($name) )
294                                 {
295                                         ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
296                                         return 0;
297                                 }
298
299                                 // add to plugin array
300                                 eval('$this->plugins[$name] = new ' . $name . '();');
301
302                                 // get plugid
303                                 $this->plugins[$name]->plugid = $this->getPidFromName($name);
304
305                                 // unload plugin if a prefix is used and the plugin cannot handle this^
306                                 global $MYSQL_PREFIX;
307                                 if ( ($MYSQL_PREFIX != '')
308                                   && !$this->plugins[$name]->supportsFeature('SqlTablePrefix') )
309                                 {
310                                         unset($this->plugins[$name]);
311                                         ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
312                                         return 0;
313                                 }
314                                 
315                                 // unload plugin if using non-mysql handler and plugin does not support it 
316                                 global $MYSQL_HANDLER;
317                                 if ( (!in_array('mysql',$MYSQL_HANDLER))
318                                   && !$this->plugins[$name]->supportsFeature('SqlApi') )
319                                 {
320                                         unset($this->plugins[$name]);
321                                         ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINSQLAPI_NOTSUPPORT, $name));
322                                         return 0;
323                                 }
324
325                                 // call init method
326                                 $this->plugins[$name]->init();
327                 }
328                 return;
329         }
330
331         /**
332          * Returns a PLUGIN object
333          */
334         function &getPlugin($name)
335         {
336                 // retrieve the name of the plugin in the right capitalisation
337                 $name = $this->getUpperCaseName ($name);
338                 // get the plugin       
339                 $plugin =& $this->plugins[$name]; 
340
341                 if ( !$plugin )
342                 {
343                         // load class if needed
344                         $this->_loadPlugin($name);
345                         $plugin =& $this->plugins[$name];
346                 }
347                 return $plugin;
348         }
349
350         /**
351           * Checks if the given plugin IS loaded or not
352           */
353         function &pluginLoaded($name)
354         {
355                 $plugin =& $this->plugins[$name];
356                 return $plugin;
357         }
358                 
359         function &pidLoaded($pid)
360         {
361                 $plugin=false;
362                 reset($this->plugins);
363                 while ( list($name) = each($this->plugins) )
364                 {
365                         if ( $pid!=$this->plugins[$name]->getId() )
366                         {
367                                 continue;
368                         }
369                         $plugin= & $this->plugins[$name];
370                         break;
371                 }
372                 return $plugin;
373         }
374
375         /**
376           * checks if the given plugin IS installed or not
377           */
378         function pluginInstalled($name)
379         {
380                 $this->_initCacheInfo('installedPlugins');
381                 return ($this->getPidFromName($name) != -1);
382         }
383
384         function pidInstalled($pid)
385         {
386                 $this->_initCacheInfo('installedPlugins');
387                 return ($this->cachedInfo['installedPlugins'][$pid] != '');
388         }
389
390         function getPidFromName($name)
391         {
392                 $this->_initCacheInfo('installedPlugins');
393                 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
394                 {
395                         if (strtolower($pfile) == strtolower($name))
396                         {
397                                 return $pid;
398                         }
399                 }
400                 return -1;
401         }
402
403         /**
404           * Retrieve the name of a plugin in the right capitalisation
405           */
406         function getUpperCaseName ($name)
407         {
408                 $this->_initCacheInfo('installedPlugins');
409                 foreach ( $this->cachedInfo['installedPlugins'] as $pid => $pfile )
410                 {
411                         if ( strtolower($pfile) == strtolower($name) )
412                         {
413                                 return $pfile;
414                         }
415                 }
416                 return -1;
417         }
418         
419         function clearCachedInfo($what)
420         {
421                 unset($this->cachedInfo[$what]);
422                 return;
423         }
424
425         /**
426          * Loads some info on the first call only
427          */
428         function _initCacheInfo($what)
429         {
430                 if ( isset($this->cachedInfo[$what]) && is_array($this->cachedInfo[$what]) )
431                 {
432                         return;
433                 }
434                 switch ($what)
435                 {
436                         // 'installedPlugins' = array ($pid => $name)
437                         case 'installedPlugins':
438                                 $this->cachedInfo['installedPlugins'] = array();
439                                 $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
440                                 while ( $o = sql_fetch_object($res) )
441                                 {
442                                         $this->cachedInfo['installedPlugins'][$o->pid] = $o->pfile;
443                                 }
444                                 break;
445                 }
446                 return;
447         }
448
449         /**
450          * A function to notify plugins that something has happened. Only the plugins
451          * that are subscribed to the event will get notified.
452          * Upon the first call, the list of subscriptions will be fetched from the
453          * database. The plugins itsself will only get loaded when they are first needed
454          *
455          * @param $eventName
456          *              Name of the event (method to be called on plugins)
457          * @param $data
458          *              Can contain any type of data, depending on the event type. Usually this is
459          *              an itemid, blogid, ... but it can also be an array containing multiple values
460          */
461         function notify($eventName, $data)
462         {
463                 // load subscription list if needed
464                 if ( !is_array($this->subscriptions) )
465                 {
466                         $this->_loadSubscriptions();
467                 }
468                 
469                 // get listening objects
470                 $listeners = false;
471                 if ( isset($this->subscriptions[$eventName]) )
472                 {
473                         $listeners = $this->subscriptions[$eventName];
474                 }
475
476                 // notify all of them
477                 if ( is_array($listeners) )
478                 {
479                         foreach( $listeners as $listener )
480                         {
481                                 // load class if needed
482                                 $this->_loadPlugin($listener);
483                                 // do notify (if method exists)
484                                 if ( isset($this->plugins[$listener])
485                                   && method_exists($this->plugins[$listener], 'event_' . $eventName))
486                                 {
487                                         call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), $data);
488                                 }
489                         }
490                 }
491                 return;
492         }
493
494         /**
495          * Loads plugin subscriptions
496          */
497         function _loadSubscriptions()
498         {
499                 // initialize as array
500                 $this->subscriptions = array();
501
502                 $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');
503                 while ( $o = sql_fetch_object($res) )
504                 {
505                         $pluginName = $o->pfile;
506                         $eventName = $o->event;
507                         $this->subscriptions[$eventName][] = $pluginName;
508                 }
509                 return;
510         }
511
512         /*
513                 Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
514                 requests. tickets are user specific
515         */
516
517         var $currentRequestTicket = '';
518
519         /**
520          * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
521          */
522         function addTicketToUrl($url)
523         {
524                 $ticketCode = 'ticket=' . $this->_generateTicket();
525                 if ( strstr($url, '?') )
526                 {
527                         $ticketCode = "{$url}&{$ticketCode}";
528                 }
529                 else
530                 {
531                         $ticketCode = "{$url}?{$ticketCode}";
532                 }
533                 return $ticketCode;
534         }
535
536         /**
537          * POST requests: Adds ticket as hidden formvar
538          */
539         function addTicketHidden()
540         {
541                 $ticket = $this->_generateTicket();
542                 echo '<input type="hidden" name="ticket" value="', i18n::hsc($ticket), '" />';
543                 return;
544         }
545
546         /**
547          * Get a new ticket
548          * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
549          */
550         function getNewTicket()
551         {
552                 $this->currentRequestTicket = '';
553                 return $this->_generateTicket();
554         }
555
556         /**
557          * Checks the ticket that was passed along with the current request
558          */
559         function checkTicket()
560         {
561                 global $member;
562
563                 // get ticket from request
564                 $ticket = requestVar('ticket');
565
566                 // no ticket -> don't allow
567                 if ( $ticket == '' )
568                 {
569                         return false;
570                 }
571
572                 // remove expired tickets first
573                 $this->_cleanUpExpiredTickets();
574
575                 // get member id
576                 if (!$member->isLoggedIn())
577                 {
578                         $memberId = -1;
579                 }
580                 else
581                 {
582                         $memberId = $member->getID();
583                 }
584
585                 // check if ticket is a valid one
586                 $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.sql_real_escape_string($ticket).'\'';
587
588                 /*
589                  * NOTE:
590                  * [in the original implementation, the checked ticket was deleted. This would lead to invalid
591                  * tickets when using the browsers back button and clicking another link/form
592                  * leaving the keys in the database is not a real problem, since they're member-specific and
593                  * only valid for a period of one hour]
594                  */
595                 if ( quickQuery($query) == 1 )
596                 {
597                         return true;
598                 }
599                 // not a valid ticket
600                 else
601                 {
602                         return false;
603                 }
604         }
605
606         /**
607          * (internal method) Removes the expired tickets
608          */
609         function _cleanUpExpiredTickets()
610         {
611                 // remove tickets older than 1 hour
612                 $oldTime = time() - 60 * 60;
613                 $query = 'DELETE FROM ' . sql_table('tickets'). ' WHERE ctime < \'' . date('Y-m-d H:i:s',$oldTime) .'\'';
614                 sql_query($query);
615                 return;
616         }
617
618         /**
619          * (internal method) Generates/returns a ticket (one ticket per page request)
620          */
621         function _generateTicket()
622         {
623                 if ( $this->currentRequestTicket == '' )
624                 {
625                         // generate new ticket (only one ticket will be generated per page request)
626                         // and store in database
627                         global $member;
628                         // get member id
629                         if ( !$member->isLoggedIn() )
630                         {
631                                 $memberId = -1;
632                         }
633                         else
634                         {
635                                 $memberId = $member->getID();
636                         }
637
638                         $ok = false;
639                         while ( !$ok )
640                         {
641                                 // generate a random token
642                                 srand((double)microtime()*1000000);
643                                 $ticket = md5(uniqid(rand(), true));
644
645                                 // add in database as non-active
646                                 $query = 'INSERT INTO ' . sql_table('tickets') . ' (ticket, member, ctime) ';
647                                 $query .= 'VALUES (\'' . sql_real_escape_string($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
648                                 if ( sql_query($query) )
649                                 {
650                                         $ok = true;
651                                 }
652                         }
653                         $this->currentRequestTicket = $ticket;
654                 }
655                 return $this->currentRequestTicket;
656         }
657 }
658