Scripts and data used for generating ZhConversion.php
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 * $Id$
5 */
6
7 /**
8 * Class to represent an image
9 *
10 * Provides methods to retrieve paths (physical, logical, URL),
11 * to generate thumbnails or for uploading.
12 * @package MediaWiki
13 */
14 class Image
15 {
16 /* private */
17 var $name, # name of the image
18 $imagePath, # Path of the image
19 $url, # Image URL
20 $title, # Title object for this image. Initialized when needed.
21 $fileExists, # does the image file exist on disk?
22 $historyLine, # Number of line to return by nextHistoryLine()
23 $historyRes, # result of the query for the image's history
24 $width, # \
25 $height, # |
26 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
27 $type, # |
28 $attr; # /
29
30
31
32 function Image( $name )
33 {
34 global $wgUploadDirectory,$wgHashedUploadDirectory;
35
36 $this->name = $name;
37 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
38 //$this->imagePath = wfImagePath( $name );
39 if ($wgHashedUploadDirectory) {
40 $hash = md5( $this->title->getDBkey() );
41 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .
42 substr( $hash, 0, 2 ) . "/{$name}";
43 } else {
44 $this->imagePath = $wgUploadDirectory . '/' . $name;
45 }
46
47 $this->url = $this->wfImageUrl( $name );
48
49 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
50 {
51 @$gis = getimagesize( $this->imagePath );
52 if( $gis !== false ) {
53 $this->width = $gis[0];
54 $this->height = $gis[1];
55 $this->type = $gis[2];
56 $this->attr = $gis[3];
57 if ( isset( $gis['bits'] ) ) {
58 $this->bits = $gis['bits'];
59 } else {
60 $this->bits = 0;
61 }
62 }
63 }
64 $this->historyLine = 0;
65 }
66
67 function newFromTitle( $nt )
68 {
69 $img = new Image( $nt->getDBKey() );
70 $img->title = $nt;
71 return $img;
72 }
73
74 function getName()
75 {
76 return $this->name;
77 }
78
79 function getTitle()
80 {
81 return $this->title;
82 }
83
84 function getURL()
85 {
86 return $this->url;
87 }
88
89 function getImagePath()
90 {
91 return $this->imagePath;
92 }
93
94 function getWidth()
95 {
96 return $this->width;
97 }
98
99 function getHeight()
100 {
101 return $this->height;
102 }
103
104 function getSize()
105 {
106 $st = stat( $this->getImagePath() );
107 return $st['size'];
108 }
109
110 function getType()
111 {
112 return $this->type;
113 }
114
115 function getEscapeLocalURL()
116 {
117 return $this->title->escapeLocalURL();
118 }
119
120 function wfImageUrl( $name )
121 {
122 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory;
123 if ($wgHashedUploadDirectory) {
124 $hash = md5( $name );
125 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/" . $hash{0} . "/" .
126 substr( $hash, 0, 2 ) . "/{$name}";
127 } else {
128 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/{$name}";
129 }
130 return wfUrlencode( $url );
131 }
132
133 function exists()
134 {
135 return $this->fileExists;
136 }
137
138 function thumbUrl( $width, $subdir='thumb' ) {
139 global $wgUploadPath,$wgHashedUploadDirectory;
140 $name = $this->thumbName( $width );
141 if ($wgHashedUploadDirectory) {
142 $hash = md5( $name );
143 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
144 substr( $hash, 0, 2 ) . "/{$name}";
145 } else {
146 $url = "{$wgUploadPath}/{$subdir}/{$name}";
147 }
148
149 return wfUrlencode($url);
150 }
151
152 function thumbName( $width ) {
153 return $width."px-".$this->name;
154 }
155
156 function createThumb( $width, $height=-1 ) {
157 if ( $height == -1 ) {
158 return $this->renderThumb( $width );
159 }
160 if ( $width < $this->width ) {
161 $thumbheight = $this->height * $width / $this->width;
162 $thumbwidth = $width;
163 } else {
164 $thumbheight = $this->height;
165 $thumbwidth = $this->width;
166 }
167 if ( $thumbheight > $height ) {
168 $thumbwidth = $thumbwidth * $height / $thumbheight;
169 $thumbheight = $height;
170 }
171 return $this->renderThumb( $thumbwidth );
172 }
173
174 /**
175 * Create a thumbnail of the image having the specified width.
176 * The thumbnail will not be created if the width is larger than the
177 * image's width. Let the browser do the scaling in this case.
178 * The thumbnail is stored on disk and is only computed if the thumbnail
179 * file does not exist OR if it is older than the image.
180 * Returns the URL.
181 */
182 function /* private */ renderThumb( $width ) {
183 global $wgUploadDirectory;
184 global $wgImageMagickConvertCommand;
185 global $wgUseImageMagick;
186 global $wgUseSquid, $wgInternalServer;
187
188 $width = IntVal( $width );
189
190 $thumbName = $this->thumbName( $width );
191 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
192 $thumbUrl = $this->thumbUrl( $width );
193
194 if ( ! $this->exists() )
195 {
196 # If there is no image, there will be no thumbnail
197 return '';
198 }
199
200 # Sanity check $width
201 if( $width <= 0 ) {
202 # BZZZT
203 return '';
204 }
205
206 if( $width > $this->width ) {
207 # Don't make an image bigger than the source
208 return $this->getURL();
209 }
210
211 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
212 if ( $wgUseImageMagick ) {
213 # use ImageMagick
214 # Specify white background color, will be used for transparent images
215 # in Internet Explorer/Windows instead of default black.
216 $cmd = $wgImageMagickConvertCommand .
217 " -quality 85 -background white -geometry {$width} ".
218 escapeshellarg($this->imagePath) . " " .
219 escapeshellarg($thumbPath);
220 $conv = shell_exec( $cmd );
221 } else {
222 # Use PHP's builtin GD library functions.
223 #
224 # First find out what kind of file this is, and select the correct
225 # input routine for this.
226
227 $truecolor = false;
228
229 switch( $this->type ) {
230 case 1: # GIF
231 $src_image = imagecreatefromgif( $this->imagePath );
232 break;
233 case 2: # JPG
234 $src_image = imagecreatefromjpeg( $this->imagePath );
235 $truecolor = true;
236 break;
237 case 3: # PNG
238 $src_image = imagecreatefrompng( $this->imagePath );
239 $truecolor = ( $this->bits > 8 );
240 break;
241 case 15: # WBMP for WML
242 $src_image = imagecreatefromwbmp( $this->imagePath );
243 break;
244 case 16: # XBM
245 $src_image = imagecreatefromxbm( $this->imagePath );
246 break;
247 default:
248 return 'Image type not supported';
249 break;
250 }
251 $height = floor( $this->height * ( $width/$this->width ) );
252 if ( $truecolor ) {
253 $dst_image = imagecreatetruecolor( $width, $height );
254 } else {
255 $dst_image = imagecreate( $width, $height );
256 }
257 imagecopyresampled( $dst_image, $src_image,
258 0,0,0,0,
259 $width, $height, $this->width, $this->height );
260 switch( $this->type ) {
261 case 1: # GIF
262 case 3: # PNG
263 case 15: # WBMP
264 case 16: # XBM
265 #$thumbUrl .= ".png";
266 #$thumbPath .= ".png";
267 imagepng( $dst_image, $thumbPath );
268 break;
269 case 2: # JPEG
270 #$thumbUrl .= ".jpg";
271 #$thumbPath .= ".jpg";
272 imageinterlace( $dst_image );
273 imagejpeg( $dst_image, $thumbPath, 95 );
274 break;
275 default:
276 break;
277 }
278 imagedestroy( $dst_image );
279 imagedestroy( $src_image );
280
281
282 }
283 #
284 # Check for zero-sized thumbnails. Those can be generated when
285 # no disk space is available or some other error occurs
286 #
287 $thumbstat = stat( $thumbPath );
288 if( $thumbstat['size'] == 0 )
289 {
290 unlink( $thumbPath );
291 }
292
293 # Purge squid
294 # This has to be done after the image is updated and present for all machines on NFS,
295 # or else the old version might be stored into the squid again
296 if ( $wgUseSquid ) {
297 $urlArr = Array(
298 $wgInternalServer.$thumbUrl
299 );
300 wfPurgeSquidServers($urlArr);
301 }
302 }
303 return $thumbUrl;
304 } // END OF function createThumb
305
306 /**
307 * Return the image history of this image, line by line.
308 * starts with current version, then old versions.
309 * uses $this->historyLine to check which line to return:
310 * 0 return line for current version
311 * 1 query for old versions, return first one
312 * 2, ... return next old version from above query
313 */
314 function nextHistoryLine()
315 {
316 $fname = 'Image::nextHistoryLine()';
317 $dbr =& wfGetDB( DB_SLAVE );
318 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
319 $this->historyRes = $dbr->select( 'image',
320 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
321 array( 'img_name' => $this->title->getDBkey() ),
322 $fname
323 );
324 if ( 0 == wfNumRows( $this->historyRes ) ) {
325 return FALSE;
326 }
327 } else if ( $this->historyLine == 1 ) {
328 $this->historyRes = $dbr->select( 'oldimage',
329 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
330 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
331 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
332 );
333 }
334 $this->historyLine ++;
335
336 return $dbr->fetchObject( $this->historyRes );
337 }
338
339 function resetHistory()
340 {
341 $this->historyLine = 0;
342 }
343
344
345 } //class
346
347
348 function wfImageDir( $fname )
349 {
350 global $wgUploadDirectory, $wgHashedUploadDirectory;
351
352 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
353
354 $hash = md5( $fname );
355 $oldumask = umask(0);
356 $dest = $wgUploadDirectory . '/' . $hash{0};
357 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
358 $dest .= '/' . substr( $hash, 0, 2 );
359 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
360
361 umask( $oldumask );
362 return $dest;
363 }
364
365 function wfImageThumbDir( $fname , $subdir='thumb')
366 {
367 return wfImageArchiveDir( $fname, $subdir );
368 }
369
370 function wfImageArchiveDir( $fname , $subdir='archive')
371 {
372 global $wgUploadDirectory, $wgHashedUploadDirectory;
373
374 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory.'/'.$subdir; }
375
376 $hash = md5( $fname );
377 $oldumask = umask(0);
378
379 # Suppress warning messages here; if the file itself can't
380 # be written we'll worry about it then.
381 $archive = $wgUploadDirectory.'/'.$subdir;
382 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
383 $archive .= '/' . $hash{0};
384 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
385 $archive .= '/' . substr( $hash, 0, 2 );
386 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
387
388 umask( $oldumask );
389 return $archive;
390 }
391
392 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
393 {
394 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
395 global $wgUseCopyrightUpload;
396
397 $fname = 'wfRecordUpload';
398 $dbw =& wfGetDB( DB_MASTER );
399
400 # img_name must be unique
401 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
402 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
403 }
404
405
406 $now = wfTimestampNow();
407 $won = wfInvertTimestamp( $now );
408 $size = IntVal( $size );
409
410 if ( $wgUseCopyrightUpload )
411 {
412 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
413 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
414 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
415 }
416 else $textdesc = $desc ;
417
418 $now = wfTimestampNow();
419 $won = wfInvertTimestamp( $now );
420
421 # Test to see if the row exists using INSERT IGNORE
422 # This avoids race conditions by locking the row until the commit, and also
423 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
424 $dbw->insertArray( 'image',
425 array(
426 'img_name' => $name,
427 'img_size'=> $size,
428 'img_timestamp' => $dbw->timestamp($now),
429 'img_description' => $desc,
430 'img_user' => $wgUser->getID(),
431 'img_user_text' => $wgUser->getName(),
432 ), $fname, 'IGNORE'
433 );
434 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
435
436 if ( $dbw->affectedRows() ) {
437 # Successfully inserted, this is a new image
438 $id = $descTitle->getArticleID();
439
440 if ( $id == 0 ) {
441 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
442 $dbw->insertArray( 'cur',
443 array(
444 'cur_id' => $seqVal,
445 'cur_namespace' => NS_IMAGE,
446 'cur_title' => $name,
447 'cur_comment' => $desc,
448 'cur_user' => $wgUser->getID(),
449 'cur_user_text' => $wgUser->getName(),
450 'cur_timestamp' => $dbw->timestamp($now),
451 'cur_is_new' => 1,
452 'cur_text' => $textdesc,
453 'inverse_timestamp' => $won,
454 'cur_touched' => $dbw->timestamp($now)
455 ), $fname
456 );
457 $id = $dbw->insertId() or 0; # We should throw an error instead
458
459 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
460
461 $u = new SearchUpdate( $id, $name, $desc );
462 $u->doUpdate();
463 }
464 } else {
465 # Collision, this is an update of an image
466 # Get current image row for update
467 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
468 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
469
470 # Insert it into oldimage
471 $dbw->insertArray( 'oldimage',
472 array(
473 'oi_name' => $s->img_name,
474 'oi_archive_name' => $oldver,
475 'oi_size' => $s->img_size,
476 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
477 'oi_description' => $s->img_description,
478 'oi_user' => $s->img_user,
479 'oi_user_text' => $s->img_user_text
480 ), $fname
481 );
482
483 # Update the current image row
484 $dbw->updateArray( 'image',
485 array( /* SET */
486 'img_size' => $size,
487 'img_timestamp' => $dbw->timestamp(),
488 'img_user' => $wgUser->getID(),
489 'img_user_text' => $wgUser->getName(),
490 'img_description' => $desc,
491 ), array( /* WHERE */
492 'img_name' => $name
493 ), $fname
494 );
495
496 # Invalidate the cache for the description page
497 $descTitle->invalidateCache();
498 }
499
500 $log = new LogPage( 'upload' );
501 $log->addEntry( 'upload', $descTitle, $desc );
502 }
503
504 function wfImageArchiveUrl( $name, $subdir='archive' )
505 {
506 global $wgUploadPath, $wgHashedUploadDirectory;
507
508 if ($wgHashedUploadDirectory) {
509 $hash = md5( substr( $name, 15) );
510 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
511 substr( $hash, 0, 2 ) . '/'.$name;
512 } else {
513 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
514 }
515 return wfUrlencode($url);
516 }
517
518 ?>