MaxSem has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/95483


Change subject: Rewrite of interaction with renderer
......................................................................

Rewrite of interaction with renderer

* Make it OOP
* Don't show end-users scary non-localised errors from servers - just log them

Change-Id: I2a5bced4d1795f715564e331985c71df240ae332
---
M Collection.body.php
M Collection.i18n.php
M Collection.php
A RenderingAPI.php
4 files changed, 366 insertions(+), 211 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/extensions/Collection 
refs/changes/83/95483/1

diff --git a/Collection.body.php b/Collection.body.php
index 02eb105..10124f5 100644
--- a/Collection.body.php
+++ b/Collection.body.php
@@ -975,112 +975,27 @@
        }
 
        /**
-        * @return array
-        */
-       function getLicenseInfos() {
-               global $wgCollectionLicenseName, $wgCollectionLicenseURL, 
$wgRightsIcon;
-               global $wgRightsPage, $wgRightsText, $wgRightsUrl;
-
-               $licenseInfo = array(
-                       "type" => "license",
-               );
-
-               $from_msg = $this->msg( 'coll-license_url' 
)->inContentLanguage();
-               if ( !$from_msg->isDisabled() ) {
-                       $licenseInfo['mw_license_url'] = $from_msg->text();
-                       return array( $licenseInfo );
-               }
-
-               if ( $wgCollectionLicenseName ) {
-                       $licenseInfo['name'] = $wgCollectionLicenseName;
-               } else {
-                       $licenseInfo['name'] = $this->msg( 'coll-license' 
)->inContentLanguage()->text();
-               }
-
-               if ( $wgCollectionLicenseURL ) {
-                       $licenseInfo['mw_license_url'] = 
$wgCollectionLicenseURL;
-               } else {
-                       $licenseInfo['mw_rights_icon'] = $wgRightsIcon;
-                       $licenseInfo['mw_rights_page'] = $wgRightsPage;
-                       $licenseInfo['mw_rights_url'] = $wgRightsUrl;
-                       $licenseInfo['mw_rights_text'] = $wgRightsText;
-               }
-
-               return array( $licenseInfo );
-       }
-
-       /**
-        * @param $collection array
-        * @return string
-        */
-       function buildJSONCollection( $collection ) {
-               $result = array(
-                       'type' => 'collection',
-                       'licenses' => $this->getLicenseInfos()
-               );
-
-               if ( isset( $collection['title'] ) ) {
-                       $result['title'] = $collection['title'];
-               }
-               if ( isset( $collection['subtitle'] ) ) {
-                       $result['subtitle'] = $collection['subtitle'];
-               }
-
-               $items = array();
-               if ( isset( $collection['items'] ) ) {
-                       $currentChapter = null;
-                       foreach ( $collection['items'] as $item ) {
-                               if ( $item['type'] == 'article' ) {
-                                       if ( is_null( $currentChapter ) ) {
-                                               $items[] = $item;
-                                       } else {
-                                               $currentChapter['items'][] = 
$item;
-                                       }
-                               } elseif ( $item['type'] == 'chapter' ) {
-                                       if ( !is_null( $currentChapter ) ) {
-                                               $items[] = $currentChapter;
-                                       }
-                                       $currentChapter = $item;
-                               }
-                       }
-                       if ( !is_null( $currentChapter ) ) {
-                               $items[] = $currentChapter;
-                       }
-               }
-               $result['items'] = $items;
-
-               return FormatJson::encode( $result );
-       }
-
-       /**
         * @param $collection
         * @param $referrer Title
         * @param $writer
         */
        function renderCollection( $collection, $referrer, $writer ) {
-               global $wgContLang, $wgScriptPath, $wgScriptExtension;
-
                if ( !$writer ) {
                        $writer = 'rl';
                }
 
-               $response = self::mwServeCommand( 'render', array(
-                       'metabook' => $this->buildJSONCollection( $collection ),
-                       'base_url' => wfExpandUrl( $wgScriptPath, PROTO_CURRENT 
),
-                       'script_extension' => $wgScriptExtension,
-                       'language' => $wgContLang->getCode(),
-                       'writer' => $writer,
-               ) );
+               $api = CollectionRenderingAPI::instance( $writer );
+               $response = $api->render( $collection );
 
-               if ( !$response ) {
+               if ( $this->handleResult( $response ) ) {
                        return;
                }
 
                $query = 'bookcmd=rendering'
                        . '&return_to=' . urlencode( 
$referrer->getPrefixedText() )
-                       . '&collection_id=' . urlencode( 
$response['collection_id'] )
-                       . '&writer=' . urlencode( $response['writer'] );
-               if ( isset( $response['is_cached'] ) && $response['is_cached'] 
) {
+                       . '&collection_id=' . urlencode( $response->get( 
'collection_id' ) )
+                       . '&writer=' . urlencode( $writer );
+               if ( $response->get( 'is_cached' ) && $response->get( 
'is_cached' ) ) {
                        $query .= '&is_cached=1';
                }
                $redirect = SkinTemplate::makeSpecialUrl( 'Book', $query );
@@ -1088,21 +1003,13 @@
        }
 
        function forceRenderCollection() {
-               global $wgContLang, $wgScriptPath, $wgScriptExtension;
-
                $request = $this->getRequest();
 
                $collectionID = $request->getVal( 'collection_id', '' );
                $writer = $request->getVal( 'writer', 'rl' );
 
-               $response = self::mwServeCommand( 'render', array(
-                       'collection_id' => $collectionID,
-                       'base_url' => wfExpandUrl( $wgScriptPath, PROTO_CURRENT 
),
-                       'script_extension' => $wgScriptExtension,
-                       'language' => $wgContLang->getCode(),
-                       'writer' => $writer,
-                       'force_render' => true
-               ) );
+               $api = CollectionRenderingAPI::instance( $writer );
+               $response = $api->forceRender( $collectionID );
 
                if ( !$response ) {
                        return;
@@ -1119,42 +1026,39 @@
        }
 
        function renderRenderingPage() {
+               $this->setHeaders();
                $request = $this->getRequest();
+               $out = $this->getOutput();
 
-               $response = self::mwServeCommand( 'render_status', array(
-                       'collection_id' => $request->getVal( 'collection_id' ),
-                       'writer' => $request->getVal( 'writer' ),
-               ) );
-               if ( !$response ) {
+               $collectioId = $request->getVal( 'collection_id' );
+               $writer = $request->getVal( 'writer' );
+               $return_to = $request->getVal( 'return_to', '' );
+
+               $result = CollectionRenderingAPI::instance( $writer 
)->getRenderStatus( $collectioId, $writer );
+               if ( !$this->handleResult( $result ) ) {
                        return; // FIXME?
                }
 
-               $this->setHeaders();
-
-               $return_to = $request->getVal( 'return_to', '' );
-
-               $query = 'collection_id=' . urlencode( 
$response['collection_id'] )
-                       . '&writer=' . urlencode( $response['writer'] )
+               $query = 'collection_id=' . urlencode( $collectioId )
+                       . '&writer=' . urlencode( $writer )
                        . '&return_to=' . urlencode( $return_to );
 
-               $out = $this->getOutput();
-
-               switch ( $response['state'] ) {
+               switch ( $result->get( 'state' ) ) {
                case 'progress':
                        $out->addHeadItem( 'refresh-nojs', '<noscript><meta 
http-equiv="refresh" content="2" /></noscript>' );
-                       $out->addInlineScript( 'var collection_id = "' . 
urlencode( $response['collection_id'] ) . '";' );
-                       $out->addInlineScript( 'var writer = "' . urlencode( 
$response['writer'] ) . '";' );
+                       $out->addInlineScript( 'var collection_id = "' . 
urlencode( $collectioId ) . '";' );
+                       $out->addInlineScript( 'var writer = "' . urlencode( 
$writer ) . '";' );
                        $out->addInlineScript( 'var collection_rendering = 
true;' );
                        $out->addModules( 'ext.collection' );
                        $out->setPageTitle( $this->msg( 'coll-rendering_title' 
) );
 
-                       if ( isset( $response['status']['status'] ) && 
$response['status']['status'] ) {
-                               $statusText = $response['status']['status'];
-                               if ( isset( $response['status']['article'] ) && 
$response['status']['article'] ) {
-                                       $statusText .= ' ' . $this->msg( 
'coll-rendering_article', $response['status']['article'] )->text();
-                               } elseif ( isset( $response['status']['page'] ) 
&& $response['status']['page'] ) {
+                       $statusText = $result->get( 'status', 'status' );
+                       if ( $statusText ) {
+                               if ( $result->get( 'status', 'article' ) ) {
+                                       $statusText .= ' ' . $this->msg( 
'coll-rendering_article', $result->get( 'status', 'article' ) )->text();
+                               } elseif ( $result->get( 'status', 'page' ) ) {
                                        $statusText .= ' ';
-                                       $statusText .= $this->msg( 
'coll-rendering_page' )->numParams( $response['status']['page'] )->text();
+                                       $statusText .= $this->msg( 
'coll-rendering_page' )->numParams( $result->get( 'status', 'page' ) )->text();
                                }
                                $status = $this->msg( 'coll-rendering_status', 
$statusText )->text();
                        } else {
@@ -1163,10 +1067,11 @@
 
                        $template = new CollectionRenderingTemplate();
                        $template->set( 'status', $status );
-                       if ( !isset( $response['status']['progress'] ) ) {
-                               $response['status']['progress'] = 1.00;
+                       $progress = $result->get( 'status', 'progress' );
+                       if ( !$progress ) {
+                               $progress = 1.00;
                        }
-                       $template->set( 'progress', 
$response['status']['progress'] );
+                       $template->set( 'progress', $progress );
                        $out->addTemplate( $template );
                        break;
                case 'finished':
@@ -1180,7 +1085,7 @@
                        $out->addTemplate( $template );
                        break;
                default:
-                       $out->addWikiText( 'state: ' . $response['state'] );
+                       throw new MWException( __METHOD__ . "(): unknow state 
'{$result->get( 'state' )}'");
                }
        }
 
@@ -1188,16 +1093,17 @@
                global $wgCollectionContentTypeToFilename;
 
                $request = $this->getRequest();
+               $collectionId = $request->getVal( 'collection_id' );
+               $writer = $request->getVal( 'writer' );
+               $api = CollectionRenderingAPI::instance( $writer );
 
                $this->tempfile = tmpfile();
-               $r = self::mwServeCommand( 'render_status', array(
-                       'collection_id' => $request->getVal( 'collection_id' ),
-                       'writer' => $request->getVal( 'writer' ),
-               ) );
+               $r = $api->getRenderStatus( $collectionId, $writer );
 
                $info = false;
-               if ( isset( $r['url'] ) ) {
-                       $req = MWHttpRequest::factory( $r['url'] );
+               $url = $r->get( 'url' );
+               if ( $url ) {
+                       $req = MWHttpRequest::factory( $url );
                        $req->setCallback( array( $this, 'writeToTempFile' ) );
                        if ( $req->execute()->isOK() ) {
                                $info = true;
@@ -1206,12 +1112,9 @@
                        $content_length = $r['content_length'];
                        $content_disposition = $r['content_disposition'];
                } else {
-                       $info = self::mwServeCommand( 'download', array(
-                               'collection_id' => $request->getVal( 
'collection_id' ),
-                               'writer' => $request->getVal( 'writer' ),
-                       ) );
-                       $content_type = $info['content_type'];
-                       $content_length = $info['download_content_length'];
+                       $info = $api->download( $collectionId, $writer );
+                       $content_type = $info->get( 'content_type' );
+                       $content_length = $info->get( 'download_content_length' 
);
                        $content_disposition = null;
                }
                if ( !$info ) {
@@ -1276,23 +1179,20 @@
         * @param $partner
         */
        function postZIP( $collection, $partner ) {
-               global $wgScriptPath, $wgScriptExtension;
-
+               $out = $this->getOutput();
                if ( !isset( $this->mPODPartners[$partner] ) ) {
-                       $this->getOutput()->showErrorPage( 
'coll-invalid_podpartner_title', 'coll-invalid_podpartner_msg' );
+                       $out->showErrorPage( 'coll-invalid_podpartner_title', 
'coll-invalid_podpartner_msg' );
                        return;
                }
 
-               $response = self::mwServeCommand( 'zip_post', array(
-                       'metabook' => $this->buildJSONCollection( $collection ),
-                       'base_url' => wfExpandUrl( $wgScriptPath, PROTO_CURRENT 
),
-                       'script_extension' => $wgScriptExtension,
-                       'pod_api_url' => 
$this->mPODPartners[$partner]['posturl'],
-               ) );
-               if ( !$response ) {
+               $api = CollectionRenderingAPI::instance();
+               $result = $api->postZip( $collection, 
$this->mPODPartners[$partner]['posturl'] );
+               if ( !$this->handleResult( $result ) ) {
                        return;
                }
-               $this->getOutput()->redirect( $response['redirect_url'] );
+               if ( $result->get( 'redirect_url' ) ) {
+                       $out->redirect( $result->get( 'redirect_url' ) );
+               }
        }
 
        /**
@@ -1326,55 +1226,18 @@
        }
 
        /**
-        * @param $command
-        * @param $args
-        * @return bool|array
+        * @param CollectionAPIResult $result
+        *
+        * @return bool: Whether the result had errors
         */
-       static function mwServeCommand( $command, $args ) {
-               global $wgOut, $wgCollectionMWServeURL, 
$wgCollectionMWServeCredentials, $wgCollectionFormatToServeURL;
-
-               $serveURL = $wgCollectionMWServeURL;
-               if ( isset ( $args['writer'] ) ) {
-                       if ( array_key_exists( $args['writer'], 
$wgCollectionFormatToServeURL ) ) {
-                               $serveURL = $wgCollectionFormatToServeURL[ 
$args['writer'] ];
-                       }
+       private function handleResult( $result ) {
+               if ( !$result->isError() ) {
+                       return true;
                }
-
-               $args['command'] = $command;
-               if ( $wgCollectionMWServeCredentials ) {
-                       $args['login_credentials'] = 
$wgCollectionMWServeCredentials;
-               }
-               $response = Http::post($serveURL, array('postData' => $args));
-
-               if ( !$response ) {
-                       $wgOut->showErrorPage(
-                               'coll-post_failed_title',
-                               'coll-post_failed_msg',
-                               array( $serveURL )
-                       );
-                       return false;
-               }
-
-               $json_response = FormatJson::decode( $response, true );
-
-               if ( !$json_response ) {
-                       $wgOut->showErrorPage(
-                               'coll-mwserve_failed_title',
-                               'coll-mwserve_failed_msg',
-                               array( $response )
-                       );
-                       return false;
-               }
-
-               if ( isset( $json_response['error'] ) && 
$json_response['error'] ) {
-                       $wgOut->showErrorPage(
-                               'coll-mwserve_failed_title',
-                               'coll-mwserve_failed_msg',
-                               array( $json_response['error'] )
-                       );
-                       return false;
-               }
-
-               return $json_response;
+               $this->getOutput()->showErrorPage(
+                       'coll-request_failed_title',
+                       'coll-request_failed_msg'
+               );
+               return false;
        }
 }
diff --git a/Collection.i18n.php b/Collection.i18n.php
index fd66207..a45b189 100644
--- a/Collection.i18n.php
+++ b/Collection.i18n.php
@@ -67,8 +67,8 @@
        'coll-rename_chapter'             => 'Enter new name for chapter',
        'coll-no_such_category'           => 'No such category',
        'coll-notitle_title'              => 'The title of the page could not 
be determined.',
-       'coll-post_failed_title'          => 'POST request failed',
-       'coll-post_failed_msg'            => 'The POST request to $1 failed 
($2).',
+       'coll-request_failed_title'       => 'Book rendering failed',
+       'coll-request_failed_msg'         => 'There was an error while 
attempting to render your book.',
        'coll-mwserve_failed_title'       => 'Render server error',
        'coll-mwserve_failed_msg'         => 'An error occurred on the render 
server: <nowiki>$1</nowiki>',
        'coll-error_reponse'              => 'Error response from server',
@@ -256,13 +256,7 @@
        'coll-subtitle' => '{{Identical|Subtitle}}',
        'coll-contents' => '{{Identical|Content}}',
        'coll-rename' => '{{Identical|Rename}}',
-       'coll-post_failed_msg' => 'Parameters:
-* $1 - URL. Default value: http://tools.pediapress.com/mw-serve/
-* $2 - error message',
-       'coll-mwserve_failed_msg' => 'Used as error message body. Parameters:
-* $1 - any one of the following information (not server name):
-** invalid JSON string
-** error message which JSON decoder returned',
+       'coll-request_failed_msg' => 'Shown when a PDF (or other format) 
rendering failed',
        'coll-empty_collection' => 'Translate "empty" as in "an empty book" 
(adj), not "empty the book" (verb)',
        'coll-revision' => 'Unused at this time.
 
diff --git a/Collection.php b/Collection.php
index dd4ae25..668ecd6 100644
--- a/Collection.php
+++ b/Collection.php
@@ -149,9 +149,14 @@
 $wgAutoloadClasses['CollectionRenderingTemplate'] = $dir . 
'Collection.templates.php';
 $wgAutoloadClasses['CollectionFinishedTemplate'] = $dir . 
'Collection.templates.php';
 $wgAutoloadClasses['CollectionSuggestTemplate'] = $dir . 
'Collection.templates.php';
+$wgAutoloadClasses['CollectionRenderingAPI'] = $dir . 'RenderingAPI.php';
+$wgAutoloadClasses['MWServeRenderingAPI'] = $dir . 'RenderingAPI.php';
+$wgAutoloadClasses['CollectionAPIResult'] = $dir . 'RenderingAPI.php';
+
 $wgExtensionMessagesFiles['CollectionCore'] = $dir . 
'CollectionCore.i18n.php'; // Only contains essential messages outside the 
special page
 $wgExtensionMessagesFiles['Collection'] = $dir . 'Collection.i18n.php'; // 
Contains all messages used on special page
 $wgExtensionMessagesFiles['CollectionAlias'] = $dir . 'Collection.alias.php';
+
 $wgSpecialPages['Book'] = 'SpecialCollection';
 $wgSpecialPageGroups['Book'] = 'pagetools';
 
@@ -233,10 +238,8 @@
 $wgAjaxExportList[] = 'wfAjaxPostCollection';
 
 function wfAjaxGetMWServeStatus( $collection_id = '', $writer = 'rl' ) {
-       $result = SpecialCollection::mwServeCommand( 'render_status', array(
-               'collection_id' => $collection_id,
-               'writer' => $writer
-       ) );
+       $response = CollectionRenderingAPI::instance( $writer 
)->getRenderStatus( $collection_id, $writer );
+       $result = $response->response;
        if ( isset( $result['status']['progress'] ) ) {
                $result['status']['progress'] = number_format( 
$result['status']['progress'], 2, '.', '' );
        }
diff --git a/RenderingAPI.php b/RenderingAPI.php
new file mode 100644
index 0000000..d7d1d83
--- /dev/null
+++ b/RenderingAPI.php
@@ -0,0 +1,295 @@
+<?php
+
+/**
+ * Base class for API that interacts with book rendering service
+ */
+abstract class CollectionRenderingAPI {
+       /** @var CollectionRenderingAPI */
+       private static $inst;
+
+       /** @var string */
+       protected $writer;
+
+       public static function instance( $writer = false ) {
+               if ( !self::$inst ) {
+                       self::$inst = new MWServeRenderingAPI( $writer );
+               }
+               return self::$inst;
+       }
+
+       /**
+        * @param string|bool $writer: Writer or false if none specified/needed
+        */
+       protected function __create( $writer ) {
+               $this->writer = $writer;
+       }
+
+       /**
+        * When overridden in derived class, performs a request to the service
+        *
+        * @param string $command
+        * @param array $params
+        * @return CollectionAPIResult
+        */
+       protected abstract function makeRequest( $command, array $params );
+
+       /**
+        * Requests a collection to be rendered
+        * @param array $collection
+        *
+        * @return CollectionAPIResult
+        */
+       public function render( $collection ) {
+               return $this->doRender( array(
+                               'metabook' => $this->buildJSONCollection( 
$collection ),
+                       )
+               );
+       }
+
+       /**
+        * Requests a queued collection to be immediately rendered
+        *
+        * @param $collectionId
+        * @return CollectionAPIResult
+        */
+       public function forceRender( $collectionId ) {
+               return $this->doRender( array(
+                               'collection_id' => $collectionId,
+                               'force_render' => true
+                       )
+               );
+       }
+
+       protected function doRender( array $params ) {
+               global $wgScriptPath, $wgScriptExtension, $wgContLang;
+
+               $params['base_url'] = wfExpandUrl( $wgScriptPath, PROTO_CURRENT 
);
+               $params['script_extension'] = $wgScriptExtension;
+               $params['language'] = $wgContLang->getCode();
+               return $this->makeRequest( 'render', $params );
+       }
+
+       /**
+        * Requests the service to create a collection package and send it to 
an external server
+        * e.g. for printing
+        *
+        * @param $collection
+        * @param $url
+        *
+        * @return CollectionAPIResult
+        */
+       public function postZip( $collection, $url ) {
+               global $wgScriptPath, $wgScriptExtension;
+
+               return $this->makeRequest( 'zip_post',
+                       array(
+                               'metabook' => $this->buildJSONCollection( 
$collection ),
+                               'base_url' => wfExpandUrl( $wgScriptPath, 
PROTO_CURRENT ),
+                               'script_extension' => $wgScriptExtension,
+                               'pod_api_url' => $url,
+                       )
+               );
+       }
+
+       /**
+        * Returns inromation about a collection's rendering status
+        *
+        * @param $collectionId
+        * @return CollectionAPIResult
+        */
+       public function getRenderStatus( $collectionId ) {
+               return $this->makeRequest( 'render_status',
+                       array(
+                               'collection_id' => $collectionId,
+                       ),
+                       'CollectionStatusAPIResult'
+               );
+       }
+
+       /**
+        * Requests a download of rendered collection
+        *
+        * @param $collectionId
+        * @return CollectionAPIResult
+        */
+       public function download( $collectionId ) {
+               return $this->makeRequest( 'download',
+                       array(
+                               'collection_id' => $collectionId,
+                       )
+               );
+       }
+
+       /**
+        * @return array
+        */
+       protected function getLicenseInfos() {
+               global $wgCollectionLicenseName, $wgCollectionLicenseURL, 
$wgRightsIcon;
+               global $wgRightsPage, $wgRightsText, $wgRightsUrl;
+
+               $licenseInfo = array(
+                       'type' => 'license',
+               );
+
+               $fromMsg = wfMessage( 'coll-license_url' )->inContentLanguage();
+               if ( !$fromMsg->isDisabled() ) {
+                       $licenseInfo['mw_license_url'] = $fromMsg->text();
+                       return array( $licenseInfo );
+               }
+
+               if ( $wgCollectionLicenseName ) {
+                       $licenseInfo['name'] = $wgCollectionLicenseName;
+               } else {
+                       $licenseInfo['name'] = wfMessage( 'coll-license' 
)->inContentLanguage()->text();
+               }
+
+               if ( $wgCollectionLicenseURL ) {
+                       $licenseInfo['mw_license_url'] = 
$wgCollectionLicenseURL;
+               } else {
+                       $licenseInfo['mw_rights_icon'] = $wgRightsIcon;
+                       $licenseInfo['mw_rights_page'] = $wgRightsPage;
+                       $licenseInfo['mw_rights_url'] = $wgRightsUrl;
+                       $licenseInfo['mw_rights_text'] = $wgRightsText;
+               }
+
+               return array( $licenseInfo );
+       }
+
+       /**
+        * @param $collection array
+        * @return string
+        */
+       protected function buildJSONCollection( $collection ) {
+               $result = array(
+                       'type' => 'collection',
+                       'licenses' => $this->getLicenseInfos()
+               );
+
+               if ( isset( $collection['title'] ) ) {
+                       $result['title'] = $collection['title'];
+               }
+               if ( isset( $collection['subtitle'] ) ) {
+                       $result['subtitle'] = $collection['subtitle'];
+               }
+
+               $items = array();
+               if ( isset( $collection['items'] ) ) {
+                       $currentChapter = null;
+                       foreach ( $collection['items'] as $item ) {
+                               if ( $item['type'] == 'article' ) {
+                                       if ( is_null( $currentChapter ) ) {
+                                               $items[] = $item;
+                                       } else {
+                                               $currentChapter['items'][] = 
$item;
+                                       }
+                               } elseif ( $item['type'] == 'chapter' ) {
+                                       if ( !is_null( $currentChapter ) ) {
+                                               $items[] = $currentChapter;
+                                       }
+                                       $currentChapter = $item;
+                               }
+                       }
+                       if ( !is_null( $currentChapter ) ) {
+                               $items[] = $currentChapter;
+                       }
+               }
+               $result['items'] = $items;
+
+               return FormatJson::encode( $result );
+       }
+}
+
+/**
+ * API for PediaPress' mw-serve
+ */
+class MWServeRenderingAPI extends CollectionRenderingAPI {
+       protected function makeRequest( $command, array $params ) {
+               global $wgCollectionMWServeURL, 
$wgCollectionMWServeCredentials, $wgCollectionFormatToServeURL;
+
+               wfProfileIn( __METHOD__ . "-$command" );
+               $serveURL = $wgCollectionMWServeURL;
+               if ( $this->writer ) {
+                       if ( isset( $wgCollectionFormatToServeURL[ 
$this->writer ] ) ) {
+                               $serveURL = $wgCollectionFormatToServeURL[ 
$this->writer ];
+                       }
+                       $args['writer'] = $this->writer;
+               }
+
+               $args['command'] = $command;
+               if ( $wgCollectionMWServeCredentials ) {
+                       $args['login_credentials'] = 
$wgCollectionMWServeCredentials;
+               }
+               $response = Http::post( $serveURL, array( 'postData' => $args ) 
);
+               if ( $response === false ) {
+                       wfDebugLog( 'collection', "Request to $serveURL 
resulted in error" );
+               }
+               $result = new CollectionAPIResult( $response );
+               wfProfileOut( __METHOD__ . "-$command" );
+
+               return $result;
+       }
+}
+
+/*
+class NewRenderingAPI extends CollectionRenderingAPI {}
+*/
+
+/**
+ * A wrapper for data returned by the API
+ */
+class CollectionAPIResult {
+       /** @var array: Decoded JSON returned by server */
+       public $response = array();
+
+       /**
+        * @param string|null $data: Data returned by HTTP request
+        */
+       public function __construct( $data ) {
+               if ( $data ) {
+                       $this->response = FormatJson::decode( $data, true );
+                       if ( $this->response === null ) {
+                               wfDebugLog( 'collection', "Server returned 
bogus data: $data" );
+                               $this->response = null;
+                       }
+                       if ( $this->isError() ) {
+                               wfDebugLog( 'collection', "Server returned 
error: {$this->getError()}" );
+                       }
+               }
+       }
+
+       /**
+        * Returns data for specified key(s)
+        * Has variable number of parameters, e.g. get( 'foo', 'bar', 'baz' )
+        * @param string $key
+        * @return mixed
+        */
+       public function get( $key /*, ... */ ) {
+               $args = func_get_args();
+               $val = $this->response;
+               foreach( $args as $arg ) {
+                       if ( !isset( $val[$arg] ) ) {
+                               return '';
+                       }
+                       $val = $val[$arg];
+               }
+               return $val;
+       }
+
+       /**
+        * @return bool
+        */
+       public function isError() {
+               return !$this->response
+                       || ( isset( $this->response['error'] ) && 
$this->response['error'] );
+       }
+
+       /**
+        * @return string: Internal (not user-facing) error description
+        */
+       protected function getError() {
+               if ( isset ( $this->response['error'] ) ) {
+                       return $this->response['error'];
+               }
+               return '(error unknown)';
+       }
+}

-- 
To view, visit https://gerrit.wikimedia.org/r/95483
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I2a5bced4d1795f715564e331985c71df240ae332
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/extensions/Collection
Gerrit-Branch: master
Gerrit-Owner: MaxSem <[email protected]>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to