c1f7d584c72d2b23b80b9933f2d0f8ba23967c17
4 * Created on Sep 5, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
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:
30 * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31 * how to parse and validate them.
33 * Profiling: various methods to allow keeping tabs on various tasks and their time costs
35 * Self-documentation: code to allow api to document its own state.
39 abstract class ApiBase
{
41 // These constants allow modules to specify exactly how to treat incomming parameters.
44 const PARAM_ISMULTI
= 1;
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
55 private $mMainModule, $mModuleName, $mModulePrefix;
60 public function __construct($mainModule, $moduleName, $modulePrefix = '') {
61 $this->mMainModule
= $mainModule;
62 $this->mModuleName
= $moduleName;
63 $this->mModulePrefix
= $modulePrefix;
66 /*****************************************************************************
68 *****************************************************************************/
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
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.
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
86 public abstract function execute();
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!
93 public abstract function getVersion();
96 * Get the name of the module being executed by this instance
98 public function getModuleName() {
99 return $this->mModuleName
;
103 * Get parameter prefix (usually two letters or an empty string).
105 public function getModulePrefix() {
106 return $this->mModulePrefix
;
110 * Get the name of the module as shown in the profiler log
112 public function getModuleProfileName($db = false) {
114 return 'API:' . $this->mModuleName
. '-DB';
116 return 'API:' . $this->mModuleName
;
122 public function getMain() {
123 return $this->mMainModule
;
127 * Returns true if this module is the main module ($this === $this->mMainModule),
130 public function isMain() {
131 return $this === $this->mMainModule
;
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.
138 public function getResult() {
139 // Main module has getResult() method overriden
140 // Safety - avoid infinite loop:
142 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
143 return $this->getMain()->getResult();
147 * Get the result data array
149 public function & getResultData() {
150 return $this->getResult()->getData();
154 * Set warning section for this module. Users should monitor this section to
155 * notice any changes in API.
157 public function setWarning($warning) {
159 ApiResult
:: setContent($msg, $warning);
160 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
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.
168 public function getCustomPrinter() {
173 * Generates help message for this module, or false if there is no description
175 public function makeHelpMsg() {
177 static $lnPrfx = "\n ";
179 $msg = $this->getDescription();
181 if ($msg !== false) {
187 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
190 $paramsMsg = $this->makeHelpMsgParameters();
191 if ($paramsMsg !== false) {
192 $msg .= "Parameters:\n$paramsMsg";
196 $examples = $this->getExamples();
197 if ($examples !== false) {
198 if (!is_array($examples))
202 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
203 $msg .= implode($lnPrfx, $examples) . "\n";
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';
211 if (is_array($versions)) {
212 foreach ($versions as &$v)
213 $v = eregi_replace($pattern, $replacement, $v);
214 $versions = implode("\n ", $versions);
217 $versions = eregi_replace($pattern, $replacement, $versions);
219 $msg .= "Version:\n $versions\n";
227 * Generates the parameter descriptions for this module, to be displayed in the
230 public function makeHelpMsgParameters() {
231 $params = $this->getAllowedParams();
232 if ($params !== false) {
234 $paramsDescription = $this->getParamDescription();
236 $paramPrefix = "\n" . str_repeat(' ', 19);
237 foreach ($params as $paramName => $paramSettings) {
238 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
240 $desc = implode($paramPrefix, $desc);
242 $type = $paramSettings[self
:: PARAM_TYPE
];
244 if (isset ($paramSettings[self
:: PARAM_ISMULTI
]))
245 $prompt = 'Values (separate with \'|\'): ';
247 $prompt = 'One value: ';
249 if (is_array($type)) {
251 $nothingPrompt = false;
252 foreach ($type as $t)
254 $nothingPrompt = 'Can be empty, or ';
257 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
261 // Special handling because namespaces are type-limited, yet they are not given
262 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase
:: getValidNamespaces());
265 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
268 $hasMin = isset($paramSettings[self
:: PARAM_MIN
]);
269 $hasMax = isset($paramSettings[self
:: PARAM_MAX
]);
270 if ($hasMin ||
$hasMax) {
272 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
274 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
276 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
278 $desc .= $paramPrefix . $intRangeStr;
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";
289 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
298 * Returns the description string for this module
300 protected function getDescription() {
305 * Returns usage examples for this module. Return null if no examples are available.
307 protected function getExamples() {
312 * Returns an array of allowed parameters (keys) => default value for that parameter
314 protected function getAllowedParams() {
319 * Returns the description string for the given parameter.
321 protected function getParamDescription() {
326 * This method mangles parameter name based on the prefix supplied to the constructor.
327 * Override this method to change parameter name during runtime
329 public function encodeParamName($paramName) {
330 return $this->mModulePrefix
. $paramName;
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.
340 public function extractRequestParams($parseMaxLimit = true) {
341 $params = $this->getAllowedParams();
344 foreach ($params as $paramName => $paramSettings)
345 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
351 * Get a value for the given parameter
353 protected function getParameter($paramName) {
354 $params = $this->getAllowedParams();
355 $paramSettings = $params[$paramName];
356 return $this->getParameterFromSettings($paramName, $paramSettings);
360 * Returns an array of the namespaces (by integer id) that exist on the
361 * wiki. Used primarily in help documentation.
363 public static function getValidNamespaces() {
364 static $mValidNamespaces = null;
365 if (is_null($mValidNamespaces)) {
368 $mValidNamespaces = array ();
369 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
371 $mValidNamespaces[] = $ns;
374 return $mValidNamespaces;
378 * Using the settings determine the value for the given parameter
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?
384 protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
386 // Some classes may decide to change parameter names
387 $encParamName = $this->encodeParamName($paramName);
389 if (!is_array($paramSettings)) {
390 $default = $paramSettings;
392 $type = gettype($paramSettings);
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;
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);
403 $type = 'NULL'; // allow everything
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'");
413 $value = $this->getMain()->getRequest()->getCheck($encParamName);
415 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
417 if (isset ($value) && $type == 'namespace')
418 $type = ApiBase
:: getValidNamespaces();
421 if (isset ($value) && ($multi ||
is_array($type)))
422 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ?
$type : null);
424 // More validation only when choices were not given
425 // choices were validated in parseMultiValue()
426 if (isset ($value)) {
427 if (!is_array($type)) {
429 case 'NULL' : // nothing to do
431 case 'string' : // nothing to do
433 case 'integer' : // Force everything using intval() and optionally validate limits
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;
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);
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");
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
]);
460 $value = intval($value);
461 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX
], $paramSettings[self
:: PARAM_MAX2
]);
466 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $encParamName");
470 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $encParamName");
471 $value = wfTimestamp(TS_UNIX
, $value);
473 $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
474 $value = wfTimestamp(TS_MW
, $value);
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();
483 ApiBase
:: dieDebug(__METHOD__
, "Param $encParamName's type is unknown - $type");
487 // There should never be any duplicate values in a list
488 if (is_array($value))
489 $value = array_unique($value);
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.
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)
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");
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");
518 return $allowMultiple ?
$valuesList : $valuesList[0];
522 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
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);
529 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
530 if ($this->getMain()->isInternalMode())
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);
541 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
547 * Call main module's error handler
549 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
550 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
554 * Array that maps message keys to error messages. $1 and friends are replaced.
556 public static $messageMap = array(
557 // This one MUST be present, or dieUsageMsg() will recurse infinitely
558 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error: ``\$1''"),
560 // Messages from Title::getUserPermissionsErrors()
561 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
562 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
563 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
564 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
565 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
566 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
567 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
568 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
569 'badaccess-group1' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Can't use the parameter 'cause it's wikilinked
570 'badaccess-group2' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
571 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
572 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
573 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
574 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
575 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
576 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages"),
577 'confirmedittiext' => array('code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit"),
578 'blockedtext' => array('code' => 'blocked', 'info' => "You have been blocked from editing"),
579 'autoblockedtext' => array('code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"),
581 // Miscellaneous interface messages
582 'alreadyrolled' => array('code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back"),
583 'cantrollback' => array('code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author"),
584 'readonlytext' => array('code' => 'readonly', 'info' => "The wiki is currently in read-only mode"),
585 'sessionfailure' => array('code' => 'badtoken', 'info' => "Invalid token"),
586 'cannotdelete' => array('code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else"),
587 'notanarticle' => array('code' => 'missingtitle', 'info' => "The page you requested doesn't exist"),
588 'selfmove' => array('code' => 'selfmove', 'info' => "Can't move a page to itself"),
589 'immobile_namespace' => array('code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving"),
590 'articleexists' => array('code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article"),
591 'protectedpage' => array('code' => 'protectedpage', 'info' => "You don't have permission to perform this move"),
592 'hookaborted' => array('code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook"),
593 'cantmove-titleprotected' => array('code' => 'protectedtitle', 'info' => "The destination article has been protected from creation"),
594 // 'badarticleerror' => shouldn't happen
595 // 'badtitletext' => shouldn't happen
596 'ip_range_invalid' => array('code' => 'invalidrange', 'info' => "Invalid IP range"),
597 'range_block_disabled' => array('code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled"),
598 'nosuchusershort' => array('code' => 'nosuchuser', 'info' => "The user you specified doesn't exist"),
599 'badipaddress' => array('code' => 'invalidip', 'info' => "Invalid IP address specified"),
600 'ipb_expiry_invalid' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
601 'ipb_already_blocked' => array('code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked"),
602 'ipb_blocked_as_range' => array('code' => 'blockedasrange', 'info' => "IP address ``\$1'' was blocked as part of range ``\$2''. You can't unblock the IP invidually, but you can unblock the range as a whole."),
603 'ipb_cant_unblock' => array('code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already"),
605 // API-specific messages
606 'missingparam' => array('code' => 'no$1', 'info' => "The \$1 parameter must be set"),
607 'invalidtitle' => array('code' => 'invalidtitle', 'info' => "Bad title ``\$1''"),
608 'invaliduser' => array('code' => 'invaliduser', 'info' => "Invalid username ``\$1''"),
609 'invalidexpiry' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
610 'pastexpiry' => array('code' => 'pastexpiry', 'info' => "Expiry time is in the past"),
611 'create-titleexists' => array('code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'"),
612 'missingtitle-createonly' => array('code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'"),
613 'cantblock' => array('code' => 'cantblock', 'info' => "You don't have permission to block users"),
614 'canthide' => array('code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log"),
615 'cantblock-email' => array('code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki"),
616 'unblock-notarget' => array('code' => 'notarget', 'info' => "Either the id or the user parameter must be set"),
617 'unblock-idanduser' => array('code' => 'idanduser', 'info' => "The id and user parameters can\'t be used together"),
618 'cantunblock' => array('code' => 'permissiondenied', 'info' => "You don't have permission to unblock users"),
619 'cannotundelete' => array('code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"),
620 'permdenied-undelete' => array('code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions"),
624 * Output the error message related to a certain array
625 * @param array $error Element of a getUserPermissionsErrors()
627 public function dieUsageMsg($error) {
628 $key = array_shift($error);
629 if(isset(self
::$messageMap[$key]))
630 $this->dieUsage(wfMsgReplaceArgs(self
::$messageMap[$key]['info'], $error), wfMsgReplaceArgs(self
::$messageMap[$key]['code'], $error));
631 // If the key isn't present, throw an "unknown error"
632 $this->dieUsageMsg(array('unknownerror', $key));
636 * Internal code errors should be reported with this method
638 protected static function dieDebug($method, $message) {
639 wfDebugDieBacktrace("Internal error in $method: $message");
643 * Indicates if API needs to check maxlag
645 public function shouldCheckMaxlag() {
650 * Indicates if this module requires edit mode
652 public function isEditMode() {
657 * Indicates whether this module must be called with a POST request
659 public function mustBePosted() {
665 * Profiling: total module execution time
667 private $mTimeIn = 0, $mModuleTime = 0;
670 * Start module profiling
672 public function profileIn() {
673 if ($this->mTimeIn
!== 0)
674 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
675 $this->mTimeIn
= microtime(true);
676 wfProfileIn($this->getModuleProfileName());
680 * End module profiling
682 public function profileOut() {
683 if ($this->mTimeIn
=== 0)
684 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
685 if ($this->mDBTimeIn
!== 0)
686 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
688 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
690 wfProfileOut($this->getModuleProfileName());
694 * When modules crash, sometimes it is needed to do a profileOut() regardless
695 * of the profiling state the module was in. This method does such cleanup.
697 public function safeProfileOut() {
698 if ($this->mTimeIn
!== 0) {
699 if ($this->mDBTimeIn
!== 0)
700 $this->profileDBOut();
706 * Total time the module was executed
708 public function getProfileTime() {
709 if ($this->mTimeIn
!== 0)
710 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
711 return $this->mModuleTime
;
715 * Profiling: database execution time
717 private $mDBTimeIn = 0, $mDBTime = 0;
720 * Start module profiling
722 public function profileDBIn() {
723 if ($this->mTimeIn
=== 0)
724 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
725 if ($this->mDBTimeIn
!== 0)
726 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
727 $this->mDBTimeIn
= microtime(true);
728 wfProfileIn($this->getModuleProfileName(true));
732 * End database profiling
734 public function profileDBOut() {
735 if ($this->mTimeIn
=== 0)
736 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
737 if ($this->mDBTimeIn
=== 0)
738 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
740 $time = microtime(true) - $this->mDBTimeIn
;
741 $this->mDBTimeIn
= 0;
743 $this->mDBTime +
= $time;
744 $this->getMain()->mDBTime +
= $time;
745 wfProfileOut($this->getModuleProfileName(true));
749 * Total time the module used the database
751 public function getProfileDBTime() {
752 if ($this->mDBTimeIn
!== 0)
753 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
754 return $this->mDBTime
;
757 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
758 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
761 print "\n" . wfBacktrace();
767 * Returns a String that identifies the version of this class.
769 public static function getBaseVersion() {
770 return __CLASS__
. ': $Id$';