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