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