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