OSDN Git Service

069a719e574b4ee70918cda8122bd64815dd5dcb
[nucleus-jp/nucleus-jp-ancient.git] / euc / nucleus / libs / PLUGIN.php
1 <?php
2         /*
3          * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
4          * Copyright (C) 2002-2007 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 is an (abstract) class of which all Nucleus Plugins must inherit
14          *
15          * for more information on plugins and how to write your own, see the
16          * plugins.html file that is included with the Nucleus documenation
17          *
18          * @license http://nucleuscms.org/license.txt GNU General Public License
19          * @copyright Copyright (C) 2002-2007 The Nucleus Group
20          * @version $Id: PLUGIN.php,v 1.7 2007-04-06 19:37:07 kmorimatsu Exp $
21          * $NucleusJP: PLUGIN.php,v 1.6 2007/03/30 22:18:54 kmorimatsu Exp $
22          */
23         class NucleusPlugin {
24
25                 // these functions _have_ to be redefined in your plugin
26
27                 function getName() { return 'Undefined'; }
28                 function getAuthor()  { return 'Undefined'; }
29                 function getURL()  { return 'Undefined'; }
30                 function getVersion() { return '0.0'; }
31                 function getDescription() { return 'Undefined';}
32
33                 // these function _may_ be redefined in your plugin
34
35                 function getMinNucleusVersion() { return 150; }
36                 function getMinNucleusPatchLevel() { return 0; }
37                 function getEventList() { return array(); }
38                 function getTableList() { return array(); }
39                 function hasAdminArea() { return 0; }
40
41                 function install() {}
42                 function unInstall() {}
43
44                 function init() {}
45
46                 function doSkinVar($skinType) {}
47                 function doTemplateVar(&$item) {
48                         $args = func_get_args();
49                         array_shift($args);
50                         array_unshift($args, 'template');
51                         call_user_func_array(array(&$this,'doSkinVar'),$args);
52                 }
53                 function doTemplateCommentsVar(&$item, &$comment) {
54                         $args = func_get_args();
55                         array_shift($args);
56                         array_shift($args);
57                         array_unshift($args, 'template');
58                         call_user_func_array(array(&$this,'doSkinVar'),$args);
59                 }
60                 function doAction($type) { return 'No Such Action'; }
61                 function doIf($key,$value) { return false; }
62                 function doItemVar () {}
63
64                 /**
65                  * Checks if a plugin supports a certain feature.
66                  *
67                  * @returns 1 if the feature is reported, 0 if not
68                  * @param $feature
69                  *              Name of the feature. See plugin documentation for more info
70                  *                      'SqlTablePrefix' -> if the plugin uses the sql_table() method to get table names
71                  *                      'HelpPage' -> if the plugin provides a helppage
72                  */
73                 function supportsFeature($feature) {
74                         return 0;
75                 }
76
77                 /**
78                  * Report a list of plugin that is required to function
79                  *
80                  * @returns an array of names of plugin, an empty array indicates no dependency
81                  */
82                 function getPluginDep() { return array(); }
83
84                 // these helper functions should not be redefined in your plugin
85
86                 /**
87                   * Creates a new option for this plugin
88                   *
89                   * @param name
90                   *             A string uniquely identifying your option. (max. length is 20 characters)
91                   * @param description
92                   *             A description that will show up in the nucleus admin area (max. length: 255 characters)
93                   * @param type
94                   *             Either 'text', 'yesno' or 'password'
95                   *             This info is used when showing 'edit plugin options' screens
96                   * @param value
97                   *             Initial value for the option (max. value length is 128 characters)
98                   */
99                 function createOption($name, $desc, $type, $defValue = '', $typeExtras = '') {
100                         return $this->_createOption('global', $name, $desc, $type, $defValue, $typeExtras);
101                 }
102                 function createBlogOption($name, $desc, $type, $defValue = '', $typeExtras = '') {
103                         return $this->_createOption('blog', $name, $desc, $type, $defValue, $typeExtras);
104                 }
105                 function createMemberOption($name, $desc, $type, $defValue = '', $typeExtras = '') {
106                         return $this->_createOption('member', $name, $desc, $type, $defValue, $typeExtras);
107                 }
108                 function createCategoryOption($name, $desc, $type, $defValue = '', $typeExtras = '') {
109                         return $this->_createOption('category', $name, $desc, $type, $defValue, $typeExtras);
110                 }
111                 function createItemOption($name, $desc, $type, $defValue = '', $typeExtras = '') {
112                         return $this->_createOption('item', $name, $desc, $type, $defValue, $typeExtras);
113                 }
114
115                 /**
116                   * Removes the option from the database
117                   *
118                   * Note: Options get erased automatically on plugin uninstall
119                   */
120                 function deleteOption($name) {
121                         return $this->_deleteOption('global', $name);
122                 }
123                 function deleteBlogOption($name) {
124                         return $this->_deleteOption('blog', $name);
125                 }
126                 function deleteMemberOption($name) {
127                         return $this->_deleteOption('member', $name);
128                 }
129                 function deleteCategoryOption($name) {
130                         return $this->_deleteOption('category', $name);
131                 }
132                 function deleteItemOption($name) {
133                         return $this->_deleteOption('item', $name);
134                 }
135
136                 /**
137                   * Sets the value of an option to something new
138                   */
139                 function setOption($name, $value) {
140                         return $this->_setOption('global', 0, $name, $value);
141                 }
142                 function setBlogOption($blogid, $name, $value) {
143                         return $this->_setOption('blog', $blogid, $name, $value);
144                 }
145                 function setMemberOption($memberid, $name, $value) {
146                         return $this->_setOption('member', $memberid, $name, $value);
147                 }
148                 function setCategoryOption($catid, $name, $value) {
149                         return $this->_setOption('category', $catid, $name, $value);
150                 }
151                 function setItemOption($itemid, $name, $value) {
152                         return $this->_setOption('item', $itemid, $name, $value);
153                 }
154
155                 /**
156                   * Retrieves the current value for an option
157                   */
158                 function getOption($name){
159                         return $this->_getOption('global', 0, $name);
160                 }
161                 function getBlogOption($blogid, $name) {
162                         return $this->_getOption('blog', $blogid, $name);
163                 }
164                 function getMemberOption($memberid, $name) {
165                         return $this->_getOption('member', $memberid, $name);
166                 }
167                 function getCategoryOption($catid, $name) {
168                         return $this->_getOption('category', $catid, $name);
169                 }
170                 function getItemOption($itemid, $name) {
171                         return $this->_getOption('item', $itemid, $name);
172                 }
173
174                 /**
175                  * Retrieves an associative array with the option value for each
176                  * context id
177                  */
178                 function getAllBlogOptions($name) {
179                         return $this->_getAllOptions('blog', $name);
180                 }
181                 function getAllMemberOptions($name) {
182                         return $this->_getAllOptions('member', $name);
183                 }
184                 function getAllCategoryOptions($name) {
185                         return $this->_getAllOptions('category', $name);
186                 }
187                 function getAllItemOptions($name) {
188                         return $this->_getAllOptions('item', $name);
189                 }
190
191                 /**
192                  * Retrieves an indexed array with the top (or bottom) of an option
193                  * (delegates to _getOptionTop())
194                  */
195                 function getBlogOptionTop($name, $amount = 10, $sort = 'desc') {
196                         return $this->_getOptionTop('blog', $name, $amount, $sort);
197                 }
198                 function getMemberOptionTop($name, $amount = 10, $sort = 'desc') {
199                         return $this->_getOptionTop('member', $name, $amount, $sort);
200                 }
201                 function getCategoryOptionTop($name, $amount = 10, $sort = 'desc') {
202                         return $this->_getOptionTop('category', $name, $amount, $sort);
203                 }
204                 function getItemOptionTop($name, $amount = 10, $sort = 'desc') {
205                         return $this->_getOptionTop('item', $name, $amount, $sort);
206                 }
207
208                 /**
209                  * Retrieves an array of the top (or bottom) of an option from a plugin.
210                  * @author TeRanEX
211                  * @param  string $context the context for the option: item, blog, member,...
212                  * @param  string $name    the name of the option
213                  * @param  int    $amount  how many rows must be returned
214                  * @param  string $sort    desc or asc
215                  * @return array           array with both values and contextid's
216                  * @access private
217                  */
218                 function _getOptionTop($context, $name, $amount = 10, $sort = 'desc') {
219                         if (($sort != 'desc') && ($sort != 'asc')) {
220                                 $sort= 'desc';
221                         }
222
223                         $oid = $this->_getOID($context, $name);
224
225                         // retrieve the data and return
226                         $q = 'SELECT otype, oextra FROM '.sql_table('plugin_option_desc').' WHERE oid = '.$oid;
227                         $query = mysql_query($q);
228
229                         $o = mysql_fetch_array($query);
230
231                         if (($this->optionCanBeNumeric($o['otype'])) && ($o['oextra'] == 'number' )) {
232                                 $orderby = 'CAST(ovalue AS SIGNED)';
233                         } else {
234                                 $orderby = 'ovalue';
235                         }
236                         $q = 'SELECT ovalue value, ocontextid id FROM '.sql_table('plugin_option').' WHERE oid = '.$oid.' ORDER BY '.$orderby.' '.$sort.' LIMIT 0,'.$amount;
237                         $query = mysql_query($q);
238
239                         // create the array
240                         $i = 0;
241                         $top = array();
242                         while($row = mysql_fetch_array($query)) {
243                                 $top[$i++] = $row;
244                         }
245
246                         // return the array (duh!)
247                         return $top;
248                 }
249
250                 /**
251                   * Returns the plugin ID
252                   */
253                 function getID() {
254                         return $this->plugid;
255                 }
256
257                 /**
258                   * returns the URL of the admin area for this plugin (in case there's
259                   * no such area, the returned information is invalid)
260                   */
261                 function getAdminURL() {
262                         global $CONF;
263                         return $CONF['PluginURL'] . $this->getShortName() . '/';
264                 }
265
266                 /**
267                   * Returns the directory where the admin directory is located and
268                   * where the plugin can maintain his extra files
269                   */
270                 function getDirectory() {
271                         global $DIR_PLUGINS;
272                         return $DIR_PLUGINS . $this->getShortName() . '/';
273                 }
274
275                 /**
276                   * Derives the short name for the plugin from the classname (all lowercase)
277                   */
278                 function getShortName() {
279                         return str_replace('np_','',strtolower(get_class($this)));
280                 }
281
282                 var $_aOptionValues;    // oid_contextid => value
283                 var $_aOptionToInfo;    // context_name => array('oid' => ..., 'default' => ...)
284                 var $plugin_options;    // see getOption()
285                 var $plugid;                    // plugin id
286
287
288                 // constructor. Initializes some internal data
289                 function NucleusPlugin() {
290                         $this->_aOptionValues = array();        // oid_contextid => value
291                         $this->_aOptionToInfo = array();        // context_name => array('oid' => ..., 'default' => ...)
292                         $this->plugin_options = 0;
293                 }
294
295                 function clearOptionValueCache(){
296                         $this->_aOptionValues = array();
297                 }
298
299                 // private
300                 function _createOption($context, $name, $desc, $type, $defValue, $typeExtras = '') {
301                         // create in plugin_option_desc
302                         $query = 'INSERT INTO ' . sql_table('plugin_option_desc')
303                                    .' (opid, oname, ocontext, odesc, otype, odef, oextra)'
304                                    .' VALUES ('.intval($this->plugid)
305                                                          .', \''.addslashes($name).'\''
306                                                          .', \''.addslashes($context).'\''
307                                                          .', \''.addslashes($desc).'\''
308                                                          .', \''.addslashes($type).'\''
309                                                          .', \''.addslashes($defValue).'\''
310                                                          .', \''.addslashes($typeExtras).'\')';
311                         sql_query($query);
312                         $oid = mysql_insert_id();
313
314                         $key = $context . '_' . $name;
315                         $this->_aOptionToInfo[$key] = array('oid' => $oid, 'default' => $defValue);
316                         return 1;
317                 }
318
319
320                 // private
321                 function _deleteOption($context, $name) {
322                         $oid = $this->_getOID($context, $name);
323                         if (!$oid) return 0; // no such option
324
325                         // delete all things from plugin_option
326                         sql_query('DELETE FROM ' . sql_table('plugin_option') . ' WHERE oid=' . $oid);
327
328                         // delete entry from plugin_option_desc
329                         sql_query('DELETE FROM ' . sql_table('plugin_option_desc') . ' WHERE oid=' . $oid);
330
331                         // clear from cache
332                         unset($this->_aOptionToInfo[$context . '_' . $name]);
333                         $this->_aOptionValues = array();
334                         return 1;
335                 }
336
337                 /**
338                  * private
339                  * returns: 1 on success, 0 on failure
340                  */
341                 function _setOption($context, $contextid, $name, $value) {
342                         global $manager;
343
344                         $oid = $this->_getOID($context, $name);
345                         if (!$oid) return 0;
346
347                         // check if context id exists
348                         switch ($context) {
349                                 case 'member':
350                                         if (!MEMBER::existsID($contextid)) return 0;
351                                         break;
352                                 case 'blog':
353                                         if (!$manager->existsBlogID($contextid)) return 0;
354                                         break;
355                                 case 'category':
356                                         if (!$manager->existsCategory($contextid)) return 0;
357                                         break;
358                                 case 'item':
359                                         if (!$manager->existsItem($contextid, true, true)) return 0;
360                                         break;
361                                 case 'global':
362                                         if ($contextid != 0) return 0;
363                                         break;
364                         }
365
366
367                         // update plugin_option
368                         sql_query('DELETE FROM ' . sql_table('plugin_option') . ' WHERE oid='.intval($oid) . ' and ocontextid='. intval($contextid));
369                         @mysql_query('INSERT INTO ' . sql_table('plugin_option') . ' (ovalue, oid, ocontextid) VALUES (\''.addslashes($value).'\', '. intval($oid) . ', ' . intval($contextid) . ')');
370
371                         // update cache
372                         $this->_aOptionValues[$oid . '_' . $contextid] = $value;
373
374                         return 1;
375                 }
376
377                 // private
378                 function _getOption($context, $contextid, $name) {
379                         $oid = $this->_getOID($context, $name);
380                         if (!$oid) return '';
381
382
383                         $key = $oid . '_' . $contextid;
384
385                         if (isset($this->_aOptionValues[$key]))
386                                 return $this->_aOptionValues[$key];
387
388                         // get from DB
389                         $res = sql_query('SELECT ovalue FROM ' . sql_table('plugin_option') . ' WHERE oid='.intval($oid).' and ocontextid=' . intval($contextid));
390
391                         if (!$res || (mysql_num_rows($res) == 0)) {
392                                 $defVal = $this->_getDefVal($context, $name);
393                                 $this->_aOptionValues[$key] = $defVal;
394
395                                 // fill DB with default value
396                                 $query = 'INSERT INTO ' . sql_table('plugin_option') . ' (oid,ocontextid,ovalue)'
397                                            .' VALUES ('.intval($oid).', '.intval($contextid).', \''.addslashes($defVal).'\')';
398                                 sql_query($query);
399                         }
400                         else {
401                                 $o = mysql_fetch_object($res);
402                                 $this->_aOptionValues[$key] = $o->ovalue;
403                         }
404
405                         return $this->_aOptionValues[$key];
406                 }
407
408                 /**
409                  * Returns assoc array with all values for a given option (one option per
410                  * possible context id)
411                  */
412                 function _getAllOptions($context, $name) {
413                         $oid = $this->_getOID($context, $name);
414                         if (!$oid) return array();
415                         $defVal = $this->_getDefVal($context, $name);
416
417                         $aOptions = array();
418                         switch ($context) {
419                                 case 'blog':
420                                         $r = sql_query('SELECT bnumber as contextid FROM ' . sql_table('blog'));
421                                         break;
422                                 case 'category':
423                                         $r = sql_query('SELECT catid as contextid FROM ' . sql_table('category'));
424                                         break;
425                                 case 'member':
426                                         $r = sql_query('SELECT mnumber as contextid FROM ' . sql_table('member'));
427                                         break;
428                                 case 'item':
429                                         $r = sql_query('SELECT inumber as contextid FROM ' . sql_table('item'));
430                                         break;
431                         }
432                         if ($r) {
433                                 while ($o = mysql_fetch_object($r))
434                                         $aOptions[$o->contextid] = $defVal;
435                         }
436
437                         $res = sql_query('SELECT ocontextid, ovalue FROM ' . sql_table('plugin_option') . ' WHERE oid=' . $oid);
438                         while ($o = mysql_fetch_object($res))
439                                 $aOptions[$o->ocontextid] = $o->ovalue;
440
441                         return $aOptions;
442                 }
443
444                 /**
445                  * Gets the 'option identifier' that corresponds to a given option name.
446                  * When this method is called for the first time, all the OIDs for the plugin
447                  * are loaded into memory, to avoid re-doing the same query all over.
448                  */
449                 function _getOID($context, $name) {
450                         $key = $context . '_' . $name;
451                         $info = $this->_aOptionToInfo[$key];
452                         if (is_array($info)) return $info['oid'];
453
454                         // load all OIDs for this plugin from the database
455                         $this->_aOptionToInfo = array();
456                         $query = 'SELECT oid, oname, ocontext, odef FROM ' . sql_table('plugin_option_desc') . ' WHERE opid=' . intval($this->plugid);
457                         $res = sql_query($query);
458                         while ($o = mysql_fetch_object($res)) {
459                                 $k = $o->ocontext . '_' . $o->oname;
460                                 $this->_aOptionToInfo[$k] = array('oid' => $o->oid, 'default' => $o->odef);
461                         }
462                         mysql_free_result($res);
463
464                         return $this->_aOptionToInfo[$key]['oid'];
465                 }
466                 function _getDefVal($context, $name) {
467                         $key = $context . '_' . $name;
468                         $info = $this->_aOptionToInfo[$key];
469                         if (is_array($info)) return $info['default'];
470                 }
471
472
473                 /**
474                  * Deletes all option values for a given context and contextid
475                  * (used when e.g. a blog, member or category is deleted)
476                  *
477                  * (static method)
478                  */
479                 function _deleteOptionValues($context, $contextid) {
480                         // delete all associated plugin options
481                         $aOIDs = array();
482                                 // find ids
483                         $query = 'SELECT oid FROM '.sql_table('plugin_option_desc') . ' WHERE ocontext=\''.addslashes($context).'\'';
484                         $res = sql_query($query);
485                         while ($o = mysql_fetch_object($res))
486                                 array_push($aOIDs, $o->oid);
487                         mysql_free_result($res);
488                                 // delete those options. go go go
489                         if (count($aOIDs) > 0) {
490                                 $query = 'DELETE FROM ' . sql_table('plugin_option') . ' WHERE oid in ('.implode(',',$aOIDs).') and ocontextid=' . intval($contextid);
491                                 sql_query($query);
492                         }
493                 }
494
495                 /**
496                  * splits the option's typeextra field (at ;'s) to split the meta collection
497                  * @param string $typeExtra the value of the typeExtra field of an option
498                  * @return array array of the meta-key/value-pairs
499                  * @author TeRanEX
500                  * @static
501                  */
502                 function getOptionMeta($typeExtra) {
503                         $tmpMeta = explode(';', $typeExtra);
504                         $meta = array();
505                         for ($i = 0; $i < count($tmpMeta); $i++) {
506                                 if (($i == 0) && (!strstr($tmpMeta[0], '='))) {
507                                         // we have the select-list
508                                         $meta['select'] = $tmpMeta[0];
509                                 } else {
510                                         $tmp = explode('=', $tmpMeta[$i]);
511                                         $meta[$tmp[0]] = $tmp[1];
512                                 }
513                         }
514                         return $meta;
515                 }
516
517                 /**
518                  * filters the selectlists out of the meta collection
519                  * @param string $typeExtra the value of the typeExtra field of an option
520                  * @return string the selectlist
521                  * @author TeRanEX
522                  */
523                 function getOptionSelectValues($typeExtra) {
524                         $meta = NucleusPlugin::getOptionMeta($typeExtra);
525                         //the select list must always be the first part
526                         return $meta['select'];
527                 }
528
529                 /**
530                  * checks if the eventlist in the database is up-to-date
531                  * @return bool if it is up-to-date it return true, else false
532                  * @author TeRanEX
533                  */
534                 function subscribtionListIsUptodate() {
535                         $res = sql_query('SELECT event FROM '.sql_table('plugin_event').' WHERE pid = '.$this->getID());
536                         $ev = array();
537                         while($a = mysql_fetch_array($res)) {
538                                 array_push($ev, $a['event']);
539                         }
540                         if (count($ev) != count($this->getEventList())) {
541                                 return false;
542                         }
543                         $d = array_diff($ev, $this->getEventList());
544                         if (count($d) > 0) {
545                                 // there are differences so the db is not up-to-date
546                                 return false;
547                         }
548                         return true;
549                 }
550
551                 /**
552                  * @param $aOptions: array ( 'oid' => array( 'contextid' => 'value'))
553                  *        (taken from request using requestVar())
554                  * @param $newContextid: integer (accepts a contextid when it is for a new
555                  *        contextid there was no id available at the moment of writing the
556                  *        formcontrols into the page (by ex: itemOptions for new item)
557                  * @static
558                  */
559                 function _applyPluginOptions(&$aOptions, $newContextid = 0) {
560                         global $manager;
561                         if (!is_array($aOptions)) return;
562
563                         foreach ($aOptions as $oid => $values) {
564
565                                 // get option type info
566                                 $query = 'SELECT opid, oname, ocontext, otype, oextra, odef FROM ' . sql_table('plugin_option_desc') . ' WHERE oid=' . intval($oid);
567                                 $res = sql_query($query);
568                                 if ($o = mysql_fetch_object($res))
569                                 {
570                                         foreach ($values as $key => $value) {
571                                                 // avoid overriding the key used by foreach statement
572                                                 $contextid=$key;
573
574                                                 // retreive any metadata
575                                                 $meta = NucleusPlugin::getOptionMeta($o->oextra);
576
577                                                 // if the option is readonly or hidden it may not be saved
578                                                 if (($meta['access'] != 'readonly') && ($meta['access'] != 'hidden')) {
579
580                                                         $value = undoMagic($value);     // value comes from request
581
582                                                         switch($o->otype) {
583                                                                 case 'yesno':
584                                                                         if (($value != 'yes') && ($value != 'no')) $value = 'no';
585                                                                         break;
586                                                                 default:
587                                                                         break;
588                                                         }
589
590                                                         // check the validity of numerical options
591                                                         if (($meta['datatype'] == 'numerical') && (!is_numeric($value))) {
592                                                                 //the option must be numeric, but the it isn't
593                                                                 //use the default for this option
594                                                                 $value = $o->odef;
595                                                         }
596
597                                                         // decide wether we are using the contextid of newContextid
598                                                         if ($newContextid != 0) {
599                                                                 $contextid = $newContextid;
600                                                         }
601
602                                                         //trigger event PrePluginOptionsUpdate to give the plugin the
603                                                         //possibility to change/validate the new value for the option
604                                                         $manager->notify('PrePluginOptionsUpdate',array('context' => $o->ocontext, 'plugid' => $o->opid, 'optionname' => $o->oname, 'contextid' => $contextid, 'value' => &$value));
605
606                                                         // delete the old value for the option
607                                                         sql_query('DELETE FROM '.sql_table('plugin_option').' WHERE oid='.intval($oid).' AND ocontextid='.intval($contextid));
608                                                         @mysql_query('INSERT INTO '.sql_table('plugin_option')." (oid, ocontextid, ovalue) VALUES (".intval($oid).",".intval($contextid).",'" . addslashes($value) . "')");
609                                                 }
610                                         }
611                                 }
612                         }
613                         // clear option value cache if the plugin object is already loaded
614                         if (is_object($o)) {
615                                 $plugin=& $manager->pidLoaded($o->opid);
616                                 if ($plugin) $plugin->clearOptionValueCache();
617                         }
618                 }
619
620         }
621 ?>