Extension:ApiMagicWord/ApiMagicWord body.php

From MediaWiki.org
Jump to: navigation, search
<?php
/**
 * Provides a magic word wiki text access to enabled Application Programming Interfaces (API) of MediaWiki Web sites.
 *
 * @author Eric Larcher <{firstname}.{surname}@yahoo.fr>
 
 * @version 0.1.
 * @version 0.1b some bugs fixe. debug mode off.
 * @version 0.1c Add "delimiter" parameter for list of lists of results.
  */
//<source lang=php>
        require_once( dirname( __FILE__ ) . '/customwikibot.classes.php' ); 
 
        class ApiMagicWord {
 
                const thisType = 'other';
                const thisName = 'ApiMagicWord';
                const  apiString='/api.php?action=$1';
                const actionQuerySiteInfos ='?action=query&format=dbg&meta=siteinfo&siprop=general';
                var $mLocalWiki = null ;
                var $mRemoteWiki = null ;
                var $mBetween = null ;
                var $mDebug=false ;
 
        function ApiMagicWord() {
 
                        # Set Debug mode: 
                 $this->setDebug(false);
 
                        # Load the internalization file  messages: 
                 wfLoadExtensionMessages('ApiMagicWord');
 
                        # Define the local wiki obj: 
                 Global $wgLocalInterwiki;            
                        $localWikiObjName=$wgLocalInterwiki.'WikiObj';
                        Global $$localWikiObjName;
 
                        //We build,, if it don't exist, the local wiki ApiMagicWord object.
                        $localWiki=&$$localWikiObjName;                                         
                        if (!isset($localWiki))
                                $$localWikiObjName=new localWiki();
                        $localWiki=&$$localWikiObjName;                 
                        $this->mLocalWiki= $localWiki;         
                        }               
 
 
        public function api( &$parser /*,...*/ ) {
                        Global $wgTitle, $wgContLang, $wgOut, $wgUser;
 
                        //dynamic piece of page so disable cache parser
                        $parser->disableCache();
 
                        $args = func_get_args();
                        array_shift( $args );
 
                        //We take the remote wiki api link interwiki code from parameters.
                        $iwRemoteApiLink=trim(array_shift($args));
 
                        //if the remote wiki api link interwiki code is '', the "remote" wiki is in fact the local wiki.
                        if ($iwRemoteApiLink === '') {
                                $this->mRemoteWiki=$this->mLocalWiki;
                                $iwRemoteApiLink=$this->mRemoteWiki->getIwApiLink();
                        }
                        else {
                                //We build, if it don't exist, the remote wiki ApiMagicWord object.
                                $this->mRemoteWiki=$this->takeRemoteWiki($iwRemoteApiLink);
                        }                 
 
                        //We build, if it don't exist, the between wiki ApiMagicWord object.
                        $this->mBetween=$this->takeBetweenWikis($this->mRemoteWiki);              
 
                        //We put others parameters of the api call in an array.
                        $argCount=0;
                $parms=array();
                        foreach ($args as $argKeyNr => $parmArg) {
                                $pp = split('=',trim($parmArg),2);
                                if (count($pp) == 2) $parms[$pp[0]] = $pp[1];
                                else $parms[$pp[0]] = '';
                                }
                        $argCount=count ($parms);
 
                        //If we have a template for the ouput, we prepare it.
                        if     ( $parms['template'] !== null )        {
                                if (strpos(':',$parms['template']) === false) $parms['template'] = '{{NS:10}}:'.$parms['template'];
                                else if ($parms['template'][0]==':') $parms['template'] = substr($parms['template'],1);
                        }
 
                        //We treat the api call depending on  parameters. For the moment, only "login", "logout", "edit" and "query/recentchanges". $out is the wiki text we return to the wiki page.
                        $out='';
                        switch( $parms['action'] ) {
 
                        case 'login':
                                $resultsArray=$this->mRemoteWiki->mMediawikiApi->login ($parms["lgname"],$parms["lgpassword"]);
                                $out=$out.$this->resultsListFormat($resultsArray,$parms['template']);
                                return array($out,'found' => true,'nowiki' => false,'noparse' => false,'noargs' => false, 'isHTML' => false);
                                break;
 
                        case 'logout':
                                $resultsArray=$this->mRemoteWiki->mMediawikiApi->logout ();
                                if ($resultsArray [ 'result' ] === 'Success') { $resultsArray [ 'site' ] = $this->mRemoteWiki->getSitename (); }
                                $out=$out.$this->resultsListFormat($resultsArray,$parms['template']);
                                return array($out,'found' => true,'nowiki' => false,'noparse' => false,'noargs' => false, 'isHTML' => false);
                                break;
 
                        case 'query':
                                switch( $parms['list'] ) {
 
                                case "recentchanges":
                                        $resultsArray=$this->mRemoteWiki->mMediawikiApi->recentchanges (( isset( $parms['rclimit'] ) ) ? $parms['rclimit'] : 10,( isset( $parms['rcnamespace'] ) ) ? $parms['rcnamespace'] : null,( isset( $parms['rcdir'] ) ) ? $parms['rcdir'] : 'older') ;
                                        // var_dump($resultsArray);
                                        $out=$out.$this->resultsListsListFormat($resultsArray,$parms['template'], $parms['delimiter']);
                                        return array($out,'found' => true,'nowiki' => false,'noparse' => false,'noargs' => true, 'isHTML' => false);
                                        break;
                                default:
                                        $resultsArray=array ('code' => 'unknown_query','info' => 'Unrecognized value for parameter \'list\': only \'recentchanges\' supported (for the moment).',
  );
                                        $out=$out.$this->resultsListFormat($resultsArray,$parms['template']);
                                        return array($out,'found' => true,'nowiki' => false,'noparse' => false,'noargs' => false, 'isHTML' => false);
                                } 
                                break;
 
                                case "edit":
                                $resultsArray=$this->mRemoteWiki->mMediawikiApi->edit ($parms['title'],$parms['text'],( isset( $parms['summary'] ) ) ? $parms['summary'] : '',( isset( $parms['minor'] ) ) ? true : false, ( isset( $parms['notbot'] ) ) ? false : true, ( isset( $parms['createonly'] ) ) ? true : false, ( isset( $parms['nocreate'] ) ) ? true : false) ;
                                $out=$out.$this->resultsListFormat($resultsArray,$parms['template']);
                                //                            return $parser->insertStripItem( $out, $parser->mStripState );
                                //                            return array($wgOut->parse($out),'found' => true,'nowiki' => false,'noparse' => true,'noargs' => false, 'isHTML' => true);
                                return array($out,'found' => true,'nowiki' => false,'noparse' => false,'noargs' => false, 'isHTML' => false);
                                break;
                        default:
                                $resultsArray=array ('code' => 'unknown_action','info' => 'Unrecognized value for parameter \'action\': only \'login\', \'logout\', \'query\' and \'edit\' supported (for the moment).',
  );
                                $out=$out.$this->resultsListFormat($resultsArray,$parms['template']);
                                return array($out,'found' => true,'nowiki' => false,'noparse' => false,'noargs' => false, 'isHTML' => false);                             
                        }
                }
 
                /**
                 * The data to pass as wiki text is a list of template paramaters (taked from $resultsArray) that we build for a use in a template call (via subst:) inside the source wiki page, or for a call of the $template gived template with this list as parameters list. We format this result.
                 * @param $resultsArray An associative array of result.
                 * @param $template Optional - template to use.
                 * @return Wiki text.
                 **/
 
                private function resultsListFormat($resultsArray, $template = null) {
                        $exp='';
                        foreach ($resultsArray as $keyresult => $result) {
                                $exp = $exp.$keyresult.'='.$result.'|' ;
                        }
                        if     ( $template !== null )     {
                                $exp='{{'.$template.'|'.substr($exp,0,strlen($exp)-1).'}}';
                        }
                        else {
                                $exp=substr($exp,0,strlen($exp)-1);
                        }
                        return $exp;
                }
 
                /**
                 * When the api result (taked from $resultsArray) is a list of lists we format the data to pass as wiki text in both step. It's a list of parmaters designed to be included in a succession of template call inside the source wiki page(via #arraymap associated to a delimiter use), or a call's serie of the $template gived template call with each sublist as parameters list. In this case too, we use $delimiter as template call's separator, if it exist.
                 * @param $resultsArray An associative array of results arrays.
                 * @param $template Optional - template to use for output each results array.
                 * @return Wiki text.
                 **/
 
                private function resultsListsListFormat($resultsArray, $template = null, $delimiter = null) {
                        $exp='';
                        foreach ($resultsArray as $results) {
                                $exp=$exp.$this->resultsListFormat($results, $template);
                                if ( $delimiter !== null ) { $exp = $exp.$delimiter; }
                        }
                        if ( $delimiter !== null ) { $exp=substr($exp,0,strlen($exp)-strlen($delimiter)); }
                return $exp;
                }
 
                public function takeRemoteWiki($iwApiLink) {
 
                        $this->debug( "takeRemoteWiki :<br/> - iwRemoteApiLink $iwApiLink<br/>" );
                        $remoteWikiObjName=$iwApiLink.'WikiObj';
                        $this->debug( "takeRemoteWiki :<br/> - remoteWikiObjName $remoteWikiObjName<br/>" );
                        Global $$remoteWikiObjName;
                        $remoteWiki=&$$remoteWikiObjName;                               
                        if (!isset($remoteWiki))
                                $$remoteWikiObjName= new remoteWiki($iwApiLink);
                        $remoteWiki=&$$remoteWikiObjName;                               
                        return $remoteWiki;
                }
 
                public function takeBetweenWikis(&$remoteWiki) {
                        $this->debug( "takeBetweenWikis :<br/>" );
                        $localIwApiLink=$this->mLocalWiki->getIwApiLink();
                        $this->debug( "- localWikiApiLink $localIwApiLink<br/>" );
                        // var_dump($localWiki);
                        $remoteIwApiLink=$this->mRemoteWiki->getIwApiLink();
                        $this->debug( "- remoteWikiApiLink $remoteIwApiLink<br/>" );
                        // var_dump($remoteWiki);             
                        $betweenWikisObjName=$this->mLocalWiki->getIwApiLink().$remoteWiki->getIwApiLink().'WikiObj';
                        $this->debug( "- betweenWikisObjName $betweenWikisObjName<br/>" );
                        Global $$betweenWikiObjName;
                        $betweenWikis=&$$betweenWikisObjName;
                        if (!isset($betweenWikis))
                                $$betweenWikisObjName= new between ($localWiki,$remoteWiki);
                        $betweenWikis=&$$betweenWikisObjName;
                        return $betweenWikis;
                }
 
                function debug( $data ) {
                        global $wgOut;
                        if( $this->mDebug ) {
                                echo ("$data \n<br />");
#                     $wgOut->addHTML(htmlspecialchars( $data ). "\n<br />") ;
                 }
                        return;
                } 
 
                function setDebug($debug) {
                        $this->mDebug = $debug;
                        return;
                }
        }
        // end class
 
        class between {
 
                const thisType = 'other';
                const thisName = 'between';
 
                var $mDebug=false ;
                var $mLocalWiki=null ;
                var $mRemoteWiki=null ;
                var $mFacsimiLoc ='';
 
                function between(&$localWiki,&$remoteWiki) {
                        // Set debug mode 
                        $this->setDebug(false);
                        $this->mLocalWiki=$localWiki;
                        $this->mRemoteWiki=$remoteWiki;
                        return;
                } 
 
                function getRemoteWiki() {
                        $this->debug( "RemoteWiki" );
                        return $this->mRemoteWiki ;
                }
 
 
                function getLocalWiki() {
                        $this->debug( "LocalWiki" );
                        return $this->mLocalWiki ;
                }
 
                function debug( $data ) {
                        global $wgOut;
                        if( $this->mDebug ) {
                                echo ("$data \n<br />");
#                     $wgOut->addHTML(htmlspecialchars( $data ). "\n<br />") ;
                 }
                        return;
                } 
 
                function setDebug($debug) {
                        $this->mDebug = $debug;
                        return;
                } 
        }
