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