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