jenkins-bot has submitted this change and it was merged. ( 
https://gerrit.wikimedia.org/r/320326 )

Change subject: Add API endpoints
......................................................................


Add API endpoints

Bug: T144865
Change-Id: Icc3b078180c3ddb7f30c82f6033a931be09e5f22
---
M extension.json
M i18n/en.json
M i18n/qqq.json
A includes/ApiQueryMostViewed.php
A includes/ApiQueryPageViews.php
A includes/ApiQuerySiteViews.php
M includes/CachedPageViewService.php
M includes/Hooks.php
M includes/ServiceWiring.php
M includes/WikimediaPageViewService.php
10 files changed, 436 insertions(+), 9 deletions(-)

Approvals:
  jenkins-bot: Verified
  Anomie: Looks good to me, approved



diff --git a/extension.json b/extension.json
index 923ef1c..f585d45 100644
--- a/extension.json
+++ b/extension.json
@@ -9,13 +9,22 @@
        "Hooks": {
                "InfoAction": [
                        
"MediaWiki\\Extensions\\PageViewInfo\\Hooks::onInfoAction"
+               ],
+               "ApiQuery::moduleManager": [
+                       
"MediaWiki\\Extensions\\PageViewInfo\\Hooks::onApiQueryModuleManager"
+               ],
+               "APIQuerySiteInfoGeneralInfo": [
+                       
"MediaWiki\\Extensions\\PageViewInfo\\Hooks::onAPIQuerySiteInfoGeneralInfo"
                ]
        },
        "AutoloadClasses": {
                "MediaWiki\\Extensions\\PageViewInfo\\Hooks": 
"includes/Hooks.php",
                "MediaWiki\\Extensions\\PageViewInfo\\PageViewService": 
"includes/PageViewService.php",
                "MediaWiki\\Extensions\\PageViewInfo\\CachedPageViewService": 
"includes/CachedPageViewService.php",
-               
"MediaWiki\\Extensions\\PageViewInfo\\WikimediaPageViewService": 
"includes/WikimediaPageViewService.php"
+               
"MediaWiki\\Extensions\\PageViewInfo\\WikimediaPageViewService": 
"includes/WikimediaPageViewService.php",
+               "MediaWiki\\Extensions\\PageViewInfo\\ApiQueryMostViewed": 
"includes/ApiQueryMostViewed.php",
+               "MediaWiki\\Extensions\\PageViewInfo\\ApiQuerySiteViews": 
"includes/ApiQuerySiteViews.php",
+               "MediaWiki\\Extensions\\PageViewInfo\\ApiQueryPageViews": 
"includes/ApiQueryPageViews.php"
        },
        "MessagesDirs": {
                "PageViewInfo": [
@@ -48,9 +57,14 @@
                "includes/ServiceWiring.php"
        ],
        "config": {
+               "@PageViewInfoWikimediaEndpoint": "URL of the Wikimedia 
Pageview API - see https://wikitech.wikimedia.org/wiki/Analytics/PageviewAPI";,
                "PageViewInfoWikimediaEndpoint": 
"https://wikimedia.org/api/rest_v1";,
+               "@PageViewInfoWikimediaDomain": "Domain name to request data 
for from the Wikimedia Pageview API, or false to fall back to $wgServerName. 
This is mainly meant for testing.",
                "PageViewInfoWikimediaDomain": false,
-               "PageViewInfoWikimediaRequestLimit": 5
+               "@PageViewInfoWikimediaRequestLimit": "Max number of calls to 
make to the Wikimedia Pageview API in a single request (false for unlimited).",
+               "PageViewInfoWikimediaRequestLimit": 5,
+               "@PageViewApiMaxDays": "Max number of days to return in the 
API.",
+               "PageViewApiMaxDays": 60
        },
        "manifest_version": 1
 }
diff --git a/i18n/en.json b/i18n/en.json
index 02f836c..1d67683 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -10,5 +10,18 @@
        "pvi-range": "$1 - $2",
        "pvi-invalidresponse": "Invalid response",
        "pvi-cached-error": "An earlier attempt to fetch this data failed. To 
limit server load, retries have been blocked for $1.",
-       "pvi-cached-error-title": "An earlier attempt to fetch page \"$1\" 
failed. To limit server load, retries have been blocked for $2."
+       "pvi-cached-error-title": "An earlier attempt to fetch page \"$1\" 
failed. To limit server load, retries have been blocked for $2.",
+       "apihelp-pageviewinfo-param-metric": "The metric to use for counting 
views. Depending on what backend is used, not all metrics might be supported. 
You can use the siteinfo API 
([[Special:ApiHelp/query+siteinfo|action=query&meta=siteinfo]]) to check, under 
<samp>pageviewservice-supported-metrics</samp> / <module name>",
+       "apihelp-pageviewinfo-paramvalue-metric-pageviews": "Plain pageviews.",
+       "apihelp-pageviewinfo-paramvalue-metric-uniques": "Unique visitors.",
+       "apihelp-pageviewinfo-param-days": "The number of days to show.",
+       "apihelp-query+pageviews-description": "Shows per-page pageview data 
(the number of daily pageviews for each of the last <var>$1days</var> days). 
The result format is page title (with underscores) => date (Ymd) => count.",
+       "apihelp-query+pageviews-example": "Show pageview statistics for the 
main page.",
+       "apihelp-query+siteviews-description": "Shows sitewide pageview data 
(daily pageview totals for each of the last <var>$1days</var> days). The result 
format is date (Ymd) => count.",
+       "apihelp-query+siteviews-example": "Show sitewide pageview totals.",
+       "apihelp-query+siteviews-example2": "Show sitewide unique visitor 
totals.",
+       "apihelp-query+mostviewed-description": "Lists the most viewed pages 
(based on last day's pageview count).",
+       "apihelp-query+mostviewed-param-limit" : "The number of pages to 
return.",
+       "apihelp-query+mostviewed-example": "List the top 10 pages.",
+       "apihelp-query+mostviewed-example2": "Show pageview data for each of 
the top 10 pages."
 }
diff --git a/i18n/qqq.json b/i18n/qqq.json
index 6a186c0..a55bb56 100644
--- a/i18n/qqq.json
+++ b/i18n/qqq.json
@@ -11,5 +11,18 @@
        "pvi-range": "Title of dialog, which is the date range the graph is 
for. $1 is the starting date, $2 is the ending date.",
        "pvi-invalidresponse": "Error message when the REST API response data 
does not have the expected structure.",
        "pvi-cached-error": "Shown when the cached result is an error. $1 is 
the retry delay in human-readable form (e.g. \"30 minutes\").",
-       "pvi-cached-error-title": "Shown when the cached result (which is part 
of a larger resultset) is an error. $1 is the page name, $2 the retry delay in 
human-readable form (e.g. \"30 minutes\")."
+       "pvi-cached-error-title": "Shown when the cached result (which is part 
of a larger resultset) is an error. $1 is the page name, $2 the retry delay in 
human-readable form (e.g. \"30 minutes\").",
+       "apihelp-pageviewinfo-param-metric": 
"{{doc-apihelp-param|query+pageviews|metric|paramvalues=1|description=Also used 
for the <code>query+siteviews</code> and <code>query+mostviewed</code> 
modules.|noseealso=1}}",
+       "apihelp-pageviewinfo-paramvalue-metric-pageviews": 
"{{doc-apihelp-paramvalue|query+pageviews|metric|pageviews|description=Also 
used for the <code>query+siteviews</code> and <code>query+mostviewed</code> 
modules.|noseealso=1}}",
+       "apihelp-pageviewinfo-paramvalue-metric-uniques": 
"{{doc-apihelp-paramvalue|query+pageviews|metric|uniques|description=Also used 
for the <code>query+siteviews</code> and <code>query+mostviewed</code> 
modules.|noseealso=1}}",
+       "apihelp-pageviewinfo-param-days": 
"{{doc-apihelp-param|query+pageviews|days|description=Also used for the 
<code>query+siteviews</code> module.|noseealso=1}}",
+       "apihelp-query+pageviews-description": 
"{{doc-apihelp-description|query+pageviews}}",
+       "apihelp-query+pageviews-example": 
"{{doc-apihelp-example|query+pageviews}}",
+       "apihelp-query+siteviews-description": 
"{{doc-apihelp-description|query+siteviews}}",
+       "apihelp-query+siteviews-example": 
"{{doc-apihelp-example|query+siteviews}}",
+       "apihelp-query+siteviews-example2": 
"{{doc-apihelp-example|query+siteviews}}",
+       "apihelp-query+mostviewed-description": 
"{{doc-apihelp-description|query+mostviewed}}",
+       "apihelp-query+mostviewed-param-limit" : 
"{{doc-apihelp-param|query+mostviewed|limit}}",
+       "apihelp-query+mostviewed-example": 
"{{doc-apihelp-example|query+mostviewed}}",
+       "apihelp-query+mostviewed-example2": 
"{{doc-apihelp-example|query+mostviewed}}"
 }
