xref: /dokuwiki/inc/media.php (revision 4ee1558545059fa73700709a9ef4c0ab22ce8f92)
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 * @author Kate Arzamastseva <pshns@ukr.net>
44 */
45function media_metasave($id,$auth,$data){
46    if($auth < AUTH_UPLOAD) return false;
47    if(!checkSecurityToken()) return false;
48    global $lang;
49    global $conf;
50    $src = mediaFN($id);
51
52    $meta = new JpegMeta($src);
53    $meta->_parseAll();
54
55    foreach($data as $key => $val){
56        $val=trim($val);
57        if(empty($val)){
58            $meta->deleteField($key);
59        }else{
60            $meta->setField($key,$val);
61        }
62    }
63
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);
68    }
69
70    if($meta->save()){
71        if($conf['fperm']) chmod($src, $conf['fperm']);
72
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']);
76
77        msg($lang['metasaveok'],1);
78        return $id;
79    }else{
80        msg($lang['metasaveerr'],-1);
81        return false;
82    }
83}
84
85/**
86 * Display the form to edit image meta data
87 *
88 * @author Andreas Gohr <andi@splitbrain.org>
89 * @author Kate Arzamastseva <pshns@ukr.net>
90 */
91function media_metaform($id,$auth,$fullscreen = false){
92    global $lang, $config_cascade;
93
94    if($auth < AUTH_UPLOAD) {
95        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
96        return false;
97    }
98
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);
105        }
106    }
107
108    $src = mediaFN($id);
109
110    // output
111    if (!$fullscreen) {
112        echo '<h1>'.hsc(noNS($id)).'</h1>'.NL;
113        $action = DOKU_BASE.'lib/exe/mediamanager.php';
114    } else {
115        $action = media_managerURL(array('tab_details' => 'view'), '&');
116    }
117    echo '<form action="'.$action.'" id="mediamanager__save_meta" accept-charset="utf-8" method="post" class="meta">'.NL;
118
119    formSecurityToken();
120    foreach($fields as $key => $field){
121        // get current value
122        if (empty($field[0])) continue;
123        $tags = array($field[0]);
124        if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
125        $value = tpl_img_getTag($tags,'',$src);
126        $value = cleanText($value);
127
128        // prepare attributes
129        $p = array();
130        $p['class'] = 'edit';
131        $p['id']    = 'meta__'.$key;
132        $p['name']  = 'meta['.$field[0].']';
133
134        // put label
135        echo '<div class="metafield">';
136        echo '<label for="meta__'.$key.'">';
137        echo ($lang[$field[1]]) ? $lang[$field[1]] : $field[1];
138        echo ':</label>';
139
140        // put input field
141        if($field[2] == 'text'){
142            $p['value'] = $value;
143            $p['type']  = 'text';
144            $att = buildAttributes($p);
145            echo "<input $att/>".NL;
146        }else{
147            $att = buildAttributes($p);
148            echo "<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'.NL;
149        }
150        echo '</div>'.NL;
151    }
152    echo '<div class="buttons">'.NL;
153    echo '<input type="hidden" name="img" value="'.hsc($id).'" />'.NL;
154    if (!$fullscreen) {
155        $do = 'do';
156    } else {
157        echo '<input type="hidden" name="mediado" value="save" />';
158        $do = 'mediado';
159    }
160    echo '<input name="'.$do.'[save]" type="submit" value="'.$lang['btn_save'].
161        '" title="'.$lang['btn_save'].' [S]" accesskey="s" class="button" />'.NL;
162    if (!$fullscreen)
163    echo '<input name="do[cancel]" type="submit" value="'.$lang['btn_cancel'].
164        '" title="'.$lang['btn_cancel'].' [C]" accesskey="c" class="button" />'.NL;
165    echo '</div>'.NL;
166    echo '</form>'.NL;
167}
168
169/**
170 * Convenience function to check if a media file is still in use
171 *
172 * @author Michael Klier <chi@chimeric.de>
173 */
174function media_inuse($id) {
175    global $conf;
176    $mediareferences = array();
177    if($conf['refcheck']){
178        $mediareferences = ft_mediause($id,$conf['refshow']);
179        if(!count($mediareferences)) {
180            return false;
181        } else {
182            return $mediareferences;
183        }
184    } else {
185        return false;
186    }
187}
188
189define('DOKU_MEDIA_DELETED', 1);
190define('DOKU_MEDIA_NOT_AUTH', 2);
191define('DOKU_MEDIA_INUSE', 4);
192define('DOKU_MEDIA_EMPTY_NS', 8);
193
194/**
195 * Handles media file deletions
196 *
197 * If configured, checks for media references before deletion
198 *
199 * @author Andreas Gohr <andi@splitbrain.org>
200 * @return int One of: 0,
201                       DOKU_MEDIA_DELETED,
202                       DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
203                       DOKU_MEDIA_NOT_AUTH,
204                       DOKU_MEDIA_INUSE
205 */
206function media_delete($id,$auth){
207    global $lang;
208    if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
209    if(media_inuse($id)) return DOKU_MEDIA_INUSE;
210
211    $file = mediaFN($id);
212
213    // trigger an event - MEDIA_DELETE_FILE
214    $data['id']   = $id;
215    $data['name'] = basename($file);
216    $data['path'] = $file;
217    $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
218
219    $data['unl'] = false;
220    $data['del'] = false;
221    $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
222    if ($evt->advise_before()) {
223        $old = @filemtime($file);
224        if(!@file_exists(mediaFN($id, $old)) && @file_exists($file)) {
225            // add old revision to the attic
226            media_saveOldRevision($id);
227        }
228
229        $data['unl'] = @unlink($file);
230        if($data['unl']){
231            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted']);
232            $data['del'] = io_sweepNS($id,'mediadir');
233        }
234    }
235    $evt->advise_after();
236    unset($evt);
237
238    if($data['unl'] && $data['del']){
239        return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
240    }
241
242    return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
243}
244
245/**
246 * Handles media file uploads
247 *
248 * @author Andreas Gohr <andi@splitbrain.org>
249 * @author Michael Klier <chi@chimeric.de>
250 * @return mixed false on error, id of the new file on success
251 */
252function media_upload($ns,$auth){
253    if(!checkSecurityToken()) return false;
254    global $lang;
255
256    // get file and id
257    $id   = $_POST['mediaid'];
258    $file = $_FILES['upload'];
259    if(empty($id)) $id = $file['name'];
260
261    // check for errors (messages are done in lib/exe/mediamanager.php)
262    if($file['error']) return false;
263
264    // check extensions
265    list($fext,$fmime,$dl) = mimetype($file['name']);
266    list($iext,$imime,$dl) = mimetype($id);
267    if($fext && !$iext){
268        // no extension specified in id - read original one
269        $id   .= '.'.$fext;
270        $imime = $fmime;
271    }elseif($fext && $fext != $iext){
272        // extension was changed, print warning
273        msg(sprintf($lang['mediaextchange'],$fext,$iext));
274    }
275
276    $res = media_save(array('name' => $file['tmp_name'],
277                            'mime' => $imime,
278                            'ext'  => $iext), $ns.':'.$id,
279                      $_REQUEST['ow'], $auth, 'move_uploaded_file');
280    if (is_array($res)) {
281        msg($res[0], $res[1]);
282        return false;
283    }
284    return $res;
285}
286
287/**
288 * This generates an action event and delegates to _media_upload_action().
289 * Action plugins are allowed to pre/postprocess the uploaded file.
290 * (The triggered event is preventable.)
291 *
292 * Event data:
293 * $data[0]     fn_tmp: the temporary file name (read from $_FILES)
294 * $data[1]     fn: the file name of the uploaded file
295 * $data[2]     id: the future directory id of the uploaded file
296 * $data[3]     imime: the mimetype of the uploaded file
297 * $data[4]     overwrite: if an existing file is going to be overwritten
298 *
299 * @triggers MEDIA_UPLOAD_FINISH
300 */
301function media_save($file, $id, $ow, $auth, $move) {
302    if($auth < AUTH_UPLOAD) {
303        return array("You don't have permissions to upload files.", -1);
304    }
305
306    if (!isset($file['mime']) || !isset($file['ext'])) {
307        list($ext, $mime) = mimetype($id);
308        if (!isset($file['mime'])) {
309            $file['mime'] = $mime;
310        }
311        if (!isset($file['ext'])) {
312            $file['ext'] = $ext;
313        }
314    }
315
316    global $lang;
317
318    // get filename
319    $id   = cleanID($id,false,true);
320    $fn   = mediaFN($id);
321
322    // get filetype regexp
323    $types = array_keys(getMimeTypes());
324    $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
325    $regex = join('|',$types);
326
327    // because a temp file was created already
328    if(!preg_match('/\.('.$regex.')$/i',$fn)) {
329        return array($lang['uploadwrong'],-1);
330    }
331
332    //check for overwrite
333    $overwrite = @file_exists($fn);
334    if($overwrite && (!$ow || $auth < AUTH_DELETE)) {
335        return array($lang['uploadexist'], 0);
336    }
337    // check for valid content
338    $ok = media_contentcheck($file['name'], $file['mime']);
339    if($ok == -1){
340        return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
341    }elseif($ok == -2){
342        return array($lang['uploadspam'],-1);
343    }elseif($ok == -3){
344        return array($lang['uploadxss'],-1);
345    }
346
347    // prepare event data
348    $data[0] = $file['name'];
349    $data[1] = $fn;
350    $data[2] = $id;
351    $data[3] = $file['mime'];
352    $data[4] = $overwrite;
353    $data[5] = $move;
354
355    // trigger event
356    return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
357}
358
359/**
360 * Callback adapter for media_upload_finish()
361 * @author Michael Klier <chi@chimeric.de>
362 */
363function _media_upload_action($data) {
364    // fixme do further sanity tests of given data?
365    if(is_array($data) && count($data)===6) {
366        return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
367    } else {
368        return false; //callback error
369    }
370}
371
372/**
373 * Saves an uploaded media file
374 *
375 * @author Andreas Gohr <andi@splitbrain.org>
376 * @author Michael Klier <chi@chimeric.de>
377 * @author Kate Arzamastseva <pshns@ukr.net>
378 */
379function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
380    global $conf;
381    global $lang;
382    global $REV;
383
384    $old = @filemtime($fn);
385    if(!@file_exists(mediaFN($id, $old)) && @file_exists($fn)) {
386        // add old revision to the attic if missing
387        media_saveOldRevision($id);
388    }
389
390    // prepare directory
391    io_createNamespace($id, 'media');
392
393    if($move($fn_tmp, $fn)) {
394        @clearstatcache(true,$fn);
395        $new = @filemtime($fn);
396        // Set the correct permission here.
397        // Always chmod media because they may be saved with different permissions than expected from the php umask.
398        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
399        chmod($fn, $conf['fmode']);
400        msg($lang['uploadsucc'],1);
401        media_notify($id,$fn,$imime,$old);
402        // add a log entry to the media changelog
403        if ($REV){
404            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_REVERT, $lang['restored'], $REV);
405        } elseif ($overwrite) {
406            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT);
407        } else {
408            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created']);
409        }
410        return $id;
411    }else{
412        return array($lang['uploadfail'],-1);
413    }
414}
415
416/**
417 * Moves the current version of media file to the media_attic
418 * directory
419 *
420 * @author Kate Arzamastseva <pshns@ukr.net>
421 * @param string $id
422 * @return int - revision date
423 */
424function media_saveOldRevision($id){
425    global $conf;
426    $oldf = mediaFN($id);
427    if(!@file_exists($oldf)) return '';
428    $date = filemtime($oldf);
429    $newf = mediaFN($id,$date);
430    io_makeFileDir($newf);
431    if(copy($oldf, $newf)) {
432        // Set the correct permission here.
433        // Always chmod media because they may be saved with different permissions than expected from the php umask.
434        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
435        chmod($newf, $conf['fmode']);
436    }
437    return $date;
438}
439
440/**
441 * This function checks if the uploaded content is really what the
442 * mimetype says it is. We also do spam checking for text types here.
443 *
444 * We need to do this stuff because we can not rely on the browser
445 * to do this check correctly. Yes, IE is broken as usual.
446 *
447 * @author Andreas Gohr <andi@splitbrain.org>
448 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
449 * @fixme  check all 26 magic IE filetypes here?
450 */
451function media_contentcheck($file,$mime){
452    global $conf;
453    if($conf['iexssprotect']){
454        $fh = @fopen($file, 'rb');
455        if($fh){
456            $bytes = fread($fh, 256);
457            fclose($fh);
458            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
459                return -3;
460            }
461        }
462    }
463    if(substr($mime,0,6) == 'image/'){
464        $info = @getimagesize($file);
465        if($mime == 'image/gif' && $info[2] != 1){
466            return -1;
467        }elseif($mime == 'image/jpeg' && $info[2] != 2){
468            return -1;
469        }elseif($mime == 'image/png' && $info[2] != 3){
470            return -1;
471        }
472        # fixme maybe check other images types as well
473    }elseif(substr($mime,0,5) == 'text/'){
474        global $TEXT;
475        $TEXT = io_readFile($file);
476        if(checkwordblock()){
477            return -2;
478        }
479    }
480    return 0;
481}
482
483/**
484 * Send a notify mail on uploads
485 *
486 * @author Andreas Gohr <andi@splitbrain.org>
487 */
488function media_notify($id,$file,$mime,$old_rev=false){
489    global $lang;
490    global $conf;
491    global $INFO;
492    if(empty($conf['notify'])) return; //notify enabled?
493
494    $ip = clientIP();
495
496    $text = rawLocale('uploadmail');
497    $text = str_replace('@DATE@',dformat(),$text);
498    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
499    $text = str_replace('@IPADDRESS@',$ip,$text);
500    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
501    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
502    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
503    $text = str_replace('@MIME@',$mime,$text);
504    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
505    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
506    if ($old_rev) {
507        $text = str_replace('@OLD@', ml($id, "rev=$old_rev", true, '&', true), $text);
508    } else {
509        $text = str_replace('@OLD@', '', $text);
510    }
511
512    if(empty($conf['mailprefix'])) {
513        $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
514    } else {
515        $subject = '['.$conf['mailprefix'].'] '.$lang['mail_upload'].' '.$id;
516    }
517
518    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
519}
520
521/**
522 * List all files in a given Media namespace
523 */
524function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=false){
525    global $conf;
526    global $lang;
527    $ns = cleanID($ns);
528
529    // check auth our self if not given (needed for ajax calls)
530    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
531
532    if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
533
534    if($auth < AUTH_READ){
535        // FIXME: print permission warning here instead?
536        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
537    }else{
538        if (!$fullscreenview) media_uploadform($ns, $auth);
539
540        $dir = utf8_encodeFN(str_replace(':','/',$ns));
541        $data = array();
542        search($data,$conf['mediadir'],'search_media',
543                array('showmsg'=>true,'depth'=>1),$dir,1,$sort);
544
545        if(!count($data)){
546            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
547        }else foreach($data as $item){
548            if (!$fullscreenview) media_printfile($item,$auth,$jump);
549            else media_printfile_thumbs($item,$auth,$jump);
550        }
551    }
552    if (!$fullscreenview) media_searchform($ns);
553}
554
555/**
556 * Prints mediamanager tab
557 *
558 * @author Kate Arzamastseva <pshns@ukr.net>
559 * @param string $link
560 * @param string $class
561 * @param string $name
562 * @param string $selected
563 */
564function media_tab($link, $class, $name, $selected=false) {
565    if (!empty($selected) && $selected == $class) $class .= ' selected';
566    $tab = '<a href="'.$link.'" class="'.$class.'" >'.$name.'</a>';
567    echo $tab;
568}
569
570/**
571 * Prints tabs for files list actions
572 *
573 * @author Kate Arzamastseva <pshns@ukr.net>
574 * @param string $selected - opened tab
575 */
576function media_tabs_files($selected=false){
577    global $lang;
578
579    echo '<div class="mediamanager-tabs" id="mediamanager__tabs_files">';
580
581    media_tab(media_managerURL(array('tab_files' => 'files')), 'files', $lang['mediaselect'], $selected);
582    media_tab(media_managerURL(array('tab_files' => 'upload')), 'upload', $lang['media_uploadtab'], $selected);
583    media_tab(media_managerURL(array('tab_files' => 'search')), 'search', $lang['media_searchtab'], $selected);
584
585    echo '<div class="clearer"></div>';
586    echo '</div>';
587}
588
589/**
590 * Prints tabs for files details actions
591 *
592 * @author Kate Arzamastseva <pshns@ukr.net>
593 * @param string $selected - opened tab
594 */
595function media_tabs_details($image, $selected=false){
596    global $lang;
597
598    echo '<div class="mediamanager-tabs" id="mediamanager__tabs_details">';
599
600    media_tab(media_managerURL(array('tab_details' => 'view')), 'view', $lang['media_viewtab'], $selected);
601
602    list($ext, $mime) = mimetype($image);
603    if ($mime == 'image/jpeg') {
604        media_tab(media_managerURL(array('tab_details' => 'edit')), 'edit', $lang['media_edittab'], $selected);
605    }
606    media_tab(media_managerURL(array('tab_details' => 'history')), 'history', $lang['media_historytab'], $selected);
607
608    echo '<div class="clearer"></div>';
609    echo '</div>';
610}
611
612/**
613 * Prints options for the tab that displays a list of all files
614 *
615 * @author Kate Arzamastseva <pshns@ukr.net>
616 */
617function media_tab_files_options($ns, $sort){
618    global $lang;
619
620    echo '<div class="background-container">';
621    echo $ns;
622
623    echo '<div id="mediamanager__tabs_list">';
624
625    echo '<a href="'.media_managerURL(array('view' => 'thumbs')).'" id="mediamanager__link_thumbs" >';
626    echo $lang['media_thumbsview'];
627    echo '</a>';
628
629    echo '<a href="'.media_managerURL(array('view' => 'list')).'" id="mediamanager__link_list" >';
630    echo $lang['media_listview'];
631    echo '</a>';
632
633    echo '</div>';
634
635    echo '<div id="mediamanager__sort">';
636    $form = new Doku_Form(array('action'=>media_managerURL(array(), '&'), 'id' => 'mediamanager__form_sort'));
637    $form->addElement(form_makeListboxField(
638                        'sort',
639                        array(
640                            'name' => $lang['media_sort_name'],
641                            'date' => $lang['media_sort_date']),
642                        $sort,
643                        $lang['media_sort']));
644    $form->addElement(form_makeButton('submit', '', $lang['btn_apply']));
645    $form->printForm();
646    echo '</div>';
647
648    echo '<div class="clearer"></div>';
649    echo '</div>';
650}
651
652/**
653 * Prints tab that displays a list of all files
654 *
655 * @author Kate Arzamastseva <pshns@ukr.net>
656 */
657function media_tab_files($ns,$auth=null,$jump='') {
658    global $lang;
659    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
660
661    $sort = $_REQUEST['sort'];
662    media_tab_files_options($ns, $sort);
663
664    echo '<div class="scroll-container" >';
665    $view = $_REQUEST['view'];
666
667    if($auth < AUTH_READ){
668        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
669    }else{
670        if ($view == 'list') {
671            echo '<ul class="mediamanager-list" id="mediamanager__file_list">';
672        } else {
673            echo '<ul class="mediamanager-thumbs" id="mediamanager__file_list">';
674        }
675        media_filelist($ns,$auth,$jump,true,$sort);
676        echo '</ul>';
677    }
678    echo '</div>';
679}
680
681/**
682 * Prints tab that displays uploading form
683 *
684 * @author Kate Arzamastseva <pshns@ukr.net>
685 */
686function media_tab_upload($ns,$auth=null,$jump='') {
687    global $lang;
688    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
689
690    echo '<div class="background-container">';
691    echo sprintf($lang['media_upload'], $ns);
692    echo '</div>';
693
694    echo '<div class="scroll-container">';
695    if ($auth >= AUTH_UPLOAD) echo '<div class="upload">' . $lang['mediaupload'] . '</div>';
696    media_uploadform($ns, $auth, true);
697    echo '</div>';
698}
699
700/**
701 * Prints tab that displays search form
702 *
703 * @author Kate Arzamastseva <pshns@ukr.net>
704 */
705function media_tab_search($ns,$auth=null) {
706    global $lang;
707
708    $do = $_REQUEST['mediado'];
709    $query = $_REQUEST['q'];
710    if (!$query) $query = '';
711
712    echo '<div class="background-container">';
713    echo sprintf($lang['media_search'], $ns);
714    echo'</div>';
715
716    echo '<div class="scroll-container">';
717    media_searchform($ns, $query, true);
718
719    if($do == 'searchlist'){
720        $view = $_REQUEST['view'];
721        if ($view == 'list') {
722            echo '<ul class="mediamanager-list" id="mediamanager__file_list">';
723        } else {
724            echo '<ul class="mediamanager-thumbs" id="mediamanager__file_list">';
725        }
726        media_searchlist($query,$ns,$auth,true);
727        echo '</ul>';
728    }
729    echo '</div>';
730}
731
732/**
733 * Prints tab that displays mediafile details
734 *
735 * @author Kate Arzamastseva <pshns@ukr.net>
736 */
737function media_tab_view($image, $ns, $auth=null, $rev=false) {
738    global $lang, $conf;
739    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
740
741    echo '<div class="background-container">';
742    list($ext,$mime,$dl) = mimetype($image,false);
743    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
744    $class = 'select mediafile mf_'.$class;
745    echo '<a class="'.$class.'" >'.$image.'</a>';
746    echo '</div>';
747
748    echo '<div class="scroll-container">';
749    if ($image && $auth >= AUTH_READ) {
750        $meta = new JpegMeta(mediaFN($image, $rev));
751        media_preview($image, $auth, $rev, $meta);
752        media_preview_buttons($image, $auth, $rev);
753        media_details($image, $auth, $rev, $meta);
754
755    } else {
756        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>';
757    }
758    echo '</div>';
759}
760
761/**
762 * Prints tab that displays form for editing mediafile metadata
763 *
764 * @author Kate Arzamastseva <pshns@ukr.net>
765 */
766function media_tab_edit($image, $ns, $auth=null) {
767    global $lang;
768    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
769
770    echo '<div class="background-container">';
771    echo $lang['media_edit'];
772    echo '</div>';
773
774    echo '<div class="scroll-container">';
775    if ($image) {
776        list($ext, $mime) = mimetype($image);
777        if ($mime == 'image/jpeg') media_metaform($image,$auth,true);
778    }
779    echo '</div>';
780}
781
782/**
783 * Prints tab that displays mediafile revisions
784 *
785 * @author Kate Arzamastseva <pshns@ukr.net>
786 */
787function media_tab_history($image, $ns, $auth=null) {
788    global $lang;
789    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
790    $do = $_REQUEST['mediado'];
791
792    echo '<div class="background-container">';
793    echo $lang['media_history'];
794    echo '</div>';
795
796    echo '<div class="scroll-container">';
797    if ($auth >= AUTH_READ && $image) {
798        if ($do == 'diff'){
799            media_diff($image, $ns, $auth);
800        } else {
801            $first = isset($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
802            html_revisions($first, $image);
803        }
804    } else {
805        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
806    }
807    echo '</div>';
808}
809
810/**
811 * Prints mediafile details
812 *
813 * @author Kate Arzamastseva <pshns@ukr.net>
814 */
815function media_preview($image, $auth, $rev=false, $meta=false) {
816    global $lang;
817
818    echo '<div id="mediamanager__preview">';
819
820    $size = media_image_preview_size($image, $rev, $meta);
821
822    if ($size) {
823        $more = '';
824        if ($rev) {
825            $more = "rev=$rev";
826        } else {
827            $t = @filemtime(mediaFN($image));
828            $more = "t=$t";
829        }
830
831        $more .= '&w='.$size[0].'&h='.$size[1];
832
833        $src = ml($image, $more);
834        echo '<img src="'.$src.'" alt="'.$image.'" style="max-width: '.$size[0].'px;" />';
835    }
836
837    echo '</div>';
838}
839
840/**
841 * Prints mediafile action buttons
842 *
843 * @author Kate Arzamastseva <pshns@ukr.net>
844 */
845function media_preview_buttons($image, $auth, $rev=false) {
846    global $lang;
847
848    echo '<div id="mediamanager__preview_buttons">';
849
850    $more = '';
851    if ($rev) {
852        $more = "rev=$rev";
853    } else {
854        $t = @filemtime(mediaFN($image));
855        $more = "t=$t";
856    }
857    $link = ml($image,$more,true,'&');
858
859    // view original file button
860    $form = new Doku_Form(array('action'=>$link, 'target'=>'_blank'));
861    $form->addElement(form_makeButton('submit','',$lang['mediaview']));
862    $form->printForm();
863
864    if($auth >= AUTH_DELETE && !$rev){
865
866        // delete button
867        $form = new Doku_Form(array('id' => 'mediamanager__btn_delete',
868            'action'=>media_managerURL(array('delete' => $image), '&')));
869        $form->addElement(form_makeButton('submit','',$lang['btn_delete']));
870        $form->printForm();
871
872        // upload new version button
873        $form = new Doku_Form(array('id' => 'mediamanager__btn_update',
874            'action'=>media_managerURL(array('image' => $image, 'mediado' => 'update'), '&')));
875        $form->addElement(form_makeButton('submit','',$lang['media_update']));
876        $form->printForm();
877    }
878
879    if($auth >= AUTH_DELETE && $rev){
880
881        // restore button
882        $form = new Doku_Form(array('id' => 'mediamanager__btn_restore',
883            'action'=>media_managerURL(array('image' => $image), '&')));
884        $form->addHidden('mediado','restore');
885        $form->addHidden('rev',$rev);
886        $form->addElement(form_makeButton('submit','',$lang['media_restore']));
887        $form->printForm();
888    }
889
890    echo '</div>';
891}
892
893/**
894 * Returns image width and height for mediamanager preview panel
895 *
896 * @author Kate Arzamastseva <pshns@ukr.net>
897 * @param string $image
898 * @param int $rev
899 * @param JpegMeta $meta
900 * @return array
901 */
902function media_image_preview_size($image, $rev, $meta) {
903    if (!preg_match("/\.(jpe?g|gif|png)$/", $image)) return false;
904
905    $info = getimagesize(mediaFN($image, $rev));
906    $w = (int) $info[0];
907    $h = (int) $info[1];
908
909    $size = 500;
910    if($meta && ($w > $size || $h > $size)){
911        $ratio = $meta->getResizeRatio($size, $size);
912        $w = floor($w * $ratio);
913        $h = floor($h * $ratio);
914    }
915    return array($w, $h);
916}
917
918/**
919 * Returns the requested EXIF/IPTC tag from the image meta
920 *
921 * @author Kate Arzamastseva <pshns@ukr.net>
922 * @param array $tags
923 * @param JpegMeta $meta
924 * @param string $alt
925 * @return string
926 */
927function media_getTag($tags,$meta,$alt=''){
928    if($meta === false) return $alt;
929    $info = $meta->getField($tags);
930    if($info == false) return $alt;
931    return $info;
932}
933
934/**
935 * Returns mediafile tags
936 *
937 * @author Kate Arzamastseva <pshns@ukr.net>
938 * @param JpegMeta $meta
939 * @return array
940 */
941function media_file_tags($meta) {
942    global $config_cascade;
943
944    // load the field descriptions
945    static $fields = null;
946    if(is_null($fields)){
947        $config_files = getConfigFiles('mediameta');
948        foreach ($config_files as $config_file) {
949            if(@file_exists($config_file)) include($config_file);
950        }
951    }
952
953    $tags = array();
954
955    foreach($fields as $key => $tag){
956        $t = array();
957        if (!empty($tag[0])) $t = array($tag[0]);
958        if(is_array($tag[3])) $t = array_merge($t,$tag[3]);
959        $value = media_getTag($t, $meta);
960        $tags[] = array('tag' => $tag, 'value' => $value);
961    }
962
963    return $tags;
964}
965
966/**
967 * Prints mediafile tags
968 *
969 * @author Kate Arzamastseva <pshns@ukr.net>
970 */
971function media_details($image, $auth, $rev=false, $meta=false) {
972    global $lang;
973
974    if (!$meta) $meta = new JpegMeta(mediaFN($image, $rev));
975    $tags = media_file_tags($meta);
976
977    echo '<dl class="img_tags">';
978    foreach($tags as $tag){
979        if ($tag['value']) {
980            $value = cleanText($tag['value']);
981            echo '<dt>'.$lang[$tag['tag'][1]].':</dt><dd>';
982            if ($tag['tag'][2] == 'date') echo dformat($value);
983            else echo hsc($value);
984            echo '</dd>';
985        }
986    }
987    echo '</dl>';
988}
989
990/**
991 * Shows difference between two revisions of file
992 *
993 * @author Kate Arzamastseva <pshns@ukr.net>
994 */
995function media_diff($image, $ns, $auth) {
996    global $lang;
997    global $conf;
998
999    if ($auth < AUTH_READ || !$image) return '';
1000
1001    $rev1 = (int) $_REQUEST['rev'];
1002
1003    if(is_array($_REQUEST['rev2'])){
1004        $rev1 = (int) $_REQUEST['rev2'][0];
1005        $rev2 = (int) $_REQUEST['rev2'][1];
1006
1007        if(!$rev1){
1008            $rev1 = $rev2;
1009            unset($rev2);
1010        }
1011    }else{
1012        $rev2 = (int) $_REQUEST['rev2'];
1013    }
1014    if($rev1 && $rev2){            // two specific revisions wanted
1015        // make sure order is correct (older on the left)
1016        if($rev1 < $rev2){
1017            $l_rev = $rev1;
1018            $r_rev = $rev2;
1019        }else{
1020            $l_rev = $rev2;
1021            $r_rev = $rev1;
1022        }
1023    }elseif($rev1){                // single revision given, compare to current
1024        $r_rev = '';
1025        $l_rev = $rev1;
1026    }else{                        // no revision was given, compare previous to current
1027        $r_rev = '';
1028        $revs = getRevisions($image, 0, 1, 8192, true);
1029        $l_rev = $revs[0];
1030    }
1031
1032    // prepare event data
1033    $data[0] = $image;
1034    $data[1] = $l_rev;
1035    $data[2] = $r_rev;
1036    $data[3] = $ns;
1037    $data[4] = $auth;
1038
1039    // trigger event
1040    return trigger_event('MEDIA_DIFF', $data, '_media_file_diff', true);
1041
1042}
1043
1044function _media_file_diff($data) {
1045    if(is_array($data) && count($data)===5) {
1046        return media_file_diff($data[0], $data[1], $data[2], $data[3], $data[4]);
1047    } else {
1048        return false;
1049    }
1050}
1051
1052/**
1053 * Shows difference between two revisions of image
1054 *
1055 * @author Kate Arzamastseva <pshns@ukr.net>
1056 */
1057function media_file_diff($image, $l_rev, $r_rev, $ns, $auth){
1058    global $lang, $config_cascade;
1059    $is_img = preg_match("/\.(jpe?g|gif|png)$/", $image);
1060
1061    if ($is_img) {
1062        $difftype = $_REQUEST['difftype'];
1063
1064        $form = new Doku_Form(array('action'=>media_managerURL(array(), '&'),
1065            'id' => 'mediamanager__form_diffview'));
1066        $form->addElement('<input type=hidden name=rev2[] value='.$l_rev.' ></input>');
1067        $form->addElement('<input type=hidden name=rev2[] value='.$r_rev.' ></input>');
1068        $form->addHidden('mediado', 'diff');
1069        $form->printForm();
1070
1071        echo '<div id="mediamanager__diff" >';
1072
1073        if ($difftype == 'opacity') return media_image_diff($image, $l_rev, $r_rev, $l_meta, 'opacity');
1074        if ($difftype == 'portions') return media_image_diff($image, $l_rev, $r_rev, $l_meta, 'portions');
1075
1076    }
1077
1078    echo '<ul id="mediamanager__diff_table">';
1079
1080    echo '<li>';
1081    media_preview($image, $auth, $l_rev, $l_meta);
1082    echo '</li>';
1083
1084    echo '<li>';
1085    media_preview($image, $auth, $r_rev, $r_meta);
1086    echo '</li>';
1087
1088    echo '<li>';
1089    media_preview_buttons($image, $auth, $l_rev);
1090    echo '</li>';
1091
1092    echo '<li>';
1093    media_preview_buttons($image, $auth, $r_rev);
1094    echo '</li>';
1095
1096    $l_meta = new JpegMeta(mediaFN($image, $l_rev));
1097    $r_meta = new JpegMeta(mediaFN($image, $r_rev));
1098
1099    $l_tags = media_file_tags($l_meta);
1100    $r_tags = media_file_tags($r_meta);
1101    foreach ($l_tags as $key => $l_tag) {
1102        if ($l_tag['value'] != $r_tags[$key]['value']) {
1103            $r_tags[$key]['class'] = 'highlighted';
1104            $l_tags[$key]['class'] = 'highlighted';
1105        } else if (!$l_tag['value'] || !$r_tags[$key]['value']) {
1106            unset($r_tags[$key]);
1107            unset($l_tags[$key]);
1108        }
1109    }
1110
1111    foreach(array($l_tags,$r_tags) as $tags){
1112        echo '<li><div>';
1113
1114        echo '<dl class="img_tags">';
1115        foreach($tags as $tag){
1116            $value = cleanText($tag['value']);
1117            if (!$value) $value = '-';
1118            echo '<dt>'.$lang[$tag['tag'][1]].':</dt>';
1119            echo '<dd class="'.$tag['class'].'" >';
1120            if ($tag['tag'][2] == 'date') echo dformat($value);
1121            else echo hsc($value);
1122            echo '</dd>';
1123        }
1124        echo '</dl>';
1125
1126        echo '</div></li>';
1127    }
1128
1129    echo '</ul>';
1130
1131    if ($is_img) echo '</div>';
1132}
1133
1134/**
1135 * Prints two images side by side
1136 * and slider
1137 *
1138 * @author Kate Arzamastseva <pshns@ukr.net>
1139 * @param string $image
1140 * @param int $l_rev
1141 * @param int $r_rev
1142 * @param JpegMeta $meta
1143 */
1144function media_image_diff($image, $l_rev, $r_rev, $meta, $type) {
1145    $l_size = media_image_preview_size($image, $l_rev, $meta);
1146    $r_size = media_image_preview_size($image, $r_rev, $meta);
1147
1148    if (!$l_size || !$r_size || $l_size != $r_size || $l_size[0] < 30) return '';
1149
1150    echo '<div class="mediamanager-preview">';
1151
1152    $l_more = 'rev='.$l_rev.'&h='.$l_size[1].'&w='.$l_size[0];
1153    $r_more = 'rev='.$r_rev.'&h='.$l_size[1].'&w='.$l_size[0];
1154
1155    $l_src = ml($image, $l_more);
1156    $r_src = ml($image, $r_more);
1157
1158    echo '<div id="mediamanager__diff_'.$type.'_image1" style="background-image: url(\''.$l_src.'\'); max-width: '.$l_size[0].'px; height: '.$l_size[1].'px; " >';
1159    echo '<div id="mediamanager__diff_'.$type.'_image2" style="background-image: url(\''.$r_src.'\'); max-width: '.$l_size[0].'px; height: '.$l_size[1].'px; " >';
1160    echo '</div>';
1161    echo '</div>';
1162
1163    echo '<div id="mediamanager__'.$type.'_slider" style="max-width: '.($l_size[0]-20).'px;" ></div>';
1164    echo '</div>';
1165}
1166
1167/**
1168 * Restores an old revision of a media file
1169 *
1170 * @param string $image
1171 * @param int $rev
1172 * @param int $auth
1173 * @return string - file's id
1174 * @author Kate Arzamastseva <pshns@ukr.net>
1175 */
1176function media_restore($image, $rev, $auth){
1177    if ($auth < AUTH_DELETE) return false;
1178    if (!$image || !file_exists(mediaFN($image))) return false;
1179    if (!$rev || !file_exists(mediaFN($image, $rev))) return false;
1180    list($iext,$imime,$dl) = mimetype($image);
1181    $res = media_upload_finish(mediaFN($image, $rev),
1182        mediaFN($image),
1183        $image,
1184        $imime,
1185        true,
1186        'copy');
1187    if (is_array($res)) {
1188        msg($res[0], $res[1]);
1189        return false;
1190    }
1191    return $res;
1192}
1193
1194/**
1195 * List all files found by the search request
1196 *
1197 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1198 * @author Andreas Gohr <gohr@cosmocode.de>
1199 * @author Kate Arzamastseva <pshns@ukr.net>
1200 * @triggers MEDIA_SEARCH
1201 */
1202function media_searchlist($query,$ns,$auth=null,$fullscreen=false){
1203    global $conf;
1204    global $lang;
1205
1206    $ns = cleanID($ns);
1207
1208    if ($query) {
1209        $evdata = array(
1210                'ns'    => $ns,
1211                'data'  => array(),
1212                'query' => $query
1213                );
1214        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
1215        if ($evt->advise_before()) {
1216            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
1217            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
1218            search($evdata['data'],
1219                    $conf['mediadir'],
1220                    'search_media',
1221                    array('showmsg'=>false,'pattern'=>$pattern),
1222                    $dir);
1223        }
1224        $evt->advise_after();
1225        unset($evt);
1226    }
1227
1228    if (!$fullscreen) {
1229        echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
1230        media_searchform($ns,$query);
1231    }
1232
1233    if(!count($evdata['data'])){
1234        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
1235    }else foreach($evdata['data'] as $item){
1236        if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
1237        else media_printfile_thumbs($item,$item['perm']);
1238    }
1239}
1240
1241/**
1242 * Print action links for a file depending on filetype
1243 * and available permissions
1244 */
1245function media_fileactions($item,$auth){
1246    global $lang;
1247
1248    // view button
1249    $link = ml($item['id'],'',true);
1250    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
1251        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
1252
1253    // no further actions if not writable
1254    if(!$item['writable']) return;
1255
1256    // delete button
1257    if($auth >= AUTH_DELETE){
1258        $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
1259            '&amp;sectok='.getSecurityToken();
1260        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
1261            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
1262            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
1263    }
1264
1265    // edit button
1266    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
1267        $link = DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']);
1268        echo ' <a href="'.$link.'">'.
1269            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
1270            'title="'.$lang['metaedit'].'" class="btn" /></a>';
1271    }
1272
1273}
1274
1275/**
1276 * Formats and prints one file in the list
1277 */
1278function media_printfile($item,$auth,$jump,$display_namespace=false){
1279    global $lang;
1280    global $conf;
1281
1282    // Prepare zebra coloring
1283    // I always wanted to use this variable name :-D
1284    static $twibble = 1;
1285    $twibble *= -1;
1286    $zebra = ($twibble == -1) ? 'odd' : 'even';
1287
1288    // Automatically jump to recent action
1289    if($jump == $item['id']) {
1290        $jump = ' id="scroll__here" ';
1291    }else{
1292        $jump = '';
1293    }
1294
1295    // Prepare fileicons
1296    list($ext,$mime,$dl) = mimetype($item['file'],false);
1297    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1298    $class = 'select mediafile mf_'.$class;
1299
1300    // Prepare filename
1301    $file = utf8_decodeFN($item['file']);
1302
1303    // Prepare info
1304    $info = '';
1305    if($item['isimg']){
1306        $info .= (int) $item['meta']->getField('File.Width');
1307        $info .= '&#215;';
1308        $info .= (int) $item['meta']->getField('File.Height');
1309        $info .= ' ';
1310    }
1311    $info .= '<i>'.dformat($item['mtime']).'</i>';
1312    $info .= ' ';
1313    $info .= filesize_h($item['size']);
1314
1315    // output
1316    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
1317    if (!$display_namespace) {
1318        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1319    } else {
1320        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1321    }
1322    echo '<span class="info">('.$info.')</span>'.NL;
1323    media_fileactions($item,$auth);
1324    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1325    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1326    echo '</div>';
1327    if($item['isimg']) media_printimgdetail($item);
1328    echo '<div class="clearer"></div>'.NL;
1329    echo '</div>'.NL;
1330}
1331
1332function media_printicon($filename){
1333    list($ext,$mime,$dl) = mimetype(mediaFN($filename),false);
1334
1335    if (@file_exists(DOKU_INC.'lib/images/fileicons/'.$ext.'.png')) {
1336        $icon = DOKU_BASE.'lib/images/fileicons/'.$ext.'.png';
1337    } else {
1338        $icon = DOKU_BASE.'lib/images/fileicons/file.png';
1339    }
1340
1341    echo '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />';
1342
1343}
1344
1345/**
1346 * Formats and prints one file in the list in the thumbnails view
1347 *
1348 * @author Kate Arzamastseva <pshns@ukr.net>
1349 */
1350function media_printfile_thumbs($item,$auth,$jump=false){
1351    global $lang;
1352    global $conf;
1353
1354    // Prepare filename
1355    $file = utf8_decodeFN($item['file']);
1356
1357    // output
1358    echo '<li><div>';
1359
1360    if($item['isimg']) {
1361        media_printimgdetail($item, true);
1362
1363    } else {
1364        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1365            media_managerURL(array('image' => hsc($item['id']))).'"><div>';
1366        media_printicon($item['id']);
1367        echo '</div></a>';
1368    }
1369    //echo '<input type=checkbox />';
1370    echo '<a href="'.media_managerURL(array('image' => hsc($item['id']))).'" name=
1371        "h_:'.$item['id'].'" class="name">'.hsc($file).'</a>';
1372    if($item['isimg']){
1373        $size = '';
1374        $size .= (int) $item['meta']->getField('File.Width');
1375        $size .= '&#215;';
1376        $size .= (int) $item['meta']->getField('File.Height');
1377        echo '<span class="size">'.$size.'</span>';
1378    } else {
1379        echo '<span class="size">&nbsp;</span>';
1380    }
1381    $date = dformat($item['mtime']);
1382    echo '<span class="date">'.$date.'</span>';
1383    $filesize = filesize_h($item['size']);
1384    echo '<span class="filesize">'.$filesize.'</span>';
1385    echo '<div class="clearer"></div>';
1386    echo '</div></li>'.NL;
1387}
1388
1389/**
1390 * Prints a thumbnail and metainfos
1391 */
1392function media_printimgdetail($item, $fullscreen=false){
1393    // prepare thumbnail
1394    if (!$fullscreen) {
1395        $size_array[] = 120;
1396    } else {
1397        $size_array = array(90, 40);
1398    }
1399    foreach ($size_array as $index => $size) {
1400        $w = (int) $item['meta']->getField('File.Width');
1401        $h = (int) $item['meta']->getField('File.Height');
1402        if($w>$size || $h>$size){
1403            if (!$fullscreen) {
1404                $ratio = $item['meta']->getResizeRatio($size);
1405            } else {
1406                $ratio = $item['meta']->getResizeRatio($size,$size);
1407            }
1408            $w = floor($w * $ratio);
1409            $h = floor($h * $ratio);
1410        }
1411        $src = ml($item['id'],array('w'=>$w,'h'=>$h,'t'=>$item['mtime']));
1412        $p = array();
1413        if (!$fullscreen) {
1414            $p['width']  = $w;
1415            $p['height'] = $h;
1416        }
1417        $p['alt']    = $item['id'];
1418        $p['class']  = 'thumb';
1419        $att = buildAttributes($p);
1420
1421        // output
1422        if ($fullscreen) {
1423            echo '<a name="d_:'.$item['id'].'" class="image'.$index.'" title="'.$item['id'].'" href="'.
1424                media_managerURL(array('image' => hsc($item['id']))).'">';
1425            echo '<div><img src="'.$src.'" '.$att.' /></div>';
1426            echo '</a>';
1427        }
1428    }
1429
1430    if ($fullscreen) return '';
1431
1432    echo '<div class="detail">';
1433    echo '<div class="thumb">';
1434    echo '<a name="d_:'.$item['id'].'" class="select">';
1435    echo '<img src="'.$src.'" '.$att.' />';
1436    echo '</a>';
1437    echo '</div>';
1438
1439    // read EXIF/IPTC data
1440    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1441    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1442                'EXIF.TIFFImageDescription',
1443                'EXIF.TIFFUserComment'));
1444    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
1445    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1446
1447    // print EXIF/IPTC data
1448    if($t || $d || $k ){
1449        echo '<p>';
1450        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
1451        if($d) echo htmlspecialchars($d).'<br />';
1452        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
1453        echo '</p>';
1454    }
1455    echo '</div>';
1456}
1457
1458/**
1459 * Build link based on the current, adding/rewriting
1460 * parameters
1461 *
1462 * @author Kate Arzamastseva <pshns@ukr.net>
1463 * @param array $params
1464 * @param string $amp - separator
1465 * @return string - link
1466 */
1467function media_managerURL($params=false, $amp='&amp;') {
1468    global $conf;
1469    global $ID;
1470
1471    $gets = array('do' => 'media');
1472    $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'view');
1473    foreach ($media_manager_params as $x) {
1474        if (isset($_REQUEST[$x])) $gets[$x] = $_REQUEST[$x];
1475    }
1476
1477    if ($params) {
1478        foreach ($params as $k => $v) {
1479            $gets[$k] = $v;
1480        }
1481    }
1482    unset($gets['id']);
1483    if ($gets['delete']) {
1484        unset($gets['image']);
1485        unset($gets['tab_details']);
1486    }
1487
1488    return wl($ID,$gets,false,$amp);
1489}
1490
1491/**
1492 * Print the media upload form if permissions are correct
1493 *
1494 * @author Andreas Gohr <andi@splitbrain.org>
1495 * @author Kate Arzamastseva <pshns@ukr.net>
1496 */
1497function media_uploadform($ns, $auth, $fullscreen = false){
1498    global $lang;
1499
1500    if($auth < AUTH_UPLOAD) {
1501        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1502        return;
1503    }
1504
1505    $update = false;
1506    $id = '';
1507    if ($auth >= AUTH_DELETE && $fullscreen && $_REQUEST['mediado'] == 'update') {
1508        $update = true;
1509        $id = cleanID($_REQUEST['image']);
1510    }
1511
1512    // The default HTML upload form
1513    $params = array('id'      => 'dw__upload',
1514                    'enctype' => 'multipart/form-data');
1515    if (!$fullscreen) {
1516        $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1517    } else {
1518        $params['action'] = media_managerURL(array('tab_files' => 'files',
1519            'tab_details' => 'view'), '&');
1520    }
1521
1522    $form = new Doku_Form($params);
1523    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
1524    $form->addElement(formSecurityToken());
1525    $form->addHidden('ns', hsc($ns));
1526    $form->addElement(form_makeOpenTag('p'));
1527    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
1528    $form->addElement(form_makeCloseTag('p'));
1529    $form->addElement(form_makeOpenTag('p'));
1530    $form->addElement(form_makeTextField('mediaid', noNS($id), $lang['txt_filename'].':', 'upload__name'));
1531    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
1532    $form->addElement(form_makeCloseTag('p'));
1533
1534    if($auth >= AUTH_DELETE){
1535        $form->addElement(form_makeOpenTag('p'));
1536        $attrs = array();
1537        if ($update) $attrs['checked'] = 'checked';
1538        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check', $attrs));
1539        $form->addElement(form_makeCloseTag('p'));
1540    }
1541    html_form('upload', $form);
1542
1543    // prepare flashvars for multiupload
1544    $opt = array(
1545            'L_gridname'  => $lang['mu_gridname'] ,
1546            'L_gridsize'  => $lang['mu_gridsize'] ,
1547            'L_gridstat'  => $lang['mu_gridstat'] ,
1548            'L_namespace' => $lang['mu_namespace'] ,
1549            'L_overwrite' => $lang['txt_overwrt'],
1550            'L_browse'    => $lang['mu_browse'],
1551            'L_upload'    => $lang['btn_upload'],
1552            'L_toobig'    => $lang['mu_toobig'],
1553            'L_ready'     => $lang['mu_ready'],
1554            'L_done'      => $lang['mu_done'],
1555            'L_fail'      => $lang['mu_fail'],
1556            'L_authfail'  => $lang['mu_authfail'],
1557            'L_progress'  => $lang['mu_progress'],
1558            'L_filetypes' => $lang['mu_filetypes'],
1559            'L_info'      => $lang['mu_info'],
1560            'L_lasterr'   => $lang['mu_lasterr'],
1561
1562            'O_ns'        => ":$ns",
1563            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
1564            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
1565            'O_extensions'=> join('|',array_keys(getMimeTypes())),
1566            'O_overwrite' => ($auth >= AUTH_DELETE),
1567            'O_sectok'    => getSecurityToken(),
1568            'O_authtok'   => auth_createToken(),
1569            );
1570    $var = buildURLparams($opt);
1571    // output the flash uploader
1572    ?>
1573        <div id="dw__flashupload" style="display:none">
1574        <div class="upload"><?php echo $lang['mu_intro']?></div>
1575        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
1576        </div>
1577        <?php
1578}
1579
1580/**
1581 * Print the search field form
1582 *
1583 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1584 * @author Kate Arzamastseva <pshns@ukr.net>
1585 */
1586function media_searchform($ns,$query='',$fullscreen=false){
1587    global $lang;
1588
1589    // The default HTML search form
1590    $params = array('id' => 'dw__mediasearch');
1591    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1592    else $params['action'] = media_managerURL(array(), '&');
1593    $form = new Doku_Form($params);
1594    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
1595    $form->addElement(formSecurityToken());
1596    $form->addHidden('ns', $ns);
1597    if (!$fullscreen) $form->addHidden('do', 'searchlist');
1598    else $form->addHidden('mediado', 'searchlist');
1599    $form->addElement(form_makeOpenTag('p'));
1600    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1601    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1602    $form->addElement(form_makeCloseTag('p'));
1603    html_form('searchmedia', $form);
1604}
1605
1606/**
1607 * Build a tree outline of available media namespaces
1608 *
1609 * @author Andreas Gohr <andi@splitbrain.org>
1610 */
1611function media_nstree($ns){
1612    global $conf;
1613    global $lang;
1614
1615    // currently selected namespace
1616    $ns  = cleanID($ns);
1617    if(empty($ns)){
1618        global $ID;
1619        $ns = dirname(str_replace(':','/',$ID));
1620        if($ns == '.') $ns ='';
1621    }
1622    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1623
1624    $data = array();
1625    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1626
1627    // wrap a list with the root level around the other namespaces
1628    array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
1629                               'label' => '['.$lang['mediaroot'].']'));
1630
1631    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1632}
1633
1634/**
1635 * Userfunction for html_buildlist
1636 *
1637 * Prints a media namespace tree item
1638 *
1639 * @author Andreas Gohr <andi@splitbrain.org>
1640 */
1641function media_nstree_item($item){
1642    $pos   = strrpos($item['id'], ':');
1643    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1644    if(!$item['label']) $item['label'] = $label;
1645
1646    $ret  = '';
1647    if (!($_REQUEST['do'] == 'media'))
1648    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1649    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id']), 'tab_files' => 'files'))
1650        .'" class="idx_dir">';
1651    $ret .= $item['label'];
1652    $ret .= '</a>';
1653    return $ret;
1654}
1655
1656/**
1657 * Userfunction for html_buildlist
1658 *
1659 * Prints a media namespace tree item opener
1660 *
1661 * @author Andreas Gohr <andi@splitbrain.org>
1662 */
1663function media_nstree_li($item){
1664    $class='media level'.$item['level'];
1665    if($item['open']){
1666        $class .= ' open';
1667        $img   = DOKU_BASE.'lib/images/minus.gif';
1668        $alt   = '&minus;';
1669    }else{
1670        $class .= ' closed';
1671        $img   = DOKU_BASE.'lib/images/plus.gif';
1672        $alt   = '+';
1673    }
1674    // TODO: only deliver an image if it actually has a subtree...
1675    return '<li class="'.$class.'">'.
1676        '<img src="'.$img.'" alt="'.$alt.'" />';
1677}
1678
1679/**
1680 * Resizes the given image to the given size
1681 *
1682 * @author  Andreas Gohr <andi@splitbrain.org>
1683 */
1684function media_resize_image($file, $ext, $w, $h=0){
1685    global $conf;
1686
1687    $info = @getimagesize($file); //get original size
1688    if($info == false) return $file; // that's no image - it's a spaceship!
1689
1690    if(!$h) $h = round(($w * $info[1]) / $info[0]);
1691
1692    // we wont scale up to infinity
1693    if($w > 2000 || $h > 2000) return $file;
1694
1695    //cache
1696    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1697    $mtime = @filemtime($local); // 0 if not exists
1698
1699    if( $mtime > filemtime($file) ||
1700            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1701            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1702        if($conf['fperm']) chmod($local, $conf['fperm']);
1703        return $local;
1704    }
1705    //still here? resizing failed
1706    return $file;
1707}
1708
1709/**
1710 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1711 * to the wanted size
1712 *
1713 * Crops are centered horizontally but prefer the upper third of an vertical
1714 * image because most pics are more interesting in that area (rule of thirds)
1715 *
1716 * @author  Andreas Gohr <andi@splitbrain.org>
1717 */
1718function media_crop_image($file, $ext, $w, $h=0){
1719    global $conf;
1720
1721    if(!$h) $h = $w;
1722    $info = @getimagesize($file); //get original size
1723    if($info == false) return $file; // that's no image - it's a spaceship!
1724
1725    // calculate crop size
1726    $fr = $info[0]/$info[1];
1727    $tr = $w/$h;
1728    if($tr >= 1){
1729        if($tr > $fr){
1730            $cw = $info[0];
1731            $ch = (int) $info[0]/$tr;
1732        }else{
1733            $cw = (int) $info[1]*$tr;
1734            $ch = $info[1];
1735        }
1736    }else{
1737        if($tr < $fr){
1738            $cw = (int) $info[1]*$tr;
1739            $ch = $info[1];
1740        }else{
1741            $cw = $info[0];
1742            $ch = (int) $info[0]/$tr;
1743        }
1744    }
1745    // calculate crop offset
1746    $cx = (int) ($info[0]-$cw)/2;
1747    $cy = (int) ($info[1]-$ch)/3;
1748
1749    //cache
1750    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1751    $mtime = @filemtime($local); // 0 if not exists
1752
1753    if( $mtime > filemtime($file) ||
1754            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1755            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1756        if($conf['fperm']) chmod($local, $conf['fperm']);
1757        return media_resize_image($local,$ext, $w, $h);
1758    }
1759
1760    //still here? cropping failed
1761    return media_resize_image($file,$ext, $w, $h);
1762}
1763
1764/**
1765 * Download a remote file and return local filename
1766 *
1767 * returns false if download fails. Uses cached file if available and
1768 * wanted
1769 *
1770 * @author  Andreas Gohr <andi@splitbrain.org>
1771 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
1772 */
1773function media_get_from_URL($url,$ext,$cache){
1774    global $conf;
1775
1776    // if no cache or fetchsize just redirect
1777    if ($cache==0)           return false;
1778    if (!$conf['fetchsize']) return false;
1779
1780    $local = getCacheName(strtolower($url),".media.$ext");
1781    $mtime = @filemtime($local); // 0 if not exists
1782
1783    //decide if download needed:
1784    if( ($mtime == 0) ||                           // cache does not exist
1785            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
1786      ){
1787        if(media_image_download($url,$local)){
1788            return $local;
1789        }else{
1790            return false;
1791        }
1792    }
1793
1794    //if cache exists use it else
1795    if($mtime) return $local;
1796
1797    //else return false
1798    return false;
1799}
1800
1801/**
1802 * Download image files
1803 *
1804 * @author Andreas Gohr <andi@splitbrain.org>
1805 */
1806function media_image_download($url,$file){
1807    global $conf;
1808    $http = new DokuHTTPClient();
1809    $http->max_bodysize = $conf['fetchsize'];
1810    $http->timeout = 25; //max. 25 sec
1811    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1812
1813    $data = $http->get($url);
1814    if(!$data) return false;
1815
1816    $fileexists = @file_exists($file);
1817    $fp = @fopen($file,"w");
1818    if(!$fp) return false;
1819    fwrite($fp,$data);
1820    fclose($fp);
1821    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1822
1823    // check if it is really an image
1824    $info = @getimagesize($file);
1825    if(!$info){
1826        @unlink($file);
1827        return false;
1828    }
1829
1830    return true;
1831}
1832
1833/**
1834 * resize images using external ImageMagick convert program
1835 *
1836 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1837 * @author Andreas Gohr <andi@splitbrain.org>
1838 */
1839function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1840    global $conf;
1841
1842    // check if convert is configured
1843    if(!$conf['im_convert']) return false;
1844
1845    // prepare command
1846    $cmd  = $conf['im_convert'];
1847    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1848    if ($ext == 'jpg' || $ext == 'jpeg') {
1849        $cmd .= ' -quality '.$conf['jpg_quality'];
1850    }
1851    $cmd .= " $from $to";
1852
1853    @exec($cmd,$out,$retval);
1854    if ($retval == 0) return true;
1855    return false;
1856}
1857
1858/**
1859 * crop images using external ImageMagick convert program
1860 *
1861 * @author Andreas Gohr <andi@splitbrain.org>
1862 */
1863function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1864    global $conf;
1865
1866    // check if convert is configured
1867    if(!$conf['im_convert']) return false;
1868
1869    // prepare command
1870    $cmd  = $conf['im_convert'];
1871    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1872    if ($ext == 'jpg' || $ext == 'jpeg') {
1873        $cmd .= ' -quality '.$conf['jpg_quality'];
1874    }
1875    $cmd .= " $from $to";
1876
1877    @exec($cmd,$out,$retval);
1878    if ($retval == 0) return true;
1879    return false;
1880}
1881
1882/**
1883 * resize or crop images using PHP's libGD support
1884 *
1885 * @author Andreas Gohr <andi@splitbrain.org>
1886 * @author Sebastian Wienecke <s_wienecke@web.de>
1887 */
1888function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1889    global $conf;
1890
1891    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1892
1893    // check available memory
1894    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1895        return false;
1896    }
1897
1898    // create an image of the given filetype
1899    if ($ext == 'jpg' || $ext == 'jpeg'){
1900        if(!function_exists("imagecreatefromjpeg")) return false;
1901        $image = @imagecreatefromjpeg($from);
1902    }elseif($ext == 'png') {
1903        if(!function_exists("imagecreatefrompng")) return false;
1904        $image = @imagecreatefrompng($from);
1905
1906    }elseif($ext == 'gif') {
1907        if(!function_exists("imagecreatefromgif")) return false;
1908        $image = @imagecreatefromgif($from);
1909    }
1910    if(!$image) return false;
1911
1912    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1913        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1914    }
1915    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1916    if(!$newimg){
1917        imagedestroy($image);
1918        return false;
1919    }
1920
1921    //keep png alpha channel if possible
1922    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1923        imagealphablending($newimg, false);
1924        imagesavealpha($newimg,true);
1925    }
1926
1927    //keep gif transparent color if possible
1928    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1929        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1930            $transcolorindex = @imagecolortransparent($image);
1931            if($transcolorindex >= 0 ) { //transparent color exists
1932                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1933                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1934                @imagefill($newimg, 0, 0, $transcolorindex);
1935                @imagecolortransparent($newimg, $transcolorindex);
1936            }else{ //filling with white
1937                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1938                @imagefill($newimg, 0, 0, $whitecolorindex);
1939            }
1940        }else{ //filling with white
1941            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1942            @imagefill($newimg, 0, 0, $whitecolorindex);
1943        }
1944    }
1945
1946    //try resampling first
1947    if(function_exists("imagecopyresampled")){
1948        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
1949            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1950        }
1951    }else{
1952        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1953    }
1954
1955    $okay = false;
1956    if ($ext == 'jpg' || $ext == 'jpeg'){
1957        if(!function_exists('imagejpeg')){
1958            $okay = false;
1959        }else{
1960            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1961        }
1962    }elseif($ext == 'png') {
1963        if(!function_exists('imagepng')){
1964            $okay = false;
1965        }else{
1966            $okay =  imagepng($newimg, $to);
1967        }
1968    }elseif($ext == 'gif') {
1969        if(!function_exists('imagegif')){
1970            $okay = false;
1971        }else{
1972            $okay = imagegif($newimg, $to);
1973        }
1974    }
1975
1976    // destroy GD image ressources
1977    if($image) imagedestroy($image);
1978    if($newimg) imagedestroy($newimg);
1979
1980    return $okay;
1981}
1982
1983/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1984