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