1<?php 2/** 3 * All output and handler function needed for the media management popup 4 * 5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6 * @author Andreas Gohr <andi@splitbrain.org> 7 */ 8 9use dokuwiki\ChangeLog\MediaChangeLog; 10use dokuwiki\HTTP\DokuHTTPClient; 11use dokuwiki\Subscriptions\MediaSubscriptionSender; 12use dokuwiki\Extension\Event; 13use dokuwiki\Search\MetadataIndex; 14 15/** 16 * Lists pages which currently use a media file selected for deletion 17 * 18 * References uses the same visual as search results and share 19 * their CSS tags except pagenames won't be links. 20 * 21 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 22 * 23 * @param array $data 24 * @param string $id 25 */ 26function media_filesinuse($data,$id){ 27 global $lang; 28 echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>'; 29 echo '<p>'.hsc($lang['ref_inuse']).'</p>'; 30 31 $hidden=0; //count of hits without read permission 32 foreach($data as $row){ 33 if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){ 34 echo '<div class="search_result">'; 35 echo '<span class="mediaref_ref">'.hsc($row).'</span>'; 36 echo '</div>'; 37 }else 38 $hidden++; 39 } 40 if ($hidden){ 41 print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>'; 42 } 43} 44 45/** 46 * Handles the saving of image meta data 47 * 48 * @author Andreas Gohr <andi@splitbrain.org> 49 * @author Kate Arzamastseva <pshns@ukr.net> 50 * 51 * @param string $id media id 52 * @param int $auth permission level 53 * @param array $data 54 * @return false|string 55 */ 56function media_metasave($id,$auth,$data){ 57 if($auth < AUTH_UPLOAD) return false; 58 if(!checkSecurityToken()) return false; 59 global $lang; 60 global $conf; 61 $src = mediaFN($id); 62 63 $meta = new JpegMeta($src); 64 $meta->_parseAll(); 65 66 foreach($data as $key => $val){ 67 $val=trim($val); 68 if(empty($val)){ 69 $meta->deleteField($key); 70 }else{ 71 $meta->setField($key,$val); 72 } 73 } 74 75 $old = @filemtime($src); 76 if(!file_exists(mediaFN($id, $old)) && file_exists($src)) { 77 // add old revision to the attic 78 media_saveOldRevision($id); 79 } 80 $filesize_old = filesize($src); 81 if($meta->save()){ 82 if($conf['fperm']) chmod($src, $conf['fperm']); 83 @clearstatcache(true, $src); 84 $new = @filemtime($src); 85 $filesize_new = filesize($src); 86 $sizechange = $filesize_new - $filesize_old; 87 88 // add a log entry to the media changelog 89 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, $lang['media_meta_edited'], '', null, $sizechange); 90 91 msg($lang['metasaveok'],1); 92 return $id; 93 }else{ 94 msg($lang['metasaveerr'],-1); 95 return false; 96 } 97} 98 99/** 100 * check if a media is external source 101 * 102 * @author Gerrit Uitslag <klapinklapin@gmail.com> 103 * 104 * @param string $id the media ID or URL 105 * @return bool 106 */ 107function media_isexternal($id){ 108 if (preg_match('#^(?:https?|ftp)://#i', $id)) return true; 109 return false; 110} 111 112/** 113 * Check if a media item is public (eg, external URL or readable by @ALL) 114 * 115 * @author Andreas Gohr <andi@splitbrain.org> 116 * 117 * @param string $id the media ID or URL 118 * @return bool 119 */ 120function media_ispublic($id){ 121 if(media_isexternal($id)) return true; 122 $id = cleanID($id); 123 if(auth_aclcheck(getNS($id).':*', '', array()) >= AUTH_READ) return true; 124 return false; 125} 126 127/** 128 * Display the form to edit image meta data 129 * 130 * @author Andreas Gohr <andi@splitbrain.org> 131 * @author Kate Arzamastseva <pshns@ukr.net> 132 * 133 * @param string $id media id 134 * @param int $auth permission level 135 * @return bool 136 */ 137function media_metaform($id,$auth){ 138 global $lang; 139 140 if($auth < AUTH_UPLOAD) { 141 echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL; 142 return false; 143 } 144 145 // load the field descriptions 146 static $fields = null; 147 if(is_null($fields)){ 148 $config_files = getConfigFiles('mediameta'); 149 foreach ($config_files as $config_file) { 150 if(file_exists($config_file)) include($config_file); 151 } 152 } 153 154 $src = mediaFN($id); 155 156 // output 157 $form = new Doku_Form(array('action' => media_managerURL(array('tab_details' => 'view'), '&'), 158 'class' => 'meta')); 159 $form->addHidden('img', $id); 160 $form->addHidden('mediado', 'save'); 161 foreach($fields as $key => $field){ 162 // get current value 163 if (empty($field[0])) continue; 164 $tags = array($field[0]); 165 if(is_array($field[3])) $tags = array_merge($tags,$field[3]); 166 $value = tpl_img_getTag($tags,'',$src); 167 $value = cleanText($value); 168 169 // prepare attributes 170 $p = array(); 171 $p['class'] = 'edit'; 172 $p['id'] = 'meta__'.$key; 173 $p['name'] = 'meta['.$field[0].']'; 174 $p_attrs = array('class' => 'edit'); 175 176 $form->addElement('<div class="row">'); 177 if($field[2] == 'text'){ 178 $form->addElement( 179 form_makeField( 180 'text', 181 $p['name'], 182 $value, 183 ($lang[$field[1]]) ? $lang[$field[1]] : $field[1] . ':', 184 $p['id'], 185 $p['class'], 186 $p_attrs 187 ) 188 ); 189 }else{ 190 $att = buildAttributes($p); 191 $form->addElement('<label for="meta__'.$key.'">'.$lang[$field[1]].'</label>'); 192 $form->addElement("<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'); 193 } 194 $form->addElement('</div>'.NL); 195 } 196 $form->addElement('<div class="buttons">'); 197 $form->addElement( 198 form_makeButton( 199 'submit', 200 '', 201 $lang['btn_save'], 202 array('accesskey' => 's', 'name' => 'mediado[save]') 203 ) 204 ); 205 $form->addElement('</div>'.NL); 206 $form->printForm(); 207 208 return true; 209} 210 211/** 212 * Convenience function to check if a media file is still in use 213 * 214 * @author Michael Klier <chi@chimeric.de> 215 * 216 * @param string $id media id 217 * @return array|bool 218 */ 219function media_inuse($id) { 220 global $conf; 221 222 if ($conf['refcheck']) { 223 $MetadataIndex = MetadataIndex::getInstance(); 224 $mediareferences = $MetadataIndex->mediause($id, true); 225 if (!count($mediareferences)) { 226 return false; 227 } else { 228 return $mediareferences; 229 } 230 } else { 231 return false; 232 } 233} 234 235/** 236 * Handles media file deletions 237 * 238 * If configured, checks for media references before deletion 239 * 240 * @author Andreas Gohr <andi@splitbrain.org> 241 * 242 * @param string $id media id 243 * @param int $auth no longer used 244 * @return int One of: 0, 245 * DOKU_MEDIA_DELETED, 246 * DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS, 247 * DOKU_MEDIA_NOT_AUTH, 248 * DOKU_MEDIA_INUSE 249 */ 250function media_delete($id,$auth){ 251 global $lang; 252 $auth = auth_quickaclcheck(ltrim(getNS($id).':*', ':')); 253 if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH; 254 if(media_inuse($id)) return DOKU_MEDIA_INUSE; 255 256 $file = mediaFN($id); 257 258 // trigger an event - MEDIA_DELETE_FILE 259 $data = array(); 260 $data['id'] = $id; 261 $data['name'] = \dokuwiki\Utf8\PhpString::basename($file); 262 $data['path'] = $file; 263 $data['size'] = (file_exists($file)) ? filesize($file) : 0; 264 265 $data['unl'] = false; 266 $data['del'] = false; 267 $evt = new Event('MEDIA_DELETE_FILE',$data); 268 if ($evt->advise_before()) { 269 $old = @filemtime($file); 270 if(!file_exists(mediaFN($id, $old)) && file_exists($file)) { 271 // add old revision to the attic 272 media_saveOldRevision($id); 273 } 274 275 $data['unl'] = @unlink($file); 276 if($data['unl']) { 277 $sizechange = 0 - $data['size']; 278 addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted'], '', null, $sizechange); 279 280 $data['del'] = io_sweepNS($id, 'mediadir'); 281 } 282 } 283 $evt->advise_after(); 284 unset($evt); 285 286 if($data['unl'] && $data['del']){ 287 return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS; 288 } 289 290 return $data['unl'] ? DOKU_MEDIA_DELETED : 0; 291} 292 293/** 294 * Handle file uploads via XMLHttpRequest 295 * 296 * @param string $ns target namespace 297 * @param int $auth current auth check result 298 * @return false|string false on error, id of the new file on success 299 */ 300function media_upload_xhr($ns,$auth){ 301 if(!checkSecurityToken()) return false; 302 global $INPUT; 303 304 $id = $INPUT->get->str('qqfile'); 305 list($ext,$mime) = mimetype($id); 306 $input = fopen("php://input", "r"); 307 if (!($tmp = io_mktmpdir())) return false; 308 $path = $tmp.'/'.md5($id); 309 $target = fopen($path, "w"); 310 $realSize = stream_copy_to_stream($input, $target); 311 fclose($target); 312 fclose($input); 313 if (isset($_SERVER["CONTENT_LENGTH"]) && ($realSize != (int)$_SERVER["CONTENT_LENGTH"])){ 314 unlink($path); 315 return false; 316 } 317 318 $res = media_save( 319 array('name' => $path, 320 'mime' => $mime, 321 'ext' => $ext), 322 $ns.':'.$id, 323 (($INPUT->get->str('ow') == 'true') ? true : false), 324 $auth, 325 'copy' 326 ); 327 unlink($path); 328 if ($tmp) io_rmdir($tmp, true); 329 if (is_array($res)) { 330 msg($res[0], $res[1]); 331 return false; 332 } 333 return $res; 334} 335 336/** 337 * Handles media file uploads 338 * 339 * @author Andreas Gohr <andi@splitbrain.org> 340 * @author Michael Klier <chi@chimeric.de> 341 * 342 * @param string $ns target namespace 343 * @param int $auth current auth check result 344 * @param bool|array $file $_FILES member, $_FILES['upload'] if false 345 * @return false|string false on error, id of the new file on success 346 */ 347function media_upload($ns,$auth,$file=false){ 348 if(!checkSecurityToken()) return false; 349 global $lang; 350 global $INPUT; 351 352 // get file and id 353 $id = $INPUT->post->str('mediaid'); 354 if (!$file) $file = $_FILES['upload']; 355 if(empty($id)) $id = $file['name']; 356 357 // check for errors (messages are done in lib/exe/mediamanager.php) 358 if($file['error']) return false; 359 360 // check extensions 361 list($fext,$fmime) = mimetype($file['name']); 362 list($iext,$imime) = mimetype($id); 363 if($fext && !$iext){ 364 // no extension specified in id - read original one 365 $id .= '.'.$fext; 366 $imime = $fmime; 367 }elseif($fext && $fext != $iext){ 368 // extension was changed, print warning 369 msg(sprintf($lang['mediaextchange'],$fext,$iext)); 370 } 371 372 $res = media_save(array('name' => $file['tmp_name'], 373 'mime' => $imime, 374 'ext' => $iext), $ns.':'.$id, 375 $INPUT->post->bool('ow'), $auth, 'copy_uploaded_file'); 376 if (is_array($res)) { 377 msg($res[0], $res[1]); 378 return false; 379 } 380 return $res; 381} 382 383/** 384 * An alternative to move_uploaded_file that copies 385 * 386 * Using copy, makes sure any setgid bits on the media directory are honored 387 * 388 * @see move_uploaded_file() 389 * 390 * @param string $from 391 * @param string $to 392 * @return bool 393 */ 394function copy_uploaded_file($from, $to){ 395 if(!is_uploaded_file($from)) return false; 396 $ok = copy($from, $to); 397 @unlink($from); 398 return $ok; 399} 400 401/** 402 * This generates an action event and delegates to _media_upload_action(). 403 * Action plugins are allowed to pre/postprocess the uploaded file. 404 * (The triggered event is preventable.) 405 * 406 * Event data: 407 * $data[0] fn_tmp: the temporary file name (read from $_FILES) 408 * $data[1] fn: the file name of the uploaded file 409 * $data[2] id: the future directory id of the uploaded file 410 * $data[3] imime: the mimetype of the uploaded file 411 * $data[4] overwrite: if an existing file is going to be overwritten 412 * $data[5] move: name of function that performs move/copy/.. 413 * 414 * @triggers MEDIA_UPLOAD_FINISH 415 * 416 * @param array $file 417 * @param string $id media id 418 * @param bool $ow overwrite? 419 * @param int $auth permission level 420 * @param string $move name of functions that performs move/copy/.. 421 * @return false|array|string 422 */ 423function media_save($file, $id, $ow, $auth, $move) { 424 if($auth < AUTH_UPLOAD) { 425 return array("You don't have permissions to upload files.", -1); 426 } 427 428 if (!isset($file['mime']) || !isset($file['ext'])) { 429 list($ext, $mime) = mimetype($id); 430 if (!isset($file['mime'])) { 431 $file['mime'] = $mime; 432 } 433 if (!isset($file['ext'])) { 434 $file['ext'] = $ext; 435 } 436 } 437 438 global $lang, $conf; 439 440 // get filename 441 $id = cleanID($id); 442 $fn = mediaFN($id); 443 444 // get filetype regexp 445 $types = array_keys(getMimeTypes()); 446 $types = array_map( 447 function ($q) { 448 return preg_quote($q, "/"); 449 }, 450 $types 451 ); 452 $regex = join('|',$types); 453 454 // because a temp file was created already 455 if(!preg_match('/\.('.$regex.')$/i',$fn)) { 456 return array($lang['uploadwrong'],-1); 457 } 458 459 //check for overwrite 460 $overwrite = file_exists($fn); 461 $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE); 462 if($overwrite && (!$ow || $auth < $auth_ow)) { 463 return array($lang['uploadexist'], 0); 464 } 465 // check for valid content 466 $ok = media_contentcheck($file['name'], $file['mime']); 467 if($ok == -1){ 468 return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1); 469 }elseif($ok == -2){ 470 return array($lang['uploadspam'],-1); 471 }elseif($ok == -3){ 472 return array($lang['uploadxss'],-1); 473 } 474 475 // prepare event data 476 $data = array(); 477 $data[0] = $file['name']; 478 $data[1] = $fn; 479 $data[2] = $id; 480 $data[3] = $file['mime']; 481 $data[4] = $overwrite; 482 $data[5] = $move; 483 484 // trigger event 485 return Event::createAndTrigger('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true); 486} 487 488/** 489 * Callback adapter for media_upload_finish() triggered by MEDIA_UPLOAD_FINISH 490 * 491 * @author Michael Klier <chi@chimeric.de> 492 * 493 * @param array $data event data 494 * @return false|array|string 495 */ 496function _media_upload_action($data) { 497 // fixme do further sanity tests of given data? 498 if(is_array($data) && count($data)===6) { 499 return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]); 500 } else { 501 return false; //callback error 502 } 503} 504 505/** 506 * Saves an uploaded media file 507 * 508 * @author Andreas Gohr <andi@splitbrain.org> 509 * @author Michael Klier <chi@chimeric.de> 510 * @author Kate Arzamastseva <pshns@ukr.net> 511 * 512 * @param string $fn_tmp 513 * @param string $fn 514 * @param string $id media id 515 * @param string $imime mime type 516 * @param bool $overwrite overwrite existing? 517 * @param string $move function name 518 * @return array|string 519 */ 520function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') { 521 global $conf; 522 global $lang; 523 global $REV; 524 525 $old = @filemtime($fn); 526 if(!file_exists(mediaFN($id, $old)) && file_exists($fn)) { 527 // add old revision to the attic if missing 528 media_saveOldRevision($id); 529 } 530 531 // prepare directory 532 io_createNamespace($id, 'media'); 533 534 $filesize_old = file_exists($fn) ? filesize($fn) : 0; 535 536 if($move($fn_tmp, $fn)) { 537 @clearstatcache(true,$fn); 538 $new = @filemtime($fn); 539 // Set the correct permission here. 540 // Always chmod media because they may be saved with different permissions than expected from the php umask. 541 // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.) 542 chmod($fn, $conf['fmode']); 543 msg($lang['uploadsucc'],1); 544 media_notify($id,$fn,$imime,$old,$new); 545 // add a log entry to the media changelog 546 $filesize_new = filesize($fn); 547 $sizechange = $filesize_new - $filesize_old; 548 if($REV) { 549 addMediaLogEntry( 550 $new, 551 $id, 552 DOKU_CHANGE_TYPE_REVERT, 553 sprintf($lang['restored'], dformat($REV)), 554 $REV, 555 null, 556 $sizechange 557 ); 558 } elseif($overwrite) { 559 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange); 560 } else { 561 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange); 562 } 563 return $id; 564 }else{ 565 return array($lang['uploadfail'],-1); 566 } 567} 568 569/** 570 * Moves the current version of media file to the media_attic 571 * directory 572 * 573 * @author Kate Arzamastseva <pshns@ukr.net> 574 * 575 * @param string $id 576 * @return int - revision date 577 */ 578function media_saveOldRevision($id){ 579 global $conf, $lang; 580 581 $oldf = mediaFN($id); 582 if(!file_exists($oldf)) return ''; 583 $date = filemtime($oldf); 584 if (!$conf['mediarevisions']) return $date; 585 586 $medialog = new MediaChangeLog($id); 587 if (!$medialog->getRevisionInfo($date)) { 588 // there was an external edit, 589 // there is no log entry for current version of file 590 $sizechange = filesize($oldf); 591 if(!file_exists(mediaMetaFN($id, '.changes'))) { 592 addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange); 593 } else { 594 $oldRev = $medialog->getRevisions(-1, 1); // from changelog 595 $oldRev = (int) (empty($oldRev) ? 0 : $oldRev[0]); 596 $filesize_old = filesize(mediaFN($id, $oldRev)); 597 $sizechange = $sizechange - $filesize_old; 598 599 addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange); 600 } 601 } 602 603 $newf = mediaFN($id,$date); 604 io_makeFileDir($newf); 605 if(copy($oldf, $newf)) { 606 // Set the correct permission here. 607 // Always chmod media because they may be saved with different permissions than expected from the php umask. 608 // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.) 609 chmod($newf, $conf['fmode']); 610 } 611 return $date; 612} 613 614/** 615 * This function checks if the uploaded content is really what the 616 * mimetype says it is. We also do spam checking for text types here. 617 * 618 * We need to do this stuff because we can not rely on the browser 619 * to do this check correctly. Yes, IE is broken as usual. 620 * 621 * @author Andreas Gohr <andi@splitbrain.org> 622 * @link http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting 623 * @fixme check all 26 magic IE filetypes here? 624 * 625 * @param string $file path to file 626 * @param string $mime mimetype 627 * @return int 628 */ 629function media_contentcheck($file,$mime){ 630 global $conf; 631 if($conf['iexssprotect']){ 632 $fh = @fopen($file, 'rb'); 633 if($fh){ 634 $bytes = fread($fh, 256); 635 fclose($fh); 636 if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){ 637 return -3; //XSS: possibly malicious content 638 } 639 } 640 } 641 if(substr($mime,0,6) == 'image/'){ 642 $info = @getimagesize($file); 643 if($mime == 'image/gif' && $info[2] != 1){ 644 return -1; // uploaded content did not match the file extension 645 }elseif($mime == 'image/jpeg' && $info[2] != 2){ 646 return -1; 647 }elseif($mime == 'image/png' && $info[2] != 3){ 648 return -1; 649 } 650 # fixme maybe check other images types as well 651 }elseif(substr($mime,0,5) == 'text/'){ 652 global $TEXT; 653 $TEXT = io_readFile($file); 654 if(checkwordblock()){ 655 return -2; //blocked by the spam blacklist 656 } 657 } 658 return 0; 659} 660 661/** 662 * Send a notify mail on uploads 663 * 664 * @author Andreas Gohr <andi@splitbrain.org> 665 * 666 * @param string $id media id 667 * @param string $file path to file 668 * @param string $mime mime type 669 * @param bool|int $old_rev revision timestamp or false 670 * @return bool 671 */ 672function media_notify($id,$file,$mime,$old_rev=false,$current_rev=false){ 673 global $conf; 674 if(empty($conf['notify'])) return false; //notify enabled? 675 676 $subscription = new MediaSubscriptionSender(); 677 return $subscription->sendMediaDiff($conf['notify'], 'uploadmail', $id, $old_rev, $current_rev); 678} 679 680/** 681 * List all files in a given Media namespace 682 * 683 * @param string $ns namespace 684 * @param null|int $auth permission level 685 * @param string $jump id 686 * @param bool $fullscreenview 687 * @param bool|string $sort sorting order, false skips sorting 688 */ 689function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=false){ 690 global $conf; 691 global $lang; 692 $ns = cleanID($ns); 693 694 // check auth our self if not given (needed for ajax calls) 695 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 696 697 if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL; 698 699 if($auth < AUTH_READ){ 700 // FIXME: print permission warning here instead? 701 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL; 702 }else{ 703 if (!$fullscreenview) { 704 media_uploadform($ns, $auth); 705 media_searchform($ns); 706 } 707 708 $dir = utf8_encodeFN(str_replace(':','/',$ns)); 709 $data = array(); 710 search($data,$conf['mediadir'],'search_media', 711 array('showmsg'=>true,'depth'=>1),$dir,1,$sort); 712 713 if(!count($data)){ 714 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL; 715 }else { 716 if ($fullscreenview) { 717 echo '<ul class="' . _media_get_list_type() . '">'; 718 } 719 foreach($data as $item){ 720 if (!$fullscreenview) { 721 media_printfile($item,$auth,$jump); 722 } else { 723 media_printfile_thumbs($item,$auth,$jump); 724 } 725 } 726 if ($fullscreenview) echo '</ul>'.NL; 727 } 728 } 729} 730 731/** 732 * Prints tabs for files list actions 733 * 734 * @author Kate Arzamastseva <pshns@ukr.net> 735 * @author Adrian Lang <mail@adrianlang.de> 736 * 737 * @param string $selected_tab - opened tab 738 */ 739 740function media_tabs_files($selected_tab = ''){ 741 global $lang; 742 $tabs = array(); 743 foreach(array('files' => 'mediaselect', 744 'upload' => 'media_uploadtab', 745 'search' => 'media_searchtab') as $tab => $caption) { 746 $tabs[$tab] = array('href' => media_managerURL(array('tab_files' => $tab), '&'), 747 'caption' => $lang[$caption]); 748 } 749 750 html_tabs($tabs, $selected_tab); 751} 752 753/** 754 * Prints tabs for files details actions 755 * 756 * @author Kate Arzamastseva <pshns@ukr.net> 757 * @param string $image filename of the current image 758 * @param string $selected_tab opened tab 759 */ 760function media_tabs_details($image, $selected_tab = ''){ 761 global $lang, $conf; 762 763 $tabs = array(); 764 $tabs['view'] = array('href' => media_managerURL(array('tab_details' => 'view'), '&'), 765 'caption' => $lang['media_viewtab']); 766 767 list(, $mime) = mimetype($image); 768 if ($mime == 'image/jpeg' && file_exists(mediaFN($image))) { 769 $tabs['edit'] = array('href' => media_managerURL(array('tab_details' => 'edit'), '&'), 770 'caption' => $lang['media_edittab']); 771 } 772 if ($conf['mediarevisions']) { 773 $tabs['history'] = array('href' => media_managerURL(array('tab_details' => 'history'), '&'), 774 'caption' => $lang['media_historytab']); 775 } 776 777 html_tabs($tabs, $selected_tab); 778} 779 780/** 781 * Prints options for the tab that displays a list of all files 782 * 783 * @author Kate Arzamastseva <pshns@ukr.net> 784 */ 785function media_tab_files_options(){ 786 global $lang; 787 global $INPUT; 788 global $ID; 789 $form = new Doku_Form(array('class' => 'options', 'method' => 'get', 790 'action' => wl($ID))); 791 $media_manager_params = media_managerURL(array(), '', false, true); 792 foreach($media_manager_params as $pKey => $pVal){ 793 $form->addHidden($pKey, $pVal); 794 } 795 $form->addHidden('sectok', null); 796 if ($INPUT->has('q')) { 797 $form->addHidden('q', $INPUT->str('q')); 798 } 799 $form->addElement('<ul>'.NL); 800 foreach(array('list' => array('listType', array('thumbs', 'rows')), 801 'sort' => array('sortBy', array('name', 'date'))) 802 as $group => $content) { 803 $checked = "_media_get_${group}_type"; 804 $checked = $checked(); 805 806 $form->addElement('<li class="' . $content[0] . '">'); 807 foreach($content[1] as $option) { 808 $attrs = array(); 809 if ($checked == $option) { 810 $attrs['checked'] = 'checked'; 811 } 812 $form->addElement(form_makeRadioField($group . '_dwmedia', $option, 813 $lang['media_' . $group . '_' . $option], 814 $content[0] . '__' . $option, 815 $option, $attrs)); 816 } 817 $form->addElement('</li>'.NL); 818 } 819 $form->addElement('<li>'); 820 $form->addElement(form_makeButton('submit', '', $lang['btn_apply'])); 821 $form->addElement('</li>'.NL); 822 $form->addElement('</ul>'.NL); 823 $form->printForm(); 824} 825 826/** 827 * Returns type of sorting for the list of files in media manager 828 * 829 * @author Kate Arzamastseva <pshns@ukr.net> 830 * 831 * @return string - sort type 832 */ 833function _media_get_sort_type() { 834 return _media_get_display_param('sort', array('default' => 'name', 'date')); 835} 836 837/** 838 * Returns type of listing for the list of files in media manager 839 * 840 * @author Kate Arzamastseva <pshns@ukr.net> 841 * 842 * @return string - list type 843 */ 844function _media_get_list_type() { 845 return _media_get_display_param('list', array('default' => 'thumbs', 'rows')); 846} 847 848/** 849 * Get display parameters 850 * 851 * @param string $param name of parameter 852 * @param array $values allowed values, where default value has index key 'default' 853 * @return string the parameter value 854 */ 855function _media_get_display_param($param, $values) { 856 global $INPUT; 857 if (in_array($INPUT->str($param), $values)) { 858 // FIXME: Set cookie 859 return $INPUT->str($param); 860 } else { 861 $val = get_doku_pref($param, $values['default']); 862 if (!in_array($val, $values)) { 863 $val = $values['default']; 864 } 865 return $val; 866 } 867} 868 869/** 870 * Prints tab that displays a list of all files 871 * 872 * @author Kate Arzamastseva <pshns@ukr.net> 873 * 874 * @param string $ns 875 * @param null|int $auth permission level 876 * @param string $jump item id 877 */ 878function media_tab_files($ns,$auth=null,$jump='') { 879 global $lang; 880 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 881 882 if($auth < AUTH_READ){ 883 echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL; 884 }else{ 885 media_filelist($ns,$auth,$jump,true,_media_get_sort_type()); 886 } 887} 888 889/** 890 * Prints tab that displays uploading form 891 * 892 * @author Kate Arzamastseva <pshns@ukr.net> 893 * 894 * @param string $ns 895 * @param null|int $auth permission level 896 * @param string $jump item id 897 */ 898function media_tab_upload($ns,$auth=null,$jump='') { 899 global $lang; 900 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 901 902 echo '<div class="upload">'.NL; 903 if ($auth >= AUTH_UPLOAD) { 904 echo '<p>' . $lang['mediaupload'] . '</p>'; 905 } 906 media_uploadform($ns, $auth, true); 907 echo '</div>'.NL; 908} 909 910/** 911 * Prints tab that displays search form 912 * 913 * @author Kate Arzamastseva <pshns@ukr.net> 914 * 915 * @param string $ns 916 * @param null|int $auth permission level 917 */ 918function media_tab_search($ns,$auth=null) { 919 global $INPUT; 920 921 $do = $INPUT->str('mediado'); 922 $query = $INPUT->str('q'); 923 echo '<div class="search">'.NL; 924 925 media_searchform($ns, $query, true); 926 if ($do == 'searchlist' || $query) { 927 media_searchlist($query,$ns,$auth,true,_media_get_sort_type()); 928 } 929 echo '</div>'.NL; 930} 931 932/** 933 * Prints tab that displays mediafile details 934 * 935 * @author Kate Arzamastseva <pshns@ukr.net> 936 * 937 * @param string $image media id 938 * @param string $ns 939 * @param null|int $auth permission level 940 * @param string|int $rev revision timestamp or empty string 941 */ 942function media_tab_view($image, $ns, $auth=null, $rev='') { 943 global $lang; 944 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 945 946 if ($image && $auth >= AUTH_READ) { 947 $meta = new JpegMeta(mediaFN($image, $rev)); 948 media_preview($image, $auth, $rev, $meta); 949 media_preview_buttons($image, $auth, $rev); 950 media_details($image, $auth, $rev, $meta); 951 952 } else { 953 echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL; 954 } 955} 956 957/** 958 * Prints tab that displays form for editing mediafile metadata 959 * 960 * @author Kate Arzamastseva <pshns@ukr.net> 961 * 962 * @param string $image media id 963 * @param string $ns 964 * @param null|int $auth permission level 965 */ 966function media_tab_edit($image, $ns, $auth=null) { 967 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 968 969 if ($image) { 970 list(, $mime) = mimetype($image); 971 if ($mime == 'image/jpeg') media_metaform($image,$auth); 972 } 973} 974 975/** 976 * Prints tab that displays mediafile revisions 977 * 978 * @author Kate Arzamastseva <pshns@ukr.net> 979 * 980 * @param string $image media id 981 * @param string $ns 982 * @param null|int $auth permission level 983 */ 984function media_tab_history($image, $ns, $auth=null) { 985 global $lang; 986 global $INPUT; 987 988 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 989 $do = $INPUT->str('mediado'); 990 991 if ($auth >= AUTH_READ && $image) { 992 if ($do == 'diff'){ 993 media_diff($image, $ns, $auth); 994 } else { 995 $first = $INPUT->int('first'); 996 html_revisions($first, $image); 997 } 998 } else { 999 echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL; 1000 } 1001} 1002 1003/** 1004 * Prints mediafile details 1005 * 1006 * @param string $image media id 1007 * @param int $auth permission level 1008 * @param int|string $rev revision timestamp or empty string 1009 * @param JpegMeta|bool $meta 1010 * 1011 * @author Kate Arzamastseva <pshns@ukr.net> 1012 */ 1013function media_preview($image, $auth, $rev='', $meta=false) { 1014 1015 $size = media_image_preview_size($image, $rev, $meta); 1016 1017 if ($size) { 1018 global $lang; 1019 echo '<div class="image">'; 1020 1021 $more = array(); 1022 if ($rev) { 1023 $more['rev'] = $rev; 1024 } else { 1025 $t = @filemtime(mediaFN($image)); 1026 $more['t'] = $t; 1027 } 1028 1029 $more['w'] = $size[0]; 1030 $more['h'] = $size[1]; 1031 $src = ml($image, $more); 1032 1033 echo '<a href="'.$src.'" target="_blank" title="'.$lang['mediaview'].'">'; 1034 echo '<img src="'.$src.'" alt="" style="max-width: '.$size[0].'px;" />'; 1035 echo '</a>'; 1036 1037 echo '</div>'.NL; 1038 } 1039} 1040 1041/** 1042 * Prints mediafile action buttons 1043 * 1044 * @author Kate Arzamastseva <pshns@ukr.net> 1045 * 1046 * @param string $image media id 1047 * @param int $auth permission level 1048 * @param string|int $rev revision timestamp, or empty string 1049 */ 1050function media_preview_buttons($image, $auth, $rev='') { 1051 global $lang, $conf; 1052 1053 echo '<ul class="actions">'.NL; 1054 1055 if($auth >= AUTH_DELETE && !$rev && file_exists(mediaFN($image))){ 1056 1057 // delete button 1058 $form = new Doku_Form(array('id' => 'mediamanager__btn_delete', 1059 'action'=>media_managerURL(array('delete' => $image), '&'))); 1060 $form->addElement(form_makeButton('submit','',$lang['btn_delete'])); 1061 echo '<li>'; 1062 $form->printForm(); 1063 echo '</li>'.NL; 1064 } 1065 1066 $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE); 1067 if($auth >= $auth_ow && !$rev){ 1068 1069 // upload new version button 1070 $form = new Doku_Form(array('id' => 'mediamanager__btn_update', 1071 'action'=>media_managerURL(array('image' => $image, 'mediado' => 'update'), '&'))); 1072 $form->addElement(form_makeButton('submit','',$lang['media_update'])); 1073 echo '<li>'; 1074 $form->printForm(); 1075 echo '</li>'.NL; 1076 } 1077 1078 if($auth >= AUTH_UPLOAD && $rev && $conf['mediarevisions'] && file_exists(mediaFN($image, $rev))){ 1079 1080 // restore button 1081 $form = new Doku_Form(array('id' => 'mediamanager__btn_restore', 1082 'action'=>media_managerURL(array('image' => $image), '&'))); 1083 $form->addHidden('mediado','restore'); 1084 $form->addHidden('rev',$rev); 1085 $form->addElement(form_makeButton('submit','',$lang['media_restore'])); 1086 echo '<li>'; 1087 $form->printForm(); 1088 echo '</li>'.NL; 1089 } 1090 1091 echo '</ul>'.NL; 1092} 1093 1094/** 1095 * Returns image width and height for mediamanager preview panel 1096 * 1097 * @author Kate Arzamastseva <pshns@ukr.net> 1098 * @param string $image 1099 * @param int|string $rev 1100 * @param JpegMeta|bool $meta 1101 * @param int $size 1102 * @return array|false 1103 */ 1104function media_image_preview_size($image, $rev, $meta, $size = 500) { 1105 if (!preg_match("/\.(jpe?g|gif|png)$/", $image) || !file_exists(mediaFN($image, $rev))) return false; 1106 1107 $info = getimagesize(mediaFN($image, $rev)); 1108 $w = (int) $info[0]; 1109 $h = (int) $info[1]; 1110 1111 if($meta && ($w > $size || $h > $size)){ 1112 $ratio = $meta->getResizeRatio($size, $size); 1113 $w = floor($w * $ratio); 1114 $h = floor($h * $ratio); 1115 } 1116 return array($w, $h); 1117} 1118 1119/** 1120 * Returns the requested EXIF/IPTC tag from the image meta 1121 * 1122 * @author Kate Arzamastseva <pshns@ukr.net> 1123 * 1124 * @param array $tags array with tags, first existing is returned 1125 * @param JpegMeta $meta 1126 * @param string $alt alternative value 1127 * @return string 1128 */ 1129function media_getTag($tags,$meta,$alt=''){ 1130 if($meta === false) return $alt; 1131 $info = $meta->getField($tags); 1132 if($info == false) return $alt; 1133 return $info; 1134} 1135 1136/** 1137 * Returns mediafile tags 1138 * 1139 * @author Kate Arzamastseva <pshns@ukr.net> 1140 * 1141 * @param JpegMeta $meta 1142 * @return array list of tags of the mediafile 1143 */ 1144function media_file_tags($meta) { 1145 // load the field descriptions 1146 static $fields = null; 1147 if(is_null($fields)){ 1148 $config_files = getConfigFiles('mediameta'); 1149 foreach ($config_files as $config_file) { 1150 if(file_exists($config_file)) include($config_file); 1151 } 1152 } 1153 1154 $tags = array(); 1155 1156 foreach($fields as $key => $tag){ 1157 $t = array(); 1158 if (!empty($tag[0])) $t = array($tag[0]); 1159 if(isset($tag[3]) && is_array($tag[3])) $t = array_merge($t,$tag[3]); 1160 $value = media_getTag($t, $meta); 1161 $tags[] = array('tag' => $tag, 'value' => $value); 1162 } 1163 1164 return $tags; 1165} 1166 1167/** 1168 * Prints mediafile tags 1169 * 1170 * @author Kate Arzamastseva <pshns@ukr.net> 1171 * 1172 * @param string $image image id 1173 * @param int $auth permission level 1174 * @param string|int $rev revision timestamp, or empty string 1175 * @param bool|JpegMeta $meta image object, or create one if false 1176 */ 1177function media_details($image, $auth, $rev = '', $meta = false) { 1178 global $lang; 1179 1180 if (!$meta) $meta = new JpegMeta(mediaFN($image, $rev)); 1181 $tags = media_file_tags($meta); 1182 1183 echo '<dl>'.NL; 1184 foreach ($tags as $tag) { 1185 if ($tag['value']) { 1186 $value = cleanText($tag['value']); 1187 echo '<dt>'.$lang[$tag['tag'][1]].'</dt><dd>'; 1188 if ($tag['tag'][2] == 'date') { 1189 echo dformat($value); 1190 } else { 1191 echo hsc($value); 1192 } 1193 echo '</dd>'.NL; 1194 } 1195 } 1196 echo '</dl>'.NL; 1197 echo '<dl>'.NL; 1198 echo '<dt>'.$lang['reference'].':</dt>'; 1199 $MetadataIndex = MetadataIndex::getInstance(); 1200 $media_usage = $MetadataIndex->mediause($image, true); 1201 if (count($media_usage) > 0) { 1202 foreach ($media_usage as $path) { 1203 echo '<dd>'.html_wikilink($path).'</dd>'; 1204 } 1205 } else { 1206 echo '<dd>'.$lang['nothingfound'].'</dd>'; 1207 } 1208 echo '</dl>'.NL; 1209 1210} 1211 1212/** 1213 * Shows difference between two revisions of file 1214 * 1215 * @author Kate Arzamastseva <pshns@ukr.net> 1216 * 1217 * @param string $image image id 1218 * @param string $ns 1219 * @param int $auth permission level 1220 * @param bool $fromajax 1221 * @return false|null|string 1222 */ 1223function media_diff($image, $ns, $auth, $fromajax = false) { 1224 global $conf; 1225 global $INPUT; 1226 1227 if ($auth < AUTH_READ || !$image || !$conf['mediarevisions']) return ''; 1228 1229 $rev1 = $INPUT->int('rev'); 1230 1231 $rev2 = $INPUT->ref('rev2'); 1232 if(is_array($rev2)){ 1233 $rev1 = (int) $rev2[0]; 1234 $rev2 = (int) $rev2[1]; 1235 1236 if(!$rev1){ 1237 $rev1 = $rev2; 1238 unset($rev2); 1239 } 1240 }else{ 1241 $rev2 = $INPUT->int('rev2'); 1242 } 1243 1244 if ($rev1 && !file_exists(mediaFN($image, $rev1))) $rev1 = false; 1245 if ($rev2 && !file_exists(mediaFN($image, $rev2))) $rev2 = false; 1246 1247 if($rev1 && $rev2){ // two specific revisions wanted 1248 // make sure order is correct (older on the left) 1249 if($rev1 < $rev2){ 1250 $l_rev = $rev1; 1251 $r_rev = $rev2; 1252 }else{ 1253 $l_rev = $rev2; 1254 $r_rev = $rev1; 1255 } 1256 }elseif($rev1){ // single revision given, compare to current 1257 $r_rev = ''; 1258 $l_rev = $rev1; 1259 }else{ // no revision was given, compare previous to current 1260 $r_rev = ''; 1261 $medialog = new MediaChangeLog($image); 1262 $revs = $medialog->getRevisions(0, 1); 1263 if (file_exists(mediaFN($image, $revs[0]))) { 1264 $l_rev = $revs[0]; 1265 } else { 1266 $l_rev = ''; 1267 } 1268 } 1269 1270 // prepare event data 1271 $data = array(); 1272 $data[0] = $image; 1273 $data[1] = $l_rev; 1274 $data[2] = $r_rev; 1275 $data[3] = $ns; 1276 $data[4] = $auth; 1277 $data[5] = $fromajax; 1278 1279 // trigger event 1280 return Event::createAndTrigger('MEDIA_DIFF', $data, '_media_file_diff', true); 1281} 1282 1283/** 1284 * Callback for media file diff 1285 * 1286 * @param array $data event data 1287 * @return false|null 1288 */ 1289function _media_file_diff($data) { 1290 if(is_array($data) && count($data)===6) { 1291 media_file_diff($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]); 1292 } else { 1293 return false; 1294 } 1295} 1296 1297/** 1298 * Shows difference between two revisions of image 1299 * 1300 * @author Kate Arzamastseva <pshns@ukr.net> 1301 * 1302 * @param string $image 1303 * @param string|int $l_rev revision timestamp, or empty string 1304 * @param string|int $r_rev revision timestamp, or empty string 1305 * @param string $ns 1306 * @param int $auth permission level 1307 * @param bool $fromajax 1308 */ 1309function media_file_diff($image, $l_rev, $r_rev, $ns, $auth, $fromajax){ 1310 global $lang; 1311 global $INPUT; 1312 1313 $l_meta = new JpegMeta(mediaFN($image, $l_rev)); 1314 $r_meta = new JpegMeta(mediaFN($image, $r_rev)); 1315 1316 $is_img = preg_match('/\.(jpe?g|gif|png)$/', $image); 1317 if ($is_img) { 1318 $l_size = media_image_preview_size($image, $l_rev, $l_meta); 1319 $r_size = media_image_preview_size($image, $r_rev, $r_meta); 1320 $is_img = ($l_size && $r_size && ($l_size[0] >= 30 || $r_size[0] >= 30)); 1321 1322 $difftype = $INPUT->str('difftype'); 1323 1324 if (!$fromajax) { 1325 $form = new Doku_Form(array( 1326 'action' => media_managerURL(array(), '&'), 1327 'method' => 'get', 1328 'id' => 'mediamanager__form_diffview', 1329 'class' => 'diffView' 1330 )); 1331 $form->addHidden('sectok', null); 1332 $form->addElement('<input type="hidden" name="rev2[]" value="'.$l_rev.'" ></input>'); 1333 $form->addElement('<input type="hidden" name="rev2[]" value="'.$r_rev.'" ></input>'); 1334 $form->addHidden('mediado', 'diff'); 1335 $form->printForm(); 1336 1337 echo NL.'<div id="mediamanager__diff" >'.NL; 1338 } 1339 1340 if ($difftype == 'opacity' || $difftype == 'portions') { 1341 media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $difftype); 1342 if (!$fromajax) echo '</div>'; 1343 return; 1344 } 1345 } 1346 1347 list($l_head, $r_head) = html_diff_head($l_rev, $r_rev, $image, true); 1348 1349 ?> 1350 <div class="table"> 1351 <table> 1352 <tr> 1353 <th><?php echo $l_head; ?></th> 1354 <th><?php echo $r_head; ?></th> 1355 </tr> 1356 <?php 1357 1358 echo '<tr class="image">'; 1359 echo '<td>'; 1360 media_preview($image, $auth, $l_rev, $l_meta); 1361 echo '</td>'; 1362 1363 echo '<td>'; 1364 media_preview($image, $auth, $r_rev, $r_meta); 1365 echo '</td>'; 1366 echo '</tr>'.NL; 1367 1368 echo '<tr class="actions">'; 1369 echo '<td>'; 1370 media_preview_buttons($image, $auth, $l_rev); 1371 echo '</td>'; 1372 1373 echo '<td>'; 1374 media_preview_buttons($image, $auth, $r_rev); 1375 echo '</td>'; 1376 echo '</tr>'.NL; 1377 1378 $l_tags = media_file_tags($l_meta); 1379 $r_tags = media_file_tags($r_meta); 1380 // FIXME r_tags-only stuff 1381 foreach ($l_tags as $key => $l_tag) { 1382 if ($l_tag['value'] != $r_tags[$key]['value']) { 1383 $r_tags[$key]['highlighted'] = true; 1384 $l_tags[$key]['highlighted'] = true; 1385 } else if (!$l_tag['value'] || !$r_tags[$key]['value']) { 1386 unset($r_tags[$key]); 1387 unset($l_tags[$key]); 1388 } 1389 } 1390 1391 echo '<tr>'; 1392 foreach(array($l_tags,$r_tags) as $tags){ 1393 echo '<td>'.NL; 1394 1395 echo '<dl class="img_tags">'; 1396 foreach($tags as $tag){ 1397 $value = cleanText($tag['value']); 1398 if (!$value) $value = '-'; 1399 echo '<dt>'.$lang[$tag['tag'][1]].'</dt>'; 1400 echo '<dd>'; 1401 if ($tag['highlighted']) { 1402 echo '<strong>'; 1403 } 1404 if ($tag['tag'][2] == 'date') echo dformat($value); 1405 else echo hsc($value); 1406 if ($tag['highlighted']) { 1407 echo '</strong>'; 1408 } 1409 echo '</dd>'; 1410 } 1411 echo '</dl>'.NL; 1412 1413 echo '</td>'; 1414 } 1415 echo '</tr>'.NL; 1416 1417 echo '</table>'.NL; 1418 echo '</div>'.NL; 1419 1420 if ($is_img && !$fromajax) echo '</div>'; 1421} 1422 1423/** 1424 * Prints two images side by side 1425 * and slider 1426 * 1427 * @author Kate Arzamastseva <pshns@ukr.net> 1428 * 1429 * @param string $image image id 1430 * @param int $l_rev revision timestamp, or empty string 1431 * @param int $r_rev revision timestamp, or empty string 1432 * @param array $l_size array with width and height 1433 * @param array $r_size array with width and height 1434 * @param string $type 1435 */ 1436function media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $type) { 1437 if ($l_size != $r_size) { 1438 if ($r_size[0] > $l_size[0]) { 1439 $l_size = $r_size; 1440 } 1441 } 1442 1443 $l_more = array('rev' => $l_rev, 'h' => $l_size[1], 'w' => $l_size[0]); 1444 $r_more = array('rev' => $r_rev, 'h' => $l_size[1], 'w' => $l_size[0]); 1445 1446 $l_src = ml($image, $l_more); 1447 $r_src = ml($image, $r_more); 1448 1449 // slider 1450 echo '<div class="slider" style="max-width: '.($l_size[0]-20).'px;" ></div>'.NL; 1451 1452 // two images in divs 1453 echo '<div class="imageDiff ' . $type . '">'.NL; 1454 echo '<div class="image1" style="max-width: '.$l_size[0].'px;">'; 1455 echo '<img src="'.$l_src.'" alt="" />'; 1456 echo '</div>'.NL; 1457 echo '<div class="image2" style="max-width: '.$l_size[0].'px;">'; 1458 echo '<img src="'.$r_src.'" alt="" />'; 1459 echo '</div>'.NL; 1460 echo '</div>'.NL; 1461} 1462 1463/** 1464 * Restores an old revision of a media file 1465 * 1466 * @param string $image media id 1467 * @param int $rev revision timestamp or empty string 1468 * @param int $auth 1469 * @return string - file's id 1470 * 1471 * @author Kate Arzamastseva <pshns@ukr.net> 1472 */ 1473function media_restore($image, $rev, $auth){ 1474 global $conf; 1475 if ($auth < AUTH_UPLOAD || !$conf['mediarevisions']) return false; 1476 $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes'))); 1477 if (!$image || (!file_exists(mediaFN($image)) && !$removed)) return false; 1478 if (!$rev || !file_exists(mediaFN($image, $rev))) return false; 1479 list(,$imime,) = mimetype($image); 1480 $res = media_upload_finish(mediaFN($image, $rev), 1481 mediaFN($image), 1482 $image, 1483 $imime, 1484 true, 1485 'copy'); 1486 if (is_array($res)) { 1487 msg($res[0], $res[1]); 1488 return false; 1489 } 1490 return $res; 1491} 1492 1493/** 1494 * List all files found by the search request 1495 * 1496 * @author Tobias Sarnowski <sarnowski@cosmocode.de> 1497 * @author Andreas Gohr <gohr@cosmocode.de> 1498 * @author Kate Arzamastseva <pshns@ukr.net> 1499 * @triggers MEDIA_SEARCH 1500 * 1501 * @param string $query 1502 * @param string $ns 1503 * @param null|int $auth 1504 * @param bool $fullscreen 1505 * @param string $sort 1506 */ 1507function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort='natural'){ 1508 global $conf; 1509 global $lang; 1510 1511 $ns = cleanID($ns); 1512 $evdata = array( 1513 'ns' => $ns, 1514 'data' => array(), 1515 'query' => $query 1516 ); 1517 if (!blank($query)) { 1518 $evt = new Event('MEDIA_SEARCH', $evdata); 1519 if ($evt->advise_before()) { 1520 $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns'])); 1521 $quoted = preg_quote($evdata['query'],'/'); 1522 //apply globbing 1523 $quoted = str_replace(array('\*', '\?'), array('.*', '.'), $quoted, $count); 1524 1525 //if we use globbing file name must match entirely but may be preceded by arbitrary namespace 1526 if ($count > 0) $quoted = '^([^:]*:)*'.$quoted.'$'; 1527 1528 $pattern = '/'.$quoted.'/i'; 1529 search($evdata['data'], 1530 $conf['mediadir'], 1531 'search_media', 1532 array('showmsg'=>false,'pattern'=>$pattern), 1533 $dir, 1534 1, 1535 $sort); 1536 } 1537 $evt->advise_after(); 1538 unset($evt); 1539 } 1540 1541 if (!$fullscreen) { 1542 echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL; 1543 media_searchform($ns,$query); 1544 } 1545 1546 if(!count($evdata['data'])){ 1547 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL; 1548 }else { 1549 if ($fullscreen) { 1550 echo '<ul class="' . _media_get_list_type() . '">'; 1551 } 1552 foreach($evdata['data'] as $item){ 1553 if (!$fullscreen) media_printfile($item,$item['perm'],'',true); 1554 else media_printfile_thumbs($item,$item['perm'],false,true); 1555 } 1556 if ($fullscreen) echo '</ul>'.NL; 1557 } 1558} 1559 1560/** 1561 * Formats and prints one file in the list 1562 * 1563 * @param array $item 1564 * @param int $auth permission level 1565 * @param string $jump item id 1566 * @param bool $display_namespace 1567 */ 1568function media_printfile($item,$auth,$jump,$display_namespace=false){ 1569 global $lang; 1570 1571 // Prepare zebra coloring 1572 // I always wanted to use this variable name :-D 1573 static $twibble = 1; 1574 $twibble *= -1; 1575 $zebra = ($twibble == -1) ? 'odd' : 'even'; 1576 1577 // Automatically jump to recent action 1578 if($jump == $item['id']) { 1579 $jump = ' id="scroll__here" '; 1580 }else{ 1581 $jump = ''; 1582 } 1583 1584 // Prepare fileicons 1585 list($ext) = mimetype($item['file'],false); 1586 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext); 1587 $class = 'select mediafile mf_'.$class; 1588 1589 // Prepare filename 1590 $file = utf8_decodeFN($item['file']); 1591 1592 // Prepare info 1593 $info = ''; 1594 if($item['isimg']){ 1595 $info .= (int) $item['meta']->getField('File.Width'); 1596 $info .= '×'; 1597 $info .= (int) $item['meta']->getField('File.Height'); 1598 $info .= ' '; 1599 } 1600 $info .= '<i>'.dformat($item['mtime']).'</i>'; 1601 $info .= ' '; 1602 $info .= filesize_h($item['size']); 1603 1604 // output 1605 echo '<div class="'.$zebra.'"'.$jump.' title="'.hsc($item['id']).'">'.NL; 1606 if (!$display_namespace) { 1607 echo '<a id="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> '; 1608 } else { 1609 echo '<a id="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>'; 1610 } 1611 echo '<span class="info">('.$info.')</span>'.NL; 1612 1613 // view button 1614 $link = ml($item['id'],'',true); 1615 echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '. 1616 'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>'; 1617 1618 // mediamanager button 1619 $link = wl('',array('do'=>'media','image'=>$item['id'],'ns'=>getNS($item['id']))); 1620 echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/mediamanager.png" '. 1621 'alt="'.$lang['btn_media'].'" title="'.$lang['btn_media'].'" class="btn" /></a>'; 1622 1623 // delete button 1624 if($item['writable'] && $auth >= AUTH_DELETE){ 1625 $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']). 1626 '&sectok='.getSecurityToken(); 1627 echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'. 1628 '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '. 1629 'title="'.$lang['btn_delete'].'" class="btn" /></a>'; 1630 } 1631 1632 echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">'; 1633 echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>'; 1634 echo '</div>'; 1635 if($item['isimg']) media_printimgdetail($item); 1636 echo '<div class="clearer"></div>'.NL; 1637 echo '</div>'.NL; 1638} 1639 1640/** 1641 * Display a media icon 1642 * 1643 * @param string $filename media id 1644 * @param string $size the size subfolder, if not specified 16x16 is used 1645 * @return string html 1646 */ 1647function media_printicon($filename, $size=''){ 1648 list($ext) = mimetype(mediaFN($filename),false); 1649 1650 if (file_exists(DOKU_INC.'lib/images/fileicons/'.$size.'/'.$ext.'.png')) { 1651 $icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/'.$ext.'.png'; 1652 } else { 1653 $icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/file.png'; 1654 } 1655 1656 return '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />'; 1657} 1658 1659/** 1660 * Formats and prints one file in the list in the thumbnails view 1661 * 1662 * @author Kate Arzamastseva <pshns@ukr.net> 1663 * 1664 * @param array $item 1665 * @param int $auth permission level 1666 * @param bool|string $jump item id 1667 * @param bool $display_namespace 1668 */ 1669function media_printfile_thumbs($item,$auth,$jump=false,$display_namespace=false){ 1670 1671 // Prepare filename 1672 $file = utf8_decodeFN($item['file']); 1673 1674 // output 1675 echo '<li><dl title="'.hsc($item['id']).'">'.NL; 1676 1677 echo '<dt>'; 1678 if($item['isimg']) { 1679 media_printimgdetail($item, true); 1680 1681 } else { 1682 echo '<a id="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'. 1683 media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']), 1684 'tab_details' => 'view')).'">'; 1685 echo media_printicon($item['id'], '32x32'); 1686 echo '</a>'; 1687 } 1688 echo '</dt>'.NL; 1689 if (!$display_namespace) { 1690 $name = hsc($file); 1691 } else { 1692 $name = hsc($item['id']); 1693 } 1694 echo '<dd class="name"><a href="'.media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']), 1695 'tab_details' => 'view')).'" id="h_:'.$item['id'].'">'.$name.'</a></dd>'.NL; 1696 1697 if($item['isimg']){ 1698 $size = ''; 1699 $size .= (int) $item['meta']->getField('File.Width'); 1700 $size .= '×'; 1701 $size .= (int) $item['meta']->getField('File.Height'); 1702 echo '<dd class="size">'.$size.'</dd>'.NL; 1703 } else { 1704 echo '<dd class="size"> </dd>'.NL; 1705 } 1706 $date = dformat($item['mtime']); 1707 echo '<dd class="date">'.$date.'</dd>'.NL; 1708 $filesize = filesize_h($item['size']); 1709 echo '<dd class="filesize">'.$filesize.'</dd>'.NL; 1710 echo '</dl></li>'.NL; 1711} 1712 1713/** 1714 * Prints a thumbnail and metainfo 1715 * 1716 * @param array $item 1717 * @param bool $fullscreen 1718 */ 1719function media_printimgdetail($item, $fullscreen=false){ 1720 // prepare thumbnail 1721 $size = $fullscreen ? 90 : 120; 1722 1723 $w = (int) $item['meta']->getField('File.Width'); 1724 $h = (int) $item['meta']->getField('File.Height'); 1725 if($w>$size || $h>$size){ 1726 if (!$fullscreen) { 1727 $ratio = $item['meta']->getResizeRatio($size); 1728 } else { 1729 $ratio = $item['meta']->getResizeRatio($size,$size); 1730 } 1731 $w = floor($w * $ratio); 1732 $h = floor($h * $ratio); 1733 } 1734 $src = ml($item['id'],array('w'=>$w,'h'=>$h,'t'=>$item['mtime'])); 1735 $p = array(); 1736 if (!$fullscreen) { 1737 // In fullscreen mediamanager view, image resizing is done via CSS. 1738 $p['width'] = $w; 1739 $p['height'] = $h; 1740 } 1741 $p['alt'] = $item['id']; 1742 $att = buildAttributes($p); 1743 1744 // output 1745 if ($fullscreen) { 1746 echo '<a id="l_:'.$item['id'].'" class="image thumb" href="'. 1747 media_managerURL(['image' => hsc($item['id']), 'ns' => getNS($item['id']), 'tab_details' => 'view']).'">'; 1748 echo '<img src="'.$src.'" '.$att.' />'; 1749 echo '</a>'; 1750 } 1751 1752 if ($fullscreen) return; 1753 1754 echo '<div class="detail">'; 1755 echo '<div class="thumb">'; 1756 echo '<a id="d_:'.$item['id'].'" class="select">'; 1757 echo '<img src="'.$src.'" '.$att.' />'; 1758 echo '</a>'; 1759 echo '</div>'; 1760 1761 // read EXIF/IPTC data 1762 $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title')); 1763 $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment', 1764 'EXIF.TIFFImageDescription', 1765 'EXIF.TIFFUserComment')); 1766 if(\dokuwiki\Utf8\PhpString::strlen($d) > 250) $d = \dokuwiki\Utf8\PhpString::substr($d,0,250).'...'; 1767 $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject')); 1768 1769 // print EXIF/IPTC data 1770 if($t || $d || $k ){ 1771 echo '<p>'; 1772 if($t) echo '<strong>'.hsc($t).'</strong><br />'; 1773 if($d) echo hsc($d).'<br />'; 1774 if($t) echo '<em>'.hsc($k).'</em>'; 1775 echo '</p>'; 1776 } 1777 echo '</div>'; 1778} 1779 1780/** 1781 * Build link based on the current, adding/rewriting parameters 1782 * 1783 * @author Kate Arzamastseva <pshns@ukr.net> 1784 * 1785 * @param array|bool $params 1786 * @param string $amp separator 1787 * @param bool $abs absolute url? 1788 * @param bool $params_array return the parmeters array? 1789 * @return string|array - link or link parameters 1790 */ 1791function media_managerURL($params=false, $amp='&', $abs=false, $params_array=false) { 1792 global $ID; 1793 global $INPUT; 1794 1795 $gets = array('do' => 'media'); 1796 $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'list', 'sort'); 1797 foreach ($media_manager_params as $x) { 1798 if ($INPUT->has($x)) $gets[$x] = $INPUT->str($x); 1799 } 1800 1801 if ($params) { 1802 $gets = $params + $gets; 1803 } 1804 unset($gets['id']); 1805 if (isset($gets['delete'])) { 1806 unset($gets['image']); 1807 unset($gets['tab_details']); 1808 } 1809 1810 if ($params_array) return $gets; 1811 1812 return wl($ID,$gets,$abs,$amp); 1813} 1814 1815/** 1816 * Print the media upload form if permissions are correct 1817 * 1818 * @author Andreas Gohr <andi@splitbrain.org> 1819 * @author Kate Arzamastseva <pshns@ukr.net> 1820 * 1821 * @param string $ns 1822 * @param int $auth permission level 1823 * @param bool $fullscreen 1824 */ 1825function media_uploadform($ns, $auth, $fullscreen = false){ 1826 global $lang; 1827 global $conf; 1828 global $INPUT; 1829 1830 if($auth < AUTH_UPLOAD) { 1831 echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL; 1832 return; 1833 } 1834 $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE); 1835 1836 $update = false; 1837 $id = ''; 1838 if ($auth >= $auth_ow && $fullscreen && $INPUT->str('mediado') == 'update') { 1839 $update = true; 1840 $id = cleanID($INPUT->str('image')); 1841 } 1842 1843 // The default HTML upload form 1844 $params = array('id' => 'dw__upload', 1845 'enctype' => 'multipart/form-data'); 1846 if (!$fullscreen) { 1847 $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php'; 1848 } else { 1849 $params['action'] = media_managerURL(array('tab_files' => 'files', 1850 'tab_details' => 'view'), '&'); 1851 } 1852 1853 $form = new Doku_Form($params); 1854 if (!$fullscreen) echo '<div class="upload">' . $lang['mediaupload'] . '</div>'; 1855 $form->addElement(formSecurityToken()); 1856 $form->addHidden('ns', hsc($ns)); 1857 $form->addElement(form_makeOpenTag('p')); 1858 $form->addElement(form_makeFileField('upload', $lang['txt_upload'], 'upload__file')); 1859 $form->addElement(form_makeCloseTag('p')); 1860 $form->addElement(form_makeOpenTag('p')); 1861 $form->addElement(form_makeTextField('mediaid', noNS($id), $lang['txt_filename'], 'upload__name')); 1862 $form->addElement(form_makeButton('submit', '', $lang['btn_upload'])); 1863 $form->addElement(form_makeCloseTag('p')); 1864 1865 if($auth >= $auth_ow){ 1866 $form->addElement(form_makeOpenTag('p')); 1867 $attrs = array(); 1868 if ($update) $attrs['checked'] = 'checked'; 1869 $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check', $attrs)); 1870 $form->addElement(form_makeCloseTag('p')); 1871 } 1872 1873 echo NL.'<div id="mediamanager__uploader">'.NL; 1874 html_form('upload', $form); 1875 1876 echo '</div>'.NL; 1877 1878 echo '<p class="maxsize">'; 1879 printf($lang['maxuploadsize'],filesize_h(media_getuploadsize())); 1880 echo '</p>'.NL; 1881 1882} 1883 1884/** 1885 * Returns the size uploaded files may have 1886 * 1887 * This uses a conservative approach using the lowest number found 1888 * in any of the limiting ini settings 1889 * 1890 * @returns int size in bytes 1891 */ 1892function media_getuploadsize(){ 1893 $okay = 0; 1894 1895 $post = (int) php_to_byte(@ini_get('post_max_size')); 1896 $suho = (int) php_to_byte(@ini_get('suhosin.post.max_value_length')); 1897 $upld = (int) php_to_byte(@ini_get('upload_max_filesize')); 1898 1899 if($post && ($post < $okay || $okay == 0)) $okay = $post; 1900 if($suho && ($suho < $okay || $okay == 0)) $okay = $suho; 1901 if($upld && ($upld < $okay || $okay == 0)) $okay = $upld; 1902 1903 return $okay; 1904} 1905 1906/** 1907 * Print the search field form 1908 * 1909 * @author Tobias Sarnowski <sarnowski@cosmocode.de> 1910 * @author Kate Arzamastseva <pshns@ukr.net> 1911 * 1912 * @param string $ns 1913 * @param string $query 1914 * @param bool $fullscreen 1915 */ 1916function media_searchform($ns,$query='',$fullscreen=false){ 1917 global $lang; 1918 1919 // The default HTML search form 1920 $params = array('id' => 'dw__mediasearch'); 1921 if (!$fullscreen) { 1922 $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php'; 1923 } else { 1924 $params['action'] = media_managerURL(array(), '&'); 1925 } 1926 $form = new Doku_Form($params); 1927 $form->addHidden('ns', $ns); 1928 $form->addHidden($fullscreen ? 'mediado' : 'do', 'searchlist'); 1929 1930 $form->addElement(form_makeOpenTag('p')); 1931 $form->addElement( 1932 form_makeTextField( 1933 'q', 1934 $query, 1935 $lang['searchmedia'], 1936 '', 1937 '', 1938 array('title' => sprintf($lang['searchmedia_in'], hsc($ns) . ':*')) 1939 ) 1940 ); 1941 $form->addElement(form_makeButton('submit', '', $lang['btn_search'])); 1942 $form->addElement(form_makeCloseTag('p')); 1943 html_form('searchmedia', $form); 1944} 1945 1946/** 1947 * Build a tree outline of available media namespaces 1948 * 1949 * @author Andreas Gohr <andi@splitbrain.org> 1950 * 1951 * @param string $ns 1952 */ 1953function media_nstree($ns){ 1954 global $conf; 1955 global $lang; 1956 1957 // currently selected namespace 1958 $ns = cleanID($ns); 1959 if(empty($ns)){ 1960 global $ID; 1961 $ns = (string)getNS($ID); 1962 } 1963 1964 $ns_dir = utf8_encodeFN(str_replace(':','/',$ns)); 1965 1966 $data = array(); 1967 search($data,$conf['mediadir'],'search_index',array('ns' => $ns_dir, 'nofiles' => true)); 1968 1969 // wrap a list with the root level around the other namespaces 1970 array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true', 1971 'label' => '['.$lang['mediaroot'].']')); 1972 1973 // insert the current ns into the hierarchy if it isn't already part of it 1974 $ns_parts = explode(':', $ns); 1975 $tmp_ns = ''; 1976 $pos = 0; 1977 foreach ($ns_parts as $level => $part) { 1978 if ($tmp_ns) $tmp_ns .= ':'.$part; 1979 else $tmp_ns = $part; 1980 1981 // find the namespace parts or insert them 1982 while ($data[$pos]['id'] != $tmp_ns) { 1983 if ( 1984 $pos >= count($data) || 1985 ( 1986 $data[$pos]['level'] <= $level+1 && 1987 strnatcmp(utf8_encodeFN($data[$pos]['id']), utf8_encodeFN($tmp_ns)) > 0 1988 ) 1989 ) { 1990 array_splice($data, $pos, 0, array(array('level' => $level+1, 'id' => $tmp_ns, 'open' => 'true'))); 1991 break; 1992 } 1993 ++$pos; 1994 } 1995 } 1996 1997 echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li'); 1998} 1999 2000/** 2001 * Userfunction for html_buildlist 2002 * 2003 * Prints a media namespace tree item 2004 * 2005 * @author Andreas Gohr <andi@splitbrain.org> 2006 * 2007 * @param array $item 2008 * @return string html 2009 */ 2010function media_nstree_item($item){ 2011 global $INPUT; 2012 $pos = strrpos($item['id'], ':'); 2013 $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0); 2014 if(empty($item['label'])) $item['label'] = $label; 2015 2016 $ret = ''; 2017 if (!($INPUT->str('do') == 'media')) 2018 $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">'; 2019 else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id'], false), 'tab_files' => 'files')) 2020 .'" class="idx_dir">'; 2021 $ret .= $item['label']; 2022 $ret .= '</a>'; 2023 return $ret; 2024} 2025 2026/** 2027 * Userfunction for html_buildlist 2028 * 2029 * Prints a media namespace tree item opener 2030 * 2031 * @author Andreas Gohr <andi@splitbrain.org> 2032 * 2033 * @param array $item 2034 * @return string html 2035 */ 2036function media_nstree_li($item){ 2037 $class='media level'.$item['level']; 2038 if($item['open']){ 2039 $class .= ' open'; 2040 $img = DOKU_BASE.'lib/images/minus.gif'; 2041 $alt = '−'; 2042 }else{ 2043 $class .= ' closed'; 2044 $img = DOKU_BASE.'lib/images/plus.gif'; 2045 $alt = '+'; 2046 } 2047 // TODO: only deliver an image if it actually has a subtree... 2048 return '<li class="'.$class.'">'. 2049 '<img src="'.$img.'" alt="'.$alt.'" />'; 2050} 2051 2052/** 2053 * Resizes the given image to the given size 2054 * 2055 * @author Andreas Gohr <andi@splitbrain.org> 2056 * 2057 * @param string $file filename, path to file 2058 * @param string $ext extension 2059 * @param int $w desired width 2060 * @param int $h desired height 2061 * @return string path to resized or original size if failed 2062 */ 2063function media_resize_image($file, $ext, $w, $h=0){ 2064 global $conf; 2065 2066 $info = @getimagesize($file); //get original size 2067 if($info == false) return $file; // that's no image - it's a spaceship! 2068 2069 if(!$h) $h = round(($w * $info[1]) / $info[0]); 2070 if(!$w) $w = round(($h * $info[0]) / $info[1]); 2071 2072 // we wont scale up to infinity 2073 if($w > 2000 || $h > 2000) return $file; 2074 2075 // resize necessary? - (w,h) = native dimensions 2076 if(($w == $info[0]) && ($h == $info[1])) return $file; 2077 2078 //cache 2079 $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext); 2080 $mtime = @filemtime($local); // 0 if not exists 2081 2082 if($mtime > filemtime($file) || 2083 media_resize_imageIM($ext, $file, $info[0], $info[1], $local, $w, $h) || 2084 media_resize_imageGD($ext, $file, $info[0], $info[1], $local, $w, $h) 2085 ) { 2086 if($conf['fperm']) @chmod($local, $conf['fperm']); 2087 return $local; 2088 } 2089 //still here? resizing failed 2090 return $file; 2091} 2092 2093/** 2094 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it 2095 * to the wanted size 2096 * 2097 * Crops are centered horizontally but prefer the upper third of an vertical 2098 * image because most pics are more interesting in that area (rule of thirds) 2099 * 2100 * @author Andreas Gohr <andi@splitbrain.org> 2101 * 2102 * @param string $file filename, path to file 2103 * @param string $ext extension 2104 * @param int $w desired width 2105 * @param int $h desired height 2106 * @return string path to resized or original size if failed 2107 */ 2108function media_crop_image($file, $ext, $w, $h=0){ 2109 global $conf; 2110 2111 if(!$h) $h = $w; 2112 $info = @getimagesize($file); //get original size 2113 if($info == false) return $file; // that's no image - it's a spaceship! 2114 2115 // calculate crop size 2116 $fr = $info[0]/$info[1]; 2117 $tr = $w/$h; 2118 2119 // check if the crop can be handled completely by resize, 2120 // i.e. the specified width & height match the aspect ratio of the source image 2121 if ($w == round($h*$fr)) { 2122 return media_resize_image($file, $ext, $w); 2123 } 2124 2125 if($tr >= 1){ 2126 if($tr > $fr){ 2127 $cw = $info[0]; 2128 $ch = (int) ($info[0]/$tr); 2129 }else{ 2130 $cw = (int) ($info[1]*$tr); 2131 $ch = $info[1]; 2132 } 2133 }else{ 2134 if($tr < $fr){ 2135 $cw = (int) ($info[1]*$tr); 2136 $ch = $info[1]; 2137 }else{ 2138 $cw = $info[0]; 2139 $ch = (int) ($info[0]/$tr); 2140 } 2141 } 2142 // calculate crop offset 2143 $cx = (int) (($info[0]-$cw)/2); 2144 $cy = (int) (($info[1]-$ch)/3); 2145 2146 //cache 2147 $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext); 2148 $mtime = @filemtime($local); // 0 if not exists 2149 2150 if( $mtime > @filemtime($file) || 2151 media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) || 2152 media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){ 2153 if($conf['fperm']) @chmod($local, $conf['fperm']); 2154 return media_resize_image($local,$ext, $w, $h); 2155 } 2156 2157 //still here? cropping failed 2158 return media_resize_image($file,$ext, $w, $h); 2159} 2160 2161/** 2162 * Calculate a token to be used to verify fetch requests for resized or 2163 * cropped images have been internally generated - and prevent external 2164 * DDOS attacks via fetch 2165 * 2166 * @author Christopher Smith <chris@jalakai.co.uk> 2167 * 2168 * @param string $id id of the image 2169 * @param int $w resize/crop width 2170 * @param int $h resize/crop height 2171 * @return string token or empty string if no token required 2172 */ 2173function media_get_token($id,$w,$h){ 2174 // token is only required for modified images 2175 if ($w || $h || media_isexternal($id)) { 2176 $token = $id; 2177 if ($w) $token .= '.'.$w; 2178 if ($h) $token .= '.'.$h; 2179 2180 return substr(\dokuwiki\PassHash::hmac('md5', $token, auth_cookiesalt()),0,6); 2181 } 2182 2183 return ''; 2184} 2185 2186/** 2187 * Download a remote file and return local filename 2188 * 2189 * returns false if download fails. Uses cached file if available and 2190 * wanted 2191 * 2192 * @author Andreas Gohr <andi@splitbrain.org> 2193 * @author Pavel Vitis <Pavel.Vitis@seznam.cz> 2194 * 2195 * @param string $url 2196 * @param string $ext extension 2197 * @param int $cache cachetime in seconds 2198 * @return false|string path to cached file 2199 */ 2200function media_get_from_URL($url,$ext,$cache){ 2201 global $conf; 2202 2203 // if no cache or fetchsize just redirect 2204 if ($cache==0) return false; 2205 if (!$conf['fetchsize']) return false; 2206 2207 $local = getCacheName(strtolower($url),".media.$ext"); 2208 $mtime = @filemtime($local); // 0 if not exists 2209 2210 //decide if download needed: 2211 if(($mtime == 0) || // cache does not exist 2212 ($cache != -1 && $mtime < time() - $cache) // 'recache' and cache has expired 2213 ) { 2214 if(media_image_download($url, $local)) { 2215 return $local; 2216 } else { 2217 return false; 2218 } 2219 } 2220 2221 //if cache exists use it else 2222 if($mtime) return $local; 2223 2224 //else return false 2225 return false; 2226} 2227 2228/** 2229 * Download image files 2230 * 2231 * @author Andreas Gohr <andi@splitbrain.org> 2232 * 2233 * @param string $url 2234 * @param string $file path to file in which to put the downloaded content 2235 * @return bool 2236 */ 2237function media_image_download($url,$file){ 2238 global $conf; 2239 $http = new DokuHTTPClient(); 2240 $http->keep_alive = false; // we do single ops here, no need for keep-alive 2241 2242 $http->max_bodysize = $conf['fetchsize']; 2243 $http->timeout = 25; //max. 25 sec 2244 $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i'; 2245 2246 $data = $http->get($url); 2247 if(!$data) return false; 2248 2249 $fileexists = file_exists($file); 2250 $fp = @fopen($file,"w"); 2251 if(!$fp) return false; 2252 fwrite($fp,$data); 2253 fclose($fp); 2254 if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']); 2255 2256 // check if it is really an image 2257 $info = @getimagesize($file); 2258 if(!$info){ 2259 @unlink($file); 2260 return false; 2261 } 2262 2263 return true; 2264} 2265 2266/** 2267 * resize images using external ImageMagick convert program 2268 * 2269 * @author Pavel Vitis <Pavel.Vitis@seznam.cz> 2270 * @author Andreas Gohr <andi@splitbrain.org> 2271 * 2272 * @param string $ext extension 2273 * @param string $from filename path to file 2274 * @param int $from_w original width 2275 * @param int $from_h original height 2276 * @param string $to path to resized file 2277 * @param int $to_w desired width 2278 * @param int $to_h desired height 2279 * @return bool 2280 */ 2281function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){ 2282 global $conf; 2283 2284 // check if convert is configured 2285 if(!$conf['im_convert']) return false; 2286 2287 // prepare command 2288 $cmd = $conf['im_convert']; 2289 $cmd .= ' -resize '.$to_w.'x'.$to_h.'!'; 2290 if ($ext == 'jpg' || $ext == 'jpeg') { 2291 $cmd .= ' -quality '.$conf['jpg_quality']; 2292 } 2293 $cmd .= " $from $to"; 2294 2295 @exec($cmd,$out,$retval); 2296 if ($retval == 0) return true; 2297 return false; 2298} 2299 2300/** 2301 * crop images using external ImageMagick convert program 2302 * 2303 * @author Andreas Gohr <andi@splitbrain.org> 2304 * 2305 * @param string $ext extension 2306 * @param string $from filename path to file 2307 * @param int $from_w original width 2308 * @param int $from_h original height 2309 * @param string $to path to resized file 2310 * @param int $to_w desired width 2311 * @param int $to_h desired height 2312 * @param int $ofs_x offset of crop centre 2313 * @param int $ofs_y offset of crop centre 2314 * @return bool 2315 */ 2316function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){ 2317 global $conf; 2318 2319 // check if convert is configured 2320 if(!$conf['im_convert']) return false; 2321 2322 // prepare command 2323 $cmd = $conf['im_convert']; 2324 $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y; 2325 if ($ext == 'jpg' || $ext == 'jpeg') { 2326 $cmd .= ' -quality '.$conf['jpg_quality']; 2327 } 2328 $cmd .= " $from $to"; 2329 2330 @exec($cmd,$out,$retval); 2331 if ($retval == 0) return true; 2332 return false; 2333} 2334 2335/** 2336 * resize or crop images using PHP's libGD support 2337 * 2338 * @author Andreas Gohr <andi@splitbrain.org> 2339 * @author Sebastian Wienecke <s_wienecke@web.de> 2340 * 2341 * @param string $ext extension 2342 * @param string $from filename path to file 2343 * @param int $from_w original width 2344 * @param int $from_h original height 2345 * @param string $to path to resized file 2346 * @param int $to_w desired width 2347 * @param int $to_h desired height 2348 * @param int $ofs_x offset of crop centre 2349 * @param int $ofs_y offset of crop centre 2350 * @return bool 2351 */ 2352function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){ 2353 global $conf; 2354 2355 if($conf['gdlib'] < 1) return false; //no GDlib available or wanted 2356 2357 // check available memory 2358 if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){ 2359 return false; 2360 } 2361 2362 // create an image of the given filetype 2363 $image = false; 2364 if ($ext == 'jpg' || $ext == 'jpeg'){ 2365 if(!function_exists("imagecreatefromjpeg")) return false; 2366 $image = @imagecreatefromjpeg($from); 2367 }elseif($ext == 'png') { 2368 if(!function_exists("imagecreatefrompng")) return false; 2369 $image = @imagecreatefrompng($from); 2370 2371 }elseif($ext == 'gif') { 2372 if(!function_exists("imagecreatefromgif")) return false; 2373 $image = @imagecreatefromgif($from); 2374 } 2375 if(!$image) return false; 2376 2377 $newimg = false; 2378 if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){ 2379 $newimg = @imagecreatetruecolor ($to_w, $to_h); 2380 } 2381 if(!$newimg) $newimg = @imagecreate($to_w, $to_h); 2382 if(!$newimg){ 2383 imagedestroy($image); 2384 return false; 2385 } 2386 2387 //keep png alpha channel if possible 2388 if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){ 2389 imagealphablending($newimg, false); 2390 imagesavealpha($newimg,true); 2391 } 2392 2393 //keep gif transparent color if possible 2394 if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) { 2395 if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) { 2396 $transcolorindex = @imagecolortransparent($image); 2397 if($transcolorindex >= 0 ) { //transparent color exists 2398 $transcolor = @imagecolorsforindex($image, $transcolorindex); 2399 $transcolorindex = @imagecolorallocate( 2400 $newimg, 2401 $transcolor['red'], 2402 $transcolor['green'], 2403 $transcolor['blue'] 2404 ); 2405 @imagefill($newimg, 0, 0, $transcolorindex); 2406 @imagecolortransparent($newimg, $transcolorindex); 2407 }else{ //filling with white 2408 $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255); 2409 @imagefill($newimg, 0, 0, $whitecolorindex); 2410 } 2411 }else{ //filling with white 2412 $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255); 2413 @imagefill($newimg, 0, 0, $whitecolorindex); 2414 } 2415 } 2416 2417 //try resampling first 2418 if(function_exists("imagecopyresampled")){ 2419 if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) { 2420 imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h); 2421 } 2422 }else{ 2423 imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h); 2424 } 2425 2426 $okay = false; 2427 if ($ext == 'jpg' || $ext == 'jpeg'){ 2428 if(!function_exists('imagejpeg')){ 2429 $okay = false; 2430 }else{ 2431 $okay = imagejpeg($newimg, $to, $conf['jpg_quality']); 2432 } 2433 }elseif($ext == 'png') { 2434 if(!function_exists('imagepng')){ 2435 $okay = false; 2436 }else{ 2437 $okay = imagepng($newimg, $to); 2438 } 2439 }elseif($ext == 'gif') { 2440 if(!function_exists('imagegif')){ 2441 $okay = false; 2442 }else{ 2443 $okay = imagegif($newimg, $to); 2444 } 2445 } 2446 2447 // destroy GD image ressources 2448 if($image) imagedestroy($image); 2449 if($newimg) imagedestroy($newimg); 2450 2451 return $okay; 2452} 2453 2454/** 2455 * Return other media files with the same base name 2456 * but different extensions. 2457 * 2458 * @param string $src - ID of media file 2459 * @param string[] $exts - alternative extensions to find other files for 2460 * @return array - array(mime type => file ID) 2461 * 2462 * @author Anika Henke <anika@selfthinker.org> 2463 */ 2464function media_alternativefiles($src, $exts){ 2465 2466 $files = array(); 2467 list($srcExt, /* $srcMime */) = mimetype($src); 2468 $filebase = substr($src, 0, -1 * (strlen($srcExt)+1)); 2469 2470 foreach($exts as $ext) { 2471 $fileid = $filebase.'.'.$ext; 2472 $file = mediaFN($fileid); 2473 if(file_exists($file)) { 2474 list(/* $fileExt */, $fileMime) = mimetype($file); 2475 $files[$fileMime] = $fileid; 2476 } 2477 } 2478 return $files; 2479} 2480 2481/** 2482 * Check if video/audio is supported to be embedded. 2483 * 2484 * @param string $mime - mimetype of media file 2485 * @param string $type - type of media files to check ('video', 'audio', or null for all) 2486 * @return boolean 2487 * 2488 * @author Anika Henke <anika@selfthinker.org> 2489 */ 2490function media_supportedav($mime, $type=NULL){ 2491 $supportedAudio = array( 2492 'ogg' => 'audio/ogg', 2493 'mp3' => 'audio/mpeg', 2494 'wav' => 'audio/wav', 2495 ); 2496 $supportedVideo = array( 2497 'webm' => 'video/webm', 2498 'ogv' => 'video/ogg', 2499 'mp4' => 'video/mp4', 2500 ); 2501 if ($type == 'audio') { 2502 $supportedAv = $supportedAudio; 2503 } elseif ($type == 'video') { 2504 $supportedAv = $supportedVideo; 2505 } else { 2506 $supportedAv = array_merge($supportedAudio, $supportedVideo); 2507 } 2508 return in_array($mime, $supportedAv); 2509} 2510 2511/** 2512 * Return track media files with the same base name 2513 * but extensions that indicate kind and lang. 2514 * ie for foo.webm search foo.sub.lang.vtt, foo.cap.lang.vtt... 2515 * 2516 * @param string $src - ID of media file 2517 * @return array - array(mediaID => array( kind, srclang )) 2518 * 2519 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 2520 */ 2521function media_trackfiles($src){ 2522 $kinds=array( 2523 'sub' => 'subtitles', 2524 'cap' => 'captions', 2525 'des' => 'descriptions', 2526 'cha' => 'chapters', 2527 'met' => 'metadata' 2528 ); 2529 2530 $files = array(); 2531 $re='/\\.(sub|cap|des|cha|met)\\.([^.]+)\\.vtt$/'; 2532 $baseid=pathinfo($src, PATHINFO_FILENAME); 2533 $pattern=mediaFN($baseid).'.*.*.vtt'; 2534 $list=glob($pattern); 2535 foreach($list as $track) { 2536 if(preg_match($re, $track, $matches)){ 2537 $files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=array( 2538 $kinds[$matches[1]], 2539 $matches[2], 2540 ); 2541 } 2542 } 2543 return $files; 2544} 2545 2546/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ 2547