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