(bug 18880) Make LogEventsList::showLogExtract() more versatile by allowing it to...
[lhc/web/wiklou.git] / includes / api / ApiDelete.php
index 2d7620a..267df2a 100644 (file)
-<?php\r
-\r
-/*\r
- * Created on Jun 30, 2007\r
- * API for MediaWiki 1.8+\r
- *\r
- * Copyright (C) 2007 Roan Kattouw <Firstname>.<Lastname>@home.nl\r
- *\r
- * This program is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * This program is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License along\r
- * with this program; if not, write to the Free Software Foundation, Inc.,\r
- * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\r
- * http://www.gnu.org/copyleft/gpl.html\r
- */\r
-\r
-if (!defined('MEDIAWIKI')) {\r
-       // Eclipse helper - will be ignored in production\r
-       require_once ("ApiBase.php");\r
-}\r
-\r
-\r
-/**\r
- * @addtogroup API\r
- */\r
-class ApiDelete extends ApiBase {\r
-\r
-       public function __construct($main, $action) {\r
-               parent :: __construct($main, $action);\r
-       }\r
-\r
-       /**\r
-        * We have our own delete() function, since Article.php's implementation is split in two phases\r
-        * @param Article $article - Article object to work on\r
-        * @param string $token - Delete token (same as edit token)\r
-        * @param string $reason - Reason for the deletion. Autogenerated if NULL\r
-        * @return DELETE_SUCCESS on success, DELETE_* on failure\r
-        */\r
-\r
-        const DELETE_SUCCESS = 0;\r
-        const DELETE_PERM = 1;\r
-        const DELETE_BLOCKED = 2;\r
-        const DELETE_READONLY = 3;\r
-        const DELETE_BADTOKEN = 4;\r
-        const DELETE_BADARTICLE = 5;\r
-\r
-       public static function delete(&$article, $token, &$reason = NULL)\r
-       {\r
-               global $wgUser;\r
-\r
-               // Check permissions first\r
-               if(!$article->mTitle->userCan('delete'))\r
-                       return self::DELETE_PERM;\r
-               if($wgUser->isBlocked())\r
-                       return self::DELETE_BLOCKED;\r
-               if(wfReadOnly())\r
-                       return self::DELETE_READONLY;\r
-\r
-               // Check token\r
-               if(!$wgUser->matchEditToken($token))\r
-                       return self::DELETE_BADTOKEN;\r
-\r
-               // Auto-generate a summary, if necessary\r
-               if(is_null($reason))\r
-               {\r
-                       $reason = $article->generateReason($hasHistory);\r
-                       if($reason === false)\r
-                               return self::DELETE_BADARTICLE;\r
-               }\r
-\r
-               // Luckily, Article.php provides a reusable delete function that does the hard work for us\r
-               if($article->doDeleteArticle($reason))\r
-                       return self::DELETE_SUCCESS;\r
-               return self::DELETE_BADARTICLE;\r
-       }\r
-\r
-       public function execute() {\r
-               global $wgUser;\r
-               $this->getMain()->requestWriteMode();\r
-               $params = $this->extractRequestParams();\r
-               \r
-               $titleObj = NULL;\r
-               if(!isset($params['title']))\r
-                       $this->dieUsage('The title parameter must be set', 'notitle');\r
-               if(!isset($params['token']))\r
-                       $this->dieUsage('The token parameter must be set', 'notoken');\r
-\r
-               // delete() also checks for these, but we wanna save some work\r
-               if(!$wgUser->isAllowed('delete'))\r
-                       $this->dieUsage('You don\'t have permission to delete pages', 'permissiondenied');\r
-               if($wgUser->isBlocked())\r
-                       $this->dieUsage('You have been blocked from editing', 'blocked');\r
-               if(wfReadOnly())\r
-                       $this->dieUsage('The wiki is in read-only mode', 'readonly');\r
-\r
-               $titleObj = Title::newFromText($params['title']);\r
-               if(!$titleObj)\r
-                       $this->dieUsage("Bad title ``{$params['title']}''", 'invalidtitle');\r
-               if(!$titleObj->exists())\r
-                       $this->dieUsage("``{$params['title']}'' doesn't exist", 'missingtitle');\r
-\r
-               $articleObj = new Article($titleObj);\r
-               $reason = (isset($params['reason']) ? $params['reason'] : NULL);\r
-               $dbw = wfGetDb(DB_MASTER);\r
-               $dbw->begin();\r
-               $retval = self::delete(&$articleObj, $params['token'], &$reason);\r
-\r
-               switch($retval)\r
-               {\r
-                       case self::DELETE_SUCCESS:\r
-                               break; // We'll deal with that later\r
-                       case self::DELETE_PERM:  // If we get PERM, BLOCKED or READONLY that's weird, but it's possible\r
-                               $this->dieUsage('You don\'t have permission to delete', 'permissiondenied');\r
-                       case self::DELETE_BLOCKED:\r
-                               $this->dieUsage('You have been blocked from editing', 'blocked');\r
-                       case self::DELETE_READONLY:\r
-                               $this->dieUsage('The wiki is in read-only mode', 'readonly');\r
-                       case self::DELETE_BADTOKEN:\r
-                               $this->dieUsage('Invalid token', 'badtoken');\r
-                       case self::DELETE_BADARTICLE:\r
-                               $this->dieUsage("The article ``{$params['title']}'' doesn't exist or has already been deleted", 'missingtitle');\r
-                       default:\r
-                               // delete() has apparently invented a new error, which is extremely weird\r
-                               $this->dieDebug(__METHOD__, "delete() returned an unknown error ($retval)");\r
-               }\r
-               // $retval has to be self::DELETE_SUCCESS if we get here\r
-               $dbw->commit();\r
-               $r = array('title' => $titleObj->getPrefixedText(), 'reason' => $reason);\r
-               $this->getResult()->addValue(null, $this->getModuleName(), $r);\r
-       }\r
-\r
-       protected function getAllowedParams() {\r
-               return array (\r
-                       'title' => null,\r
-                       'token' => null,\r
-                       'reason' => null,\r
-               );\r
-       }\r
-\r
-       protected function getParamDescription() {\r
-               return array (\r
-                       'title' => 'Title of the page you want to delete.',\r
-                       'token' => 'A delete token previously retrieved through prop=info',\r
-                       'reason' => 'Reason for the deletion. If not set, an automatically generated reason will be used.'\r
-               );\r
-       }\r
-\r
-       protected function getDescription() {\r
-               return array(\r
-                       'Deletes a page. You need to be logged in as a sysop to use this function, see also action=login.'\r
-               );\r
-       }\r
-\r
-       protected function getExamples() {\r
-               return array (\r
-                       'api.php?action=delete&title=Main%20Page&token=123ABC',\r
-                       'api.php?action=delete&title=Main%20Page&token=123ABC&reason=Preparing%20for%20move'\r
-               );\r
-       }\r
-\r
-       public function getVersion() {\r
-               return __CLASS__ . ': $Id: ApiDelete.php 22289 2007-05-20 23:31:44Z yurik $';\r
-       }\r
-}\r
+<?php
+
+/*
+ * Created on Jun 30, 2007
+ * API for MediaWiki 1.8+
+ *
+ * Copyright (C) 2007 Roan Kattouw <Firstname>.<Lastname>@home.nl
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ */
+
+if (!defined('MEDIAWIKI')) {
+       // Eclipse helper - will be ignored in production
+       require_once ("ApiBase.php");
+}
+
+
+/**
+ * API module that facilitates deleting pages. The API eqivalent of action=delete.
+ * Requires API write mode to be enabled.
+ *
+ * @ingroup API
+ */
+class ApiDelete extends ApiBase {
+
+       public function __construct($main, $action) {
+               parent :: __construct($main, $action);
+       }
+
+       /**
+        * Extracts the title, token, and reason from the request parameters and invokes
+        * the local delete() function with these as arguments. It does not make use of
+        * the delete function specified by Article.php. If the deletion succeeds, the
+        * details of the article deleted and the reason for deletion are added to the
+        * result object.
+        */
+       public function execute() {
+               global $wgUser;
+               $params = $this->extractRequestParams();
+
+               $this->requireOnlyOneParameter($params, 'title', 'pageid');
+               if(!isset($params['token']))
+                       $this->dieUsageMsg(array('missingparam', 'token'));
+
+               if(isset($params['title']))
+               {
+                       $titleObj = Title::newFromText($params['title']);
+                       if(!$titleObj)
+                               $this->dieUsageMsg(array('invalidtitle', $params['title']));
+               }
+               else if(isset($params['pageid']))
+               {
+                       $titleObj = Title::newFromID($params['pageid']);
+                       if(!$titleObj)
+                               $this->dieUsageMsg(array('nosuchpageid', $params['pageid']));
+               }
+               if(!$titleObj->exists())
+                       $this->dieUsageMsg(array('notanarticle'));
+
+               $reason = (isset($params['reason']) ? $params['reason'] : NULL);
+               if ($titleObj->getNamespace() == NS_FILE) {
+                       $retval = self::deleteFile($params['token'], $titleObj, $params['oldimage'], $reason, false);
+                       if(count($retval))
+                               // We don't care about multiple errors, just report one of them
+                               $this->dieUsageMsg(reset($retval));
+               } else {
+                       $articleObj = new Article($titleObj);
+                       $retval = self::delete($articleObj, $params['token'], $reason);
+                       
+                       if(count($retval))
+                               // We don't care about multiple errors, just report one of them
+                               $this->dieUsageMsg(reset($retval));
+                       
+                       if($params['watch'] || $wgUser->getOption('watchdeletion'))
+                               $articleObj->doWatch();
+                       else if($params['unwatch'])
+                               $articleObj->doUnwatch();
+               }
+
+               $r = array('title' => $titleObj->getPrefixedText(), 'reason' => $reason);
+               $this->getResult()->addValue(null, $this->getModuleName(), $r);
+       }
+
+       private static function getPermissionsError(&$title, $token) {
+               global $wgUser;
+               
+               // Check permissions
+               $errors = $title->getUserPermissionsErrors('delete', $wgUser);
+               if (count($errors) > 0) return $errors;
+               
+               // Check token
+               if(!$wgUser->matchEditToken($token))
+                       return array(array('sessionfailure'));
+               return array();
+       }
+
+       /**
+        * We have our own delete() function, since Article.php's implementation is split in two phases
+        *
+        * @param Article $article - Article object to work on
+        * @param string $token - Delete token (same as edit token)
+        * @param string $reason - Reason for the deletion. Autogenerated if NULL
+        * @return Title::getUserPermissionsErrors()-like array
+        */
+       public static function delete(&$article, $token, &$reason = NULL)
+       {
+               global $wgUser;
+               if($article->isBigDeletion() && !$wgUser->isAllowed('bigdelete')) {
+                       global $wgDeleteRevisionsLimit;
+                       return array(array('delete-toobig', $wgDeleteRevisionsLimit));
+               }
+               $title = $article->getTitle();
+               $errors = self::getPermissionsError($title, $token);
+               if (count($errors)) return $errors;
+
+               // Auto-generate a summary, if necessary
+               if(is_null($reason))
+               {
+                       # Need to pass a throwaway variable because generateReason expects
+                       # a reference
+                       $hasHistory = false;
+                       $reason = $article->generateReason($hasHistory);
+                       if($reason === false)
+                               return array(array('cannotdelete'));
+               }
+
+               $error = '';
+               if (!wfRunHooks('ArticleDelete', array(&$article, &$wgUser, &$reason, $error)))
+                       $this->dieUsageMsg(array('hookaborted', $error));
+
+               // Luckily, Article.php provides a reusable delete function that does the hard work for us
+               if($article->doDeleteArticle($reason)) {
+                       wfRunHooks('ArticleDeleteComplete', array(&$article, &$wgUser, $reason, $article->getId()));
+                       return array();
+               }
+               return array(array('cannotdelete', $article->mTitle->getPrefixedText()));
+       }
+
+       public static function deleteFile($token, &$title, $oldimage, &$reason = NULL, $suppress = false)
+       {
+               $errors = self::getPermissionsError($title, $token);
+               if (count($errors)) return $errors;
+
+               if( $oldimage && !FileDeleteForm::isValidOldSpec($oldimage) )
+                       return array(array('invalidoldimage'));
+
+               $file = wfFindFile( $title, array( 'ignoreRedirect' => true ) );
+               $oldfile = false;
+               
+               if( $oldimage )
+                       $oldfile = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $oldimage );
+                       
+               if( !FileDeleteForm::haveDeletableFile($file, $oldfile, $oldimage) )
+                       return self::delete(new Article($title), $token, $reason);
+               if (is_null($reason)) # Log and RC don't like null reasons
+                       $reason = '';
+               $status = FileDeleteForm::doDelete( $title, $file, $oldimage, $reason, $suppress );
+                               
+               if( !$status->isGood() )
+                       return array(array('cannotdelete', $title->getPrefixedText()));
+                       
+               return array();
+       }
+       
+       public function mustBePosted() { return true; }
+
+       public function isWriteMode() {
+               return true;
+       }
+
+       public function getAllowedParams() {
+               return array (
+                       'title' => null,
+                       'pageid' => array(
+                               ApiBase::PARAM_TYPE => 'integer'
+                       ),
+                       'token' => null,
+                       'reason' => null,
+                       'watch' => false,
+                       'unwatch' => false,
+                       'oldimage' => null
+               );
+       }
+
+       public function getParamDescription() {
+               return array (
+                       'title' => 'Title of the page you want to delete. Cannot be used together with pageid',
+                       'pageid' => 'Page ID of the page you want to delete. Cannot be used together with title',
+                       'token' => 'A delete token previously retrieved through prop=info',
+                       'reason' => 'Reason for the deletion. If not set, an automatically generated reason will be used.',
+                       'watch' => 'Add the page to your watchlist',
+                       'unwatch' => 'Remove the page from your watchlist',
+                       'oldimage' => 'The name of the old image to delete as provided by iiprop=archivename'
+               );
+       }
+
+       public function getDescription() {
+               return array(
+                       'Delete a page.'
+               );
+       }
+
+       protected function getExamples() {
+               return array (
+                       'api.php?action=delete&title=Main%20Page&token=123ABC',
+                       'api.php?action=delete&title=Main%20Page&token=123ABC&reason=Preparing%20for%20move'
+               );
+       }
+
+       public function getVersion() {
+               return __CLASS__ . ': $Id$';
+       }
+}