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