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