summaryrefslogtreecommitdiff
path: root/includes/filerepo/ForeignAPIRepo.php
blob: 6fc9c46528482ff4ff98bf2b190d34c25adc2e89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<?php

/**
 * A foreign repository with a remote MediaWiki with an API thingy
 * Very hacky and inefficient
 * do not use except for testing :D
 *
 * Example config:
 *
 * $wgForeignFileRepos[] = array(
 *   'class'                  => 'ForeignAPIRepo',
 *   'name'                   => 'shared',
 *   'apibase'                => 'http://en.wikipedia.org/w/api.php',
 *   'fetchDescription'       => true, // Optional
 *   'descriptionCacheExpiry' => 3600,
 * );
 *
 * @ingroup FileRepo
 */
class ForeignAPIRepo extends FileRepo {
	var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
	var $apiThumbCacheExpiry = 0;
	protected $mQueryCache = array();
	
	function __construct( $info ) {
		parent::__construct( $info );
		$this->mApiBase = $info['apibase']; // http://commons.wikimedia.org/w/api.php
		if( !$this->scriptDirUrl ) {
			// hack for description fetches
			$this->scriptDirUrl = dirname( $this->mApiBase );
		}
	}

/**
 * No-ops
 */
	function storeBatch( $triplets, $flags = 0 ) {
		return false;
	}
	function storeTemp( $originalName, $srcPath ) {
		return false;
	}
	function publishBatch( $triplets, $flags = 0 ) {
		return false;
	}
	function deleteBatch( $sourceDestPairs ) {
		return false;
	}
	function getFileProps( $virtualUrl ) {
		return false;
	}
	
	protected function queryImage( $query ) {
		$data = $this->fetchImageQuery( $query );
		
		if( isset( $data['query']['pages'] ) ) {
			foreach( $data['query']['pages'] as $pageid => $info ) {
				if( isset( $info['imageinfo'][0] ) ) {
					return $info['imageinfo'][0];
				}
			}
		}
		return false;
	}
	
	protected function fetchImageQuery( $query ) {
		global $wgMemc;
		
		$url = $this->mApiBase .
			'?' .
			wfArrayToCgi(
				array_merge( $query,
					array(
						'format' => 'json',
						'action' => 'query' ) ) );
		
		if( !isset( $this->mQueryCache[$url] ) ) {
			$key = wfMemcKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
			$data = $wgMemc->get( $key );
			if( !$data ) {
				$data = Http::get( $url );
				if ( !$data ) {
					return null;
				}
				$wgMemc->set( $key, $data, 3600 );
			}

			if( count( $this->mQueryCache ) > 100 ) {
				// Keep the cache from growing infinitely
				$this->mQueryCache = array();
			}
			$this->mQueryCache[$url] = $data;
		}
		return json_decode( $this->mQueryCache[$url], true );
	}
	
	function getImageInfo( $title, $time = false ) {
		return $this->queryImage( array(
			'titles' => 'Image:' . $title->getText(),
			'iiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
			'prop' => 'imageinfo' ) );
	}
	
	function findBySha1( $hash ) {
		$results = $this->fetchImageQuery( array(
										'aisha1base36' => $hash,
										'aiprop'       => 'timestamp|user|comment|url|size|sha1|metadata|mime',
										'list'         => 'allimages', ) );
		$ret = array();
		if ( isset( $results['query']['allimages'] ) ) {
			foreach ( $results['query']['allimages'] as $img ) {
				$ret[] = new ForeignAPIFile( Title::makeTitle( NS_IMAGE, $img['name'] ), $this, $img );
			}
		}
		return $ret;
	}
	
	function getThumbUrl( $name, $width=-1, $height=-1 ) {
		$info = $this->queryImage( array(
			'titles' => 'Image:' . $name,
			'iiprop' => 'url',
			'iiurlwidth' => $width,
			'iiurlheight' => $height,
			'prop' => 'imageinfo' ) );
		if( $info ) {
			wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
			return $info['thumburl'];
		} else {
			return false;
		}
	}
	
	function getThumbUrlFromCache( $name, $width, $height ) {
		global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
		
		if ( !$this->canCacheThumbs() ) {
			return $this->getThumbUrl( $name, $width, $height );
		}
		
		$key = wfMemcKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
		if ( $thumbUrl = $wgMemc->get($key) ) {
			wfDebug("Got thumb from local cache. $thumbUrl \n");
			return $thumbUrl;
		}
		else {
			$foreignUrl = $this->getThumbUrl( $name, $width, $height );
			
			// We need the same filename as the remote one :)
			$fileName = ltrim( substr( $foreignUrl, strrpos( $foreignUrl, '/' ) ), '/' );
			$path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
			if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
				wfMkdirParents($wgUploadDirectory . '/' . $path);
			}
			if ( !is_writable( $wgUploadDirectory . '/' . $path . $fileName ) ) {
				wfDebug( __METHOD__ . " could not write to thumb path\n" );
				return $foreignUrl;
			}
			$localUrl =  $wgServer . $wgUploadPath . '/' . $path . $fileName;
			$thumb = Http::get( $foreignUrl );
			# FIXME: Delete old thumbs that aren't being used. Maintenance script?
			file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb );
			$wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
			wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
			return $localUrl;
		}
	}
	
	/**
	 * Are we locally caching the thumbnails?
	 * @return bool
	 */
	public function canCacheThumbs() {
		return ( $this->apiThumbCacheExpiry > 0 );
	}
}