// end class
 
        class wikiPiece {
 
                const thisType = 'other';
                const thisName = 'wikiPiece';
 
                var $mSitename = '';
                var $mServer = '';
                var $mScriptPath = '';
                var $mScript = '';
                var $mArticlePath = '';
                var $mApiPath = '';       
                var $mContLangCode = '';
                var $mContLang = '';
                var $mIwLink = '';
                var $mDebug = false;
                var $mArticleLoc = '';
                var $mApiLoc = '';
                var $mIwApiLink = '';
                var $mTimeZone = '' ;
                var $mTimeOffset = 0 ;
 
                function wikiPiece() {
                        // Set debug mode 
                        $this->setDebug(false);
                }
 
                function debug( $data ) {
                        global $wgOut;
                        if( $this->mDebug ) {
                                echo ("$data \n<br />");
        #                     $wgOut->addHTML(htmlspecialchars( $data ). "\n<br />") ;
                 }
                        return;
                } 
 
                function setDebug($debug) {
                        $this->mDebug = $debug;
                        return;
                }
 
                function setIwApiLink($iwApiLink) {
                        $this->mIwApiLink = $iwApiLink;
                        $this->debug( "setIwApiLink $this->mIwApiLink" );
                        return;
                }
 
                function getIwApiLink() {
                        $this->debug( "getIwApiLink $this->mIwApiLink" );
                        return $this->mIwApiLink ;
                } 
 
                function setScriptPath ($scriptPath) {
                        $this->mScriptPath = $scriptPath;
                        $this->debug( "setScriptPath $this->mScriptPath" );
                        return;
                }
 
                function getScriptPath () {
                        $this->debug( "getScriptPath $this->mScriptPath" );
                        return $this->mScriptPath;
                }
 
                function setScript ($script) {
                        $this->mScript = $script;
                        $this->debug( "setScript $this->mScript" );
                        return;
                }
 
                function getScript () {
                        $this->debug( "getScript $this->mScript" );
                        return $this->mScript;
                }
 
                function setIwLink ($iwLink) {
                        $this->mIwLink = $iwLink ;
                        $this->debug( "setIwLink $this->mIwLink" );
                        return;
                }
 
                function getIwLink () {
                        $this->debug( "getIwLink $this->mIwLink" );
                        return $this->mIwLink;
                }
 
                function setSitename($sitename) {
                        $this->mSitename = $sitename;
                        $this->debug( "setSitename $this->mSitename" );
                        return;
                }
 
                function getSitename() {
                        $this->debug( "getSitename $this->mSitename" );
                        return $this->mSitename ;
                }
 
                function setServer($server) {
                        $this->mServer = $server;
                        $this->debug( "setServer $this->mServer" );
                        return;
                }
 
                function getServer() {
                        $this->debug( "getServer $this->mServer" );
                        return $this->mServer ;
                }
 
                function setArticlePath($articlePath) {
                        $this->mArticlePath = $articlePath;
                        $this->debug( "setArticlePath $this->mArticlePath" );
                        return;
                }
 
                function getArticlePath() {
                        $this->debug( "getArticlePath $this->mArticlePath" );
                        return $this->mArticlePath ;
                }
 
                function setArticleLoc($articleLoc) {
                        $this->mArticleLoc = $articleLoc;
                        $this->debug( "setArticleLoc $this->mArticleLoc" );
                        return;
                }
 
                function getArticleLoc() {
                        $this->debug( "getArticleLoc $this->mArticleLoc" );
                        return $this->mArticleLoc ;
                }
 
                function setApiPath($apiPath) {
                        $this->mApiPath = $apiPath;
                        $this->debug( "setApiPath $this->mApiPath" );
                        return;
                }
 
                function getApiPath() {
                        $this->debug( "getApiPath $this->mApiPath" );
                        return $this->mApiPath ;
                }
 
                function setApiLoc($apiLoc) {
                        $this->mApiLoc = $apiLoc;
                        $this->debug( "setApiLoc $this->mApiLoc" );
                        return;
                }
 
                function getApiLoc() {
                        $this->debug( "getApiLoc $this->mApiLoc" );
                        return $this->mApiLoc ;
                }
 
                function setContLang($contLang) {
                        $this->debug( "setContLang $this->mContLang" );
                        $this->mContLang = $contLang;
                        return;
                }
 
                function getContLang() {
                        $this->debug( "getContLang $this->mContLang" );
                        return $this->mContLang ;
                }
 
                function setContLangCode($contLangCode) {
                        $this->debug( "setContLangCode $this->mContLangCode" );
                        $this->mContLangCode = $contLangCode;
                        return;
                }
 
                function getContLangCode() {
                        $this->debug( "getContLangCode $this->mContLangCode" );
                        return $this->mContLangCode ;
                }
 
                function rawPageGetContent($pageName) {
                        $pageName=rawurlencode($pageName);
                        $url=$this->getServer().$this->getScript().'?title='.$pageName.'&action=raw';
                        $text = Http::get($url);
                        $this->debug( "rawPageGetContent $text" );
                        $this->debug( "rawPageGetContent :<br/>- pageName $pageName<br/>- url $url<br/>- text $text<br/>");
                        return $text;
                } 
 
                function setTimeZone($timeZone) {
                        $this->debug( "setTimeZone $this->mTimeZone" );
                        $this->mTimeZone = $timeZone;
                        return;
                }
 
                function setTimeOffset($timeOffset) {
                        $this->debug( "setTimeOffset $this->mTimeOffset" );
                        $this->mTimeOffset = $timeOffset;
                        return;
                }         
        }
        // end class
 
        class localWiki        extends wikiPiece {
 
                const thisType = 'other';
                const thisName = 'localWiki';
 
                var $mLang = null; 
                var $mMediawikiApi = null ;
 
                function localWiki() {
 
                        Global $wgSitename, $wgServer, $wgScriptPath, $wgScript, $wgArticlePath, $wgLang, $wgContLang, $wgLocalInterwiki;
 
                        $this->mSitename = &$wgSitename;
                        $this->mServer = &$wgServer;
                        $this->mScript = &$wgScript;
                        $this->mScriptPath = &$wgScriptPath;              
                        $this->mArticlePath = &$wgArticlePath;
                        $this->mApiPath = $this->mScriptPath.ApiMagicWord::apiString;  
                        $this->mContLangCode = $wgContLang->getCode();
                        $this->mIwLink = &$wgLocalInterwiki;
                        $this->setIwApiLink($this->mIwLink.'api');
                        $this->mMediawikiApi = new localMediawikiApi;                  
                }
        }
        // end class
 
        class remoteWiki extends wikiPiece    {
 
                const thisType = 'other';
                const thisName = 'remoteWiki';
 
 
                var $mNameSpaces = array() ;
                var $mNameSpaceAliases = array() ;
                var $mSpecialPageAliases = array() ;
                var $mMagicWords = array() ;
                var $mMediawikiApi = null ;
 
                function remoteWiki($iwApiLink) {
 
                        // Set debug mode 
                        $this->setDebug(false);
                        $this->debug( "remoteWiki :<br/>" );
 
                        // Set the interwiki links of the remote wiki. For the api and for articles.
                        $this->debug( "-remoteWiki iwApiLink $iwApiLink<br/>" );
                        $this->setIwApiLink($iwApiLink);
                        $this->setIwLink(str_replace('api','',$iwApiLink));
                        $this->debug( "-remoteWiki setIwLink ".$this->getIwLink()."<br/>" );
 
                        // Set the url path to the api actions of the remote wiki.  Create the associate mediawikiApi object.
                        $apiTitleObject=Title::newFromText($this->getIwApiLink().':');
                        $this->setApiLoc($apiTitleObject->getFullUrl().'$1');
                        $this->mMediawikiApi = new mediawikiApi;
                        $this->mMediawikiApi->setApiUrl(str_replace('?action=$1','',$this->getApiLoc()));
 
                        //We prepare an url for a Siteinfo query to the remote wiki
                        $this->debug( '-remoteWiki setApiLoc : '.$this->getApiLoc().'<br/>' );
                        $siteInfosUrl=$this->mMediawikiApi->getApiUrl().ApiMagicWord::actionQuerySiteInfos;
                        $this->debug( '-remoteWiki siteInfosUrl : '.$siteInfosUrl.'<br/>' );
 
                        // We put the call and receive a string in return (see Mediawiki api.php documentation for details). We convert this string into an array.
                        // var_dump($this);
//                    $mediawikiApi = &$this->mMediawikiApi;                   
//                    $siteInfosText = $mediawikiApi->getSiteInfosText ($siteInfosUrl);
                        $siteInfosText = Http::get($siteInfosUrl);
//                    $this->debug( "-remoteWiki siteInfosText".$siteInfosText."<br/>" );
                        $siteInfos=eval ('return '.$siteInfosText.';');
                        // var_dump($siteInfos);
                        // We set the paths of the remote wiki. Example : http://fr.wikipedia.org/wiki/$1 for the french Wikipédia.
                        $mainpage=($siteInfos ['query'] ['general'] ['mainpage']);
                        $base=($siteInfos ['query'] ['general'] ['base']);
                        $this->setPaths($base,$mainpage,$this->getApiLoc());
 
                        // We set the site name of the remote wiki. Example : Wikipédia.
                        $this->setSitename($siteInfos ['query'] ['general'] ['sitename']);
 
                        // We set the content langage code of the remote wiki. Example : 'fr'.
                        $this->setContLangCode($siteInfos ['query'] ['general'] ['lang']);
 
                        // We set the time zone of the remote wiki. Example : 'Europe/Paris'.
 
                        $this->setTimeZone($siteInfos ['query'] ['general'] ['timezone']);
 
                        // We set the time zone of the remote wiki. Example : 'Europe/Paris'.
                        $this->setTimeOffset($siteInfos ['query'] ['general'] ['timeoffset']);
                }
 
                function setPaths($base,$mainpage,$apiLoc) {
 
                        $this->debug( "setPaths base $base mainpage $mainpage apiLoc $apiLoc" );
                        $this->setArticleLoc(str_replace($mainpage,'$1',$base));
                        $articlesUrlArray=explode('/',$this->getArticleLoc());
                        $actionsApiUrlArray=explode('/',$apiLoc);
                        $this->setServer($actionsApiUrlArray [0].'//'.$actionsApiUrlArray [2]);
                        $this->setScriptPath(str_replace('/api.php?action=$1','',str_replace($this->getServer(),'', $apiLoc)));
                        $this->setScript($this->getScriptPath().'/index.php');
                        $this->setApiPath(str_replace($this->getServer(),'',$this->getApiLoc()));
                        $this->setArticlePath(str_replace($this->getServer(),'',$this->getArticleLoc()));
                        return;
                }
 
                function setNameSpaces($nameSpaces) {
                        $this->debug( "setNameSpaces" );
                        $this->mNameSpaces = $nameSpaces;
                        return;
                }
 
                function setNameSpaceAliases($nameSpaceAliases) {
                        $this->debug( "setNameSpaceAliases" );
                        $this->mNameSpaceAliases = $nameSpaceAliases;
                        return;
                }
 
                function setSpecialPageAliases($specialPageAliases) {
                        $this->debug( "setSpecialPageAliases" );
                        $this->mSpecialPageAliases = $specialPageAliases;
                        return;
                }
 
                function setMagicWords($magicWords) {
                        $this->debug( "setMagicWords" );
                        $this->mMagicWords = $magicWords;
                        return;
                } 
        }
        // end class  
 
        class mediawikiApi extends wikipediaapi {
 
                function setApiUrl($url) {
                        $this->apiurl = $url;
                        return;
                } 
 
                function getApiUrl() {
                        return $this->apiurl;
                } 
 
                function getSiteInfosText ($url) {
                        return $this->http->get($url);
                }
        }
        // end class  
                class localMediawikiApi extends wikipediaapi {
 
                function setApiUrl($url) {
                        $this->apiurl = $url;
                        return;
                } 
 
                function getApiUrl() {
                        return $this->apiurl;
                } 
 
                function getSiteInfosText ($url) {
                        return $this->http->get($url);
                }
 
 
                /**
                 * Fake to Post data to the Api of the local site by FauxRequest.
                 * @param $data The the fake POST values to post, array of *non*-urlencoded key => value pairs.
                 * @param $enableWrite bool should be set to true if the api may modify data             
                 * @return Data retrieved from the fake POST request. In case of an exception, an associative error message array will be returned.
                 **/
 
                function fauxPost ($data, $enableWrite = false ) {
 
                        $wasPosted = true;          
                        $request = new FauxRequest($data, $wasPosted);
                        $api = new ApiMain($request, $enableWrite);
                        try {
                                $api->execute();
                                $x = & $api->getResultData();
                        } catch (Exception $e) {
                                if ( $e instanceof MWException ) {
                                wfDebugLog( 'exception', $e->getLogMessage() );
                                }
                                //
                                // ??? Handle any kind of exception 
                                //
                                global $wgShowSQLErrors, $wgShowExceptionDetails;
                                //
                                // Something is seriously wrong
                                //
                                if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
                                        $info = "Database query error";
                                } else {
                                        $info = "Exception Caught: {$e->getMessage()}";
                                }
                                $errMessage = array (
                                'code' => 'internal_api_error_'. get_class($e),
                                'info' => $info,
                                );
                                $x = $errMessage;
                                //        echo("\n\n{$e->getTraceAsString()}\n\n" );                     
                        }
                        return $x ;
                }
 
                /**
                 * Fake to Get data from the Api of local site by FauxRequest.
                 * @param $data The the fake POST values to post, array of *non*-urlencoded key => value pairs.               
                 * @return Data retrieved from the fake from the GET request. In case of an exception, an associative error message array will be returned.
                 **/
 
                function fauxGet ($data) {
 
                        $wasPosted = false;
                        $enableWrite = false;                       
                        $request = new FauxRequest($data, $wasPosted);
                        $api = new ApiMain($request, $enableWrite);
                        try {
                                $api->execute();
                                $x = & $api->getResultData();
                        } catch (Exception $e) {
                                if ( $e instanceof MWException ) {
                                wfDebugLog( 'exception', $e->getLogMessage() );
                                }
                                //
                                // ??? Handle any kind of exception 
                                //
                                global $wgShowSQLErrors, $wgShowExceptionDetails;
                                //
                                // Something is seriously wrong
                                //
                                if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
                                        $info = "Database query error";
                                } else {
                                        $info = "Exception Caught: {$e->getMessage()}";
                                }
                                $errMessage = array (
                                'code' => 'internal_api_error_'. get_class($e),
                                'info' => $info,
                                );
                                $x = $errMessage;
                                //        echo("\n\n{$e->getTraceAsString()}\n\n" );                     
                        }
                        return $x ;
                }         
 
                /**
                 * This  FauxRequest fake local api request function takes a username and password and logs you into the local wiki.
                 * @param $user Username to login as.
                 * @param $pass Password that corresponds to the username.
                 * @return void
                 **/
 
                function login ($user,$pass) {
 
                        $data = array();
                        $data ['action'] = 'login';
                        $data ['lgname' ] = $user;
                        $data ['lgpassword'] = $pass;
                        return $this->fauxPost ($data) ;
                }
 
                /**
                 * This FauxRequest fake local api request function is used to logout and clear session data
                 * @return void 
                 **/
                function logout () {
 
                        $data = array();
                        $data ['action'] = 'logout';
                        $x=$this->fauxGet ($data);
                        if ( isset( $x['code']) && isset( $x['info'])) { return $x; }
                        return array( 'result' => 'Success');
                }
 
                /**
                 * This FauxRequest fake local api request function returns the various tokens for a certain page.
                 * @param $title Page to get the tokens for.
                 * @param $flush Optional - internal use only.  Flushes the token cache.
                 * @return An associative array of tokens for the page.
                 **/
                function gettokens ($title,$flush = false) {
                        if (!is_array($this->tokencache)) $this->tokencache = array();
                        foreach ($this->tokencache as $t => $data) if (time() - $data['timestamp'] > 6*60*60) unset($this->tokencache[$t]);
                        if (isset($this->tokencache[$title]) && (!$flush)) {
                                return $this->tokencache[$title]['tokens'];
                        } else {
                                $tokens = array();
                                $data = array();
                                $data [ 'action' ] = 'query';
                                $data [ 'prop' ] = 'info';
                                $data [ 'intoken'] = 'edit|delete|protect|move|block|unblock|email';
                                $data [ 'titles' ] = $title;                                                            
                                $x=$this->fauxGet ($data);
                                if ( isset( $x['code']) && isset( $x['info'])) { return $x; }
                                foreach ($x['query']['pages'] as $y) {
                                        $tokens['edittoken'] = $y['edittoken'];
                                        $tokens['deletetoken'] = $y['deletetoken'];
                                        $tokens['protecttoken'] = $y['protecttoken'];
                                        $tokens['movetoken'] = $y['movetoken'];
                                        $tokens['blocktoken'] = $y['blocktoken'];
                                        $tokens['unblocktoken'] = $y['unblocktoken'];
                                        $tokens['emailtoken'] = $y['emailtoken'];
                                        $this->tokencache[$title] = array(
                                                        'timestamp' => time(),
                                                        'tokens' => $tokens
                                                                         );
                                        return $tokens;
                                }
                        }
                }         
 
                /**
                 * This FauxRequest fake local api request function returns the recent changes for the local wiki.
                 * @param $count The number of items to return. (Default 10)
                 * @param $namespace The namespace ID to filter items on. Null for no filtering. (Default null)
                 * @param $dir The direction to pull items.  "older" or "newer".  (Default 'older')
                 * @param $ts The timestamp to start at.  Null for the beginning/end (depending on direction).  (Default null)
                 * @return Associative array of recent changes metadata.
                 **/
                function recentchanges ($count = 10,$namespace = null,$dir = 'older',$ts = null) {
 
                        $data = array();
                        $data [ 'action' ] = 'query';
                        $data [ 'list' ] = 'recentchanges';
                        $data [ 'rcprop'] = 'user|comment|flags|timestamp|title|ids|sizes';
                        $data [ 'rclimit' ] = $count;           
                        if ($namespace !== null) { $data [ 'rcnamespace' ] = $namespace; }
                        $data [ 'rcdir' ] = $dir;
                        if ($ts !== null) { $data [ 'rcstart' ] = $ts ; }
                        $x = $this->fauxGet ($data);
                        if ( isset( $x['code']) && isset( $x['info'])) { return $x; }
                        return $x['query']['recentchanges'];
                }         
 
 
 
 
 
                /**
                 * Edits a page.
                 * @param $page Page name to edit.
                 * @param $data Data to post to page.
                 * @param $summary Edit summary to use.
                 * @param $minor Whether or not to mark edit as minor.  (Default false)
                 * @param $bot Whether or not to mark edit as a bot edit.  (Default true)
                 * @param $wpStarttime Time in MW TS format of beginning of edit.  (Default now)
                 * @param $wpEdittime Time in MW TS format of last edit to that page.  (Default correct)
                 * @return boolean True on success, false on failure.
                 **/
 
                 function edit ($page,$data,$summary = '',$minor = false,$bot = false,$createonly = false,$nocreate = false, $wpStarttime = null,$wpEdittime = null) {
 
                        $data = Array(
                                'action' => 'edit',
                                'format' => 'php',
                                'title' => $page,
                                'text' => $data,
                                'token' => $this->getedittoken(),
                                'summary' => $summary,
                                ($minor?'minor':'notminor') => '1',
                                ($bot?'bot':'notbot') => '1'
                        );
                        if ($createonly !== false) { $data [ 'createonly' ] = '1'; }
                        if ($nocreate !== false) { $data [ 'nocreate' ] = '1'; }
                        $enableWrite = true;
                        $x = $this->fauxPost ($data, $enableWrite);
                        if ( isset( $x[ 'code' ]) && isset( $x[ 'info' ])) {
                                $x[ 'title' ] = $page;
                                return $x;
                        }
                        return $x['edit'];
                }
        }
        // end class
//

</source>

Personal tools
Namespaces
Variants
Actions
Site
Support
Download
Development
Communication
Print/export
Toolbox