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