3 * All output and handler function needed for the media management popup
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
9 if(!defined('DOKU_INC')) die('meh.');
10 if(!defined('NL')) define('NL',"\n");
13 * Lists pages which currently use a media file selected for deletion
15 * References uses the same visual as search results and share
16 * their CSS tags except pagenames won't be links.
18 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
20 function media_filesinuse($data,$id){
22 echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
23 echo '<p>'.hsc($lang['ref_inuse']).'</p>';
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>';
35 print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
40 * Handles the saving of image meta data
42 * @author Andreas Gohr <andi@splitbrain.org>
43 * @author Kate Arzamastseva <pshns@ukr.net>
45 function media_metasave($id,$auth,$data){
46 if($auth < AUTH_UPLOAD) return false;
47 if(!checkSecurityToken()) return false;
52 $meta = new JpegMeta($src);
55 foreach($data as $key => $val){
58 $meta->deleteField($key);
60 $meta->setField($key,$val);
64 $old = @filemtime($src);
65 if(!@file_exists(mediaFN($id, $old)) && @file_exists($src)) {
66 // add old revision to the attic
67 media_saveOldRevision($id);
71 if($conf['fperm']) chmod($src, $conf['fperm']);
73 $new = @filemtime($src);
74 // add a log entry to the media changelog
75 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, $lang['media_meta_edited']);
77 msg($lang['metasaveok'],1);
80 msg($lang['metasaveerr'],-1);
86 * Display the form to edit image meta data
88 * @author Andreas Gohr <andi@splitbrain.org>
89 * @author Kate Arzamastseva <pshns@ukr.net>
91 function media_metaform($id,$auth){
92 global $lang, $config_cascade;
94 if($auth < AUTH_UPLOAD) {
95 echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
99 // load the field descriptions
100 static $fields = null;
101 if(is_null($fields)){
102 $config_files = getConfigFiles('mediameta');
103 foreach ($config_files as $config_file) {
104 if(@file_exists($config_file)) include($config_file);
111 $form = new Doku_Form(array('action' => media_managerURL(array('tab_details' => 'view'), '&'),
113 $form->addHidden('img', $id);
114 $form->addHidden('mediado', 'save');
115 foreach($fields as $key => $field){
117 if (empty($field[0])) continue;
118 $tags = array($field[0]);
119 if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
120 $value = tpl_img_getTag($tags,'',$src);
121 $value = cleanText($value);
123 // prepare attributes
125 $p['class'] = 'edit';
126 $p['id'] = 'meta__'.$key;
127 $p['name'] = 'meta['.$field[0].']';
128 $p_attrs = array('class' => 'edit');
130 $form->addElement('<div class="row">');
131 if($field[2] == 'text'){
132 $form->addElement(form_makeField('text', $p['name'], $value, ($lang[$field[1]]) ? $lang[$field[1]] : $field[1] . ':', $p['id'], $p['class'], $p_attrs));
134 $att = buildAttributes($p);
135 $form->addElement('<label for="meta__'.$key.'">'.$lang[$field[1]].'</label>');
136 $form->addElement("<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>');
138 $form->addElement('</div>'.NL);
140 $form->addElement('<div class="buttons">');
141 $form->addElement(form_makeButton('submit', '', $lang['btn_save'], array('accesskey' => 's', 'name' => 'mediado[save]')));
142 $form->addElement('</div>'.NL);
147 * Convenience function to check if a media file is still in use
149 * @author Michael Klier <chi@chimeric.de>
151 function media_inuse($id) {
153 $mediareferences = array();
154 if($conf['refcheck']){
155 $mediareferences = ft_mediause($id,$conf['refshow']);
156 if(!count($mediareferences)) {
159 return $mediareferences;
166 define('DOKU_MEDIA_DELETED', 1);
167 define('DOKU_MEDIA_NOT_AUTH', 2);
168 define('DOKU_MEDIA_INUSE', 4);
169 define('DOKU_MEDIA_EMPTY_NS', 8);
172 * Handles media file deletions
174 * If configured, checks for media references before deletion
176 * @author Andreas Gohr <andi@splitbrain.org>
177 * @return int One of: 0,
178 * DOKU_MEDIA_DELETED,
179 * DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
180 * DOKU_MEDIA_NOT_AUTH,
183 function media_delete($id,$auth){
185 if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
186 if(media_inuse($id)) return DOKU_MEDIA_INUSE;
188 $file = mediaFN($id);
190 // trigger an event - MEDIA_DELETE_FILE
192 $data['name'] = utf8_basename($file);
193 $data['path'] = $file;
194 $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
196 $data['unl'] = false;
197 $data['del'] = false;
198 $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
199 if ($evt->advise_before()) {
200 $old = @filemtime($file);
201 if(!@file_exists(mediaFN($id, $old)) && @file_exists($file)) {
202 // add old revision to the attic
203 media_saveOldRevision($id);
206 $data['unl'] = @unlink($file);
208 addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted']);
209 $data['del'] = io_sweepNS($id,'mediadir');
212 $evt->advise_after();
215 if($data['unl'] && $data['del']){
216 return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
219 return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
223 * Handle file uploads via XMLHttpRequest
225 * @return mixed false on error, id of the new file on success
227 function media_upload_xhr($ns,$auth){
228 if(!checkSecurityToken()) return false;
231 $id = $INPUT->get->str('qqfile');
232 list($ext,$mime,$dl) = mimetype($id);
233 $input = fopen("php://input", "r");
234 if (!($tmp = io_mktmpdir())) return false;
235 $path = $tmp.'/'.md5($id);
236 $target = fopen($path, "w");
237 $realSize = stream_copy_to_stream($input, $target);
240 if ($realSize != (int)$_SERVER["CONTENT_LENGTH"]){
247 array('name' => $path,
251 (($INPUT->get->str('ow') == 'checked') ? true : false),
256 if ($tmp) dir_delete($tmp);
257 if (is_array($res)) {
258 msg($res[0], $res[1]);
265 * Handles media file uploads
267 * @author Andreas Gohr <andi@splitbrain.org>
268 * @author Michael Klier <chi@chimeric.de>
269 * @return mixed false on error, id of the new file on success
271 function media_upload($ns,$auth,$file=false){
272 if(!checkSecurityToken()) return false;
277 $id = $INPUT->post->str('mediaid');
278 if (!$file) $file = $_FILES['upload'];
279 if(empty($id)) $id = $file['name'];
281 // check for errors (messages are done in lib/exe/mediamanager.php)
282 if($file['error']) return false;
285 list($fext,$fmime,$dl) = mimetype($file['name']);
286 list($iext,$imime,$dl) = mimetype($id);
288 // no extension specified in id - read original one
291 }elseif($fext && $fext != $iext){
292 // extension was changed, print warning
293 msg(sprintf($lang['mediaextchange'],$fext,$iext));
296 $res = media_save(array('name' => $file['tmp_name'],
298 'ext' => $iext), $ns.':'.$id,
299 $INPUT->post->bool('ow'), $auth, 'copy_uploaded_file');
300 if (is_array($res)) {
301 msg($res[0], $res[1]);
308 * An alternative to move_uploaded_file that copies
310 * Using copy, makes sure any setgid bits on the media directory are honored
312 * @see move_uploaded_file()
313 * @param string $from
317 function copy_uploaded_file($from, $to){
318 if(!is_uploaded_file($from)) return false;
319 $ok = copy($from, $to);
325 * This generates an action event and delegates to _media_upload_action().
326 * Action plugins are allowed to pre/postprocess the uploaded file.
327 * (The triggered event is preventable.)
330 * $data[0] fn_tmp: the temporary file name (read from $_FILES)
331 * $data[1] fn: the file name of the uploaded file
332 * $data[2] id: the future directory id of the uploaded file
333 * $data[3] imime: the mimetype of the uploaded file
334 * $data[4] overwrite: if an existing file is going to be overwritten
336 * @triggers MEDIA_UPLOAD_FINISH
338 function media_save($file, $id, $ow, $auth, $move) {
339 if($auth < AUTH_UPLOAD) {
340 return array("You don't have permissions to upload files.", -1);
343 if (!isset($file['mime']) || !isset($file['ext'])) {
344 list($ext, $mime) = mimetype($id);
345 if (!isset($file['mime'])) {
346 $file['mime'] = $mime;
348 if (!isset($file['ext'])) {
359 // get filetype regexp
360 $types = array_keys(getMimeTypes());
361 $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
362 $regex = join('|',$types);
364 // because a temp file was created already
365 if(!preg_match('/\.('.$regex.')$/i',$fn)) {
366 return array($lang['uploadwrong'],-1);
369 //check for overwrite
370 $overwrite = @file_exists($fn);
371 $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
372 if($overwrite && (!$ow || $auth < $auth_ow)) {
373 return array($lang['uploadexist'], 0);
375 // check for valid content
376 $ok = media_contentcheck($file['name'], $file['mime']);
378 return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
380 return array($lang['uploadspam'],-1);
382 return array($lang['uploadxss'],-1);
385 // prepare event data
386 $data[0] = $file['name'];
389 $data[3] = $file['mime'];
390 $data[4] = $overwrite;
394 return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
398 * Callback adapter for media_upload_finish()
399 * @author Michael Klier <chi@chimeric.de>
401 function _media_upload_action($data) {
402 // fixme do further sanity tests of given data?
403 if(is_array($data) && count($data)===6) {
404 return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
406 return false; //callback error
411 * Saves an uploaded media file
413 * @author Andreas Gohr <andi@splitbrain.org>
414 * @author Michael Klier <chi@chimeric.de>
415 * @author Kate Arzamastseva <pshns@ukr.net>
417 function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
422 $old = @filemtime($fn);
423 if(!@file_exists(mediaFN($id, $old)) && @file_exists($fn)) {
424 // add old revision to the attic if missing
425 media_saveOldRevision($id);
429 io_createNamespace($id, 'media');
431 if($move($fn_tmp, $fn)) {
432 @clearstatcache(true,$fn);
433 $new = @filemtime($fn);
434 // Set the correct permission here.
435 // Always chmod media because they may be saved with different permissions than expected from the php umask.
436 // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
437 chmod($fn, $conf['fmode']);
438 msg($lang['uploadsucc'],1);
439 media_notify($id,$fn,$imime,$old);
440 // add a log entry to the media changelog
442 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_REVERT, sprintf($lang['restored'], dformat($REV)), $REV);
443 } elseif ($overwrite) {
444 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT);
446 addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created']);
450 return array($lang['uploadfail'],-1);
455 * Moves the current version of media file to the media_attic
458 * @author Kate Arzamastseva <pshns@ukr.net>
460 * @return int - revision date
462 function media_saveOldRevision($id){
465 $oldf = mediaFN($id);
466 if(!@file_exists($oldf)) return '';
467 $date = filemtime($oldf);
468 if (!$conf['mediarevisions']) return $date;
470 if (!getRevisionInfo($id, $date, 8192, true)) {
471 // there was an external edit,
472 // there is no log entry for current version of file
473 if (!@file_exists(mediaMetaFN($id,'.changes'))) {
474 addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created']);
476 addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_EDIT);
480 $newf = mediaFN($id,$date);
481 io_makeFileDir($newf);
482 if(copy($oldf, $newf)) {
483 // Set the correct permission here.
484 // Always chmod media because they may be saved with different permissions than expected from the php umask.
485 // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
486 chmod($newf, $conf['fmode']);
492 * This function checks if the uploaded content is really what the
493 * mimetype says it is. We also do spam checking for text types here.
495 * We need to do this stuff because we can not rely on the browser
496 * to do this check correctly. Yes, IE is broken as usual.
498 * @author Andreas Gohr <andi@splitbrain.org>
499 * @link http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
500 * @fixme check all 26 magic IE filetypes here?
502 function media_contentcheck($file,$mime){
504 if($conf['iexssprotect']){
505 $fh = @fopen($file, 'rb');
507 $bytes = fread($fh, 256);
509 if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
514 if(substr($mime,0,6) == 'image/'){
515 $info = @getimagesize($file);
516 if($mime == 'image/gif' && $info[2] != 1){
518 }elseif($mime == 'image/jpeg' && $info[2] != 2){
520 }elseif($mime == 'image/png' && $info[2] != 3){
523 # fixme maybe check other images types as well
524 }elseif(substr($mime,0,5) == 'text/'){
526 $TEXT = io_readFile($file);
527 if(checkwordblock()){
535 * Send a notify mail on uploads
537 * @author Andreas Gohr <andi@splitbrain.org>
538 * @fixme this should embed thumbnails of images in HTML version
540 function media_notify($id,$file,$mime,$old_rev=false){
544 if(empty($conf['notify'])) return; //notify enabled?
546 $text = rawLocale('uploadmail');
549 'MEDIA' => ml($id,'',true,'&',true),
550 'SIZE' => filesize_h(filesize($file)),
553 if ($old_rev && $conf['mediarevisions']) {
554 $trep['OLD'] = ml($id, "rev=$old_rev", true, '&', true);
556 $trep['OLD'] = '---';
559 $mail = new Mailer();
560 $mail->to($conf['notify']);
561 $mail->subject($lang['mail_upload'].' '.$id);
562 $mail->setBody($text,$trep);
563 return $mail->send();
567 * List all files in a given Media namespace
569 function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=false){
574 // check auth our self if not given (needed for ajax calls)
575 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
577 if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
579 if($auth < AUTH_READ){
580 // FIXME: print permission warning here instead?
581 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
583 if (!$fullscreenview) media_uploadform($ns, $auth);
585 $dir = utf8_encodeFN(str_replace(':','/',$ns));
587 search($data,$conf['mediadir'],'search_media',
588 array('showmsg'=>true,'depth'=>1),$dir,1,$sort);
591 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
593 if ($fullscreenview) {
594 echo '<ul class="' . _media_get_list_type() . '">';
596 foreach($data as $item){
597 if (!$fullscreenview) {
598 media_printfile($item,$auth,$jump);
600 media_printfile_thumbs($item,$auth,$jump);
603 if ($fullscreenview) echo '</ul>'.NL;
606 if (!$fullscreenview) media_searchform($ns);
610 * Prints tabs for files list actions
612 * @author Kate Arzamastseva <pshns@ukr.net>
613 * @author Adrian Lang <mail@adrianlang.de>
615 * @param string $selected_tab - opened tab
618 function media_tabs_files($selected_tab = ''){
621 foreach(array('files' => 'mediaselect',
622 'upload' => 'media_uploadtab',
623 'search' => 'media_searchtab') as $tab => $caption) {
624 $tabs[$tab] = array('href' => media_managerURL(array('tab_files' => $tab), '&'),
625 'caption' => $lang[$caption]);
628 html_tabs($tabs, $selected_tab);
632 * Prints tabs for files details actions
634 * @author Kate Arzamastseva <pshns@ukr.net>
635 * @param string $selected_tab - opened tab
637 function media_tabs_details($image, $selected_tab = ''){
641 $tabs['view'] = array('href' => media_managerURL(array('tab_details' => 'view'), '&'),
642 'caption' => $lang['media_viewtab']);
644 list($ext, $mime) = mimetype($image);
645 if ($mime == 'image/jpeg' && @file_exists(mediaFN($image))) {
646 $tabs['edit'] = array('href' => media_managerURL(array('tab_details' => 'edit'), '&'),
647 'caption' => $lang['media_edittab']);
649 if ($conf['mediarevisions']) {
650 $tabs['history'] = array('href' => media_managerURL(array('tab_details' => 'history'), '&'),
651 'caption' => $lang['media_historytab']);
654 html_tabs($tabs, $selected_tab);
658 * Prints options for the tab that displays a list of all files
660 * @author Kate Arzamastseva <pshns@ukr.net>
662 function media_tab_files_options(){
667 $form = new Doku_Form(array('class' => 'options', 'method' => 'get',
668 'action' => wl($ID)));
669 $media_manager_params = media_managerURL(array(), '', false, true);
670 foreach($media_manager_params as $pKey => $pVal){
671 $form->addHidden($pKey, $pVal);
673 $form->addHidden('sectok', null);
674 if ($INPUT->has('q')) {
675 $form->addHidden('q', $INPUT->str('q'));
677 $form->addElement('<ul>'.NL);
678 foreach(array('list' => array('listType', array('thumbs', 'rows')),
679 'sort' => array('sortBy', array('name', 'date')))
680 as $group => $content) {
681 $checked = "_media_get_${group}_type";
682 $checked = $checked();
684 $form->addElement('<li class="' . $content[0] . '">');
685 foreach($content[1] as $option) {
687 if ($checked == $option) {
688 $attrs['checked'] = 'checked';
690 $form->addElement(form_makeRadioField($group, $option,
691 $lang['media_' . $group . '_' . $option],
692 $content[0] . '__' . $option,
695 $form->addElement('</li>'.NL);
697 $form->addElement('<li>');
698 $form->addElement(form_makeButton('submit', '', $lang['btn_apply']));
699 $form->addElement('</li>'.NL);
700 $form->addElement('</ul>'.NL);
705 * Returns type of sorting for the list of files in media manager
707 * @author Kate Arzamastseva <pshns@ukr.net>
708 * @return string - sort type
710 function _media_get_sort_type() {
711 return _media_get_display_param('sort', array('default' => 'name', 'date'));
714 function _media_get_list_type() {
715 return _media_get_display_param('list', array('default' => 'thumbs', 'rows'));
718 function _media_get_display_param($param, $values) {
720 if (in_array($INPUT->str($param), $values)) {
722 return $INPUT->str($param);
724 $val = get_doku_pref($param, $values['default']);
725 if (!in_array($val, $values)) {
726 $val = $values['default'];
733 * Prints tab that displays a list of all files
735 * @author Kate Arzamastseva <pshns@ukr.net>
737 function media_tab_files($ns,$auth=null,$jump='') {
739 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
741 if($auth < AUTH_READ){
742 echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
744 media_filelist($ns,$auth,$jump,true,_media_get_sort_type());
749 * Prints tab that displays uploading form
751 * @author Kate Arzamastseva <pshns@ukr.net>
753 function media_tab_upload($ns,$auth=null,$jump='') {
755 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
757 echo '<div class="upload">'.NL;
758 if ($auth >= AUTH_UPLOAD) {
759 echo '<p>' . $lang['mediaupload'] . '</p>';
761 media_uploadform($ns, $auth, true);
766 * Prints tab that displays search form
768 * @author Kate Arzamastseva <pshns@ukr.net>
770 function media_tab_search($ns,$auth=null) {
774 $do = $INPUT->str('mediado');
775 $query = $INPUT->str('q');
776 echo '<div class="search">'.NL;
778 media_searchform($ns, $query, true);
779 if ($do == 'searchlist' || $query) {
780 media_searchlist($query,$ns,$auth,true,_media_get_sort_type());
786 * Prints tab that displays mediafile details
788 * @author Kate Arzamastseva <pshns@ukr.net>
790 function media_tab_view($image, $ns, $auth=null, $rev=false) {
792 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
794 if ($image && $auth >= AUTH_READ) {
795 $meta = new JpegMeta(mediaFN($image, $rev));
796 media_preview($image, $auth, $rev, $meta);
797 media_preview_buttons($image, $auth, $rev);
798 media_details($image, $auth, $rev, $meta);
801 echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
806 * Prints tab that displays form for editing mediafile metadata
808 * @author Kate Arzamastseva <pshns@ukr.net>
810 function media_tab_edit($image, $ns, $auth=null) {
812 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
815 list($ext, $mime) = mimetype($image);
816 if ($mime == 'image/jpeg') media_metaform($image,$auth);
821 * Prints tab that displays mediafile revisions
823 * @author Kate Arzamastseva <pshns@ukr.net>
825 function media_tab_history($image, $ns, $auth=null) {
829 if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
830 $do = $INPUT->str('mediado');
832 if ($auth >= AUTH_READ && $image) {
834 media_diff($image, $ns, $auth);
836 $first = $INPUT->int('first');
837 html_revisions($first, $image);
840 echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
845 * Prints mediafile details
847 * @author Kate Arzamastseva <pshns@ukr.net>
849 function media_preview($image, $auth, $rev=false, $meta=false) {
851 $size = media_image_preview_size($image, $rev, $meta);
855 echo '<div class="image">';
861 $t = @filemtime(mediaFN($image));
865 $more['w'] = $size[0];
866 $more['h'] = $size[1];
867 $src = ml($image, $more);
869 echo '<a href="'.$src.'" target="_blank" title="'.$lang['mediaview'].'">';
870 echo '<img src="'.$src.'" alt="" style="max-width: '.$size[0].'px;" />';
878 * Prints mediafile action buttons
880 * @author Kate Arzamastseva <pshns@ukr.net>
882 function media_preview_buttons($image, $auth, $rev=false) {
885 echo '<ul class="actions">'.NL;
887 if($auth >= AUTH_DELETE && !$rev && @file_exists(mediaFN($image))){
890 $form = new Doku_Form(array('id' => 'mediamanager__btn_delete',
891 'action'=>media_managerURL(array('delete' => $image), '&')));
892 $form->addElement(form_makeButton('submit','',$lang['btn_delete']));
898 $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
899 if($auth >= $auth_ow && !$rev){
901 // upload new version button
902 $form = new Doku_Form(array('id' => 'mediamanager__btn_update',
903 'action'=>media_managerURL(array('image' => $image, 'mediado' => 'update'), '&')));
904 $form->addElement(form_makeButton('submit','',$lang['media_update']));
910 if($auth >= AUTH_UPLOAD && $rev && $conf['mediarevisions'] && @file_exists(mediaFN($image, $rev))){
913 $form = new Doku_Form(array('id' => 'mediamanager__btn_restore',
914 'action'=>media_managerURL(array('image' => $image), '&')));
915 $form->addHidden('mediado','restore');
916 $form->addHidden('rev',$rev);
917 $form->addElement(form_makeButton('submit','',$lang['media_restore']));
927 * Returns image width and height for mediamanager preview panel
929 * @author Kate Arzamastseva <pshns@ukr.net>
930 * @param string $image
932 * @param JpegMeta $meta
935 function media_image_preview_size($image, $rev, $meta, $size = 500) {
936 if (!preg_match("/\.(jpe?g|gif|png)$/", $image) || !file_exists(mediaFN($image, $rev))) return false;
938 $info = getimagesize(mediaFN($image, $rev));
942 if($meta && ($w > $size || $h > $size)){
943 $ratio = $meta->getResizeRatio($size, $size);
944 $w = floor($w * $ratio);
945 $h = floor($h * $ratio);
947 return array($w, $h);
951 * Returns the requested EXIF/IPTC tag from the image meta
953 * @author Kate Arzamastseva <pshns@ukr.net>
955 * @param JpegMeta $meta
959 function media_getTag($tags,$meta,$alt=''){
960 if($meta === false) return $alt;
961 $info = $meta->getField($tags);
962 if($info == false) return $alt;
967 * Returns mediafile tags
969 * @author Kate Arzamastseva <pshns@ukr.net>
970 * @param JpegMeta $meta
973 function media_file_tags($meta) {
974 global $config_cascade;
976 // load the field descriptions
977 static $fields = null;
978 if(is_null($fields)){
979 $config_files = getConfigFiles('mediameta');
980 foreach ($config_files as $config_file) {
981 if(@file_exists($config_file)) include($config_file);
987 foreach($fields as $key => $tag){
989 if (!empty($tag[0])) $t = array($tag[0]);
990 if(is_array($tag[3])) $t = array_merge($t,$tag[3]);
991 $value = media_getTag($t, $meta);
992 $tags[] = array('tag' => $tag, 'value' => $value);
999 * Prints mediafile tags
1001 * @author Kate Arzamastseva <pshns@ukr.net>
1003 function media_details($image, $auth, $rev=false, $meta=false) {
1006 if (!$meta) $meta = new JpegMeta(mediaFN($image, $rev));
1007 $tags = media_file_tags($meta);
1010 foreach($tags as $tag){
1011 if ($tag['value']) {
1012 $value = cleanText($tag['value']);
1013 echo '<dt>'.$lang[$tag['tag'][1]].':</dt><dd>';
1014 if ($tag['tag'][2] == 'date') echo dformat($value);
1015 else echo hsc($value);
1023 * Shows difference between two revisions of file
1025 * @author Kate Arzamastseva <pshns@ukr.net>
1027 function media_diff($image, $ns, $auth, $fromajax = false) {
1032 if ($auth < AUTH_READ || !$image || !$conf['mediarevisions']) return '';
1034 $rev1 = $INPUT->int('rev');
1036 $rev2 = $INPUT->ref('rev2');
1037 if(is_array($rev2)){
1038 $rev1 = (int) $rev2[0];
1039 $rev2 = (int) $rev2[1];
1046 $rev2 = $INPUT->int('rev2');
1049 if ($rev1 && !file_exists(mediaFN($image, $rev1))) $rev1 = false;
1050 if ($rev2 && !file_exists(mediaFN($image, $rev2))) $rev2 = false;
1052 if($rev1 && $rev2){ // two specific revisions wanted
1053 // make sure order is correct (older on the left)
1061 }elseif($rev1){ // single revision given, compare to current
1064 }else{ // no revision was given, compare previous to current
1066 $revs = getRevisions($image, 0, 1, 8192, true);
1067 if (file_exists(mediaFN($image, $revs[0]))) {
1074 // prepare event data
1080 $data[5] = $fromajax;
1083 return trigger_event('MEDIA_DIFF', $data, '_media_file_diff', true);
1087 function _media_file_diff($data) {
1088 if(is_array($data) && count($data)===6) {
1089 return media_file_diff($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
1096 * Shows difference between two revisions of image
1098 * @author Kate Arzamastseva <pshns@ukr.net>
1100 function media_file_diff($image, $l_rev, $r_rev, $ns, $auth, $fromajax){
1102 global $config_cascade;
1105 $l_meta = new JpegMeta(mediaFN($image, $l_rev));
1106 $r_meta = new JpegMeta(mediaFN($image, $r_rev));
1108 $is_img = preg_match("/\.(jpe?g|gif|png)$/", $image);
1110 $l_size = media_image_preview_size($image, $l_rev, $l_meta);
1111 $r_size = media_image_preview_size($image, $r_rev, $r_meta);
1112 $is_img = ($l_size && $r_size && ($l_size[0] >= 30 || $r_size[0] >= 30));
1114 $difftype = $INPUT->str('difftype');
1117 $form = new Doku_Form(array(
1118 'action' => media_managerURL(array(), '&'),
1120 'id' => 'mediamanager__form_diffview',
1121 'class' => 'diffView'
1123 $form->addHidden('sectok', null);
1124 $form->addElement('<input type="hidden" name="rev2[]" value="'.$l_rev.'" ></input>');
1125 $form->addElement('<input type="hidden" name="rev2[]" value="'.$r_rev.'" ></input>');
1126 $form->addHidden('mediado', 'diff');
1129 echo NL.'<div id="mediamanager__diff" >'.NL;
1132 if ($difftype == 'opacity' || $difftype == 'portions') {
1133 media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $difftype);
1134 if (!$fromajax) echo '</div>';
1139 list($l_head, $r_head) = html_diff_head($l_rev, $r_rev, $image, true);
1145 <th><?php echo $l_head; ?></th>
1146 <th><?php echo $r_head; ?></th>
1150 echo '<tr class="image">';
1152 media_preview($image, $auth, $l_rev, $l_meta);
1156 media_preview($image, $auth, $r_rev, $r_meta);
1160 echo '<tr class="actions">';
1162 media_preview_buttons($image, $auth, $l_rev);
1166 media_preview_buttons($image, $auth, $r_rev);
1170 $l_tags = media_file_tags($l_meta);
1171 $r_tags = media_file_tags($r_meta);
1172 // FIXME r_tags-only stuff
1173 foreach ($l_tags as $key => $l_tag) {
1174 if ($l_tag['value'] != $r_tags[$key]['value']) {
1175 $r_tags[$key]['highlighted'] = true;
1176 $l_tags[$key]['highlighted'] = true;
1177 } else if (!$l_tag['value'] || !$r_tags[$key]['value']) {
1178 unset($r_tags[$key]);
1179 unset($l_tags[$key]);
1184 foreach(array($l_tags,$r_tags) as $tags){
1187 echo '<dl class="img_tags">';
1188 foreach($tags as $tag){
1189 $value = cleanText($tag['value']);
1190 if (!$value) $value = '-';
1191 echo '<dt>'.$lang[$tag['tag'][1]].':</dt>';
1193 if ($tag['highlighted']) {
1196 if ($tag['tag'][2] == 'date') echo dformat($value);
1197 else echo hsc($value);
1198 if ($tag['highlighted']) {
1212 if ($is_img && !$fromajax) echo '</div>';
1216 * Prints two images side by side
1219 * @author Kate Arzamastseva <pshns@ukr.net>
1220 * @param string $image
1223 * @param array $l_size
1224 * @param array $r_size
1225 * @param string $type
1227 function media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $type) {
1228 if ($l_size != $r_size) {
1229 if ($r_size[0] > $l_size[0]) {
1234 $l_more = array('rev' => $l_rev, 'h' => $l_size[1], 'w' => $l_size[0]);
1235 $r_more = array('rev' => $r_rev, 'h' => $l_size[1], 'w' => $l_size[0]);
1237 $l_src = ml($image, $l_more);
1238 $r_src = ml($image, $r_more);
1241 echo '<div class="slider" style="max-width: '.($l_size[0]-20).'px;" ></div>'.NL;
1243 // two images in divs
1244 echo '<div class="imageDiff ' . $type . '">'.NL;
1245 echo '<div class="image1" style="max-width: '.$l_size[0].'px;">';
1246 echo '<img src="'.$l_src.'" alt="" />';
1248 echo '<div class="image2" style="max-width: '.$l_size[0].'px;">';
1249 echo '<img src="'.$r_src.'" alt="" />';
1255 * Restores an old revision of a media file
1257 * @param string $image
1260 * @return string - file's id
1261 * @author Kate Arzamastseva <pshns@ukr.net>
1263 function media_restore($image, $rev, $auth){
1265 if ($auth < AUTH_UPLOAD || !$conf['mediarevisions']) return false;
1266 $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')));
1267 if (!$image || (!file_exists(mediaFN($image)) && !$removed)) return false;
1268 if (!$rev || !file_exists(mediaFN($image, $rev))) return false;
1269 list($iext,$imime,$dl) = mimetype($image);
1270 $res = media_upload_finish(mediaFN($image, $rev),
1276 if (is_array($res)) {
1277 msg($res[0], $res[1]);
1284 * List all files found by the search request
1286 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1287 * @author Andreas Gohr <gohr@cosmocode.de>
1288 * @author Kate Arzamastseva <pshns@ukr.net>
1289 * @triggers MEDIA_SEARCH
1291 function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort=''){
1303 $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
1304 if ($evt->advise_before()) {
1305 $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
1306 $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
1307 search($evdata['data'],
1310 array('showmsg'=>false,'pattern'=>$pattern),
1315 foreach ($evdata['data'] as $k => $v) {
1316 $data[$k] = ($sort == 'date') ? $v['mtime'] : $v['id'];
1318 array_multisort($data, SORT_DESC, SORT_NUMERIC, $evdata['data']);
1320 $evt->advise_after();
1325 echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
1326 media_searchform($ns,$query);
1329 if(!count($evdata['data'])){
1330 echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
1333 echo '<ul class="' . _media_get_list_type() . '">';
1335 foreach($evdata['data'] as $item){
1336 if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
1337 else media_printfile_thumbs($item,$item['perm'],false,true);
1339 if ($fullscreen) echo '</ul>'.NL;
1344 * Formats and prints one file in the list
1346 function media_printfile($item,$auth,$jump,$display_namespace=false){
1350 // Prepare zebra coloring
1351 // I always wanted to use this variable name :-D
1352 static $twibble = 1;
1354 $zebra = ($twibble == -1) ? 'odd' : 'even';
1356 // Automatically jump to recent action
1357 if($jump == $item['id']) {
1358 $jump = ' id="scroll__here" ';
1363 // Prepare fileicons
1364 list($ext,$mime,$dl) = mimetype($item['file'],false);
1365 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1366 $class = 'select mediafile mf_'.$class;
1369 $file = utf8_decodeFN($item['file']);
1374 $info .= (int) $item['meta']->getField('File.Width');
1376 $info .= (int) $item['meta']->getField('File.Height');
1379 $info .= '<i>'.dformat($item['mtime']).'</i>';
1381 $info .= filesize_h($item['size']);
1384 echo '<div class="'.$zebra.'"'.$jump.' title="'.hsc($item['id']).'">'.NL;
1385 if (!$display_namespace) {
1386 echo '<a id="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1388 echo '<a id="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1390 echo '<span class="info">('.$info.')</span>'.NL;
1393 $link = ml($item['id'],'',true);
1394 echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
1395 'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
1397 // mediamanager button
1398 $link = wl('',array('do'=>'media','image'=>$item['id'],'ns'=>getNS($item['id'])));
1399 echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/mediamanager.png" '.
1400 'alt="'.$lang['btn_media'].'" title="'.$lang['btn_media'].'" class="btn" /></a>';
1403 if($item['writable'] && $auth >= AUTH_DELETE){
1404 $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
1405 '&sectok='.getSecurityToken();
1406 echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
1407 '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
1408 'title="'.$lang['btn_delete'].'" class="btn" /></a>';
1411 echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1412 echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1414 if($item['isimg']) media_printimgdetail($item);
1415 echo '<div class="clearer"></div>'.NL;
1419 function media_printicon($filename){
1420 list($ext,$mime,$dl) = mimetype(mediaFN($filename),false);
1422 if (@file_exists(DOKU_INC.'lib/images/fileicons/'.$ext.'.png')) {
1423 $icon = DOKU_BASE.'lib/images/fileicons/'.$ext.'.png';
1425 $icon = DOKU_BASE.'lib/images/fileicons/file.png';
1428 return '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />';
1433 * Formats and prints one file in the list in the thumbnails view
1435 * @author Kate Arzamastseva <pshns@ukr.net>
1437 function media_printfile_thumbs($item,$auth,$jump=false,$display_namespace=false){
1442 $file = utf8_decodeFN($item['file']);
1445 echo '<li><dl title="'.hsc($item['id']).'">'.NL;
1448 if($item['isimg']) {
1449 media_printimgdetail($item, true);
1452 echo '<a id="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1453 media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']),
1454 'tab_details' => 'view')).'">';
1455 echo media_printicon($item['id']);
1459 if (!$display_namespace) {
1462 $name = hsc($item['id']);
1464 echo '<dd class="name"><a href="'.media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']),
1465 'tab_details' => 'view')).'" id="h_:'.$item['id'].'">'.$name.'</a></dd>'.NL;
1469 $size .= (int) $item['meta']->getField('File.Width');
1471 $size .= (int) $item['meta']->getField('File.Height');
1472 echo '<dd class="size">'.$size.'</dd>'.NL;
1474 echo '<dd class="size"> </dd>'.NL;
1476 $date = dformat($item['mtime']);
1477 echo '<dd class="date">'.$date.'</dd>'.NL;
1478 $filesize = filesize_h($item['size']);
1479 echo '<dd class="filesize">'.$filesize.'</dd>'.NL;
1480 echo '</dl></li>'.NL;
1484 * Prints a thumbnail and metainfos
1486 function media_printimgdetail($item, $fullscreen=false){
1487 // prepare thumbnail
1488 $size = $fullscreen ? 90 : 120;
1490 $w = (int) $item['meta']->getField('File.Width');
1491 $h = (int) $item['meta']->getField('File.Height');
1492 if($w>$size || $h>$size){
1494 $ratio = $item['meta']->getResizeRatio($size);
1496 $ratio = $item['meta']->getResizeRatio($size,$size);
1498 $w = floor($w * $ratio);
1499 $h = floor($h * $ratio);
1501 $src = ml($item['id'],array('w'=>$w,'h'=>$h,'t'=>$item['mtime']));
1504 // In fullscreen mediamanager view, image resizing is done via CSS.
1508 $p['alt'] = $item['id'];
1509 $att = buildAttributes($p);
1513 echo '<a id="l_:'.$item['id'].'" class="image thumb" href="'.
1514 media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']), 'tab_details' => 'view')).'">';
1515 echo '<img src="'.$src.'" '.$att.' />';
1519 if ($fullscreen) return;
1521 echo '<div class="detail">';
1522 echo '<div class="thumb">';
1523 echo '<a id="d_:'.$item['id'].'" class="select">';
1524 echo '<img src="'.$src.'" '.$att.' />';
1528 // read EXIF/IPTC data
1529 $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1530 $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1531 'EXIF.TIFFImageDescription',
1532 'EXIF.TIFFUserComment'));
1533 if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
1534 $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1536 // print EXIF/IPTC data
1537 if($t || $d || $k ){
1539 if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
1540 if($d) echo htmlspecialchars($d).'<br />';
1541 if($t) echo '<em>'.htmlspecialchars($k).'</em>';
1548 * Build link based on the current, adding/rewriting
1551 * @author Kate Arzamastseva <pshns@ukr.net>
1552 * @param array $params
1553 * @param string $amp - separator
1554 * @return string - link
1556 function media_managerURL($params=false, $amp='&', $abs=false, $params_array=false) {
1561 $gets = array('do' => 'media');
1562 $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'list', 'sort');
1563 foreach ($media_manager_params as $x) {
1564 if ($INPUT->has($x)) $gets[$x] = $INPUT->str($x);
1568 $gets = $params + $gets;
1571 if (isset($gets['delete'])) {
1572 unset($gets['image']);
1573 unset($gets['tab_details']);
1576 if ($params_array) return $gets;
1578 return wl($ID,$gets,$abs,$amp);
1582 * Print the media upload form if permissions are correct
1584 * @author Andreas Gohr <andi@splitbrain.org>
1585 * @author Kate Arzamastseva <pshns@ukr.net>
1587 function media_uploadform($ns, $auth, $fullscreen = false){
1592 if($auth < AUTH_UPLOAD) {
1593 echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1596 $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
1600 if ($auth >= $auth_ow && $fullscreen && $INPUT->str('mediado') == 'update') {
1602 $id = cleanID($INPUT->str('image'));
1605 // The default HTML upload form
1606 $params = array('id' => 'dw__upload',
1607 'enctype' => 'multipart/form-data');
1609 $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1611 $params['action'] = media_managerURL(array('tab_files' => 'files',
1612 'tab_details' => 'view'), '&');
1615 $form = new Doku_Form($params);
1616 if (!$fullscreen) echo '<div class="upload">' . $lang['mediaupload'] . '</div>';
1617 $form->addElement(formSecurityToken());
1618 $form->addHidden('ns', hsc($ns));
1619 $form->addElement(form_makeOpenTag('p'));
1620 $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
1621 $form->addElement(form_makeCloseTag('p'));
1622 $form->addElement(form_makeOpenTag('p'));
1623 $form->addElement(form_makeTextField('mediaid', noNS($id), $lang['txt_filename'].':', 'upload__name'));
1624 $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
1625 $form->addElement(form_makeCloseTag('p'));
1627 if($auth >= $auth_ow){
1628 $form->addElement(form_makeOpenTag('p'));
1630 if ($update) $attrs['checked'] = 'checked';
1631 $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check', $attrs));
1632 $form->addElement(form_makeCloseTag('p'));
1635 echo NL.'<div id="mediamanager__uploader">'.NL;
1636 html_form('upload', $form);
1640 echo '<p class="maxsize">';
1641 printf($lang['maxuploadsize'],filesize_h(media_getuploadsize()));
1647 * Returns the size uploaded files may have
1649 * This uses a conservative approach using the lowest number found
1650 * in any of the limiting ini settings
1652 * @returns int size in bytes
1654 function media_getuploadsize(){
1657 $post = (int) php_to_byte(@ini_get('post_max_size'));
1658 $suho = (int) php_to_byte(@ini_get('suhosin.post.max_value_length'));
1659 $upld = (int) php_to_byte(@ini_get('upload_max_filesize'));
1661 if($post && ($post < $okay || $okay == 0)) $okay = $post;
1662 if($suho && ($suho < $okay || $okay == 0)) $okay = $suho;
1663 if($upld && ($upld < $okay || $okay == 0)) $okay = $upld;
1669 * Print the search field form
1671 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1672 * @author Kate Arzamastseva <pshns@ukr.net>
1674 function media_searchform($ns,$query='',$fullscreen=false){
1677 // The default HTML search form
1678 $params = array('id' => 'dw__mediasearch');
1680 $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1682 $params['action'] = media_managerURL(array(), '&');
1684 $form = new Doku_Form($params);
1685 $form->addHidden('ns', $ns);
1686 $form->addHidden($fullscreen ? 'mediado' : 'do', 'searchlist');
1688 if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>'.NL);
1689 $form->addElement(form_makeOpenTag('p'));
1690 $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1691 $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1692 $form->addElement(form_makeCloseTag('p'));
1693 html_form('searchmedia', $form);
1697 * Build a tree outline of available media namespaces
1699 * @author Andreas Gohr <andi@splitbrain.org>
1701 function media_nstree($ns){
1705 // currently selected namespace
1709 $ns = dirname(str_replace(':','/',$ID));
1710 if($ns == '.') $ns ='';
1712 $ns = utf8_encodeFN(str_replace(':','/',$ns));
1715 search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1717 // wrap a list with the root level around the other namespaces
1718 array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
1719 'label' => '['.$lang['mediaroot'].']'));
1721 echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1725 * Userfunction for html_buildlist
1727 * Prints a media namespace tree item
1729 * @author Andreas Gohr <andi@splitbrain.org>
1731 function media_nstree_item($item){
1733 $pos = strrpos($item['id'], ':');
1734 $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1735 if(!$item['label']) $item['label'] = $label;
1738 if (!($INPUT->str('do') == 'media'))
1739 $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1740 else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id'], false), 'tab_files' => 'files'))
1741 .'" class="idx_dir">';
1742 $ret .= $item['label'];
1748 * Userfunction for html_buildlist
1750 * Prints a media namespace tree item opener
1752 * @author Andreas Gohr <andi@splitbrain.org>
1754 function media_nstree_li($item){
1755 $class='media level'.$item['level'];
1758 $img = DOKU_BASE.'lib/images/minus.gif';
1761 $class .= ' closed';
1762 $img = DOKU_BASE.'lib/images/plus.gif';
1765 // TODO: only deliver an image if it actually has a subtree...
1766 return '<li class="'.$class.'">'.
1767 '<img src="'.$img.'" alt="'.$alt.'" />';
1771 * Resizes the given image to the given size
1773 * @author Andreas Gohr <andi@splitbrain.org>
1775 function media_resize_image($file, $ext, $w, $h=0){
1778 $info = @getimagesize($file); //get original size
1779 if($info == false) return $file; // that's no image - it's a spaceship!
1781 if(!$h) $h = round(($w * $info[1]) / $info[0]);
1783 // we wont scale up to infinity
1784 if($w > 2000 || $h > 2000) return $file;
1787 $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1788 $mtime = @filemtime($local); // 0 if not exists
1790 if( $mtime > filemtime($file) ||
1791 media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1792 media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1793 if($conf['fperm']) chmod($local, $conf['fperm']);
1796 //still here? resizing failed
1801 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1802 * to the wanted size
1804 * Crops are centered horizontally but prefer the upper third of an vertical
1805 * image because most pics are more interesting in that area (rule of thirds)
1807 * @author Andreas Gohr <andi@splitbrain.org>
1809 function media_crop_image($file, $ext, $w, $h=0){
1813 $info = @getimagesize($file); //get original size
1814 if($info == false) return $file; // that's no image - it's a spaceship!
1816 // calculate crop size
1817 $fr = $info[0]/$info[1];
1822 $ch = (int) $info[0]/$tr;
1824 $cw = (int) $info[1]*$tr;
1829 $cw = (int) $info[1]*$tr;
1833 $ch = (int) $info[0]/$tr;
1836 // calculate crop offset
1837 $cx = (int) ($info[0]-$cw)/2;
1838 $cy = (int) ($info[1]-$ch)/3;
1841 $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1842 $mtime = @filemtime($local); // 0 if not exists
1844 if( $mtime > @filemtime($file) ||
1845 media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1846 media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1847 if($conf['fperm']) chmod($local, $conf['fperm']);
1848 return media_resize_image($local,$ext, $w, $h);
1851 //still here? cropping failed
1852 return media_resize_image($file,$ext, $w, $h);
1856 * Download a remote file and return local filename
1858 * returns false if download fails. Uses cached file if available and
1861 * @author Andreas Gohr <andi@splitbrain.org>
1862 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1864 function media_get_from_URL($url,$ext,$cache){
1867 // if no cache or fetchsize just redirect
1868 if ($cache==0) return false;
1869 if (!$conf['fetchsize']) return false;
1871 $local = getCacheName(strtolower($url),".media.$ext");
1872 $mtime = @filemtime($local); // 0 if not exists
1874 //decide if download needed:
1875 if( ($mtime == 0) || // cache does not exist
1876 ($cache != -1 && $mtime < time()-$cache) // 'recache' and cache has expired
1878 if(media_image_download($url,$local)){
1885 //if cache exists use it else
1886 if($mtime) return $local;
1893 * Download image files
1895 * @author Andreas Gohr <andi@splitbrain.org>
1897 function media_image_download($url,$file){
1899 $http = new DokuHTTPClient();
1900 $http->max_bodysize = $conf['fetchsize'];
1901 $http->timeout = 25; //max. 25 sec
1902 $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1904 $data = $http->get($url);
1905 if(!$data) return false;
1907 $fileexists = @file_exists($file);
1908 $fp = @fopen($file,"w");
1909 if(!$fp) return false;
1912 if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1914 // check if it is really an image
1915 $info = @getimagesize($file);
1925 * resize images using external ImageMagick convert program
1927 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1928 * @author Andreas Gohr <andi@splitbrain.org>
1930 function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1933 // check if convert is configured
1934 if(!$conf['im_convert']) return false;
1937 $cmd = $conf['im_convert'];
1938 $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1939 if ($ext == 'jpg' || $ext == 'jpeg') {
1940 $cmd .= ' -quality '.$conf['jpg_quality'];
1942 $cmd .= " $from $to";
1944 @exec($cmd,$out,$retval);
1945 if ($retval == 0) return true;
1950 * crop images using external ImageMagick convert program
1952 * @author Andreas Gohr <andi@splitbrain.org>
1954 function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1957 // check if convert is configured
1958 if(!$conf['im_convert']) return false;
1961 $cmd = $conf['im_convert'];
1962 $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1963 if ($ext == 'jpg' || $ext == 'jpeg') {
1964 $cmd .= ' -quality '.$conf['jpg_quality'];
1966 $cmd .= " $from $to";
1968 @exec($cmd,$out,$retval);
1969 if ($retval == 0) return true;
1974 * resize or crop images using PHP's libGD support
1976 * @author Andreas Gohr <andi@splitbrain.org>
1977 * @author Sebastian Wienecke <s_wienecke@web.de>
1979 function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1982 if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1984 // check available memory
1985 if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1989 // create an image of the given filetype
1990 if ($ext == 'jpg' || $ext == 'jpeg'){
1991 if(!function_exists("imagecreatefromjpeg")) return false;
1992 $image = @imagecreatefromjpeg($from);
1993 }elseif($ext == 'png') {
1994 if(!function_exists("imagecreatefrompng")) return false;
1995 $image = @imagecreatefrompng($from);
1997 }elseif($ext == 'gif') {
1998 if(!function_exists("imagecreatefromgif")) return false;
1999 $image = @imagecreatefromgif($from);
2001 if(!$image) return false;
2003 if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
2004 $newimg = @imagecreatetruecolor ($to_w, $to_h);
2006 if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
2008 imagedestroy($image);
2012 //keep png alpha channel if possible
2013 if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
2014 imagealphablending($newimg, false);
2015 imagesavealpha($newimg,true);
2018 //keep gif transparent color if possible
2019 if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
2020 if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
2021 $transcolorindex = @imagecolortransparent($image);
2022 if($transcolorindex >= 0 ) { //transparent color exists
2023 $transcolor = @imagecolorsforindex($image, $transcolorindex);
2024 $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
2025 @imagefill($newimg, 0, 0, $transcolorindex);
2026 @imagecolortransparent($newimg, $transcolorindex);
2027 }else{ //filling with white
2028 $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2029 @imagefill($newimg, 0, 0, $whitecolorindex);
2031 }else{ //filling with white
2032 $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2033 @imagefill($newimg, 0, 0, $whitecolorindex);
2037 //try resampling first
2038 if(function_exists("imagecopyresampled")){
2039 if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
2040 imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2043 imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2047 if ($ext == 'jpg' || $ext == 'jpeg'){
2048 if(!function_exists('imagejpeg')){
2051 $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
2053 }elseif($ext == 'png') {
2054 if(!function_exists('imagepng')){
2057 $okay = imagepng($newimg, $to);
2059 }elseif($ext == 'gif') {
2060 if(!function_exists('imagegif')){
2063 $okay = imagegif($newimg, $to);
2067 // destroy GD image ressources
2068 if($image) imagedestroy($image);
2069 if($newimg) imagedestroy($newimg);
2074 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */