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