diff --git a/includes/ApiQueryMostViewed.php b/includes/ApiQueryMostViewed.php
new file mode 100644
index 0000000..ff04fa5
--- /dev/null
+++ b/includes/ApiQueryMostViewed.php
@@ -0,0 +1,104 @@
+<?php
+
+namespace MediaWiki\Extensions\PageViewInfo;
+
+use ApiBase;
+use ApiPageSet;
+use ApiQueryGeneratorBase;
+use MediaWiki\MediaWikiServices;
+use Title;
+
+/**
+ * Expose PageViewService::getTopPages().
+ */
+class ApiQueryMostViewed extends ApiQueryGeneratorBase {
+       public function __construct( $query, $moduleName ) {
+               parent::__construct( $query, $moduleName, 'pvim' );
+       }
+
+       public function execute() {
+               $this->run();
+       }
+
+       public function executeGenerator( $resultPageSet ) {
+               $this->run( $resultPageSet );
+       }
+
+       /**
+        * @param ApiPageSet|null $resultPageSet
+        */
+       private function run( ApiPageSet $resultPageSet = null ) {
+               /** @var PageViewService $service */
+               $service = MediaWikiServices::getInstance()->getService( 
'PageViewService' );
+               $metric = Hooks::getApiMetricsMap()[$this->getParameter( 
'metric' )];
+               $status = $service->getTopPages( $metric );
+
+               if ( $status->isOK() ) {
+                       $this->addMessagesFromStatus( 
Hooks::makeWarningsOnlyStatus( $status ) );
+                       $limit = $this->getParameter( 'limit' );
+                       $offset = $this->getParameter( 'offset' );
+
+                       $data = $status->getValue();
+                       if ( count( $data ) > $offset + $limit ) {
+                               $this->setContinueEnumParameter( 'offset', 
$offset + $limit );
+                       }
+                       $data = array_slice( $data, $offset, $limit, true );
+
+                       if ( $resultPageSet ) {
+                               $titles = [];
+                               foreach ( $data as $title => $_ ) {
+                                       $titles[] = Title::newFromText( $title 
);
+                               }
+                               $resultPageSet->populateFromTitles( $titles );
+                       } else {
+                               $result = $this->getResult();
+                               $result->addIndexedTagName( [ 'query', 
$this->getModuleName() ], 'page' );
+                               foreach ( $data as $title => $titleData ) {
+                                       $item = [];
+                                       self::addTitleInfo( $item, 
\Title::newFromText( $title ) );
+                                       $item['count'] = $titleData;
+                                       $fits = $result->addValue( [ 'query', 
$this->getModuleName() ], null, $item );
+                                       if ( !$fits ) {
+                                               
$this->setContinueEnumParameter( 'offset', $offset );
+                                               break;
+                                       }
+                                       $offset++;
+                               }
+                       }
+               } else {
+                       $this->dieStatus( $status );
+               }
+       }
+
+       public function getCacheMode( $params ) {
+               return 'public';
+       }
+
+       public function getAllowedParams() {
+               return Hooks::getApiMetricsHelp( PageViewService::SCOPE_TOP ) + 
[
+                       'limit' => [
+                               ApiBase::PARAM_DFLT => 10,
+                               ApiBase::PARAM_TYPE => 'limit',
+                               ApiBase::PARAM_MIN => 1,
+                               ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
+                               ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2,
+                       ],
+                       'offset' => [
+                               ApiBase::PARAM_DFLT => 0,
+                               ApiBase::PARAM_TYPE => 'integer',
+                               ApiBase::PARAM_HELP_MSG => 
'api-help-param-continue',
+                       ],
+               ];
+       }
+
+       protected function getExamplesMessages() {
+               return [
+                       'action=query&list=mostviewed' => 
'apihelp-query+mostviewed-example',
+                       'action=query&generator=mostviewed&prop=pageviews' => 
'apihelp-query+mostviewed-example2',
+               ];
+       }
+
+       public function getHelpUrls() {
+               return 'https://www.mediawiki.org/wiki/Extension:PageViewInfo';
+       }
+}
diff --git a/includes/ApiQueryPageViews.php b/includes/ApiQueryPageViews.php
new file mode 100644
index 0000000..1c452db
--- /dev/null
+++ b/includes/ApiQueryPageViews.php
@@ -0,0 +1,99 @@
+<?php
+
+namespace MediaWiki\Extensions\PageViewInfo;
+
+use ApiBase;
+use ApiQueryBase;
+use ApiResult;
+use MediaWiki\MediaWikiServices;
+use StatusValue;
+use Title;
+
+/**
+ * Expose PageViewService::getPageData().
+ */
+class ApiQueryPageViews extends ApiQueryBase {
+       public function __construct( $query, $moduleName ) {
+               parent::__construct( $query, $moduleName, 'pvip' );
+       }
+
+       public function execute() {
+               $continue = $this->getParameter( 'continue' );
+               $titles = $this->getPageSet()->getMissingTitles()
+                       + $this->getPageSet()->getSpecialTitles()
+                       + $this->getPageSet()->getGoodTitles();
+
+               // sort titles alphabetically and discard those already 
processed in a previous request
+               $indexToTitle = array_map( function( Title $t ) {
+                       return $t->getPrefixedDBkey();
+               }, $titles );
+               asort( $indexToTitle );
+               $indexToTitle = array_filter( $indexToTitle, function ( $title 
) use ( $continue ) {
+                       return $title >= $continue;
+               } );
+               $titleToIndex = array_flip( $indexToTitle );
+               $titles = array_filter( array_values( array_map( function ( 
$index ) use ( $titles ) {
+                       return isset( $titles[$index] ) ? $titles[$index] : 
null;
+               }, $titleToIndex ) ) );
+
+               /** @var PageViewService $service */
+               $service = MediaWikiServices::getInstance()->getService( 
'PageViewService' );
+               $metric = Hooks::getApiMetricsMap()[$this->getParameter( 
'metric' )];
+               $status = $service->getPageData( $titles, $this->getParameter( 
'days' ), $metric );
+               if ( $status->isOK() ) {
+                       $this->addMessagesFromStatus( 
Hooks::makeWarningsOnlyStatus( $status ) );
+                       $data = $status->getValue();
+                       foreach ( $titles as $title ) {
+                               $index = 
$titleToIndex[$title->getPrefixedDBkey()];
+                               $fit = $this->addData( $index, $title, $data );
+                               if ( !$fit ) {
+                                       $this->setContinueEnumParameter( 
'continue', $title->getPrefixedDBkey() );
+                                       break;
+                               }
+                       }
+               } else {
+                       $this->dieStatus( $status );
+               }
+       }
+
+       /**
+        * @param int $index Pageset ID (real or fake)
+        * @param Title $title
+        * @param array $data Data for all titles.
+        * @return bool Success.
+        */
+       protected function addData( $index, Title $title, array $data ) {
+               if ( !isset( $data[$title->getPrefixedDBkey()] ) ) {
+                       // PageViewService retains the ordering of titles so 
the first missing title means we
+                       // have run out of data.
+                       return false;
+               }
+               $value = $data[$title->getPrefixedDBkey()];
+               ApiResult::setArrayType( $value, 'kvp', 'date' );
+               ApiResult::setIndexedTagName( $value, 'count' );
+               $retval = $this->addPageSubItems( $index, $value );
+               return $retval;
+       }
+
+       public function getCacheMode( $params ) {
+               return 'public';
+       }
+
+       public function getAllowedParams() {
+               return Hooks::getApiMetricsHelp( PageViewService::SCOPE_ARTICLE 
) + Hooks::getApiDaysHelp() + [
+                       'continue' => [
+                               ApiBase::PARAM_HELP_MSG => 
'api-help-param-continue',
+                       ],
+               ];
+       }
+
+       protected function getExamplesMessages() {
+               return [
+                       'action=query&title=Main_Page&prop=pageviews' => 
'apihelp-query+pageviews-example',
+               ];
+       }
+
+       public function getHelpUrls() {
+               return 'https://www.mediawiki.org/wiki/Extension:PageViewInfo';
+       }
+}
diff --git a/includes/ApiQuerySiteViews.php b/includes/ApiQuerySiteViews.php
new file mode 100644
index 0000000..8fe2940
--- /dev/null
+++ b/includes/ApiQuerySiteViews.php
@@ -0,0 +1,53 @@
+<?php
+
+namespace MediaWiki\Extensions\PageViewInfo;
+
+use ApiBase;
+use ApiQueryBase;
+use ApiResult;
+use MediaWiki\MediaWikiServices;
+
+/**
+ * Expose PageViewService::getSiteData().
+ */
+class ApiQuerySiteViews extends ApiQueryBase  {
+       public function __construct( $query, $moduleName ) {
+               parent::__construct( $query, $moduleName, 'pvis' );
+       }
+
+       public function execute() {
+               /** @var PageViewService $service */
+               $service = MediaWikiServices::getInstance()->getService( 
'PageViewService' );
+               $metric = Hooks::getApiMetricsMap()[$this->getParameter( 
'metric' )];
+               $status = $service->getSiteData( $this->getParameter( 'days' ), 
$metric );
+               if ( $status->isOK() ) {
+                       $this->addMessagesFromStatus( 
Hooks::makeWarningsOnlyStatus( $status ) );
+                       $result = $this->getResult();
+                       $value = $status->getValue();
+                       ApiResult::setArrayType( $value, 'kvp', 'date' );
+                       ApiResult::setIndexedTagName( $value, 'count' );
+                       $result->addValue( 'query', $this->getModuleName(), 
$value );
+               } else {
+                       $this->dieStatus( $status );
+               }
+       }
+
+       public function getCacheMode( $params ) {
+               return 'public';
+       }
+
+       public function getAllowedParams() {
+               return Hooks::getApiMetricsHelp( PageViewService::SCOPE_SITE ) 
+ Hooks::getApiDaysHelp();
+       }
+
+       protected function getExamplesMessages() {
+               return [
+                       'action=query&meta=siteviews' => 
'apihelp-query+siteviews-example',
+                       'action=query&meta=siteviews&metric=uniques' => 
'apihelp-query+siteviews-example2',
+               ];
+       }
+
+       public function getHelpUrls() {
+               return 'https://www.mediawiki.org/wiki/Extension:PageViewInfo';
+       }
+}
diff --git a/includes/CachedPageViewService.php 
b/includes/CachedPageViewService.php
index b3fb540..77f3b58 100644
--- a/includes/CachedPageViewService.php
+++ b/includes/CachedPageViewService.php
@@ -141,7 +141,7 @@
         * @param Title[] $titles
         * @return StatusValue
         */
