API:
[lhc/web/wiklou.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 * ABSTRACT METHODS *
68 *****************************************************************************/
69
70 /**
71 * Evaluates the parameters, performs the requested query, and sets up the
72 * result. Concrete implementations of ApiBase must override this method to
73 * provide whatever functionality their module offers. Implementations must
74 * not produce any output on their own and are not expected to handle any
75 * errors.
76 *
77 * The execute method will be invoked directly by ApiMain immediately before
78 * the result of the module is output. Aside from the constructor, implementations
79 * should assume that no other methods will be called externally on the module
80 * before the result is processed.
81 *
82 * The result data should be stored in the result object referred to by
83 * "getResult()". Refer to ApiResult.php for details on populating a result
84 * object.
85 */
86 public abstract function execute();
87
88 /**
89 * Returns a String that identifies the version of the extending class. Typically
90 * includes the class name, the svn revision, timestamp, and last author. May
91 * be severely incorrect in many implementations!
92 */
93 public abstract function getVersion();
94
95 /**
96 * Get the name of the module being executed by this instance
97 */
98 public function getModuleName() {
99 return $this->mModuleName;
100 }
101
102 /**
103 * Get parameter prefix (usually two letters or an empty string).
104 */
105 public function getModulePrefix() {
106 return $this->mModulePrefix;
107 }
108
109 /**
110 * Get the name of the module as shown in the profiler log
111 */
112 public function getModuleProfileName($db = false) {
113 if ($db)
114 return 'API:' . $this->mModuleName . '-DB';
115 else
116 return 'API:' . $this->mModuleName;
117 }
118
119 /**
120 * Get main module
121 */
122 public function getMain() {
123 return $this->mMainModule;
124 }
125
126 /**
127 * Returns true if this module is the main module ($this === $this->mMainModule),
128 * false otherwise.
129 */
130 public function isMain() {
131 return $this === $this->mMainModule;
132 }
133
134 /**
135 * Get the result object. Please refer to the documentation in ApiResult.php
136 * for details on populating and accessing data in a result object.
137 */
138 public function getResult() {
139 // Main module has getResult() method overriden
140 // Safety - avoid infinite loop:
141 if ($this->isMain())
142 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
143 return $this->getMain()->getResult();
144 }
145
146 /**
147 * Get the result data array
148 */
149 public function & getResultData() {
150 return $this->getResult()->getData();
151 }
152
153 /**
154 * Set warning section for this module. Users should monitor this section to
155 * notice any changes in API.
156 */
157 public function setWarning($warning) {
158 $msg = array();
159 ApiResult :: setContent($msg, $warning);
160 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
161 }
162
163 /**
164 * If the module may only be used with a certain format module,
165 * it should override this method to return an instance of that formatter.
166 * A value of null means the default format will be used.
167 */
168 public function getCustomPrinter() {
169 return null;
170 }
171
172 /**
173 * Generates help message for this module, or false if there is no description
174 */
175 public function makeHelpMsg() {
176
177 static $lnPrfx = "\n ";
178
179 $msg = $this->getDescription();
180
181 if ($msg !== false) {
182
183 if (!is_array($msg))
184 $msg = array (
185 $msg
186 );
187 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
188
189 // Parameters
190 $paramsMsg = $this->makeHelpMsgParameters();
191 if ($paramsMsg !== false) {
192 $msg .= "Parameters:\n$paramsMsg";
193 }
194
195 // Examples
196 $examples = $this->getExamples();
197 if ($examples !== false) {
198 if (!is_array($examples))
199 $examples = array (
200 $examples
201 );
202 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
203 $msg .= implode($lnPrfx, $examples) . "\n";
204 }
205
206 if ($this->getMain()->getShowVersions()) {
207 $versions = $this->getVersion();
208 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
209 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
210
211 if (is_array($versions)) {
212 foreach ($versions as &$v)
213 $v = eregi_replace($pattern, $replacement, $v);
214 $versions = implode("\n ", $versions);
215 }
216 else
217 $versions = eregi_replace($pattern, $replacement, $versions);
218
219 $msg .= "Version:\n $versions\n";
220 }
221 }
222
223 return $msg;
224 }
225
226 /**
227 * Generates the parameter descriptions for this module, to be displayed in the
228 * module's help.
229 */
230 public function makeHelpMsgParameters() {
231 $params = $this->getAllowedParams();
232 if ($params !== false) {
233
234 $paramsDescription = $this->getParamDescription();
235 $msg = '';
236 $paramPrefix = "\n" . str_repeat(' ', 19);
237 foreach ($params as $paramName => $paramSettings) {
238 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
239 if (is_array($desc))
240 $desc = implode($paramPrefix, $desc);
241
242 $type = $paramSettings[self :: PARAM_TYPE];
243 if (isset ($type)) {
244 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
245 $prompt = 'Values (separate with \'|\'): ';
246 else
247 $prompt = 'One value: ';
248
249 if (is_array($type)) {
250 $choices = array();
251 $nothingPrompt = false;
252 foreach ($type as $t)
253 if ($t=='')
254 $nothingPrompt = 'Can be empty, or ';
255 else
256 $choices[] = $t;
257 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
258 } else {
259 switch ($type) {
260 case 'namespace':
261 // Special handling because namespaces are type-limited, yet they are not given
262 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
263 break;
264 case 'limit':
265 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
266 break;
267 case 'integer':
268 $hasMin = isset($paramSettings[self :: PARAM_MIN]);
269 $hasMax = isset($paramSettings[self :: PARAM_MAX]);
270 if ($hasMin || $hasMax) {
271 if (!$hasMax)
272 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
273 elseif (!$hasMin)
274 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
275 else
276 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
277
278 $desc .= $paramPrefix . $intRangeStr;
279 }
280 break;
281 }
282 }
283 }
284
285 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
286 if (!is_null($default) && $default !== false)
287 $desc .= $paramPrefix . "Default: $default";
288
289 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
290 }
291 return $msg;
292
293 } else
294 return false;
295 }
296
297 /**
298 * Returns the description string for this module
299 */
300 protected function getDescription() {
301 return false;
302 }
303
304 /**
305 * Returns usage examples for this module. Return null if no examples are available.
306 */
307 protected function getExamples() {
308 return false;
309 }
310
311 /**
312 * Returns an array of allowed parameters (keys) => default value for that parameter
313 */
314 protected function getAllowedParams() {
315 return false;
316 }
317
318 /**
319 * Returns the description string for the given parameter.
320 */
321 protected function getParamDescription() {
322 return false;
323 }
324
325 /**
326 * This method mangles parameter name based on the prefix supplied to the constructor.
327 * Override this method to change parameter name during runtime
328 */
329 public function encodeParamName($paramName) {
330 return $this->mModulePrefix . $paramName;
331 }
332
333 /**
334 * Using getAllowedParams(), makes an array of the values provided by the user,
335 * with key being the name of the variable, and value - validated value from user or default.
336 * This method can be used to generate local variables using extract().
337 * limit=max will not be parsed if $parseMaxLimit is set to false; use this
338 * when the max limit is not definite, e.g. when getting revisions.
339 */
340 public function extractRequestParams($parseMaxLimit = true) {
341 $params = $this->getAllowedParams();
342 $results = array ();
343
344 foreach ($params as $paramName => $paramSettings)
345 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
346
347 return $results;
348 }
349
350 /**
351 * Get a value for the given parameter
352 */
353 protected function getParameter($paramName) {
354 $params = $this->getAllowedParams();
355 $paramSettings = $params[$paramName];
356 return $this->getParameterFromSettings($paramName, $paramSettings);
357 }
358
359 /**
360 * Returns an array of the namespaces (by integer id) that exist on the
361 * wiki. Used primarily in help documentation.
362 */
363 public static function getValidNamespaces() {
364 static $mValidNamespaces = null;
365 if (is_null($mValidNamespaces)) {
366
367 global $wgContLang;
368 $mValidNamespaces = array ();
369 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
370 if ($ns >= 0)
371 $mValidNamespaces[] = $ns;
372 }
373 }
374 return $mValidNamespaces;
375 }
376
377 /**
378 * Using the settings determine the value for the given parameter
379 *
380 * @param $paramName String: parameter name
381 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
382 * @param $parseMaxLimit Boolean: parse limit when max is given?
383 */
384 protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
385
386 // Some classes may decide to change parameter names
387 $encParamName = $this->encodeParamName($paramName);
388
389 if (!is_array($paramSettings)) {
390 $default = $paramSettings;
391 $multi = false;
392 $type = gettype($paramSettings);
393 } else {
394 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
395 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
396 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
397
398 // When type is not given, and no choices, the type is the same as $default
399 if (!isset ($type)) {
400 if (isset ($default))
401 $type = gettype($default);
402 else
403 $type = 'NULL'; // allow everything
404 }
405 }
406
407 if ($type == 'boolean') {
408 if (isset ($default) && $default !== false) {
409 // Having a default value of anything other than 'false' is pointless
410 ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
411 }
412
413 $value = $this->getMain()->getRequest()->getCheck($encParamName);
414 } else {
415 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
416
417 if (isset ($value) && $type == 'namespace')
418 $type = ApiBase :: getValidNamespaces();
419 }
420
421 if (isset ($value) && ($multi || is_array($type)))
422 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
423
424 // More validation only when choices were not given
425 // choices were validated in parseMultiValue()
426 if (isset ($value)) {
427 if (!is_array($type)) {
428 switch ($type) {
429 case 'NULL' : // nothing to do
430 break;
431 case 'string' : // nothing to do
432 break;
433 case 'integer' : // Force everything using intval() and optionally validate limits
434
435 $value = is_array($value) ? array_map('intval', $value) : intval($value);
436 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
437 $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
438
439 if (!is_null($min) || !is_null($max)) {
440 $values = is_array($value) ? $value : array($value);
441 foreach ($values as $v) {
442 $this->validateLimit($paramName, $v, $min, $max);
443 }
444 }
445 break;
446 case 'limit' :
447 if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
448 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
449 if ($multi)
450 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
451 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
452 if( $value == 'max' ) {
453 if( $parseMaxLimit ) {
454 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self :: PARAM_MAX2] : $paramSettings[self :: PARAM_MAX];
455 $this->getResult()->addValue( 'limits', 'limit', $value );
456 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
457 }
458 }
459 else {
460 $value = intval($value);
461 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
462 }
463 break;
464 case 'boolean' :
465 if ($multi)
466 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
467 break;
468 case 'timestamp' :
469 if ($multi)
470 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
471 $value = wfTimestamp(TS_UNIX, $value);
472 if ($value === 0)
473 $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
474 $value = wfTimestamp(TS_MW, $value);
475 break;
476 case 'user' :
477 $title = Title::makeTitleSafe( NS_USER, $value );
478 if ( is_null( $title ) )
479 $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
480 $value = $title->getText();
481 break;
482 default :
483 ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
484 }
485 }
486
487 // There should never be any duplicate values in a list
488 if (is_array($value))
489 $value = array_unique($value);
490 }
491
492 return $value;
493 }
494
495 /**
496 * Return an array of values that were given in a 'a|b|c' notation,
497 * after it optionally validates them against the list allowed values.
498 *
499 * @param valueName - The name of the parameter (for error reporting)
500 * @param value - The value being parsed
501 * @param allowMultiple - Can $value contain more than one value separated by '|'?
502 * @param allowedValues - An array of values to check against. If null, all values are accepted.
503 * @return (allowMultiple ? an_array_of_values : a_single_value)
504 */
505 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
506 $valuesList = explode('|', $value);
507 if (!$allowMultiple && count($valuesList) != 1) {
508 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
509 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
510 }
511 if (is_array($allowedValues)) {
512 $unknownValues = array_diff($valuesList, $allowedValues);
513 if ($unknownValues) {
514 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
515 }
516 }
517
518 return $allowMultiple ? $valuesList : $valuesList[0];
519 }
520
521 /**
522 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
523 */
524 function validateLimit($paramName, $value, $min, $max, $botMax = null) {
525 if (!is_null($min) && $value < $min) {
526 $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
527 }
528
529 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
530 if ($this->getMain()->isInternalMode())
531 return;
532
533 // Optimization: do not check user's bot status unless really needed -- skips db query
534 // assumes $botMax >= $max
535 if (!is_null($max) && $value > $max) {
536 if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
537 if ($value > $botMax) {
538 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
539 }
540 } else {
541 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
542 }
543 }
544 }
545
546 /**
547 * Call main module's error handler
548 */
549 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
550 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
551 }
552
553 /**
554 * Array that maps message keys to error messages. $1 and friends are replaced.
555 */
556 public static $messageMap = array(
557 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
558 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
559 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
560 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
561 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
562 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
563 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
564 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
565 'badaccess-group1' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Can't use the parameter 'cause it's wikilinked
566 'badaccess-group2' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
567 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
568 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error"),
569 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
570 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
571 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
572 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
573 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages")
574 );
575
576 /**
577 * Output the error message related to a certain array
578 * @param array $error Element of a getUserPermissionsErrors()
579 */
580 public function dieUsageMsg($error) {
581 $key = array_shift($error);
582 if(isset(self::$messageMap[$key]))
583 $this->dieUsage(wfMsgReplaceArgs(self::$messageMap[$key]['info'], $error), self::$messageMap[$key]['code']);
584 // If the key isn't present, throw an "unknown error
585 $this->dieUsage(self::$messageMap['unknownerror']['info'], self::$messageMap['unknownerror']['code']);
586 }
587
588 /**
589 * Internal code errors should be reported with this method
590 */
591 protected static function dieDebug($method, $message) {
592 wfDebugDieBacktrace("Internal error in $method: $message");
593 }
594
595 /**
596 * Indicates if API needs to check maxlag
597 */
598 public function shouldCheckMaxlag() {
599 return true;
600 }
601
602 /**
603 * Indicates if this module requires edit mode
604 */
605 public function isEditMode() {
606 return false;
607 }
608
609
610 /**
611 * Profiling: total module execution time
612 */
613 private $mTimeIn = 0, $mModuleTime = 0;
614
615 /**
616 * Start module profiling
617 */
618 public function profileIn() {
619 if ($this->mTimeIn !== 0)
620 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
621 $this->mTimeIn = microtime(true);
622 wfProfileIn($this->getModuleProfileName());
623 }
624
625 /**
626 * End module profiling
627 */
628 public function profileOut() {
629 if ($this->mTimeIn === 0)
630 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
631 if ($this->mDBTimeIn !== 0)
632 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
633
634 $this->mModuleTime += microtime(true) - $this->mTimeIn;
635 $this->mTimeIn = 0;
636 wfProfileOut($this->getModuleProfileName());
637 }
638
639 /**
640 * When modules crash, sometimes it is needed to do a profileOut() regardless
641 * of the profiling state the module was in. This method does such cleanup.
642 */
643 public function safeProfileOut() {
644 if ($this->mTimeIn !== 0) {
645 if ($this->mDBTimeIn !== 0)
646 $this->profileDBOut();
647 $this->profileOut();
648 }
649 }
650
651 /**
652 * Total time the module was executed
653 */
654 public function getProfileTime() {
655 if ($this->mTimeIn !== 0)
656 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
657 return $this->mModuleTime;
658 }
659
660 /**
661 * Profiling: database execution time
662 */
663 private $mDBTimeIn = 0, $mDBTime = 0;
664
665 /**
666 * Start module profiling
667 */
668 public function profileDBIn() {
669 if ($this->mTimeIn === 0)
670 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
671 if ($this->mDBTimeIn !== 0)
672 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
673 $this->mDBTimeIn = microtime(true);
674 wfProfileIn($this->getModuleProfileName(true));
675 }
676
677 /**
678 * End database profiling
679 */
680 public function profileDBOut() {
681 if ($this->mTimeIn === 0)
682 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
683 if ($this->mDBTimeIn === 0)
684 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
685
686 $time = microtime(true) - $this->mDBTimeIn;
687 $this->mDBTimeIn = 0;
688
689 $this->mDBTime += $time;
690 $this->getMain()->mDBTime += $time;
691 wfProfileOut($this->getModuleProfileName(true));
692 }
693
694 /**
695 * Total time the module used the database
696 */
697 public function getProfileDBTime() {
698 if ($this->mDBTimeIn !== 0)
699 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
700 return $this->mDBTime;
701 }
702
703 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
704 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
705 var_export($value);
706 if ($backtrace)
707 print "\n" . wfBacktrace();
708 print "\n</pre>\n";
709 }
710
711
712 /**
713 * Returns a String that identifies the version of this class.
714 */
715 public static function getBaseVersion() {
716 return __CLASS__ . ': $Id$';
717 }
718 }
719