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