]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiBase.php
MediaWiki 1.11.0
[autoinstalls/mediawiki.git] / includes / api / ApiBase.php
1 <?php
2
3 /*
4  * Created on Sep 5, 2006
5  *
6  * API for MediaWiki 1.8+
7  *
8  * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  * http://www.gnu.org/copyleft/gpl.html
24  */
25
26 /**
27  * This abstract class implements many basic API functions, and is the base of all API classes.
28  * The class functions are divided into several areas of functionality:
29  * 
30  * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31  *      how to parse and validate them.
32  * 
33  * Profiling: various methods to allow keeping tabs on various tasks and their time costs
34  * 
35  * Self-documentation: code to allow api to document its own state.
36  * 
37  * @addtogroup API
38  */
39 abstract class ApiBase {
40
41         // These constants allow modules to specify exactly how to treat incomming parameters.
42
43         const PARAM_DFLT = 0;
44         const PARAM_ISMULTI = 1;
45         const PARAM_TYPE = 2;
46         const PARAM_MAX = 3;
47         const PARAM_MAX2 = 4;
48         const PARAM_MIN = 5;
49
50         const LIMIT_BIG1 = 500; // Fast query, std user limit
51         const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
52         const LIMIT_SML1 = 50; // Slow query, std user limit
53         const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
54
55         private $mMainModule, $mModuleName, $mModulePrefix;
56
57         /**
58         * Constructor
59         */
60         public function __construct($mainModule, $moduleName, $modulePrefix = '') {
61                 $this->mMainModule = $mainModule;
62                 $this->mModuleName = $moduleName;
63                 $this->mModulePrefix = $modulePrefix;
64         }
65
66         /**
67          * Executes this module
68          */
69         public abstract function execute();
70
71         /**
72          * Get the name of the module being executed by this instance 
73          */
74         public function getModuleName() {
75                 return $this->mModuleName;
76         }
77
78         /**
79          * Get parameter prefix (usually two letters or an empty string). 
80          */
81         public function getModulePrefix() {
82                 return $this->mModulePrefix;
83         }       
84
85         /**
86          * Get the name of the module as shown in the profiler log 
87          */
88         public function getModuleProfileName($db = false) {
89                 if ($db)
90                         return 'API:' . $this->mModuleName . '-DB';
91                 else
92                         return 'API:' . $this->mModuleName;
93         }
94
95         /**
96          * Get main module
97          */
98         public function getMain() {
99                 return $this->mMainModule;
100         }
101
102         /**
103          * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
104          */
105         public function isMain() {
106                 return $this === $this->mMainModule;
107         }
108
109         /**
110          * Get result object
111          */
112         public function getResult() {
113                 // Main module has getResult() method overriden
114                 // Safety - avoid infinite loop:
115                 if ($this->isMain())
116                         ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
117                 return $this->getMain()->getResult();
118         }
119
120         /**
121          * Get the result data array
122          */
123         public function & getResultData() {
124                 return $this->getResult()->getData();
125         }
126
127         /**
128          * Set warning section for this module. Users should monitor this section to notice any changes in API.
129          */
130         public function setWarning($warning) {
131                 $msg = array();
132                 ApiResult :: setContent($msg, $warning);
133                 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
134         }
135
136         /**
137          * If the module may only be used with a certain format module,
138          * it should override this method to return an instance of that formatter.
139          * A value of null means the default format will be used.  
140          */
141         public function getCustomPrinter() {
142                 return null;
143         }
144
145         /**
146          * Generates help message for this module, or false if there is no description
147          */
148         public function makeHelpMsg() {
149
150                 static $lnPrfx = "\n  ";
151
152                 $msg = $this->getDescription();
153
154                 if ($msg !== false) {
155
156                         if (!is_array($msg))
157                                 $msg = array (
158                                         $msg
159                                 );
160                         $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
161
162                         // Parameters
163                         $paramsMsg = $this->makeHelpMsgParameters();
164                         if ($paramsMsg !== false) {
165                                 $msg .= "Parameters:\n$paramsMsg";
166                         }
167
168                         // Examples
169                         $examples = $this->getExamples();
170                         if ($examples !== false) {
171                                 if (!is_array($examples))
172                                         $examples = array (
173                                                 $examples
174                                         );
175                                 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n  ";
176                                 $msg .= implode($lnPrfx, $examples) . "\n";
177                         }
178
179                         if ($this->getMain()->getShowVersions()) {
180                                 $versions = $this->getVersion();
181                                 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
182                                 $replacement = '\\0' . "\n    " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
183                                 
184                                 if (is_array($versions)) {
185                                         foreach ($versions as &$v)
186                                                 $v = eregi_replace($pattern, $replacement, $v);
187                                         $versions = implode("\n  ", $versions);
188                                 }
189                                 else
190                                         $versions = eregi_replace($pattern, $replacement, $versions);
191
192                                 $msg .= "Version:\n  $versions\n";
193                         }
194                 }
195
196                 return $msg;
197         }
198
199         public function makeHelpMsgParameters() {
200                 $params = $this->getAllowedParams();
201                 if ($params !== false) {
202
203                         $paramsDescription = $this->getParamDescription();
204                         $msg = '';
205                         $paramPrefix = "\n" . str_repeat(' ', 19);
206                         foreach ($params as $paramName => $paramSettings) {
207                                 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
208                                 if (is_array($desc))
209                                         $desc = implode($paramPrefix, $desc);
210
211                                 @ $type = $paramSettings[self :: PARAM_TYPE];
212                                 if (isset ($type)) {
213                                         if (isset ($paramSettings[self :: PARAM_ISMULTI]))
214                                                 $prompt = 'Values (separate with \'|\'): ';
215                                         else
216                                                 $prompt = 'One value: ';
217
218                                         if (is_array($type)) {
219                                                 $choices = array();
220                                                 $nothingPrompt = false;
221                                                 foreach ($type as $t)
222                                                         if ($t=='')
223                                                                 $nothingPrompt = 'Can be empty, or ';
224                                                         else
225                                                                 $choices[] =  $t;
226                                                 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
227                                         } else {
228                                                 switch ($type) {
229                                                         case 'namespace':
230                                                                 // Special handling because namespaces are type-limited, yet they are not given
231                                                                 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
232                                                                 break;
233                                                         case 'limit':
234                                                                 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
235                                                                 break;
236                                                         case 'integer':
237                                                                 $hasMin = isset($paramSettings[self :: PARAM_MIN]);
238                                                                 $hasMax = isset($paramSettings[self :: PARAM_MAX]);
239                                                                 if ($hasMin || $hasMax) {
240                                                                         if (!$hasMax)
241                                                                                 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
242                                                                         elseif (!$hasMin)
243                                                                                 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
244                                                                         else
245                                                                                 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
246                                                                                 
247                                                                         $desc .= $paramPrefix . $intRangeStr;
248                                                                 }
249                                                                 break;
250                                                 }
251                                         }
252                                 }
253
254                                 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
255                                 if (!is_null($default) && $default !== false)
256                                         $desc .= $paramPrefix . "Default: $default";
257
258                                 $msg .= sprintf("  %-14s - %s\n", $this->encodeParamName($paramName), $desc);
259                         }
260                         return $msg;
261
262                 } else
263                         return false;
264         }
265
266         /**
267          * Returns the description string for this module
268          */
269         protected function getDescription() {
270                 return false;
271         }
272
273         /**
274          * Returns usage examples for this module. Return null if no examples are available.
275          */
276         protected function getExamples() {
277                 return false;
278         }
279
280         /**
281          * Returns an array of allowed parameters (keys) => default value for that parameter
282          */
283         protected function getAllowedParams() {
284                 return false;
285         }
286
287         /**
288          * Returns the description string for the given parameter.
289          */
290         protected function getParamDescription() {
291                 return false;
292         }
293
294         /**
295          * This method mangles parameter name based on the prefix supplied to the constructor.
296          * Override this method to change parameter name during runtime 
297          */
298         public function encodeParamName($paramName) {
299                 return $this->mModulePrefix . $paramName;
300         }
301
302         /**
303         * Using getAllowedParams(), makes an array of the values provided by the user,
304         * with key being the name of the variable, and value - validated value from user or default.
305         * This method can be used to generate local variables using extract().
306         */
307         public function extractRequestParams() {
308                 $params = $this->getAllowedParams();
309                 $results = array ();
310
311                 foreach ($params as $paramName => $paramSettings)
312                         $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
313
314                 return $results;
315         }
316
317         /**
318          * Get a value for the given parameter 
319          */
320         protected function getParameter($paramName) {
321                 $params = $this->getAllowedParams();
322                 $paramSettings = $params[$paramName];
323                 return $this->getParameterFromSettings($paramName, $paramSettings);
324         }
325
326         public static function getValidNamespaces() {
327                 static $mValidNamespaces = null;
328                 if (is_null($mValidNamespaces)) {
329
330                         global $wgContLang;
331                         $mValidNamespaces = array ();
332                         foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
333                                 if ($ns >= 0)
334                                         $mValidNamespaces[] = $ns;
335                         }
336                 }
337                 return $mValidNamespaces;
338         }
339
340         /**
341          * Using the settings determine the value for the given parameter
342          * @param $paramName String: parameter name
343          * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
344          */
345         protected function getParameterFromSettings($paramName, $paramSettings) {
346
347                 // Some classes may decide to change parameter names
348                 $encParamName = $this->encodeParamName($paramName);
349
350                 if (!is_array($paramSettings)) {
351                         $default = $paramSettings;
352                         $multi = false;
353                         $type = gettype($paramSettings);
354                 } else {
355                         $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
356                         $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
357                         $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
358
359                         // When type is not given, and no choices, the type is the same as $default
360                         if (!isset ($type)) {
361                                 if (isset ($default))
362                                         $type = gettype($default);
363                                 else
364                                         $type = 'NULL'; // allow everything
365                         }
366                 }
367
368                 if ($type == 'boolean') {
369                         if (isset ($default) && $default !== false) {
370                                 // Having a default value of anything other than 'false' is pointless
371                                 ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
372                         }
373
374                         $value = $this->getMain()->getRequest()->getCheck($encParamName);
375                 } else {
376                         $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
377
378                         if (isset ($value) && $type == 'namespace')
379                                 $type = ApiBase :: getValidNamespaces();
380                 }
381
382                 if (isset ($value) && ($multi || is_array($type)))
383                         $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
384
385                 // More validation only when choices were not given
386                 // choices were validated in parseMultiValue()
387                 if (isset ($value)) {
388                         if (!is_array($type)) {
389                                 switch ($type) {
390                                         case 'NULL' : // nothing to do
391                                                 break;
392                                         case 'string' : // nothing to do
393                                                 break;
394                                         case 'integer' : // Force everything using intval() and optionally validate limits
395
396                                                 $value = is_array($value) ? array_map('intval', $value) : intval($value);
397                                                 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
398                                                 $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
399                                                 
400                                                 if (!is_null($min) || !is_null($max)) {
401                                                         $values = is_array($value) ? $value : array($value);
402                                                         foreach ($values as $v) {
403                                                                 $this->validateLimit($paramName, $v, $min, $max);
404                                                         }
405                                                 }
406                                                 break;
407                                         case 'limit' :
408                                                 if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
409                                                         ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
410                                                 if ($multi)
411                                                         ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
412                                                 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
413                                                 $value = intval($value);
414                                                 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
415                                                 break;
416                                         case 'boolean' :
417                                                 if ($multi)
418                                                         ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
419                                                 break;
420                                         case 'timestamp' :
421                                                 if ($multi)
422                                                         ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
423                                                 $value = wfTimestamp(TS_UNIX, $value);
424                                                 if ($value === 0)
425                                                         $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
426                                                 $value = wfTimestamp(TS_MW, $value);
427                                                 break;
428                                         case 'user' :
429                                                 $title = Title::makeTitleSafe( NS_USER, $value );
430                                                 if ( is_null( $title ) )
431                                                         $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
432                                                 $value = $title->getText();
433                                                 break;
434                                         default :
435                                                 ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
436                                 }
437                         }
438
439                         // There should never be any duplicate values in a list
440                         if (is_array($value))
441                                 $value = array_unique($value);
442                 }
443
444                 return $value;
445         }
446
447         /**
448         * Return an array of values that were given in a 'a|b|c' notation,
449         * after it optionally validates them against the list allowed values.
450         * 
451         * @param valueName - The name of the parameter (for error reporting)
452         * @param value - The value being parsed
453         * @param allowMultiple - Can $value contain more than one value separated by '|'?
454         * @param allowedValues - An array of values to check against. If null, all values are accepted.
455         * @return (allowMultiple ? an_array_of_values : a_single_value) 
456         */
457         protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
458                 $valuesList = explode('|', $value);
459                 if (!$allowMultiple && count($valuesList) != 1) {
460                         $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
461                         $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
462                 }
463                 if (is_array($allowedValues)) {
464                         $unknownValues = array_diff($valuesList, $allowedValues);
465                         if ($unknownValues) {
466                                 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
467                         }
468                 }
469
470                 return $allowMultiple ? $valuesList : $valuesList[0];
471         }
472
473         /**
474         * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
475         */
476         function validateLimit($paramName, $value, $min, $max, $botMax = null) {
477                 if (!is_null($min) && $value < $min) {
478                         $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
479                 }
480
481                 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
482                 if ($this->getMain()->isInternalMode())
483                         return;
484
485                 // Optimization: do not check user's bot status unless really needed -- skips db query
486                 // assumes $botMax >= $max
487                 if (!is_null($max) && $value > $max) {
488                         if (!is_null($botMax) && ($this->getMain()->isBot() || $this->getMain()->isSysop())) {
489                                 if ($value > $botMax) {
490                                         $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
491                                 }
492                         } else {
493                                 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
494                         }
495                 }
496         }
497
498         /**
499          * Call main module's error handler 
500          */
501         public function dieUsage($description, $errorCode, $httpRespCode = 0) {
502                 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
503         }
504
505         /**
506          * Internal code errors should be reported with this method
507          */
508         protected static function dieDebug($method, $message) {
509                 wfDebugDieBacktrace("Internal error in $method: $message");
510         }
511
512         /**
513          * Profiling: total module execution time
514          */
515         private $mTimeIn = 0, $mModuleTime = 0;
516
517         /**
518          * Start module profiling
519          */
520         public function profileIn() {
521                 if ($this->mTimeIn !== 0)
522                         ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
523                 $this->mTimeIn = microtime(true);
524                 wfProfileIn($this->getModuleProfileName());
525         }
526
527         /**
528          * End module profiling
529          */
530         public function profileOut() {
531                 if ($this->mTimeIn === 0)
532                         ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
533                 if ($this->mDBTimeIn !== 0)
534                         ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
535
536                 $this->mModuleTime += microtime(true) - $this->mTimeIn;
537                 $this->mTimeIn = 0;
538                 wfProfileOut($this->getModuleProfileName());
539         }
540
541         /**
542          * When modules crash, sometimes it is needed to do a profileOut() regardless
543          * of the profiling state the module was in. This method does such cleanup. 
544          */
545         public function safeProfileOut() {
546                 if ($this->mTimeIn !== 0) {
547                         if ($this->mDBTimeIn !== 0)
548                                 $this->profileDBOut();
549                         $this->profileOut();
550                 }
551         }
552
553         /**
554          * Total time the module was executed
555          */
556         public function getProfileTime() {
557                 if ($this->mTimeIn !== 0)
558                         ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
559                 return $this->mModuleTime;
560         }
561
562         /**
563          * Profiling: database execution time
564          */
565         private $mDBTimeIn = 0, $mDBTime = 0;
566
567         /**
568          * Start module profiling
569          */
570         public function profileDBIn() {
571                 if ($this->mTimeIn === 0)
572                         ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
573                 if ($this->mDBTimeIn !== 0)
574                         ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
575                 $this->mDBTimeIn = microtime(true);
576                 wfProfileIn($this->getModuleProfileName(true));
577         }
578
579         /**
580          * End database profiling
581          */
582         public function profileDBOut() {
583                 if ($this->mTimeIn === 0)
584                         ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
585                 if ($this->mDBTimeIn === 0)
586                         ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
587
588                 $time = microtime(true) - $this->mDBTimeIn;
589                 $this->mDBTimeIn = 0;
590
591                 $this->mDBTime += $time;
592                 $this->getMain()->mDBTime += $time;
593                 wfProfileOut($this->getModuleProfileName(true));
594         }
595
596         /**
597          * Total time the module used the database
598          */
599         public function getProfileDBTime() {
600                 if ($this->mDBTimeIn !== 0)
601                         ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
602                 return $this->mDBTime;
603         }
604         
605         public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
606                 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
607                 var_export($value);
608                 if ($backtrace)
609                         print "\n" . wfBacktrace();
610                 print "\n</pre>\n";
611         }
612
613         public abstract function getVersion();
614
615         public static function getBaseVersion() {
616                 return __CLASS__ . ': $Id: ApiBase.php 24934 2007-08-20 08:04:12Z nickj $';
617         }
618 }
619