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