-       protected function getTitlesWithCache( $metric, array $titles = null ) {
+       protected function getTitlesWithCache( $metric, array $titles ) {
                // Set up the response array, without any values. This will 
help preserve the order of titles.
                $data = array_fill_keys( array_map( function ( Title $t ) {
                        return $t->getPrefixedDBkey();
@@ -161,7 +161,7 @@
                        // assume some implementations might return that key 
with a value of false
                        if ( $value !== false ) {
                                $statuses[$cacheKeyToTitle[$key]] = empty( 
$value['#error'] ) ? StatusValue::newGood()
-                                       : StatusValue::newFatal( 
'pvi-cached-error-title', $cacheKeyToTitle[$key],
+                                       : StatusValue::newFatal( 
'pvi-cached-error-title', wfEscapeWikiText( $cacheKeyToTitle[$key] ),
                                                \Message::durationParam( 
self::ERROR_EXPIRY ) );
                                unset( $value['#error'] );
                                $data[$cacheKeyToTitle[$key]] = $value;
@@ -194,7 +194,7 @@
                                $expiry = $this->getCacheExpiry( $metric, 
self::SCOPE_ARTICLE );
                        } else {
                                $data[$title]['#error'] = true;
-                               $statuses[$title] = StatusValue::newFatal( 
'pvi-cached-error-title', $title,
+                               $statuses[$title] = StatusValue::newFatal( 
'pvi-cached-error-title', wfEscapeWikiText( $title ),
                                        \Message::durationParam( 
self::ERROR_EXPIRY ) );
                                $expiry = self::ERROR_EXPIRY;
                        }
@@ -216,7 +216,7 @@
                }, $statuses );
                $status->successCount = count( array_filter( $status->success ) 
);
                $status->failCount = count( $status->success ) - 
$status->successCount;
-               $status->setResult( array_filter( $status->success ), $data );
+               $status->setResult( $status->successCount || !$titles, $data );
                return $status;
        }
 
diff --git a/includes/Hooks.php b/includes/Hooks.php
index 7ec083e..919214d 100644
--- a/includes/Hooks.php
+++ b/includes/Hooks.php
@@ -2,13 +2,19 @@
 
 namespace MediaWiki\Extensions\PageViewInfo;
 
+use ApiBase;
+use ApiModuleManager;
+use ApiQuerySiteinfo;
 use IContextSource;
 use FormatJson;
 use Html;
 use MediaWiki\MediaWikiServices;
+use StatusValue;
+use User;
 
 class Hooks {
        /**
+        * Display total pageviews in the last 30 days and show a graph with 
details when clicked.
         * @param IContextSource $ctx
         * @param array $pageInfo
         */
@@ -62,6 +68,129 @@
        }
 
        /**
+        * Limit enabled PageViewInfo API modules to those which are supported 
by the service.
+        * @param ApiModuleManager $moduleManager
+        */
+       public static function onApiQueryModuleManager( ApiModuleManager 
$moduleManager ) {
+               $moduleMap = [
+                       'pageviews' => [ 'pageviews', 'prop', 
ApiQueryPageViews::class ],
+                       'siteviews' => [ 'siteviews', 'meta', 
ApiQuerySiteViews::class ],
+                       'mostviewed' => [ 'mostviewed', 'list', 
ApiQueryMostViewed::class ],
+               ];
+               /** @var PageViewService $service */
+               $service = MediaWikiServices::getInstance()->getService( 
'PageViewService' );
+               foreach ( self::getApiScopeMap() as $apiModuleName => 
$serviceScopeConstant ) {
+                       foreach ( self::getApiMetricsMap() as 
$serviceMetricConstant ) {
+                               if ( $service->supports( 
$serviceMetricConstant, $serviceScopeConstant ) ) {
+                                       call_user_func_array( [ $moduleManager, 
'addModule' ], $moduleMap[$apiModuleName] );
+                                       continue 2;
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Add information to the siteinfo API output about which metrics are 
supported.
+        * @param ApiQuerySiteinfo $module
+        * @param array $result
+        */
+       public static function onAPIQuerySiteInfoGeneralInfo( ApiQuerySiteinfo 
$module, array &$result ) {
+               /** @var PageViewService $service */
+               $service = MediaWikiServices::getInstance()->getService( 
'PageViewService' );
+               $supportedMetrics = [];
+               foreach ( self::getApiScopeMap() as $apiModuleName => 
$serviceScopeConstant ) {
+                       foreach ( self::getApiMetricsMap() as $apiMetricsName 
=> $serviceMetricConstant ) {
+                               
$supportedMetrics[$apiModuleName][$apiMetricsName] =
+                                       $service->supports( 
$serviceMetricConstant, $serviceScopeConstant );
+                       }
+               }
+               $result['pageviewservice-supported-metrics'] = 
$supportedMetrics;
+       }
+
+       /**
+        * Maps allowed values of the 'metric' parameter of the 
pageview-related APIs to service constants.
+        * @return array
+        */
+       public static function getApiMetricsMap() {
+               return [
+                       'pageviews' => PageViewService::METRIC_VIEW,
+                       'uniques' => PageViewService::METRIC_UNIQUE,
+               ];
+       }
+
+       /**
+        * Maps API module names to service constants.
+        * @return array
+        */
+       public static function getApiScopeMap() {
+               return [
+                       'pageviews' => PageViewService::SCOPE_ARTICLE,
+                       'siteviews' => PageViewService::SCOPE_SITE,
+                       'mostviewed' => PageViewService::SCOPE_TOP,
+               ];
+       }
+
+       /**
+        * Returns an array suitable for merging into getAllowedParams()
+        * @param string $scope One of the PageViewService::SCOPE_* constants
+        * @return array
+        */
+       public static function getApiMetricsHelp( $scope ) {
+               /** @var PageViewService $service */
+               $service = MediaWikiServices::getInstance()->getService( 
'PageViewService' );
+               $metrics = array_keys( array_filter( self::getApiMetricsMap(),
+                       function ( $metric ) use ( $scope, $service ) {
+                               return $service->supports( $metric, $scope );
+                       } ) );
+               $reverseMap = array_flip( self::getApiMetricsMap() );
+               $default = isset( $reverseMap[PageViewService::METRIC_VIEW] ) ?
+                       $reverseMap[PageViewService::METRIC_VIEW] : reset( 
$reverseMap );
+
+               return $default ? [
+                       'metric' => [
+                               ApiBase::PARAM_TYPE => $metrics,
+                               ApiBase::PARAM_DFLT => $default,
+                               ApiBase::PARAM_HELP_MSG => 
'apihelp-pageviewinfo-param-metric',
+                               ApiBase::PARAM_HELP_MSG_PER_VALUE => array_map( 
function ( $metric ) {
+                                       return 
'apihelp-pageviewinfo-paramvalue-metric-' . $metric;
+                               }, array_combine( $metrics, $metrics ) ),
+                       ],
+               ] : [];
+       }
+
+       /**
+        * Returns an array suitable for merging into getAllowedParams()
+        * @return array
+        */
+       public static function getApiDaysHelp() {
+               $days = 
MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 
'PageViewInfo' )
+                       ->get( 'PageViewApiMaxDays' );
+               return [
+                       'days' => [
+                               ApiBase::PARAM_TYPE => 'integer',
+                               ApiBase::PARAM_DFLT => $days,
+                               ApiBase::PARAM_MAX => $days,
+                               ApiBase::PARAM_MIN => 1,
+                               ApiBase::PARAM_HELP_MSG => 
'apihelp-pageviewinfo-param-days',
+                       ],
+               ];
+       }
+
+       /**
+        * Transform into a status with errors replaced with warnings
+        * @param StatusValue $status
+        * @return StatusValue
+        */
+       public static function makeWarningsOnlyStatus( StatusValue $status ) {
+               list( $errors, $warnings ) = $status->splitByErrorType();
+               foreach ( $errors->getErrors() as $error ) {
+                       call_user_func_array( [ $warnings, 'warning' ],
+                               array_merge( [ $error['message'] ], 
$error['params'] ) );
+               }
+               return $warnings;
+       }
+
+       /**
         * Convert YYYY-MM-DD to YYYYMMDD
         * @param string $date
         * @return string
diff --git a/includes/ServiceWiring.php b/includes/ServiceWiring.php
index 981aea9..6beabdd 100644
--- a/includes/ServiceWiring.php
+++ b/includes/ServiceWiring.php
@@ -15,11 +15,13 @@
                        ?: $mainConfig->get( 'ServerName' );
                $cache = ObjectCache::getLocalClusterInstance();
                $logger = LoggerFactory::getInstance( 'PageViewInfo' );
+               $cachedDays = max( 30, $extensionConfig->get( 
'PageViewApiMaxDays' ) );
 
                $service = new WikimediaPageViewService( $endpoint, [ 'project' 
=> $project ],
                        $extensionConfig->get( 
'PageViewInfoWikimediaRequestLimit' ) );
                $service->setLogger( $logger );
                $cachedService = new CachedPageViewService( $service, $cache );
+               $cachedService->setCachedDays( $cachedDays );
                $cachedService->setLogger( $logger );
                return $cachedService;
        },
diff --git a/includes/WikimediaPageViewService.php 
b/includes/WikimediaPageViewService.php
index 441a000..60e7cb3 100644
--- a/includes/WikimediaPageViewService.php
+++ b/includes/WikimediaPageViewService.php
@@ -293,7 +293,7 @@
                        ] + $prefixedApiErrorData );
                }
                if ( !$status->isOK() && isset( $apiErrorData['detail'] ) ) {
-                       $status->error( new \RawMessage( 
$apiErrorData['detail'] ) );
+                       $status->error( new \RawMessage( wfEscapeWikiText( 
$apiErrorData['detail'] ) ) );
                }
 
                return $status;

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

Gerrit-MessageType: merged
Gerrit-Change-Id: Icc3b078180c3ddb7f30c82f6033a931be09e5f22
Gerrit-PatchSet: 9
Gerrit-Project: mediawiki/extensions/PageViewInfo
Gerrit-Branch: master
Gerrit-Owner: GergÅ‘ Tisza <[email protected]>
Gerrit-Reviewer: Anomie <[email protected]>
Gerrit-Reviewer: GergÅ‘ Tisza <[email protected]>
Gerrit-Reviewer: Legoktm <[email protected]>
Gerrit-Reviewer: jenkins-bot <>

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

Reply via email to