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