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