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"); 11require_once(DOKU_INC.'inc/html.php'); 12require_once(DOKU_INC.'inc/search.php'); 13require_once(DOKU_INC.'inc/JpegMeta.php'); 14 15/** 16 * Lists pages which currently use a media file selected for deletion 17 * 18 * References uses the same visual as search results and share 19 * their CSS tags except pagenames won't be links. 20 * 21 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 22 */ 23function media_filesinuse($data,$id){ 24 global $lang; 25 echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>'; 26 echo '<p>'.hsc($lang['ref_inuse']).'</p>'; 27 28 $hidden=0; //count of hits without read permission 29 foreach($data as $row){ 30 if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){ 31 echo '<div class="search_result">'; 32 echo '<span class="mediaref_ref">'.hsc($row).'</span>'; 33 echo '</div>'; 34 }else 35 $hidden++; 36 } 37 if ($hidden){ 38 print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>'; 39 } 40} 41 42/** 43 * Handles the saving of image meta data 44 * 45 * @author Andreas Gohr <andi@splitbrain.org> 46 */ 47function media_metasave($id,$auth,$data){ 48 if($auth < AUTH_UPLOAD) return false; 49 if(!checkSecurityToken()) return false; 50 global $lang; 51 global $conf; 52 $src = mediaFN($id); 53 54 $meta = new JpegMeta($src); 55 $meta->_parseAll(); 56 57 foreach($data as $key => $val){ 58 $val=trim($val); 59 if(empty($val)){ 60 $meta->deleteField($key); 61 }else{ 62 $meta->setField($key,$val); 63 } 64 } 65 66 if($meta->save()){ 67 if($conf['fperm']) chmod($src, $conf['fperm']); 68 msg($lang['metasaveok'],1); 69 return $id; 70 }else{ 71 msg($lang['metasaveerr'],-1); 72 return false; 73 } 74} 75 76/** 77 * Display the form to edit image meta data 78 * 79 * @author Andreas Gohr <andi@splitbrain.org> 80 */ 81function media_metaform($id,$auth){ 82 if($auth < AUTH_UPLOAD) return false; 83 global $lang; 84 85 // load the field descriptions 86 static $fields = null; 87 if(is_null($fields)){ 88 include(DOKU_CONF.'mediameta.php'); 89 if(@file_exists(DOKU_CONF.'mediameta.local.php')){ 90 include(DOKU_CONF.'mediameta.local.php'); 91 } 92 } 93 94 $src = mediaFN($id); 95 96 // output 97 echo '<h1>'.hsc(noNS($id)).'</h1>'.NL; 98 echo '<form action="'.DOKU_BASE.'lib/exe/mediamanager.php" accept-charset="utf-8" method="post" class="meta">'.NL; 99 formSecurityToken(); 100 foreach($fields as $key => $field){ 101 // get current value 102 $tags = array($field[0]); 103 if(is_array($field[3])) $tags = array_merge($tags,$field[3]); 104 $value = tpl_img_getTag($tags,'',$src); 105 $value = cleanText($value); 106 107 // prepare attributes 108 $p = array(); 109 $p['class'] = 'edit'; 110 $p['id'] = 'meta__'.$key; 111 $p['name'] = 'meta['.$field[0].']'; 112 113 // put label 114 echo '<div class="metafield">'; 115 echo '<label for="meta__'.$key.'">'; 116 echo ($lang[$field[1]]) ? $lang[$field[1]] : $field[1]; 117 echo ':</label>'; 118 119 // put input field 120 if($field[2] == 'text'){ 121 $p['value'] = $value; 122 $p['type'] = 'text'; 123 $att = buildAttributes($p); 124 echo "<input $att/>".NL; 125 }else{ 126 $att = buildAttributes($p); 127 echo "<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'.NL; 128 } 129 echo '</div>'.NL; 130 } 131 echo '<div class="buttons">'.NL; 132 echo '<input type="hidden" name="img" value="'.hsc($id).'" />'.NL; 133 echo '<input name="do[save]" type="submit" value="'.$lang['btn_save']. 134 '" title="'.$lang['btn_save'].' [S]" accesskey="s" class="button" />'.NL; 135 echo '<input name="do[cancel]" type="submit" value="'.$lang['btn_cancel']. 136 '" title="'.$lang['btn_cancel'].' [C]" accesskey="c" class="button" />'.NL; 137 echo '</div>'.NL; 138 echo '</form>'.NL; 139} 140 141 142/** 143 * Handles media file deletions 144 * 145 * If configured, checks for media references before deletion 146 * 147 * @author Andreas Gohr <andi@splitbrain.org> 148 * @return mixed false on error, true on delete or array with refs 149 */ 150function media_delete($id,$auth){ 151 if($auth < AUTH_DELETE) return false; 152 if(!checkSecurityToken()) return false; 153 global $conf; 154 global $lang; 155 156 // check for references if needed 157 $mediareferences = array(); 158 if($conf['refcheck']){ 159 require_once(DOKU_INC.'inc/fulltext.php'); 160 $mediareferences = ft_mediause($id,$conf['refshow']); 161 } 162 163 if(!count($mediareferences)){ 164 $file = mediaFN($id); 165 166 // trigger an event - MEDIA_DELETE_FILE 167 $data['name'] = basename($file); 168 $data['path'] = $file; 169 $data['size'] = (@file_exists($file)) ? filesize($file) : 0; 170 $evt = new Doku_Event('MEDIA_DELETE_FILE',$data); 171 if ($evt->advise_before()) { 172 if(@unlink($file)){ 173 msg(str_replace('%s',noNS($id),$lang['deletesucc']),1); 174 $del = io_sweepNS($id,'mediadir'); 175 if($del){ 176 // current namespace was removed. redirecting to root ns passing msg along 177 header('Location: '.DOKU_URL.'lib/exe/mediamanager.php?msg1='. 178 rawurlencode(str_replace('%s',noNS($id),$lang['deletesucc']))); 179 exit; 180 } 181 return true; 182 } 183 } 184 $evt->advise_after(); 185 unset($evt); 186 187 //something went wrong 188 msg(str_replace('%s',$file,$lang['deletefail']),-1); 189 return false; 190 }elseif(!$conf['refshow']){ 191 msg(str_replace('%s',noNS($id),$lang['mediainuse']),0); 192 return false; 193 } 194 195 return $mediareferences; 196} 197 198/** 199 * Handles media file uploads 200 * 201 * This generates an action event and delegates to _media_upload_action(). 202 * Action plugins are allowed to pre/postprocess the uploaded file. 203 * (The triggered event is preventable.) 204 * 205 * Event data: 206 * $data[0] fn_tmp: the temporary file name (read from $_FILES) 207 * $data[1] fn: the file name of the uploaded file 208 * $data[2] id: the future directory id of the uploaded file 209 * $data[3] imime: the mimetype of the uploaded file 210 * 211 * @triggers MEDIA_UPLOAD_FINISH 212 * @author Andreas Gohr <andi@splitbrain.org> 213 * @author Michael Klier <chi@chimeric.de> 214 * @return mixed false on error, id of the new file on success 215 */ 216function media_upload($ns,$auth){ 217 if($auth < AUTH_UPLOAD) return false; 218 if(!checkSecurityToken()) return false; 219 require_once(DOKU_INC.'inc/confutils.php'); 220 global $lang; 221 global $conf; 222 223 // get file and id 224 $id = $_POST['id']; 225 $file = $_FILES['upload']; 226 if(empty($id)) $id = $file['name']; 227 228 // check for data 229 if(!@filesize($file['tmp_name'])){ 230 msg('No data uploaded. Disk full?',-1); 231 return false; 232 } 233 234 // check extensions 235 list($fext,$fmime,$dl) = mimetype($file['name']); 236 list($iext,$imime,$dl) = mimetype($id); 237 if($fext && !$iext){ 238 // no extension specified in id - read original one 239 $id .= '.'.$fext; 240 $imime = $fmime; 241 }elseif($fext && $fext != $iext){ 242 // extension was changed, print warning 243 msg(sprintf($lang['mediaextchange'],$fext,$iext)); 244 } 245 246 // get filename 247 $id = cleanID($ns.':'.$id,false,true); 248 $fn = mediaFN($id); 249 250 // get filetype regexp 251 $types = array_keys(getMimeTypes()); 252 $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types); 253 $regex = join('|',$types); 254 255 // because a temp file was created already 256 if(preg_match('/\.('.$regex.')$/i',$fn)){ 257 //check for overwrite 258 if(@file_exists($fn) && (!$_REQUEST['ow'] || $auth < AUTH_DELETE)){ 259 msg($lang['uploadexist'],0); 260 return false; 261 } 262 // check for valid content 263 $ok = media_contentcheck($file['tmp_name'],$imime); 264 if($ok == -1){ 265 msg(sprintf($lang['uploadbadcontent'],".$iext"),-1); 266 return false; 267 }elseif($ok == -2){ 268 msg($lang['uploadspam'],-1); 269 return false; 270 }elseif($ok == -3){ 271 msg($lang['uploadxss'],-1); 272 return false; 273 } 274 275 // prepare event data 276 $data[0] = $file['tmp_name']; 277 $data[1] = $fn; 278 $data[2] = $id; 279 $data[3] = $imime; 280 281 // trigger event 282 return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true); 283 284 }else{ 285 msg($lang['uploadwrong'],-1); 286 } 287 return false; 288} 289 290/** 291 * Callback adapter for media_upload_finish() 292 * @author Michael Klier <chi@chimeric.de> 293 */ 294function _media_upload_action($data) { 295 // fixme do further sanity tests of given data? 296 if(is_array($data) && count($data)===4) { 297 return media_upload_finish($data[0], $data[1], $data[2], $data[3]); 298 } else { 299 return false; //callback error 300 } 301} 302 303/** 304 * Saves an uploaded media file 305 * 306 * @author Andreas Gohr <andi@splitbrain.org> 307 * @author Michael Klier <chi@chimeric.de> 308 */ 309function media_upload_finish($fn_tmp, $fn, $id, $imime) { 310 global $conf; 311 global $lang; 312 313 // prepare directory 314 io_createNamespace($id, 'media'); 315 316 if(move_uploaded_file($fn_tmp, $fn)) { 317 // Set the correct permission here. 318 // Always chmod media because they may be saved with different permissions than expected from the php umask. 319 // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.) 320 chmod($fn, $conf['fmode']); 321 msg($lang['uploadsucc'],1); 322 media_notify($id,$fn,$imime); 323 return $id; 324 }else{ 325 msg($lang['uploadfail'],-1); 326 } 327} 328 329/** 330 * This function checks if the uploaded content is really what the 331 * mimetype says it is. We also do spam checking for text types here. 332 * 333 * We need to do this stuff because we can not rely on the browser 334 * to do this check correctly. Yes, IE is broken as usual. 335 * 336 * @author Andreas Gohr <andi@splitbrain.org> 337 * @link http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting 338 * @fixme check all 26 magic IE filetypes here? 339 */ 340function media_contentcheck($file,$mime){ 341 global $conf; 342 if($conf['iexssprotect']){ 343 $fh = @fopen($file, 'rb'); 344 if($fh){ 345 $bytes = fread($fh, 256); 346 fclose($fh); 347 if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){ 348 return -3; 349 } 350 } 351 } 352 if(substr($mime,0,6) == 'image/'){ 353 $info = @getimagesize($file); 354 if($mime == 'image/gif' && $info[2] != 1){ 355 return -1; 356 }elseif($mime == 'image/jpeg' && $info[2] != 2){ 357 return -1; 358 }elseif($mime == 'image/png' && $info[2] != 3){ 359 return -1; 360 } 361 # fixme maybe check other images types as well 362 }elseif(substr($mime,0,5) == 'text/'){ 363 global $TEXT; 364 $TEXT = io_readFile($file); 365 if(checkwordblock()){ 366 return -2; 367 } 368 } 369 return 0; 370} 371 372/** 373 * Send a notify mail on uploads 374 * 375 * @author Andreas Gohr <andi@splitbrain.org> 376 */ 377function media_notify($id,$file,$mime){ 378 global $lang; 379 global $conf; 380 if(empty($conf['notify'])) return; //notify enabled? 381 382 $text = rawLocale('uploadmail'); 383 $text = str_replace('@DATE@',strftime($conf['dformat']),$text); 384 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text); 385 $text = str_replace('@IPADDRESS@',$_SERVER['REMOTE_ADDR'],$text); 386 $text = str_replace('@HOSTNAME@',gethostbyaddr($_SERVER['REMOTE_ADDR']),$text); 387 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 388 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text); 389 $text = str_replace('@MIME@',$mime,$text); 390 $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text); 391 $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text); 392 393 $from = $conf['mailfrom']; 394 $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from); 395 $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from); 396 $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from); 397 398 $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id; 399 400 mail_send($conf['notify'],$subject,$text,$from); 401} 402 403/** 404 * List all files in a given Media namespace 405 */ 406function media_filelist($ns,$auth=null,$jump=''){ 407 global $conf; 408 global $lang; 409 $ns = cleanID($ns); 410 411 // check auth our self if not given (needed for ajax calls) 412 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*"); 413 414 echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL; 415 416 if($auth < AUTH_READ){ 417 // FIXME: print permission warning here instead? 418 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL; 419 return; 420 } 421 422 media_uploadform($ns, $auth); 423 424 $dir = utf8_encodeFN(str_replace(':','/',$ns)); 425 $data = array(); 426 search($data,$conf['mediadir'],'search_media',array('showmsg'=>true),$dir); 427 428 if(!count($data)){ 429 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL; 430 return; 431 } 432 433 foreach($data as $item){ 434 media_printfile($item,$auth,$jump); 435 } 436} 437 438/** 439 * Print action links for a file depending on filetype 440 * and available permissions 441 * 442 * @todo contains inline javascript 443 */ 444function media_fileactions($item,$auth){ 445 global $lang; 446 447 // view button 448 $link = ml($item['id'],'',true); 449 echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '. 450 'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>'; 451 452 453 // no further actions if not writable 454 if(!$item['writable']) return; 455 456 // delete button 457 if($auth >= AUTH_DELETE){ 458 echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']). 459 '&sectok='.getSecurityToken().'" class="btn_media_delete" title="'.$item['id'].'">'. 460 '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '. 461 'title="'.$lang['btn_delete'].'" class="btn" /></a>'; 462 } 463 464 // edit button 465 if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){ 466 echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']).'">'. 467 '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '. 468 'title="'.$lang['metaedit'].'" class="btn" /></a>'; 469 } 470 471} 472 473/** 474 * Formats and prints one file in the list 475 */ 476function media_printfile($item,$auth,$jump){ 477 global $lang; 478 global $conf; 479 480 // Prepare zebra coloring 481 // I always wanted to use this variable name :-D 482 static $twibble = 1; 483 $twibble *= -1; 484 $zebra = ($twibble == -1) ? 'odd' : 'even'; 485 486 // Automatically jump to recent action 487 if($jump == $item['id']) { 488 $jump = ' id="scroll__here" '; 489 }else{ 490 $jump = ''; 491 } 492 493 // Prepare fileicons 494 list($ext,$mime,$dl) = mimetype($item['file']); 495 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext); 496 $class = 'select mediafile mf_'.$class; 497 498 // Prepare filename 499 $file = utf8_decodeFN($item['file']); 500 501 // Prepare info 502 $info = ''; 503 if($item['isimg']){ 504 $info .= (int) $item['meta']->getField('File.Width'); 505 $info .= '×'; 506 $info .= (int) $item['meta']->getField('File.Height'); 507 $info .= ' '; 508 } 509 $info .= '<i>'.strftime($conf['dformat'],$item['mtime']).'</i>'; 510 $info .= ' '; 511 $info .= filesize_h($item['size']); 512 513 // ouput 514 echo '<div class="'.$zebra.'"'.$jump.'>'.NL; 515 echo '<a name="h_'.$item['id'].'" class="'.$class.'">'.$file.'</a> '; 516 echo '<span class="info">('.$info.')</span>'.NL; 517 media_fileactions($item,$auth); 518 echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">'; 519 echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>'; 520 echo '</div>'; 521 if($item['isimg']) media_printimgdetail($item); 522 echo '<div class="clearer"></div>'.NL; 523 echo '</div>'.NL; 524} 525 526/** 527 * Prints a thumbnail and metainfos 528 */ 529function media_printimgdetail($item){ 530 // prepare thumbnail 531 $w = (int) $item['meta']->getField('File.Width'); 532 $h = (int) $item['meta']->getField('File.Height'); 533 if($w>120 || $h>120){ 534 $ratio = $item['meta']->getResizeRatio(120); 535 $w = floor($w * $ratio); 536 $h = floor($h * $ratio); 537 } 538 $src = ml($item['id'],array('w'=>$w,'h'=>$h)); 539 $p = array(); 540 $p['width'] = $w; 541 $p['height'] = $h; 542 $p['alt'] = $item['id']; 543 $p['class'] = 'thumb'; 544 $att = buildAttributes($p); 545 546 // output 547 echo '<div class="detail">'; 548 echo '<div class="thumb">'; 549 echo '<a name="d_'.$item['id'].'" class="select">'; 550 echo '<img src="'.$src.'" '.$att.' />'; 551 echo '</a>'; 552 echo '</div>'; 553 554 // read EXIF/IPTC data 555 $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title')); 556 $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment', 557 'EXIF.TIFFImageDescription', 558 'EXIF.TIFFUserComment')); 559 if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...'; 560 $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject')); 561 562 // print EXIF/IPTC data 563 if($t || $d || $k ){ 564 echo '<p>'; 565 if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />'; 566 if($d) echo htmlspecialchars($d).'<br />'; 567 if($t) echo '<em>'.htmlspecialchars($k).'</em>'; 568 echo '</p>'; 569 } 570 echo '</div>'; 571} 572 573/** 574 * Print the media upload form if permissions are correct 575 * 576 * @author Andreas Gohr <andi@splitbrain.org> 577 */ 578function media_uploadform($ns, $auth){ 579 global $lang; 580 581 if($auth < AUTH_UPLOAD) return; //fixme print info on missing permissions? 582 583 // The default HTML upload form 584 $form = new Doku_Form('dw__upload', DOKU_BASE.'lib/exe/mediamanager.php', false, 'multipart/form-data'); 585 $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>'); 586 $form->addElement(formSecurityToken()); 587 $form->addHidden('ns', hsc($ns)); 588 $form->addElement(form_makeOpenTag('p')); 589 $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file')); 590 $form->addElement(form_makeCloseTag('p')); 591 $form->addElement(form_makeOpenTag('p')); 592 $form->addElement(form_makeTextField('id', '', $lang['txt_filename'].':', 'upload__name')); 593 $form->addElement(form_makeButton('submit', '', $lang['btn_upload'])); 594 $form->addElement(form_makeCloseTag('p')); 595 596 if($auth >= AUTH_DELETE){ 597 $form->addElement(form_makeOpenTag('p')); 598 $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check')); 599 $form->addElement(form_makeCloseTag('p')); 600 } 601 html_form('upload', $form); 602 603 // prepare flashvars for multiupload 604 $opt = array( 605 'L_gridname' => $lang['mu_gridname'] , 606 'L_gridsize' => $lang['mu_gridsize'] , 607 'L_gridstat' => $lang['mu_gridstat'] , 608 'L_namespace' => $lang['mu_namespace'] , 609 'L_overwrite' => $lang['txt_overwrt'], 610 'L_browse' => $lang['mu_browse'], 611 'L_upload' => $lang['btn_upload'], 612 'L_toobig' => $lang['mu_toobig'], 613 'L_ready' => $lang['mu_ready'], 614 'L_done' => $lang['mu_done'], 615 'L_fail' => $lang['mu_fail'], 616 'L_authfail' => $lang['mu_authfail'], 617 'L_progress' => $lang['mu_progress'], 618 'L_filetypes' => $lang['mu_filetypes'], 619 620 'O_ns' => ":$ns", 621 'O_backend' => 'mediamanager.php?'.session_name().'='.session_id(), 622 'O_size' => php_to_byte(ini_get('upload_max_filesize')), 623 'O_extensions'=> join('|',array_keys(getMimeTypes())), 624 'O_overwrite' => ($auth >= AUTH_DELETE), 625 'O_sectok' => getSecurityToken(), 626 'O_authtok' => auth_createToken(), 627 ); 628 $var = buildURLparams($opt); 629 // output the flash uploader 630 ?> 631 <div id="dw__flashupload" style="display:none"> 632 <div class="upload"><?php echo $lang['mu_intro']?></div> 633 <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?> 634 </div> 635 <?php 636} 637 638/** 639 * Build a tree outline of available media namespaces 640 * 641 * @author Andreas Gohr <andi@splitbrain.org> 642 */ 643function media_nstree($ns){ 644 global $conf; 645 global $lang; 646 647 // currently selected namespace 648 $ns = cleanID($ns); 649 if(empty($ns)){ 650 $ns = dirname(str_replace(':','/',$ID)); 651 if($ns == '.') $ns =''; 652 } 653 $ns = utf8_encodeFN(str_replace(':','/',$ns)); 654 655 $data = array(); 656 search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true)); 657 658 // wrap a list with the root level around the other namespaces 659 $item = array( 'level' => 0, 'id' => '', 660 'open' =>'true', 'label' => '['.$lang['mediaroot'].']'); 661 662 echo '<ul class="idx">'; 663 echo media_nstree_li($item); 664 echo media_nstree_item($item); 665 echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li'); 666 echo '</li>'; 667 echo '</ul>'; 668} 669 670/** 671 * Userfunction for html_buildlist 672 * 673 * Prints a media namespace tree item 674 * 675 * @author Andreas Gohr <andi@splitbrain.org> 676 */ 677function media_nstree_item($item){ 678 $pos = strrpos($item['id'], ':'); 679 $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0); 680 if(!$item['label']) $item['label'] = $label; 681 682 $ret = ''; 683 $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">'; 684 $ret .= $item['label']; 685 $ret .= '</a>'; 686 return $ret; 687} 688 689/** 690 * Userfunction for html_buildlist 691 * 692 * Prints a media namespace tree item opener 693 * 694 * @author Andreas Gohr <andi@splitbrain.org> 695 */ 696function media_nstree_li($item){ 697 $class='media level'.$item['level']; 698 if($item['open']){ 699 $class .= ' open'; 700 $img = DOKU_BASE.'lib/images/minus.gif'; 701 $alt = '−'; 702 }else{ 703 $class .= ' closed'; 704 $img = DOKU_BASE.'lib/images/plus.gif'; 705 $alt = '+'; 706 } 707 return '<li class="'.$class.'">'. 708 '<img src="'.$img.'" alt="'.$alt.'" />'; 709} 710 711/** 712 * Resizes the given image to the given size 713 * 714 * @author Andreas Gohr <andi@splitbrain.org> 715 */ 716function media_resize_image($file, $ext, $w, $h=0){ 717 global $conf; 718 719 $info = @getimagesize($file); //get original size 720 if($info == false) return $file; // that's no image - it's a spaceship! 721 722 if(!$h) $h = round(($w * $info[1]) / $info[0]); 723 724 // we wont scale up to infinity 725 if($w > 2000 || $h > 2000) return $file; 726 727 //cache 728 $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext); 729 $mtime = @filemtime($local); // 0 if not exists 730 731 if( $mtime > filemtime($file) || 732 media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) || 733 media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){ 734 if($conf['fperm']) chmod($local, $conf['fperm']); 735 return $local; 736 } 737 //still here? resizing failed 738 return $file; 739} 740 741/** 742 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it 743 * to the wanted size 744 * 745 * Crops are centered horizontally but prefer the upper third of an vertical 746 * image because most pics are more interesting in that area (rule of thirds) 747 * 748 * @author Andreas Gohr <andi@splitbrain.org> 749 */ 750function media_crop_image($file, $ext, $w, $h=0){ 751 global $conf; 752 753 if(!$h) $h = $w; 754 $info = @getimagesize($file); //get original size 755 if($info == false) return $file; // that's no image - it's a spaceship! 756 757 // calculate crop size 758 $fr = $info[0]/$info[1]; 759 $tr = $w/$h; 760 if($tr >= 1){ 761 if($tr > $fr){ 762 $cw = $info[0]; 763 $ch = (int) $info[0]/$tr; 764 }else{ 765 $cw = (int) $info[1]*$tr; 766 $ch = $info[1]; 767 } 768 }else{ 769 if($tr < $fr){ 770 $cw = (int) $info[1]*$tr; 771 $ch = $info[1]; 772 }else{ 773 $cw = $info[0]; 774 $ch = (int) $info[0]/$tr; 775 } 776 } 777 // calculate crop offset 778 $cx = (int) ($info[0]-$cw)/2; 779 $cy = (int) ($info[1]-$ch)/3; 780 781 //cache 782 $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext); 783 $mtime = @filemtime($local); // 0 if not exists 784 785 if( $mtime > filemtime($file) || 786 media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) || 787 media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){ 788 if($conf['fperm']) chmod($local, $conf['fperm']); 789 return media_resize_image($local,$ext, $w, $h); 790 } 791 792 //still here? cropping failed 793 return media_resize_image($file,$ext, $w, $h); 794} 795 796/** 797 * Download a remote file and return local filename 798 * 799 * returns false if download fails. Uses cached file if available and 800 * wanted 801 * 802 * @author Andreas Gohr <andi@splitbrain.org> 803 * @author Pavel Vitis <Pavel.Vitis@seznam.cz> 804 */ 805function media_get_from_URL($url,$ext,$cache){ 806 global $conf; 807 808 // if no cache or fetchsize just redirect 809 if ($cache==0) return false; 810 if (!$conf['fetchsize']) return false; 811 812 $local = getCacheName(strtolower($url),".media.$ext"); 813 $mtime = @filemtime($local); // 0 if not exists 814 815 //decide if download needed: 816 if( ($mtime == 0) || // cache does not exist 817 ($cache != -1 && $mtime < time()-$cache) // 'recache' and cache has expired 818 ){ 819 if(media_image_download($url,$local)){ 820 return $local; 821 }else{ 822 return false; 823 } 824 } 825 826 //if cache exists use it else 827 if($mtime) return $local; 828 829 //else return false 830 return false; 831} 832 833/** 834 * Download image files 835 * 836 * @author Andreas Gohr <andi@splitbrain.org> 837 */ 838function media_image_download($url,$file){ 839 global $conf; 840 $http = new DokuHTTPClient(); 841 $http->max_bodysize = $conf['fetchsize']; 842 $http->timeout = 25; //max. 25 sec 843 $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i'; 844 845 $data = $http->get($url); 846 if(!$data) return false; 847 848 $fileexists = @file_exists($file); 849 $fp = @fopen($file,"w"); 850 if(!$fp) return false; 851 fwrite($fp,$data); 852 fclose($fp); 853 if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']); 854 855 // check if it is really an image 856 $info = @getimagesize($file); 857 if(!$info){ 858 @unlink($file); 859 return false; 860 } 861 862 return true; 863} 864 865/** 866 * resize images using external ImageMagick convert program 867 * 868 * @author Pavel Vitis <Pavel.Vitis@seznam.cz> 869 * @author Andreas Gohr <andi@splitbrain.org> 870 */ 871function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){ 872 global $conf; 873 874 // check if convert is configured 875 if(!$conf['im_convert']) return false; 876 877 // prepare command 878 $cmd = $conf['im_convert']; 879 $cmd .= ' -resize '.$to_w.'x'.$to_h.'!'; 880 if ($ext == 'jpg' || $ext == 'jpeg') { 881 $cmd .= ' -quality '.$conf['jpg_quality']; 882 } 883 $cmd .= " $from $to"; 884 885 @exec($cmd,$out,$retval); 886 if ($retval == 0) return true; 887 return false; 888} 889 890/** 891 * crop images using external ImageMagick convert program 892 * 893 * @author Andreas Gohr <andi@splitbrain.org> 894 */ 895function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){ 896 global $conf; 897 898 // check if convert is configured 899 if(!$conf['im_convert']) return false; 900 901 // prepare command 902 $cmd = $conf['im_convert']; 903 $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y; 904 if ($ext == 'jpg' || $ext == 'jpeg') { 905 $cmd .= ' -quality '.$conf['jpg_quality']; 906 } 907 $cmd .= " $from $to"; 908 909 @exec($cmd,$out,$retval); 910 if ($retval == 0) return true; 911 return false; 912} 913 914/** 915 * resize or crop images using PHP's libGD support 916 * 917 * @author Andreas Gohr <andi@splitbrain.org> 918 * @author Sebastian Wienecke <s_wienecke@web.de> 919 */ 920function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){ 921 global $conf; 922 923 if($conf['gdlib'] < 1) return false; //no GDlib available or wanted 924 925 // check available memory 926 if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){ 927 return false; 928 } 929 930 // create an image of the given filetype 931 if ($ext == 'jpg' || $ext == 'jpeg'){ 932 if(!function_exists("imagecreatefromjpeg")) return false; 933 $image = @imagecreatefromjpeg($from); 934 }elseif($ext == 'png') { 935 if(!function_exists("imagecreatefrompng")) return false; 936 $image = @imagecreatefrompng($from); 937 938 }elseif($ext == 'gif') { 939 if(!function_exists("imagecreatefromgif")) return false; 940 $image = @imagecreatefromgif($from); 941 } 942 if(!$image) return false; 943 944 if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){ 945 $newimg = @imagecreatetruecolor ($to_w, $to_h); 946 } 947 if(!$newimg) $newimg = @imagecreate($to_w, $to_h); 948 if(!$newimg){ 949 imagedestroy($image); 950 return false; 951 } 952 953 //keep png alpha channel if possible 954 if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){ 955 imagealphablending($newimg, false); 956 imagesavealpha($newimg,true); 957 } 958 959 //keep gif transparent color if possible 960 if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) { 961 if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) { 962 $transcolorindex = @imagecolortransparent($image); 963 if($transcolorindex >= 0 ) { //transparent color exists 964 $transcolor = @imagecolorsforindex($image, $transcolorindex); 965 $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']); 966 @imagefill($newimg, 0, 0, $transcolorindex); 967 @imagecolortransparent($newimg, $transcolorindex); 968 }else{ //filling with white 969 $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255); 970 @imagefill($newimg, 0, 0, $whitecolorindex); 971 } 972 }else{ //filling with white 973 $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255); 974 @imagefill($newimg, 0, 0, $whitecolorindex); 975 } 976 } 977 978 //try resampling first 979 if(function_exists("imagecopyresampled")){ 980 if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) { 981 imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h); 982 } 983 }else{ 984 imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h); 985 } 986 987 $okay = false; 988 if ($ext == 'jpg' || $ext == 'jpeg'){ 989 if(!function_exists('imagejpeg')){ 990 $okay = false; 991 }else{ 992 $okay = imagejpeg($newimg, $to, $conf['jpg_quality']); 993 } 994 }elseif($ext == 'png') { 995 if(!function_exists('imagepng')){ 996 $okay = false; 997 }else{ 998 $okay = imagepng($newimg, $to); 999 } 1000 }elseif($ext == 'gif') { 1001 if(!function_exists('imagegif')){ 1002 $okay = false; 1003 }else{ 1004 $okay = imagegif($newimg, $to); 1005 } 1006 } 1007 1008 // destroy GD image ressources 1009 if($image) imagedestroy($image); 1010 if($newimg) imagedestroy($newimg); 1011 1012 return $okay; 1013} 1014 1015