Add descriptionCacheExpiry to configuration example to avoid 2 notices.
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2
3 /**
4 * A foreign repository with a remote MediaWiki with an API thingy
5 * Very hacky and inefficient
6 * do not use except for testing :D
7 *
8 * Example config:
9 *
10 * $wgForeignFileRepos[] = array(
11 * 'class' => 'ForeignAPIRepo',
12 * 'name' => 'shared',
13 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
14 * 'fetchDescription' => true, // Optional
15 * 'descriptionCacheExpiry' => 3600,
16 * );
17 *
18 * @ingroup FileRepo
19 */
20 class ForeignAPIRepo extends FileRepo {
21 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
22 protected $mQueryCache = array();
23
24 function __construct( $info ) {
25 parent::__construct( $info );
26 $this->mApiBase = $info['apibase']; // http://commons.wikimedia.org/w/api.php
27 if( !$this->scriptDirUrl ) {
28 // hack for description fetches
29 $this->scriptDirUrl = dirname( $this->mApiBase );
30 }
31 }
32
33 function storeBatch( $triplets, $flags = 0 ) {
34 return false;
35 }
36
37 function storeTemp( $originalName, $srcPath ) {
38 return false;
39 }
40 function publishBatch( $triplets, $flags = 0 ) {
41 return false;
42 }
43 function deleteBatch( $sourceDestPairs ) {
44 return false;
45 }
46 function getFileProps( $virtualUrl ) {
47 return false;
48 }
49
50 protected function queryImage( $query ) {
51 $data = $this->fetchImageQuery( $query );
52
53 if( isset( $data['query']['pages'] ) ) {
54 foreach( $data['query']['pages'] as $pageid => $info ) {
55 if( isset( $info['imageinfo'][0] ) ) {
56 return $info['imageinfo'][0];
57 }
58 }
59 }
60 return false;
61 }
62
63 protected function fetchImageQuery( $query ) {
64 global $wgMemc;
65
66 $url = $this->mApiBase .
67 '?' .
68 wfArrayToCgi(
69 array_merge( $query,
70 array(
71 'format' => 'json',
72 'action' => 'query',
73 'prop' => 'imageinfo' ) ) );
74
75 if( !isset( $this->mQueryCache[$url] ) ) {
76 $key = wfMemcKey( 'ForeignAPIRepo', $url );
77 $data = $wgMemc->get( $key );
78 if( !$data ) {
79 $data = Http::get( $url );
80 $wgMemc->set( $key, $data, 3600 );
81 }
82
83 if( count( $this->mQueryCache ) > 100 ) {
84 // Keep the cache from growing infinitely
85 $this->mQueryCache = array();
86 }
87 $this->mQueryCache[$url] = $data;
88 }
89 return json_decode( $this->mQueryCache[$url], true );
90 }
91
92 function getImageInfo( $title, $time = false ) {
93 return $this->queryImage( array(
94 'titles' => 'Image:' . $title->getText(),
95 'iiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime' ) );
96 }
97
98 function getThumbUrl( $name, $width=-1, $height=-1 ) {
99 $info = $this->queryImage( array(
100 'titles' => 'Image:' . $name,
101 'iiprop' => 'url',
102 'iiurlwidth' => $width,
103 'iiurlheight' => $height ) );
104 if( $info ) {
105 return $info['thumburl'];
106 } else {
107 return false;
108 }
109 }
110 }