Remove ancient comment, collapse if, move USE INDEX into if further down doing the...
[lhc/web/wiklou.git] / includes / api / ApiDelete.php
index 2d7620a..5d28174 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
+ *
+ * Copyright © 2007 Roan Kattouw <Firstname>.<Lastname>@gmail.com
+ *
+ * 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ */
+
+if ( !defined( 'MEDIAWIKI' ) ) {
+       // Eclipse helper - will be ignored in production
+       require_once( "ApiBase.php" );
+}
+
+/**
+ * API module that facilitates deleting pages. The API equivalent 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() {
+               $params = $this->extractRequestParams();
+
+               $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
+
+               if ( isset( $params['title'] ) ) {
+                       $titleObj = Title::newFromText( $params['title'] );
+                       if ( !$titleObj ) {
+                               $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
+                       }
+               } elseif ( 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 ) ) {
+                               $this->dieUsageMsg( reset( $retval ) ); // We don't care about multiple errors, just report one of them
+                       }
+               } else {
+                       $articleObj = new Article( $titleObj );
+                       $retval = self::delete( $articleObj, $params['token'], $reason );
+
+                       if ( count( $retval ) ) {
+                               $this->dieUsageMsg( reset( $retval ) ); // We don't care about multiple errors, just report one of them
+                       }
+
+                       // Deprecated parameters
+                       if ( $params['watch'] ) {
+                               $watch = 'watch';
+                       } elseif ( $params['unwatch'] ) {
+                               $watch = 'unwatch';
+                       } else {
+                               $watch = $params['watchlist'];
+                       }
+                       $this->setWatch( $watch, $titleObj, 'watchdeletion' );
+               }
+
+               $r = array( 'title' => $titleObj->getPrefixedText(), 'reason' => $reason );
+               $this->getResult()->addValue( null, $this->getModuleName(), $r );
+       }
+
+       /**
+        *
+        * @param &$title Title
+        * @param $token String
+        */
+       private static function getPermissionsError( &$title, $token ) {
+               global $wgUser;
+
+               // Check permissions
+               $errors = $title->getUserPermissionsErrors( 'delete', $wgUser );
+               if ( count( $errors ) > 0 ) {
+                       return $errors;
+               }
+
+               return array();
+       }
+
+       /**
+        * We have our own delete() function, since Article.php's implementation is split in two phases
+        *
+        * @param $article Article object to work on
+        * @param $token String: delete token (same as edit token)
+        * @param $reason String: 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 ) ) ) {
+                       return array( 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() ) );
+       }
+
+       /**
+        * @static
+        * @param $token
+        * @param $title
+        * @param $oldimage
+        * @param $reason
+        * @param $suppress bool
+        * @return \type|array|Title
+        */
+       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' => array(
+                               ApiBase::PARAM_DFLT => false,
+                               ApiBase::PARAM_DEPRECATED => true,
+                       ),
+                       'watchlist' => array(
+                               ApiBase::PARAM_DFLT => 'preferences',
+                               ApiBase::PARAM_TYPE => array(
+                                       'watch',
+                                       'unwatch',
+                                       'preferences',
+                                       'nochange'
+                               ),
+                       ),
+                       'unwatch' => array(
+                               ApiBase::PARAM_DFLT => false,
+                               ApiBase::PARAM_DEPRECATED => true,
+                       ),
+                       'oldimage' => null,
+               );
+       }
+
+       public function getParamDescription() {
+               $p = $this->getModulePrefix();
+               return array(
+                       'title' => "Title of the page you want to delete. Cannot be used together with {$p}pageid",
+                       'pageid' => "Page ID of the page you want to delete. Cannot be used together with {$p}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',
+                       'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
+                       '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 'Delete a page';
+       }
+
+       public function getPossibleErrors() {
+               return array_merge( parent::getPossibleErrors(), array(
+                       array( 'code' => 'missingparam', 'info' => 'One of the parameters title, pageid is required' ),
+                       array( 'code' => 'invalidparammix', 'info' => 'The parameters title, pageid can not be used together' ),
+                       array( 'invalidtitle', 'title' ),
+                       array( 'nosuchpageid', 'pageid' ),
+                       array( 'notanarticle' ),
+                       array( 'hookaborted', 'error' ),
+               ) );
+       }
+
+       public function needsToken() {
+               return true;
+       }
+
+       public function getTokenSalt() {
+               return '';
+       }
+
+       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$';
+       }
+}
\ No newline at end of file