xref: /dokuwiki/inc/media.php (revision edb50e6a038ec10ad5f1879b2753ed4f4eaf0b27)
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
9use dokuwiki\ChangeLog\MediaChangeLog;
10use dokuwiki\HTTP\DokuHTTPClient;
11use dokuwiki\Subscriptions\MediaSubscriptionSender;
12use dokuwiki\Extension\Event;
13use dokuwiki\Form\Form;
14use dokuwiki\Utf8\Sort;
15
16/**
17 * Lists pages which currently use a media file selected for deletion
18 *
19 * References uses the same visual as search results and share
20 * their CSS tags except pagenames won't be links.
21 *
22 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
23 *
24 * @param array $data
25 * @param string $id
26 */
27function media_filesinuse($data,$id){
28    global $lang;
29    echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
30    echo '<p>'.hsc($lang['ref_inuse']).'</p>';
31
32    $hidden=0; //count of hits without read permission
33    foreach($data as $row){
34        if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
35            echo '<div class="search_result">';
36            echo '<span class="mediaref_ref">'.hsc($row).'</span>';
37            echo '</div>';
38        }else
39            $hidden++;
40    }
41    if ($hidden){
42        print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
43    }
44}
45
46/**
47 * Handles the saving of image meta data
48 *
49 * @author Andreas Gohr <andi@splitbrain.org>
50 * @author Kate Arzamastseva <pshns@ukr.net>
51 *
52 * @param string $id media id
53 * @param int $auth permission level
54 * @param array $data
55 * @return false|string
56 */
57function media_metasave($id,$auth,$data){
58    if($auth < AUTH_UPLOAD) return false;
59    if(!checkSecurityToken()) return false;
60    global $lang;
61    global $conf;
62    $src = mediaFN($id);
63
64    $meta = new JpegMeta($src);
65    $meta->_parseAll();
66
67    foreach($data as $key => $val){
68        $val=trim($val);
69        if(empty($val)){
70            $meta->deleteField($key);
71        }else{
72            $meta->setField($key,$val);
73        }
74    }
75
76    $old = @filemtime($src);
77    if(!file_exists(mediaFN($id, $old)) && file_exists($src)) {
78        // add old revision to the attic
79        media_saveOldRevision($id);
80    }
81    $filesize_old = filesize($src);
82    if($meta->save()){
83        if($conf['fperm']) chmod($src, $conf['fperm']);
84        @clearstatcache(true, $src);
85        $new = @filemtime($src);
86        $filesize_new = filesize($src);
87        $sizechange = $filesize_new - $filesize_old;
88
89        // add a log entry to the media changelog
90        addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, $lang['media_meta_edited'], '', null, $sizechange);
91
92        msg($lang['metasaveok'],1);
93        return $id;
94    }else{
95        msg($lang['metasaveerr'],-1);
96        return false;
97    }
98}
99
100/**
101 * check if a media is external source
102 *
103 * @author Gerrit Uitslag <klapinklapin@gmail.com>
104 *
105 * @param string $id the media ID or URL
106 * @return bool
107 */
108function media_isexternal($id){
109    if (preg_match('#^(?:https?|ftp)://#i', $id)) return true;
110    return false;
111}
112
113/**
114 * Check if a media item is public (eg, external URL or readable by @ALL)
115 *
116 * @author Andreas Gohr <andi@splitbrain.org>
117 *
118 * @param string $id  the media ID or URL
119 * @return bool
120 */
121function media_ispublic($id){
122    if(media_isexternal($id)) return true;
123    $id = cleanID($id);
124    if(auth_aclcheck(getNS($id).':*', '', array()) >= AUTH_READ) return true;
125    return false;
126}
127
128/**
129 * Display the form to edit image meta data
130 *
131 * @author Andreas Gohr <andi@splitbrain.org>
132 * @author Kate Arzamastseva <pshns@ukr.net>
133 *
134 * @param string $id media id
135 * @param int $auth permission level
136 * @return bool
137 */
138function media_metaform($id, $auth) {
139    global $lang;
140
141    if ($auth < AUTH_UPLOAD) {
142        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.DOKU_LF;
143        return false;
144    }
145
146    // load the field descriptions
147    static $fields = null;
148    if ($fields === null) {
149        $config_files = getConfigFiles('mediameta');
150        foreach ($config_files as $config_file) {
151            if (file_exists($config_file)) include($config_file);
152        }
153    }
154
155    $src = mediaFN($id);
156
157    // output
158    $form = new Form([
159            'action' => media_managerURL(['tab_details' => 'view'], '&'),
160            'class' => 'meta'
161    ]);
162    $form->addTagOpen('div')->addClass('no');
163    $form->setHiddenField('img', $id);
164    $form->setHiddenField('mediado', 'save');
165    foreach ($fields as $key => $field) {
166        // get current value
167        if (empty($field[0])) continue;
168        $tags = array($field[0]);
169        if (is_array($field[3])) $tags = array_merge($tags, $field[3]);
170        $value = tpl_img_getTag($tags, '', $src);
171        $value = cleanText($value);
172
173        // prepare attributes
174        $p = array(
175            'class' => 'edit',
176            'id'    => 'meta__'.$key,
177            'name'  => 'meta['.$field[0].']',
178        );
179
180        $form->addTagOpen('div')->addClass('row');
181        if ($field[2] == 'text') {
182            $form->addTextInput(
183                $p['name'],
184                ($lang[$field[1]] ? $lang[$field[1]] : $field[1] . ':')
185            )->id($p['id'])->addClass($p['class'])->val($value);
186        } else {
187            $form->addTextarea($p['name'], $lang[$field[1]])->id($p['id'])
188                ->val(formText($value))
189                ->addClass($p['class'])
190                ->attr('rows', '6')->attr('cols', '50');
191        }
192        $form->addTagClose('div');
193    }
194    $form->addTagOpen('div')->addClass('buttons');
195    $form->addButton('mediado[save]', $lang['btn_save'])->attr('type', 'submit')
196        ->attrs(['accesskey' => 's']);
197    $form->addTagClose('div');
198
199    $form->addTagClose('div');
200    echo $form->toHTML();
201    return true;
202}
203
204/**
205 * Convenience function to check if a media file is still in use
206 *
207 * @author Michael Klier <chi@chimeric.de>
208 *
209 * @param string $id media id
210 * @return array|bool
211 */
212function media_inuse($id) {
213    global $conf;
214
215    if($conf['refcheck']){
216        $mediareferences = ft_mediause($id,true);
217        if(!count($mediareferences)) {
218            return false;
219        } else {
220            return $mediareferences;
221        }
222    } else {
223        return false;
224    }
225}
226
227/**
228 * Handles media file deletions
229 *
230 * If configured, checks for media references before deletion
231 *
232 * @author             Andreas Gohr <andi@splitbrain.org>
233 *
234 * @param string $id media id
235 * @param int $auth no longer used
236 * @return int One of: 0,
237 *                     DOKU_MEDIA_DELETED,
238 *                     DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
239 *                     DOKU_MEDIA_NOT_AUTH,
240 *                     DOKU_MEDIA_INUSE
241 */
242function media_delete($id,$auth){
243    global $lang;
244    $auth = auth_quickaclcheck(ltrim(getNS($id).':*', ':'));
245    if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
246    if(media_inuse($id)) return DOKU_MEDIA_INUSE;
247
248    $file = mediaFN($id);
249
250    // trigger an event - MEDIA_DELETE_FILE
251    $data = array();
252    $data['id']   = $id;
253    $data['name'] = \dokuwiki\Utf8\PhpString::basename($file);
254    $data['path'] = $file;
255    $data['size'] = (file_exists($file)) ? filesize($file) : 0;
256
257    $data['unl'] = false;
258    $data['del'] = false;
259    $evt = new Event('MEDIA_DELETE_FILE',$data);
260    if ($evt->advise_before()) {
261        $old = @filemtime($file);
262        if(!file_exists(mediaFN($id, $old)) && file_exists($file)) {
263            // add old revision to the attic
264            media_saveOldRevision($id);
265        }
266
267        $data['unl'] = @unlink($file);
268        if($data['unl']) {
269            $sizechange = 0 - $data['size'];
270            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted'], '', null, $sizechange);
271
272            $data['del'] = io_sweepNS($id, 'mediadir');
273        }
274    }
275    $evt->advise_after();
276    unset($evt);
277
278    if($data['unl'] && $data['del']){
279        return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
280    }
281
282    return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
283}
284
285/**
286 * Handle file uploads via XMLHttpRequest
287 *
288 * @param string $ns   target namespace
289 * @param int    $auth current auth check result
290 * @return false|string false on error, id of the new file on success
291 */
292function media_upload_xhr($ns,$auth){
293    if(!checkSecurityToken()) return false;
294    global $INPUT;
295
296    $id = $INPUT->get->str('qqfile');
297    list($ext,$mime) = mimetype($id);
298    $input = fopen("php://input", "r");
299    if (!($tmp = io_mktmpdir())) return false;
300    $path = $tmp.'/'.md5($id);
301    $target = fopen($path, "w");
302    $realSize = stream_copy_to_stream($input, $target);
303    fclose($target);
304    fclose($input);
305    if (isset($_SERVER["CONTENT_LENGTH"]) && ($realSize != (int)$_SERVER["CONTENT_LENGTH"])){
306        unlink($path);
307        return false;
308    }
309
310    $res = media_save(
311        array('name' => $path,
312            'mime' => $mime,
313            'ext'  => $ext),
314        $ns.':'.$id,
315        (($INPUT->get->str('ow') == 'true') ? true : false),
316        $auth,
317        'copy'
318    );
319    unlink($path);
320    if ($tmp) io_rmdir($tmp, true);
321    if (is_array($res)) {
322        msg($res[0], $res[1]);
323        return false;
324    }
325    return $res;
326}
327
328/**
329 * Handles media file uploads
330 *
331 * @author Andreas Gohr <andi@splitbrain.org>
332 * @author Michael Klier <chi@chimeric.de>
333 *
334 * @param string     $ns    target namespace
335 * @param int        $auth  current auth check result
336 * @param bool|array $file  $_FILES member, $_FILES['upload'] if false
337 * @return false|string false on error, id of the new file on success
338 */
339function media_upload($ns,$auth,$file=false){
340    if(!checkSecurityToken()) return false;
341    global $lang;
342    global $INPUT;
343
344    // get file and id
345    $id   = $INPUT->post->str('mediaid');
346    if (!$file) $file = $_FILES['upload'];
347    if(empty($id)) $id = $file['name'];
348
349    // check for errors (messages are done in lib/exe/mediamanager.php)
350    if($file['error']) return false;
351
352    // check extensions
353    list($fext,$fmime) = mimetype($file['name']);
354    list($iext,$imime) = mimetype($id);
355    if($fext && !$iext){
356        // no extension specified in id - read original one
357        $id   .= '.'.$fext;
358        $imime = $fmime;
359    }elseif($fext && $fext != $iext){
360        // extension was changed, print warning
361        msg(sprintf($lang['mediaextchange'],$fext,$iext));
362    }
363
364    $res = media_save(array('name' => $file['tmp_name'],
365                            'mime' => $imime,
366                            'ext'  => $iext), $ns.':'.$id,
367                      $INPUT->post->bool('ow'), $auth, 'copy_uploaded_file');
368    if (is_array($res)) {
369        msg($res[0], $res[1]);
370        return false;
371    }
372    return $res;
373}
374
375/**
376 * An alternative to move_uploaded_file that copies
377 *
378 * Using copy, makes sure any setgid bits on the media directory are honored
379 *
380 * @see   move_uploaded_file()
381 *
382 * @param string $from
383 * @param string $to
384 * @return bool
385 */
386function copy_uploaded_file($from, $to){
387    if(!is_uploaded_file($from)) return false;
388    $ok = copy($from, $to);
389    @unlink($from);
390    return $ok;
391}
392
393/**
394 * This generates an action event and delegates to _media_upload_action().
395 * Action plugins are allowed to pre/postprocess the uploaded file.
396 * (The triggered event is preventable.)
397 *
398 * Event data:
399 * $data[0]     fn_tmp:    the temporary file name (read from $_FILES)
400 * $data[1]     fn:        the file name of the uploaded file
401 * $data[2]     id:        the future directory id of the uploaded file
402 * $data[3]     imime:     the mimetype of the uploaded file
403 * $data[4]     overwrite: if an existing file is going to be overwritten
404 * $data[5]     move:      name of function that performs move/copy/..
405 *
406 * @triggers MEDIA_UPLOAD_FINISH
407 *
408 * @param array  $file
409 * @param string $id   media id
410 * @param bool   $ow   overwrite?
411 * @param int    $auth permission level
412 * @param string $move name of functions that performs move/copy/..
413 * @return false|array|string
414 */
415function media_save($file, $id, $ow, $auth, $move) {
416    if($auth < AUTH_UPLOAD) {
417        return array("You don't have permissions to upload files.", -1);
418    }
419
420    if (!isset($file['mime']) || !isset($file['ext'])) {
421        list($ext, $mime) = mimetype($id);
422        if (!isset($file['mime'])) {
423            $file['mime'] = $mime;
424        }
425        if (!isset($file['ext'])) {
426            $file['ext'] = $ext;
427        }
428    }
429
430    global $lang, $conf;
431
432    // get filename
433    $id   = cleanID($id);
434    $fn   = mediaFN($id);
435
436    // get filetype regexp
437    $types = array_keys(getMimeTypes());
438    $types = array_map(
439        function ($q) {
440            return preg_quote($q, "/");
441        },
442        $types
443    );
444    $regex = join('|',$types);
445
446    // because a temp file was created already
447    if(!preg_match('/\.('.$regex.')$/i',$fn)) {
448        return array($lang['uploadwrong'],-1);
449    }
450
451    //check for overwrite
452    $overwrite = file_exists($fn);
453    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
454    if($overwrite && (!$ow || $auth < $auth_ow)) {
455        return array($lang['uploadexist'], 0);
456    }
457    // check for valid content
458    $ok = media_contentcheck($file['name'], $file['mime']);
459    if($ok == -1){
460        return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
461    }elseif($ok == -2){
462        return array($lang['uploadspam'],-1);
463    }elseif($ok == -3){
464        return array($lang['uploadxss'],-1);
465    }
466
467    // prepare event data
468    $data = array();
469    $data[0] = $file['name'];
470    $data[1] = $fn;
471    $data[2] = $id;
472    $data[3] = $file['mime'];
473    $data[4] = $overwrite;
474    $data[5] = $move;
475
476    // trigger event
477    return Event::createAndTrigger('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
478}
479
480/**
481 * Callback adapter for media_upload_finish() triggered by MEDIA_UPLOAD_FINISH
482 *
483 * @author Michael Klier <chi@chimeric.de>
484 *
485 * @param array $data event data
486 * @return false|array|string
487 */
488function _media_upload_action($data) {
489    // fixme do further sanity tests of given data?
490    if(is_array($data) && count($data)===6) {
491        return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
492    } else {
493        return false; //callback error
494    }
495}
496
497/**
498 * Saves an uploaded media file
499 *
500 * @author Andreas Gohr <andi@splitbrain.org>
501 * @author Michael Klier <chi@chimeric.de>
502 * @author Kate Arzamastseva <pshns@ukr.net>
503 *
504 * @param string $fn_tmp
505 * @param string $fn
506 * @param string $id        media id
507 * @param string $imime     mime type
508 * @param bool   $overwrite overwrite existing?
509 * @param string $move      function name
510 * @return array|string
511 */
512function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
513    global $conf;
514    global $lang;
515    global $REV;
516
517    $old = @filemtime($fn);
518    if(!file_exists(mediaFN($id, $old)) && file_exists($fn)) {
519        // add old revision to the attic if missing
520        media_saveOldRevision($id);
521    }
522
523    // prepare directory
524    io_createNamespace($id, 'media');
525
526    $filesize_old = file_exists($fn) ? filesize($fn) : 0;
527
528    if($move($fn_tmp, $fn)) {
529        @clearstatcache(true,$fn);
530        $new = @filemtime($fn);
531        // Set the correct permission here.
532        // Always chmod media because they may be saved with different permissions than expected from the php umask.
533        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
534        chmod($fn, $conf['fmode']);
535        msg($lang['uploadsucc'],1);
536        media_notify($id,$fn,$imime,$old,$new);
537        // add a log entry to the media changelog
538        $filesize_new = filesize($fn);
539        $sizechange = $filesize_new - $filesize_old;
540        if($REV) {
541            addMediaLogEntry(
542                $new,
543                $id,
544                DOKU_CHANGE_TYPE_REVERT,
545                sprintf($lang['restored'], dformat($REV)),
546                $REV,
547                null,
548                $sizechange
549            );
550        } elseif($overwrite) {
551            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange);
552        } else {
553            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange);
554        }
555        return $id;
556    }else{
557        return array($lang['uploadfail'],-1);
558    }
559}
560
561/**
562 * Moves the current version of media file to the media_attic
563 * directory
564 *
565 * @author Kate Arzamastseva <pshns@ukr.net>
566 *
567 * @param string $id
568 * @return int - revision date
569 */
570function media_saveOldRevision($id){
571    global $conf, $lang;
572
573    $oldf = mediaFN($id);
574    if(!file_exists($oldf)) return '';
575    $date = filemtime($oldf);
576    if (!$conf['mediarevisions']) return $date;
577
578    $medialog = new MediaChangeLog($id);
579    if (!$medialog->getRevisionInfo($date)) {
580        // there was an external edit,
581        // there is no log entry for current version of file
582        $sizechange = filesize($oldf);
583        if(!file_exists(mediaMetaFN($id, '.changes'))) {
584            addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange);
585        } else {
586            $oldRev = $medialog->getRevisions(-1, 1); // from changelog
587            $oldRev = (int) (empty($oldRev) ? 0 : $oldRev[0]);
588            $filesize_old = filesize(mediaFN($id, $oldRev));
589            $sizechange = $sizechange - $filesize_old;
590
591            addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange);
592        }
593    }
594
595    $newf = mediaFN($id,$date);
596    io_makeFileDir($newf);
597    if(copy($oldf, $newf)) {
598        // Set the correct permission here.
599        // Always chmod media because they may be saved with different permissions than expected from the php umask.
600        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
601        chmod($newf, $conf['fmode']);
602    }
603    return $date;
604}
605
606/**
607 * This function checks if the uploaded content is really what the
608 * mimetype says it is. We also do spam checking for text types here.
609 *
610 * We need to do this stuff because we can not rely on the browser
611 * to do this check correctly. Yes, IE is broken as usual.
612 *
613 * @author Andreas Gohr <andi@splitbrain.org>
614 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
615 * @fixme  check all 26 magic IE filetypes here?
616 *
617 * @param string $file path to file
618 * @param string $mime mimetype
619 * @return int
620 */
621function media_contentcheck($file,$mime){
622    global $conf;
623    if($conf['iexssprotect']){
624        $fh = @fopen($file, 'rb');
625        if($fh){
626            $bytes = fread($fh, 256);
627            fclose($fh);
628            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
629                return -3; //XSS: possibly malicious content
630            }
631        }
632    }
633    if(substr($mime,0,6) == 'image/'){
634        $info = @getimagesize($file);
635        if($mime == 'image/gif' && $info[2] != 1){
636            return -1; // uploaded content did not match the file extension
637        }elseif($mime == 'image/jpeg' && $info[2] != 2){
638            return -1;
639        }elseif($mime == 'image/png' && $info[2] != 3){
640            return -1;
641        }
642        # fixme maybe check other images types as well
643    }elseif(substr($mime,0,5) == 'text/'){
644        global $TEXT;
645        $TEXT = io_readFile($file);
646        if(checkwordblock()){
647            return -2; //blocked by the spam blacklist
648        }
649    }
650    return 0;
651}
652
653/**
654 * Send a notify mail on uploads
655 *
656 * @author Andreas Gohr <andi@splitbrain.org>
657 *
658 * @param string   $id      media id
659 * @param string   $file    path to file
660 * @param string   $mime    mime type
661 * @param bool|int $old_rev revision timestamp or false
662 * @return bool
663 */
664function media_notify($id,$file,$mime,$old_rev=false,$current_rev=false){
665    global $conf;
666    if(empty($conf['notify'])) return false; //notify enabled?
667
668    $subscription = new MediaSubscriptionSender();
669    return $subscription->sendMediaDiff($conf['notify'], 'uploadmail', $id, $old_rev, $current_rev);
670}
671
672/**
673 * List all files in a given Media namespace
674 *
675 * @param string      $ns             namespace
676 * @param null|int    $auth           permission level
677 * @param string      $jump           id
678 * @param bool        $fullscreenview
679 * @param bool|string $sort           sorting order, false skips sorting
680 */
681function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=false){
682    global $conf;
683    global $lang;
684    $ns = cleanID($ns);
685
686    // check auth our self if not given (needed for ajax calls)
687    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
688
689    if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
690
691    if($auth < AUTH_READ){
692        // FIXME: print permission warning here instead?
693        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
694    }else{
695        if (!$fullscreenview) {
696            media_uploadform($ns, $auth);
697            media_searchform($ns);
698        }
699
700        $dir = utf8_encodeFN(str_replace(':','/',$ns));
701        $data = array();
702        search($data,$conf['mediadir'],'search_media',
703                array('showmsg'=>true,'depth'=>1),$dir,1,$sort);
704
705        if(!count($data)){
706            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
707        }else {
708            if ($fullscreenview) {
709                echo '<ul class="' . _media_get_list_type() . '">';
710            }
711            foreach($data as $item){
712                if (!$fullscreenview) {
713                    media_printfile($item,$auth,$jump);
714                } else {
715                    media_printfile_thumbs($item,$auth,$jump);
716                }
717            }
718            if ($fullscreenview) echo '</ul>'.NL;
719        }
720    }
721}
722
723/**
724 * Prints tabs for files list actions
725 *
726 * @author Kate Arzamastseva <pshns@ukr.net>
727 * @author Adrian Lang <mail@adrianlang.de>
728 *
729 * @param string $selected_tab - opened tab
730 */
731
732function media_tabs_files($selected_tab = ''){
733    global $lang;
734    $tabs = array();
735    foreach(array('files'  => 'mediaselect',
736                  'upload' => 'media_uploadtab',
737                  'search' => 'media_searchtab') as $tab => $caption) {
738        $tabs[$tab] = array('href'    => media_managerURL(['tab_files' => $tab], '&'),
739                            'caption' => $lang[$caption]);
740    }
741
742    html_tabs($tabs, $selected_tab);
743}
744
745/**
746 * Prints tabs for files details actions
747 *
748 * @author Kate Arzamastseva <pshns@ukr.net>
749 * @param string $image filename of the current image
750 * @param string $selected_tab opened tab
751 */
752function media_tabs_details($image, $selected_tab = '') {
753    global $lang, $conf;
754
755    $tabs = array();
756    $tabs['view'] = array('href'    => media_managerURL(['tab_details' => 'view'], '&'),
757                          'caption' => $lang['media_viewtab']);
758
759    list(, $mime) = mimetype($image);
760    if ($mime == 'image/jpeg' && file_exists(mediaFN($image))) {
761        $tabs['edit'] = array('href'    => media_managerURL(['tab_details' => 'edit'], '&'),
762                              'caption' => $lang['media_edittab']);
763    }
764    if ($conf['mediarevisions']) {
765        $tabs['history'] = array('href'    => media_managerURL(['tab_details' => 'history'], '&'),
766                                 'caption' => $lang['media_historytab']);
767    }
768
769    html_tabs($tabs, $selected_tab);
770}
771
772/**
773 * Prints options for the tab that displays a list of all files
774 *
775 * @author Kate Arzamastseva <pshns@ukr.net>
776 */
777function media_tab_files_options() {
778    global $lang;
779    global $INPUT;
780    global $ID;
781
782    $form = new Form([
783            'method' => 'get',
784            'action' => wl($ID),
785            'class' => 'options'
786    ]);
787    $form->addTagOpen('div')->addClass('no');
788    $form->setHiddenField('sectok', null);
789    $media_manager_params = media_managerURL([], '', false, true);
790    foreach ($media_manager_params as $pKey => $pVal) {
791        $form->setHiddenField($pKey, $pVal);
792    }
793    if ($INPUT->has('q')) {
794        $form->setHiddenField('q', $INPUT->str('q'));
795    }
796    $form->addHTML('<ul>'.NL);
797    foreach (array('list' => array('listType', array('thumbs', 'rows')),
798                  'sort' => array('sortBy', array('name', 'date')))
799            as $group => $content) {
800        $checked = "_media_get_${group}_type";
801        $checked = $checked();
802
803        $form->addHTML('<li class="'. $content[0] .'">');
804        foreach ($content[1] as $option) {
805            $attrs = array();
806            if ($checked == $option) {
807                $attrs['checked'] = 'checked';
808            }
809            $radio = $form->addRadioButton(
810                $group.'_dwmedia',
811                $lang['media_'.$group.'_'.$option]
812            )->val($option)->id($content[0].'__'.$option)->addClass($option);
813            $radio->attrs($attrs);
814        }
815        $form->addHTML('</li>'.NL);
816    }
817    $form->addHTML('<li>');
818    $form->addButton('', $lang['btn_apply'])->attr('type', 'submit');
819    $form->addHTML('</li>'.NL);
820    $form->addHTML('</ul>'.NL);
821    $form->addTagClose('div');
822    print $form->toHTML();
823}
824
825/**
826 * Returns type of sorting for the list of files in media manager
827 *
828 * @author Kate Arzamastseva <pshns@ukr.net>
829 *
830 * @return string - sort type
831 */
832function _media_get_sort_type() {
833    return _media_get_display_param('sort', array('default' => 'name', 'date'));
834}
835
836/**
837 * Returns type of listing for the list of files in media manager
838 *
839 * @author Kate Arzamastseva <pshns@ukr.net>
840 *
841 * @return string - list type
842 */
843function _media_get_list_type() {
844    return _media_get_display_param('list', array('default' => 'thumbs', 'rows'));
845}
846
847/**
848 * Get display parameters
849 *
850 * @param string $param   name of parameter
851 * @param array  $values  allowed values, where default value has index key 'default'
852 * @return string the parameter value
853 */
854function _media_get_display_param($param, $values) {
855    global $INPUT;
856    if (in_array($INPUT->str($param), $values)) {
857        // FIXME: Set cookie
858        return $INPUT->str($param);
859    } else {
860        $val = get_doku_pref($param, $values['default']);
861        if (!in_array($val, $values)) {
862            $val = $values['default'];
863        }
864        return $val;
865    }
866}
867
868/**
869 * Prints tab that displays a list of all files
870 *
871 * @author Kate Arzamastseva <pshns@ukr.net>
872 *
873 * @param string    $ns
874 * @param null|int  $auth permission level
875 * @param string    $jump item id
876 */
877function media_tab_files($ns,$auth=null,$jump='') {
878    global $lang;
879    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
880
881    if($auth < AUTH_READ){
882        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
883    }else{
884        media_filelist($ns,$auth,$jump,true,_media_get_sort_type());
885    }
886}
887
888/**
889 * Prints tab that displays uploading form
890 *
891 * @author Kate Arzamastseva <pshns@ukr.net>
892 *
893 * @param string   $ns
894 * @param null|int $auth permission level
895 * @param string   $jump item id
896 */
897function media_tab_upload($ns,$auth=null,$jump='') {
898    global $lang;
899    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
900
901    echo '<div class="upload">'.NL;
902    if ($auth >= AUTH_UPLOAD) {
903        echo '<p>' . $lang['mediaupload'] . '</p>';
904    }
905    media_uploadform($ns, $auth, true);
906    echo '</div>'.NL;
907}
908
909/**
910 * Prints tab that displays search form
911 *
912 * @author Kate Arzamastseva <pshns@ukr.net>
913 *
914 * @param string $ns
915 * @param null|int $auth permission level
916 */
917function media_tab_search($ns,$auth=null) {
918    global $INPUT;
919
920    $do = $INPUT->str('mediado');
921    $query = $INPUT->str('q');
922    echo '<div class="search">'.NL;
923
924    media_searchform($ns, $query, true);
925    if ($do == 'searchlist' || $query) {
926        media_searchlist($query,$ns,$auth,true,_media_get_sort_type());
927    }
928    echo '</div>'.NL;
929}
930
931/**
932 * Prints tab that displays mediafile details
933 *
934 * @author Kate Arzamastseva <pshns@ukr.net>
935 *
936 * @param string     $image media id
937 * @param string     $ns
938 * @param null|int   $auth  permission level
939 * @param string|int $rev   revision timestamp or empty string
940 */
941function media_tab_view($image, $ns, $auth=null, $rev='') {
942    global $lang;
943    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
944
945    if ($image && $auth >= AUTH_READ) {
946        $meta = new JpegMeta(mediaFN($image, $rev));
947        media_preview($image, $auth, $rev, $meta);
948        media_preview_buttons($image, $auth, $rev);
949        media_details($image, $auth, $rev, $meta);
950
951    } else {
952        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
953    }
954}
955
956/**
957 * Prints tab that displays form for editing mediafile metadata
958 *
959 * @author Kate Arzamastseva <pshns@ukr.net>
960 *
961 * @param string     $image media id
962 * @param string     $ns
963 * @param null|int   $auth permission level
964 */
965function media_tab_edit($image, $ns, $auth=null) {
966    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
967
968    if ($image) {
969        list(, $mime) = mimetype($image);
970        if ($mime == 'image/jpeg') media_metaform($image,$auth);
971    }
972}
973
974/**
975 * Prints tab that displays mediafile revisions
976 *
977 * @author Kate Arzamastseva <pshns@ukr.net>
978 *
979 * @param string     $image media id
980 * @param string     $ns
981 * @param null|int   $auth permission level
982 */
983function media_tab_history($image, $ns, $auth=null) {
984    global $lang;
985    global $INPUT;
986
987    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
988    $do = $INPUT->str('mediado');
989
990    if ($auth >= AUTH_READ && $image) {
991        if ($do == 'diff'){
992            (new dokuwiki\Ui\MediaDiff($image))->show(); //media_diff($image, $ns, $auth);
993        } else {
994            $first = $INPUT->int('first');
995            (new dokuwiki\Ui\MediaRevisions($image))->show($first);
996        }
997    } else {
998        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
999    }
1000}
1001
1002/**
1003 * Prints mediafile details
1004 *
1005 * @param string         $image media id
1006 * @param int            $auth permission level
1007 * @param int|string     $rev revision timestamp or empty string
1008 * @param JpegMeta|bool  $meta
1009 *
1010 * @author Kate Arzamastseva <pshns@ukr.net>
1011 */
1012function media_preview($image, $auth, $rev='', $meta=false) {
1013
1014    $size = media_image_preview_size($image, $rev, $meta);
1015
1016    if ($size) {
1017        global $lang;
1018        echo '<div class="image">';
1019
1020        $more = array();
1021        if ($rev) {
1022            $more['rev'] = $rev;
1023        } else {
1024            $t = @filemtime(mediaFN($image));
1025            $more['t'] = $t;
1026        }
1027
1028        $more['w'] = $size[0];
1029        $more['h'] = $size[1];
1030        $src = ml($image, $more);
1031
1032        echo '<a href="'.$src.'" target="_blank" title="'.$lang['mediaview'].'">';
1033        echo '<img src="'.$src.'" alt="" style="max-width: '.$size[0].'px;" />';
1034        echo '</a>';
1035
1036        echo '</div>'.NL;
1037    }
1038}
1039
1040/**
1041 * Prints mediafile action buttons
1042 *
1043 * @author Kate Arzamastseva <pshns@ukr.net>
1044 *
1045 * @param string     $image media id
1046 * @param int        $auth  permission level
1047 * @param string|int $rev   revision timestamp, or empty string
1048 */
1049function media_preview_buttons($image, $auth, $rev = '') {
1050    global $lang, $conf;
1051
1052    echo '<ul class="actions">'.DOKU_LF;
1053
1054    if ($auth >= AUTH_DELETE && !$rev && file_exists(mediaFN($image))) {
1055
1056        // delete button
1057        $form = new Form([
1058            'id' => 'mediamanager__btn_delete',
1059            'action' => media_managerURL(['delete' => $image], '&'),
1060        ]);
1061        $form->addTagOpen('div')->addClass('no');
1062        $form->addButton('', $lang['btn_delete'])->attr('type', 'submit');
1063        $form->addTagClose('div');
1064        echo '<li>';
1065        echo $form->toHTML();
1066        echo '</li>'.DOKU_LF;
1067    }
1068
1069    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
1070    if ($auth >= $auth_ow && !$rev) {
1071
1072        // upload new version button
1073        $form = new Form([
1074            'id' => 'mediamanager__btn_update',
1075            'action' => media_managerURL(['image' => $image, 'mediado' => 'update'], '&'),
1076        ]);
1077        $form->addTagOpen('div')->addClass('no');
1078        $form->addButton('', $lang['media_update'])->attr('type', 'submit');
1079        $form->addTagClose('div');
1080        echo '<li>';
1081        echo $form->toHTML();
1082        echo '</li>'.DOKU_LF;
1083    }
1084
1085    if ($auth >= AUTH_UPLOAD && $rev && $conf['mediarevisions'] && file_exists(mediaFN($image, $rev))) {
1086
1087        // restore button
1088        $form = new Form([
1089            'id' => 'mediamanager__btn_restore',
1090            'action'=>media_managerURL(['image' => $image], '&'),
1091        ]);
1092        $form->addTagOpen('div')->addClass('no');
1093        $form->setHiddenField('mediado', 'restore');
1094        $form->setHiddenField('rev', $rev);
1095        $form->addButton('', $lang['media_restore'])->attr('type', 'submit');
1096        $form->addTagClose('div');
1097        echo '<li>';
1098        echo $form->toHTML();
1099        echo '</li>'.DOKU_LF;
1100    }
1101
1102    echo '</ul>'.DOKU_LF;
1103}
1104
1105/**
1106 * Returns image width and height for mediamanager preview panel
1107 *
1108 * @author Kate Arzamastseva <pshns@ukr.net>
1109 * @param string         $image
1110 * @param int|string     $rev
1111 * @param JpegMeta|bool  $meta
1112 * @param int            $size
1113 * @return array|false
1114 */
1115function media_image_preview_size($image, $rev, $meta, $size = 500) {
1116    if (!preg_match("/\.(jpe?g|gif|png)$/", $image) || !file_exists(mediaFN($image, $rev))) return false;
1117
1118    $info = getimagesize(mediaFN($image, $rev));
1119    $w = (int) $info[0];
1120    $h = (int) $info[1];
1121
1122    if($meta && ($w > $size || $h > $size)){
1123        $ratio = $meta->getResizeRatio($size, $size);
1124        $w = floor($w * $ratio);
1125        $h = floor($h * $ratio);
1126    }
1127    return array($w, $h);
1128}
1129
1130/**
1131 * Returns the requested EXIF/IPTC tag from the image meta
1132 *
1133 * @author Kate Arzamastseva <pshns@ukr.net>
1134 *
1135 * @param array    $tags array with tags, first existing is returned
1136 * @param JpegMeta $meta
1137 * @param string   $alt  alternative value
1138 * @return string
1139 */
1140function media_getTag($tags,$meta,$alt=''){
1141    if($meta === false) return $alt;
1142    $info = $meta->getField($tags);
1143    if($info == false) return $alt;
1144    return $info;
1145}
1146
1147/**
1148 * Returns mediafile tags
1149 *
1150 * @author Kate Arzamastseva <pshns@ukr.net>
1151 *
1152 * @param JpegMeta $meta
1153 * @return array list of tags of the mediafile
1154 */
1155function media_file_tags($meta) {
1156    // load the field descriptions
1157    static $fields = null;
1158    if(is_null($fields)){
1159        $config_files = getConfigFiles('mediameta');
1160        foreach ($config_files as $config_file) {
1161            if(file_exists($config_file)) include($config_file);
1162        }
1163    }
1164
1165    $tags = array();
1166
1167    foreach($fields as $key => $tag){
1168        $t = array();
1169        if (!empty($tag[0])) $t = array($tag[0]);
1170        if(isset($tag[3]) && is_array($tag[3])) $t = array_merge($t,$tag[3]);
1171        $value = media_getTag($t, $meta);
1172        $tags[] = array('tag' => $tag, 'value' => $value);
1173    }
1174
1175    return $tags;
1176}
1177
1178/**
1179 * Prints mediafile tags
1180 *
1181 * @author Kate Arzamastseva <pshns@ukr.net>
1182 *
1183 * @param string        $image image id
1184 * @param int           $auth  permission level
1185 * @param string|int    $rev   revision timestamp, or empty string
1186 * @param bool|JpegMeta $meta  image object, or create one if false
1187 */
1188function media_details($image, $auth, $rev='', $meta=false) {
1189    global $lang;
1190
1191    if (!$meta) $meta = new JpegMeta(mediaFN($image, $rev));
1192    $tags = media_file_tags($meta);
1193
1194    echo '<dl>'.NL;
1195    foreach($tags as $tag){
1196        if ($tag['value']) {
1197            $value = cleanText($tag['value']);
1198            echo '<dt>'.$lang[$tag['tag'][1]].'</dt><dd>';
1199            if ($tag['tag'][2] == 'date') echo dformat($value);
1200            else echo hsc($value);
1201            echo '</dd>'.NL;
1202        }
1203    }
1204    echo '</dl>'.NL;
1205    echo '<dl>'.NL;
1206    echo '<dt>'.$lang['reference'].':</dt>';
1207    $media_usage = ft_mediause($image,true);
1208    if(count($media_usage) > 0){
1209        foreach($media_usage as $path){
1210            echo '<dd>'.html_wikilink($path).'</dd>';
1211        }
1212    }else{
1213        echo '<dd>'.$lang['nothingfound'].'</dd>';
1214    }
1215    echo '</dl>'.NL;
1216
1217}
1218
1219/**
1220 * Shows difference between two revisions of file
1221 *
1222 * @author Kate Arzamastseva <pshns@ukr.net>
1223 *
1224 * @param string $image  image id
1225 * @param string $ns
1226 * @param int $auth permission level
1227 * @param bool $fromajax
1228 * @return false|null|string
1229 */
1230function media_diff($image, $ns, $auth, $fromajax = false) {
1231    global $conf;
1232    global $INPUT;
1233
1234    if ($auth < AUTH_READ || !$image || !$conf['mediarevisions']) return '';
1235
1236    $rev1 = $INPUT->int('rev');
1237
1238    $rev2 = $INPUT->ref('rev2');
1239    if(is_array($rev2)){
1240        $rev1 = (int) $rev2[0];
1241        $rev2 = (int) $rev2[1];
1242
1243        if(!$rev1){
1244            $rev1 = $rev2;
1245            unset($rev2);
1246        }
1247    }else{
1248        $rev2 = $INPUT->int('rev2');
1249    }
1250
1251    if ($rev1 && !file_exists(mediaFN($image, $rev1))) $rev1 = false;
1252    if ($rev2 && !file_exists(mediaFN($image, $rev2))) $rev2 = false;
1253
1254    if($rev1 && $rev2){            // two specific revisions wanted
1255        // make sure order is correct (older on the left)
1256        if($rev1 < $rev2){
1257            $l_rev = $rev1;
1258            $r_rev = $rev2;
1259        }else{
1260            $l_rev = $rev2;
1261            $r_rev = $rev1;
1262        }
1263    }elseif($rev1){                // single revision given, compare to current
1264        $r_rev = '';
1265        $l_rev = $rev1;
1266    }else{                        // no revision was given, compare previous to current
1267        $r_rev = '';
1268        $medialog = new MediaChangeLog($image);
1269        $revs = $medialog->getRevisions(0, 1);
1270        if (file_exists(mediaFN($image, $revs[0]))) {
1271            $l_rev = $revs[0];
1272        } else {
1273            $l_rev = '';
1274        }
1275    }
1276
1277    // prepare event data
1278    $data = array();
1279    $data[0] = $image;
1280    $data[1] = $l_rev;
1281    $data[2] = $r_rev;
1282    $data[3] = $ns;
1283    $data[4] = $auth;
1284    $data[5] = $fromajax;
1285
1286    // trigger event
1287    return Event::createAndTrigger('MEDIA_DIFF', $data, '_media_file_diff', true);
1288}
1289
1290/**
1291 * Callback for media file diff
1292 *
1293 * @param array $data event data
1294 * @return false|null
1295 */
1296function _media_file_diff($data) {
1297    if(is_array($data) && count($data)===6) {
1298        media_file_diff($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
1299    } else {
1300        return false;
1301    }
1302}
1303
1304/**
1305 * Shows difference between two revisions of image
1306 *
1307 * @author Kate Arzamastseva <pshns@ukr.net>
1308 *
1309 * @param string $image
1310 * @param string|int $l_rev revision timestamp, or empty string
1311 * @param string|int $r_rev revision timestamp, or empty string
1312 * @param string $ns
1313 * @param int $auth permission level
1314 * @param bool $fromajax
1315 */
1316function media_file_diff($image, $l_rev, $r_rev, $ns, $auth, $fromajax) {
1317    global $lang;
1318    global $INPUT;
1319
1320    $l_meta = new JpegMeta(mediaFN($image, $l_rev));
1321    $r_meta = new JpegMeta(mediaFN($image, $r_rev));
1322
1323    $is_img = preg_match('/\.(jpe?g|gif|png)$/', $image);
1324    if ($is_img) {
1325        $l_size = media_image_preview_size($image, $l_rev, $l_meta);
1326        $r_size = media_image_preview_size($image, $r_rev, $r_meta);
1327        $is_img = ($l_size && $r_size && ($l_size[0] >= 30 || $r_size[0] >= 30));
1328
1329        $difftype = $INPUT->str('difftype');
1330
1331        if (!$fromajax) {
1332            $form = new Form([
1333                'id' => 'mediamanager__form_diffview',
1334                'action' => media_managerURL([], '&'),
1335                'method' => 'get',
1336                'class' => 'diffView',
1337            ]);
1338            $form->addTagOpen('div')->addClass('no');
1339            $form->setHiddenField('sectok', null);
1340            $form->setHiddenField('mediado', 'diff');
1341            $form->setHiddenField('rev2[0]', $l_rev);
1342            $form->setHiddenField('rev2[1]', $r_rev);
1343            $form->addTagClose('div');
1344            echo $form->toHTML();
1345
1346            echo NL.'<div id="mediamanager__diff" >'.NL;
1347        }
1348
1349        if ($difftype == 'opacity' || $difftype == 'portions') {
1350            media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $difftype);
1351            if (!$fromajax) echo '</div>';
1352            return;
1353        }
1354    }
1355
1356    $medialog = new MediaChangeLog($image);
1357    list($l_head, $r_head) = (new dokuwiki\Ui\MediaDiff($image))->diffHead($medialog, $l_rev, $r_rev);
1358
1359    ?>
1360    <div class="table">
1361    <table>
1362      <tr>
1363        <th><?php echo $l_head; ?></th>
1364        <th><?php echo $r_head; ?></th>
1365      </tr>
1366    <?php
1367
1368    echo '<tr class="image">';
1369    echo '<td>';
1370    media_preview($image, $auth, $l_rev, $l_meta);
1371    echo '</td>';
1372
1373    echo '<td>';
1374    media_preview($image, $auth, $r_rev, $r_meta);
1375    echo '</td>';
1376    echo '</tr>'.NL;
1377
1378    echo '<tr class="actions">';
1379    echo '<td>';
1380    media_preview_buttons($image, $auth, $l_rev);
1381    echo '</td>';
1382
1383    echo '<td>';
1384    media_preview_buttons($image, $auth, $r_rev);
1385    echo '</td>';
1386    echo '</tr>'.NL;
1387
1388    $l_tags = media_file_tags($l_meta);
1389    $r_tags = media_file_tags($r_meta);
1390    // FIXME r_tags-only stuff
1391    foreach ($l_tags as $key => $l_tag) {
1392        if ($l_tag['value'] != $r_tags[$key]['value']) {
1393            $r_tags[$key]['highlighted'] = true;
1394            $l_tags[$key]['highlighted'] = true;
1395        } else if (!$l_tag['value'] || !$r_tags[$key]['value']) {
1396            unset($r_tags[$key]);
1397            unset($l_tags[$key]);
1398        }
1399    }
1400
1401    echo '<tr>';
1402    foreach(array($l_tags,$r_tags) as $tags){
1403        echo '<td>'.NL;
1404
1405        echo '<dl class="img_tags">';
1406        foreach($tags as $tag){
1407            $value = cleanText($tag['value']);
1408            if (!$value) $value = '-';
1409            echo '<dt>'.$lang[$tag['tag'][1]].'</dt>';
1410            echo '<dd>';
1411            if ($tag['highlighted']) {
1412                echo '<strong>';
1413            }
1414            if ($tag['tag'][2] == 'date') echo dformat($value);
1415            else echo hsc($value);
1416            if ($tag['highlighted']) {
1417                echo '</strong>';
1418            }
1419            echo '</dd>';
1420        }
1421        echo '</dl>'.NL;
1422
1423        echo '</td>';
1424    }
1425    echo '</tr>'.NL;
1426
1427    echo '</table>'.NL;
1428    echo '</div>'.NL;
1429
1430    if ($is_img && !$fromajax) echo '</div>';
1431}
1432
1433/**
1434 * Prints two images side by side
1435 * and slider
1436 *
1437 * @author Kate Arzamastseva <pshns@ukr.net>
1438 *
1439 * @param string $image   image id
1440 * @param int    $l_rev   revision timestamp, or empty string
1441 * @param int    $r_rev   revision timestamp, or empty string
1442 * @param array  $l_size  array with width and height
1443 * @param array  $r_size  array with width and height
1444 * @param string $type
1445 */
1446function media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $type) {
1447    if ($l_size != $r_size) {
1448        if ($r_size[0] > $l_size[0]) {
1449            $l_size = $r_size;
1450        }
1451    }
1452
1453    $l_more = array('rev' => $l_rev, 'h' => $l_size[1], 'w' => $l_size[0]);
1454    $r_more = array('rev' => $r_rev, 'h' => $l_size[1], 'w' => $l_size[0]);
1455
1456    $l_src = ml($image, $l_more);
1457    $r_src = ml($image, $r_more);
1458
1459    // slider
1460    echo '<div class="slider" style="max-width: '.($l_size[0]-20).'px;" ></div>'.NL;
1461
1462    // two images in divs
1463    echo '<div class="imageDiff ' . $type . '">'.NL;
1464    echo '<div class="image1" style="max-width: '.$l_size[0].'px;">';
1465    echo '<img src="'.$l_src.'" alt="" />';
1466    echo '</div>'.NL;
1467    echo '<div class="image2" style="max-width: '.$l_size[0].'px;">';
1468    echo '<img src="'.$r_src.'" alt="" />';
1469    echo '</div>'.NL;
1470    echo '</div>'.NL;
1471}
1472
1473/**
1474 * Restores an old revision of a media file
1475 *
1476 * @param string $image media id
1477 * @param int    $rev   revision timestamp or empty string
1478 * @param int    $auth
1479 * @return string - file's id
1480 *
1481 * @author Kate Arzamastseva <pshns@ukr.net>
1482 */
1483function media_restore($image, $rev, $auth){
1484    global $conf;
1485    if ($auth < AUTH_UPLOAD || !$conf['mediarevisions']) return false;
1486    $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')));
1487    if (!$image || (!file_exists(mediaFN($image)) && !$removed)) return false;
1488    if (!$rev || !file_exists(mediaFN($image, $rev))) return false;
1489    list(,$imime,) = mimetype($image);
1490    $res = media_upload_finish(mediaFN($image, $rev),
1491        mediaFN($image),
1492        $image,
1493        $imime,
1494        true,
1495        'copy');
1496    if (is_array($res)) {
1497        msg($res[0], $res[1]);
1498        return false;
1499    }
1500    return $res;
1501}
1502
1503/**
1504 * List all files found by the search request
1505 *
1506 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1507 * @author Andreas Gohr <gohr@cosmocode.de>
1508 * @author Kate Arzamastseva <pshns@ukr.net>
1509 * @triggers MEDIA_SEARCH
1510 *
1511 * @param string $query
1512 * @param string $ns
1513 * @param null|int $auth
1514 * @param bool $fullscreen
1515 * @param string $sort
1516 */
1517function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort='natural'){
1518    global $conf;
1519    global $lang;
1520
1521    $ns = cleanID($ns);
1522    $evdata = array(
1523        'ns'    => $ns,
1524        'data'  => array(),
1525        'query' => $query
1526    );
1527    if (!blank($query)) {
1528        $evt = new Event('MEDIA_SEARCH', $evdata);
1529        if ($evt->advise_before()) {
1530            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
1531            $quoted = preg_quote($evdata['query'],'/');
1532            //apply globbing
1533            $quoted = str_replace(array('\*', '\?'), array('.*', '.'), $quoted, $count);
1534
1535            //if we use globbing file name must match entirely but may be preceded by arbitrary namespace
1536            if ($count > 0) $quoted = '^([^:]*:)*'.$quoted.'$';
1537
1538            $pattern = '/'.$quoted.'/i';
1539            search($evdata['data'],
1540                    $conf['mediadir'],
1541                    'search_media',
1542                    array('showmsg'=>false,'pattern'=>$pattern),
1543                    $dir,
1544                    1,
1545                    $sort);
1546        }
1547        $evt->advise_after();
1548        unset($evt);
1549    }
1550
1551    if (!$fullscreen) {
1552        echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
1553        media_searchform($ns,$query);
1554    }
1555
1556    if(!count($evdata['data'])){
1557        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
1558    }else {
1559        if ($fullscreen) {
1560            echo '<ul class="' . _media_get_list_type() . '">';
1561        }
1562        foreach($evdata['data'] as $item){
1563            if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
1564            else media_printfile_thumbs($item,$item['perm'],false,true);
1565        }
1566        if ($fullscreen) echo '</ul>'.NL;
1567    }
1568}
1569
1570/**
1571 * Formats and prints one file in the list
1572 *
1573 * @param array     $item
1574 * @param int       $auth              permission level
1575 * @param string    $jump              item id
1576 * @param bool      $display_namespace
1577 */
1578function media_printfile($item,$auth,$jump,$display_namespace=false){
1579    global $lang;
1580
1581    // Prepare zebra coloring
1582    // I always wanted to use this variable name :-D
1583    static $twibble = 1;
1584    $twibble *= -1;
1585    $zebra = ($twibble == -1) ? 'odd' : 'even';
1586
1587    // Automatically jump to recent action
1588    if($jump == $item['id']) {
1589        $jump = ' id="scroll__here" ';
1590    }else{
1591        $jump = '';
1592    }
1593
1594    // Prepare fileicons
1595    list($ext) = mimetype($item['file'],false);
1596    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1597    $class = 'select mediafile mf_'.$class;
1598
1599    // Prepare filename
1600    $file = utf8_decodeFN($item['file']);
1601
1602    // Prepare info
1603    $info = '';
1604    if($item['isimg']){
1605        $info .= (int) $item['meta']->getField('File.Width');
1606        $info .= '&#215;';
1607        $info .= (int) $item['meta']->getField('File.Height');
1608        $info .= ' ';
1609    }
1610    $info .= '<i>'.dformat($item['mtime']).'</i>';
1611    $info .= ' ';
1612    $info .= filesize_h($item['size']);
1613
1614    // output
1615    echo '<div class="'.$zebra.'"'.$jump.' title="'.hsc($item['id']).'">'.NL;
1616    if (!$display_namespace) {
1617        echo '<a id="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1618    } else {
1619        echo '<a id="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1620    }
1621    echo '<span class="info">('.$info.')</span>'.NL;
1622
1623    // view button
1624    $link = ml($item['id'],'',true);
1625    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
1626        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
1627
1628    // mediamanager button
1629    $link = wl('',array('do'=>'media','image'=>$item['id'],'ns'=>getNS($item['id'])));
1630    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/mediamanager.png" '.
1631        'alt="'.$lang['btn_media'].'" title="'.$lang['btn_media'].'" class="btn" /></a>';
1632
1633    // delete button
1634    if($item['writable'] && $auth >= AUTH_DELETE){
1635        $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
1636            '&amp;sectok='.getSecurityToken();
1637        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
1638            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
1639            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
1640    }
1641
1642    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1643    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1644    echo '</div>';
1645    if($item['isimg']) media_printimgdetail($item);
1646    echo '<div class="clearer"></div>'.NL;
1647    echo '</div>'.NL;
1648}
1649
1650/**
1651 * Display a media icon
1652 *
1653 * @param string $filename media id
1654 * @param string $size     the size subfolder, if not specified 16x16 is used
1655 * @return string html
1656 */
1657function media_printicon($filename, $size=''){
1658    list($ext) = mimetype(mediaFN($filename),false);
1659
1660    if (file_exists(DOKU_INC.'lib/images/fileicons/'.$size.'/'.$ext.'.png')) {
1661        $icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/'.$ext.'.png';
1662    } else {
1663        $icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/file.png';
1664    }
1665
1666    return '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />';
1667}
1668
1669/**
1670 * Formats and prints one file in the list in the thumbnails view
1671 *
1672 * @author Kate Arzamastseva <pshns@ukr.net>
1673 *
1674 * @param array       $item
1675 * @param int         $auth              permission level
1676 * @param bool|string $jump              item id
1677 * @param bool        $display_namespace
1678 */
1679function media_printfile_thumbs($item,$auth,$jump=false,$display_namespace=false){
1680
1681    // Prepare filename
1682    $file = utf8_decodeFN($item['file']);
1683
1684    // output
1685    echo '<li><dl title="'.hsc($item['id']).'">'.NL;
1686
1687        echo '<dt>';
1688    if($item['isimg']) {
1689        media_printimgdetail($item, true);
1690
1691    } else {
1692        echo '<a id="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1693            media_managerURL(['image' => hsc($item['id']), 'ns' => getNS($item['id']),
1694            'tab_details' => 'view']).'">';
1695        echo media_printicon($item['id'], '32x32');
1696        echo '</a>';
1697    }
1698    echo '</dt>'.NL;
1699    if (!$display_namespace) {
1700        $name = hsc($file);
1701    } else {
1702        $name = hsc($item['id']);
1703    }
1704    echo '<dd class="name"><a href="'.media_managerURL(['image' => hsc($item['id']), 'ns' => getNS($item['id']),
1705        'tab_details' => 'view']).'" id="h_:'.$item['id'].'">'.$name.'</a></dd>'.NL;
1706
1707    if($item['isimg']){
1708        $size = '';
1709        $size .= (int) $item['meta']->getField('File.Width');
1710        $size .= '&#215;';
1711        $size .= (int) $item['meta']->getField('File.Height');
1712        echo '<dd class="size">'.$size.'</dd>'.NL;
1713    } else {
1714        echo '<dd class="size">&#160;</dd>'.NL;
1715    }
1716    $date = dformat($item['mtime']);
1717    echo '<dd class="date">'.$date.'</dd>'.NL;
1718    $filesize = filesize_h($item['size']);
1719    echo '<dd class="filesize">'.$filesize.'</dd>'.NL;
1720    echo '</dl></li>'.NL;
1721}
1722
1723/**
1724 * Prints a thumbnail and metainfo
1725 *
1726 * @param array $item
1727 * @param bool  $fullscreen
1728 */
1729function media_printimgdetail($item, $fullscreen=false){
1730    // prepare thumbnail
1731    $size = $fullscreen ? 90 : 120;
1732
1733    $w = (int) $item['meta']->getField('File.Width');
1734    $h = (int) $item['meta']->getField('File.Height');
1735    if($w>$size || $h>$size){
1736        if (!$fullscreen) {
1737            $ratio = $item['meta']->getResizeRatio($size);
1738        } else {
1739            $ratio = $item['meta']->getResizeRatio($size,$size);
1740        }
1741        $w = floor($w * $ratio);
1742        $h = floor($h * $ratio);
1743    }
1744    $src = ml($item['id'],array('w'=>$w,'h'=>$h,'t'=>$item['mtime']));
1745    $p = array();
1746    if (!$fullscreen) {
1747        // In fullscreen mediamanager view, image resizing is done via CSS.
1748        $p['width']  = $w;
1749        $p['height'] = $h;
1750    }
1751    $p['alt']    = $item['id'];
1752    $att = buildAttributes($p);
1753
1754    // output
1755    if ($fullscreen) {
1756        echo '<a id="l_:'.$item['id'].'" class="image thumb" href="'.
1757            media_managerURL(['image' => hsc($item['id']), 'ns' => getNS($item['id']), 'tab_details' => 'view']).'">';
1758        echo '<img src="'.$src.'" '.$att.' />';
1759        echo '</a>';
1760    }
1761
1762    if ($fullscreen) return;
1763
1764    echo '<div class="detail">';
1765    echo '<div class="thumb">';
1766    echo '<a id="d_:'.$item['id'].'" class="select">';
1767    echo '<img src="'.$src.'" '.$att.' />';
1768    echo '</a>';
1769    echo '</div>';
1770
1771    // read EXIF/IPTC data
1772    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1773    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1774                'EXIF.TIFFImageDescription',
1775                'EXIF.TIFFUserComment'));
1776    if(\dokuwiki\Utf8\PhpString::strlen($d) > 250) $d = \dokuwiki\Utf8\PhpString::substr($d,0,250).'...';
1777    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1778
1779    // print EXIF/IPTC data
1780    if($t || $d || $k ){
1781        echo '<p>';
1782        if($t) echo '<strong>'.hsc($t).'</strong><br />';
1783        if($d) echo hsc($d).'<br />';
1784        if($t) echo '<em>'.hsc($k).'</em>';
1785        echo '</p>';
1786    }
1787    echo '</div>';
1788}
1789
1790/**
1791 * Build link based on the current, adding/rewriting parameters
1792 *
1793 * @author Kate Arzamastseva <pshns@ukr.net>
1794 *
1795 * @param array|bool $params
1796 * @param string     $amp           separator
1797 * @param bool       $abs           absolute url?
1798 * @param bool       $params_array  return the parmeters array?
1799 * @return string|array - link or link parameters
1800 */
1801function media_managerURL($params = false, $amp = '&amp;', $abs = false, $params_array = false) {
1802    global $ID;
1803    global $INPUT;
1804
1805    $gets = array('do' => 'media');
1806    $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'list', 'sort');
1807    foreach ($media_manager_params as $x) {
1808        if ($INPUT->has($x)) $gets[$x] = $INPUT->str($x);
1809    }
1810
1811    if ($params) {
1812        $gets = $params + $gets;
1813    }
1814    unset($gets['id']);
1815    if (isset($gets['delete'])) {
1816        unset($gets['image']);
1817        unset($gets['tab_details']);
1818    }
1819
1820    if ($params_array) return $gets;
1821
1822    return wl($ID,$gets,$abs,$amp);
1823}
1824
1825/**
1826 * Print the media upload form if permissions are correct
1827 *
1828 * @author Andreas Gohr <andi@splitbrain.org>
1829 * @author Kate Arzamastseva <pshns@ukr.net>
1830 *
1831 * @param string $ns
1832 * @param int    $auth permission level
1833 * @param bool  $fullscreen
1834 */
1835function media_uploadform($ns, $auth, $fullscreen = false) {
1836    global $lang;
1837    global $conf;
1838    global $INPUT;
1839
1840    if ($auth < AUTH_UPLOAD) {
1841        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1842        return;
1843    }
1844    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
1845
1846    $update = false;
1847    $id = '';
1848    if ($auth >= $auth_ow && $fullscreen && $INPUT->str('mediado') == 'update') {
1849        $update = true;
1850        $id = cleanID($INPUT->str('image'));
1851    }
1852
1853    // The default HTML upload form
1854    $form = new Form([
1855        'id' => 'dw__upload',
1856        'enctype' => 'multipart/form-data',
1857        'action' => ($fullscreen)
1858                    ? media_managerURL(['tab_files' => 'files', 'tab_details' => 'view'], '&')
1859                    : DOKU_BASE.'lib/exe/mediamanager.php',
1860    ]);
1861    $form->addTagOpen('div')->addClass('no');
1862    $form->setHiddenField('ns', hsc($ns));  // FIXME hsc required?
1863    $form->addTagOpen('p');
1864    $form->addTextInput('upload', $lang['txt_upload'])->id('upload__file')
1865            ->attrs(['type' => 'file']);
1866    $form->addTagClose('p');
1867    $form->addTagOpen('p');
1868    $form->addTextInput('mediaid', $lang['txt_filename'])->id('upload__name')
1869            ->val(noNS($id));
1870    $form->addButton('', $lang['btn_upload'])->attr('type', 'submit');
1871    $form->addTagClose('p');
1872    if ($auth >= $auth_ow){
1873        $form->addTagOpen('p');
1874        $attrs = array();
1875        if ($update) $attrs['checked'] = 'checked';
1876        $form->addCheckbox('ow', $lang['txt_overwrt'])->id('dw__ow')->val('1')
1877            ->addClass('check')->attrs($attrs);
1878        $form->addTagClose('p');
1879    }
1880    $form->addTagClose('div');
1881
1882    if (!$fullscreen) {
1883        echo '<div class="upload">'. $lang['mediaupload'] .'</div>'.DOKU_LF;
1884    } else {
1885        echo DOKU_LF;
1886    }
1887
1888    echo '<div id="mediamanager__uploader">'.DOKU_LF;
1889    echo $form->toHTML('Upload');
1890    echo '</div>'.DOKU_LF;
1891
1892    echo '<p class="maxsize">';
1893    printf($lang['maxuploadsize'], filesize_h(media_getuploadsize()));
1894    echo ' <a class="allowedmime" href="#">'. $lang['allowedmime'] .'</a>';
1895    echo ' <span>'. implode(', ', array_keys(getMimeTypes())) .'</span>';
1896    echo '</p>'.DOKU_LF;
1897}
1898
1899/**
1900 * Returns the size uploaded files may have
1901 *
1902 * This uses a conservative approach using the lowest number found
1903 * in any of the limiting ini settings
1904 *
1905 * @returns int size in bytes
1906 */
1907function media_getuploadsize(){
1908    $okay = 0;
1909
1910    $post = (int) php_to_byte(@ini_get('post_max_size'));
1911    $suho = (int) php_to_byte(@ini_get('suhosin.post.max_value_length'));
1912    $upld = (int) php_to_byte(@ini_get('upload_max_filesize'));
1913
1914    if($post && ($post < $okay || $okay == 0)) $okay = $post;
1915    if($suho && ($suho < $okay || $okay == 0)) $okay = $suho;
1916    if($upld && ($upld < $okay || $okay == 0)) $okay = $upld;
1917
1918    return $okay;
1919}
1920
1921/**
1922 * Print the search field form
1923 *
1924 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1925 * @author Kate Arzamastseva <pshns@ukr.net>
1926 *
1927 * @param string $ns
1928 * @param string $query
1929 * @param bool $fullscreen
1930 */
1931function media_searchform($ns, $query = '', $fullscreen = false) {
1932    global $lang;
1933
1934    // The default HTML search form
1935    $form = new Form([
1936        'id'     => 'dw__mediasearch',
1937        'action' => ($fullscreen)
1938                    ? media_managerURL([], '&')
1939                    : DOKU_BASE.'lib/exe/mediamanager.php',
1940    ]);
1941    $form->addTagOpen('div')->addClass('no');
1942    $form->setHiddenField('ns', $ns);
1943    $form->setHiddenField($fullscreen ? 'mediado' : 'do', 'searchlist');
1944
1945    $form->addTagOpen('p');
1946    $form->addTextInput('q', $lang['searchmedia'])
1947            ->attr('title', sprintf($lang['searchmedia_in'], hsc($ns) .':*'))
1948            ->val($query);
1949    $form->addHTML(' ');
1950    $form->addButton('', $lang['btn_search'])->attr('type', 'submit');
1951    $form->addTagClose('p');
1952    $form->addTagClose('div');
1953    print $form->toHTML('SearchMedia');
1954}
1955
1956/**
1957 * Build a tree outline of available media namespaces
1958 *
1959 * @author Andreas Gohr <andi@splitbrain.org>
1960 *
1961 * @param string $ns
1962 */
1963function media_nstree($ns){
1964    global $conf;
1965    global $lang;
1966
1967    // currently selected namespace
1968    $ns  = cleanID($ns);
1969    if(empty($ns)){
1970        global $ID;
1971        $ns = (string)getNS($ID);
1972    }
1973
1974    $ns_dir  = utf8_encodeFN(str_replace(':','/',$ns));
1975
1976    $data = array();
1977    search($data,$conf['mediadir'],'search_index',array('ns' => $ns_dir, 'nofiles' => true));
1978
1979    // wrap a list with the root level around the other namespaces
1980    array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
1981                               'label' => '['.$lang['mediaroot'].']'));
1982
1983    // insert the current ns into the hierarchy if it isn't already part of it
1984    $ns_parts = explode(':', $ns);
1985    $tmp_ns = '';
1986    $pos = 0;
1987    foreach ($ns_parts as $level => $part) {
1988        if ($tmp_ns) $tmp_ns .= ':'.$part;
1989        else $tmp_ns = $part;
1990
1991        // find the namespace parts or insert them
1992        while ($data[$pos]['id'] != $tmp_ns) {
1993            if (
1994                $pos >= count($data) ||
1995                ($data[$pos]['level'] <= $level+1 && Sort::strcmp($data[$pos]['id'], $tmp_ns) > 0)
1996            ) {
1997                array_splice($data, $pos, 0, array(array('level' => $level+1, 'id' => $tmp_ns, 'open' => 'true')));
1998                break;
1999            }
2000            ++$pos;
2001        }
2002    }
2003
2004    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
2005}
2006
2007/**
2008 * Userfunction for html_buildlist
2009 *
2010 * Prints a media namespace tree item
2011 *
2012 * @author Andreas Gohr <andi@splitbrain.org>
2013 *
2014 * @param array $item
2015 * @return string html
2016 */
2017function media_nstree_item($item){
2018    global $INPUT;
2019    $pos   = strrpos($item['id'], ':');
2020    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
2021    if(empty($item['label'])) $item['label'] = $label;
2022
2023    $ret  = '';
2024    if (!($INPUT->str('do') == 'media'))
2025    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
2026    else $ret .= '<a href="'.media_managerURL(['ns' => idfilter($item['id'], false), 'tab_files' => 'files'])
2027        .'" class="idx_dir">';
2028    $ret .= $item['label'];
2029    $ret .= '</a>';
2030    return $ret;
2031}
2032
2033/**
2034 * Userfunction for html_buildlist
2035 *
2036 * Prints a media namespace tree item opener
2037 *
2038 * @author Andreas Gohr <andi@splitbrain.org>
2039 *
2040 * @param array $item
2041 * @return string html
2042 */
2043function media_nstree_li($item){
2044    $class='media level'.$item['level'];
2045    if($item['open']){
2046        $class .= ' open';
2047        $img   = DOKU_BASE.'lib/images/minus.gif';
2048        $alt   = '−';
2049    }else{
2050        $class .= ' closed';
2051        $img   = DOKU_BASE.'lib/images/plus.gif';
2052        $alt   = '+';
2053    }
2054    // TODO: only deliver an image if it actually has a subtree...
2055    return '<li class="'.$class.'">'.
2056        '<img src="'.$img.'" alt="'.$alt.'" />';
2057}
2058
2059/**
2060 * Resizes the given image to the given size
2061 *
2062 * @author  Andreas Gohr <andi@splitbrain.org>
2063 *
2064 * @param string $file filename, path to file
2065 * @param string $ext  extension
2066 * @param int    $w    desired width
2067 * @param int    $h    desired height
2068 * @return string path to resized or original size if failed
2069 */
2070function media_resize_image($file, $ext, $w, $h=0){
2071    global $conf;
2072    if(!$h) $h = $w;
2073    // we wont scale up to infinity
2074    if($w > 2000 || $h > 2000) return $file;
2075
2076    //cache
2077    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
2078    $mtime = (int) @filemtime($local); // 0 if not exists
2079
2080    $options = [
2081        'quality' => $conf['jpg_quality'],
2082        'imconvert' => $conf['im_convert'],
2083    ];
2084
2085    if( $mtime <= (int) @filemtime($file) ) {
2086        try {
2087            \splitbrain\slika\Slika::run($file, $options)
2088                                   ->autorotate()
2089                                   ->resize($w, $h)
2090                                   ->save($local, $ext);
2091            if($conf['fperm']) @chmod($local, $conf['fperm']);
2092        } catch (\splitbrain\slika\Exception $e) {
2093            dbglog($e->getMessage());
2094            return $file;
2095        }
2096    }
2097
2098    return $local;
2099}
2100
2101/**
2102 * Center crops the given image to the wanted size
2103 *
2104 * @author  Andreas Gohr <andi@splitbrain.org>
2105 *
2106 * @param string $file filename, path to file
2107 * @param string $ext  extension
2108 * @param int    $w    desired width
2109 * @param int    $h    desired height
2110 * @return string path to resized or original size if failed
2111 */
2112function media_crop_image($file, $ext, $w, $h=0){
2113    global $conf;
2114    if(!$h) $h = $w;
2115    // we wont scale up to infinity
2116    if($w > 2000 || $h > 2000) return $file;
2117
2118    //cache
2119    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.crop.'.$ext);
2120    $mtime = (int) @filemtime($local); // 0 if not exists
2121
2122    $options = [
2123        'quality' => $conf['jpg_quality'],
2124        'imconvert' => $conf['im_convert'],
2125    ];
2126
2127    if( $mtime <= (int) @filemtime($file) ) {
2128        try {
2129            \splitbrain\slika\Slika::run($file, $options)
2130                                   ->autorotate()
2131                                    ->crop($w, $h)
2132                                    ->save($local, $ext);
2133            if($conf['fperm']) @chmod($local, $conf['fperm']);
2134        } catch (\splitbrain\slika\Exception $e) {
2135            dbglog($e->getMessage());
2136            return $file;
2137        }
2138    }
2139
2140    return $local;
2141}
2142
2143/**
2144 * Calculate a token to be used to verify fetch requests for resized or
2145 * cropped images have been internally generated - and prevent external
2146 * DDOS attacks via fetch
2147 *
2148 * @author Christopher Smith <chris@jalakai.co.uk>
2149 *
2150 * @param string  $id    id of the image
2151 * @param int     $w     resize/crop width
2152 * @param int     $h     resize/crop height
2153 * @return string token or empty string if no token required
2154 */
2155function media_get_token($id,$w,$h){
2156    // token is only required for modified images
2157    if ($w || $h || media_isexternal($id)) {
2158        $token = $id;
2159        if ($w) $token .= '.'.$w;
2160        if ($h) $token .= '.'.$h;
2161
2162        return substr(\dokuwiki\PassHash::hmac('md5', $token, auth_cookiesalt()),0,6);
2163    }
2164
2165    return '';
2166}
2167
2168/**
2169 * Download a remote file and return local filename
2170 *
2171 * returns false if download fails. Uses cached file if available and
2172 * wanted
2173 *
2174 * @author  Andreas Gohr <andi@splitbrain.org>
2175 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
2176 *
2177 * @param string $url
2178 * @param string $ext   extension
2179 * @param int    $cache cachetime in seconds
2180 * @return false|string path to cached file
2181 */
2182function media_get_from_URL($url,$ext,$cache){
2183    global $conf;
2184
2185    // if no cache or fetchsize just redirect
2186    if ($cache==0)           return false;
2187    if (!$conf['fetchsize']) return false;
2188
2189    $local = getCacheName(strtolower($url),".media.$ext");
2190    $mtime = @filemtime($local); // 0 if not exists
2191
2192    //decide if download needed:
2193    if(($mtime == 0) || // cache does not exist
2194        ($cache != -1 && $mtime < time() - $cache) // 'recache' and cache has expired
2195    ) {
2196        if(media_image_download($url, $local)) {
2197            return $local;
2198        } else {
2199            return false;
2200        }
2201    }
2202
2203    //if cache exists use it else
2204    if($mtime) return $local;
2205
2206    //else return false
2207    return false;
2208}
2209
2210/**
2211 * Download image files
2212 *
2213 * @author Andreas Gohr <andi@splitbrain.org>
2214 *
2215 * @param string $url
2216 * @param string $file path to file in which to put the downloaded content
2217 * @return bool
2218 */
2219function media_image_download($url,$file){
2220    global $conf;
2221    $http = new DokuHTTPClient();
2222    $http->keep_alive = false; // we do single ops here, no need for keep-alive
2223
2224    $http->max_bodysize = $conf['fetchsize'];
2225    $http->timeout = 25; //max. 25 sec
2226    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
2227
2228    $data = $http->get($url);
2229    if(!$data) return false;
2230
2231    $fileexists = file_exists($file);
2232    $fp = @fopen($file,"w");
2233    if(!$fp) return false;
2234    fwrite($fp,$data);
2235    fclose($fp);
2236    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
2237
2238    // check if it is really an image
2239    $info = @getimagesize($file);
2240    if(!$info){
2241        @unlink($file);
2242        return false;
2243    }
2244
2245    return true;
2246}
2247
2248/**
2249 * resize images using external ImageMagick convert program
2250 *
2251 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
2252 * @author Andreas Gohr <andi@splitbrain.org>
2253 *
2254 * @param string $ext     extension
2255 * @param string $from    filename path to file
2256 * @param int    $from_w  original width
2257 * @param int    $from_h  original height
2258 * @param string $to      path to resized file
2259 * @param int    $to_w    desired width
2260 * @param int    $to_h    desired height
2261 * @return bool
2262 */
2263function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
2264    global $conf;
2265
2266    // check if convert is configured
2267    if(!$conf['im_convert']) return false;
2268
2269    // prepare command
2270    $cmd  = $conf['im_convert'];
2271    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
2272    if ($ext == 'jpg' || $ext == 'jpeg') {
2273        $cmd .= ' -quality '.$conf['jpg_quality'];
2274    }
2275    $cmd .= " $from $to";
2276
2277    @exec($cmd,$out,$retval);
2278    if ($retval == 0) return true;
2279    return false;
2280}
2281
2282/**
2283 * crop images using external ImageMagick convert program
2284 *
2285 * @author Andreas Gohr <andi@splitbrain.org>
2286 *
2287 * @param string $ext     extension
2288 * @param string $from    filename path to file
2289 * @param int    $from_w  original width
2290 * @param int    $from_h  original height
2291 * @param string $to      path to resized file
2292 * @param int    $to_w    desired width
2293 * @param int    $to_h    desired height
2294 * @param int    $ofs_x   offset of crop centre
2295 * @param int    $ofs_y   offset of crop centre
2296 * @return bool
2297 * @deprecated 2020-09-01
2298 */
2299function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
2300    global $conf;
2301    dbg_deprecated('splitbrain\\Slika');
2302
2303    // check if convert is configured
2304    if(!$conf['im_convert']) return false;
2305
2306    // prepare command
2307    $cmd  = $conf['im_convert'];
2308    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
2309    if ($ext == 'jpg' || $ext == 'jpeg') {
2310        $cmd .= ' -quality '.$conf['jpg_quality'];
2311    }
2312    $cmd .= " $from $to";
2313
2314    @exec($cmd,$out,$retval);
2315    if ($retval == 0) return true;
2316    return false;
2317}
2318
2319/**
2320 * resize or crop images using PHP's libGD support
2321 *
2322 * @author Andreas Gohr <andi@splitbrain.org>
2323 * @author Sebastian Wienecke <s_wienecke@web.de>
2324 *
2325 * @param string $ext     extension
2326 * @param string $from    filename path to file
2327 * @param int    $from_w  original width
2328 * @param int    $from_h  original height
2329 * @param string $to      path to resized file
2330 * @param int    $to_w    desired width
2331 * @param int    $to_h    desired height
2332 * @param int    $ofs_x   offset of crop centre
2333 * @param int    $ofs_y   offset of crop centre
2334 * @return bool
2335 * @deprecated 2020-09-01
2336 */
2337function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
2338    global $conf;
2339    dbg_deprecated('splitbrain\\Slika');
2340
2341    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
2342
2343    // check available memory
2344    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
2345        return false;
2346    }
2347
2348    // create an image of the given filetype
2349    $image = false;
2350    if ($ext == 'jpg' || $ext == 'jpeg'){
2351        if(!function_exists("imagecreatefromjpeg")) return false;
2352        $image = @imagecreatefromjpeg($from);
2353    }elseif($ext == 'png') {
2354        if(!function_exists("imagecreatefrompng")) return false;
2355        $image = @imagecreatefrompng($from);
2356
2357    }elseif($ext == 'gif') {
2358        if(!function_exists("imagecreatefromgif")) return false;
2359        $image = @imagecreatefromgif($from);
2360    }
2361    if(!$image) return false;
2362
2363    $newimg = false;
2364    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
2365        $newimg = @imagecreatetruecolor ($to_w, $to_h);
2366    }
2367    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
2368    if(!$newimg){
2369        imagedestroy($image);
2370        return false;
2371    }
2372
2373    //keep png alpha channel if possible
2374    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
2375        imagealphablending($newimg, false);
2376        imagesavealpha($newimg,true);
2377    }
2378
2379    //keep gif transparent color if possible
2380    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
2381        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
2382            $transcolorindex = @imagecolortransparent($image);
2383            if($transcolorindex >= 0 ) { //transparent color exists
2384                $transcolor = @imagecolorsforindex($image, $transcolorindex);
2385                $transcolorindex = @imagecolorallocate(
2386                    $newimg,
2387                    $transcolor['red'],
2388                    $transcolor['green'],
2389                    $transcolor['blue']
2390                );
2391                @imagefill($newimg, 0, 0, $transcolorindex);
2392                @imagecolortransparent($newimg, $transcolorindex);
2393            }else{ //filling with white
2394                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2395                @imagefill($newimg, 0, 0, $whitecolorindex);
2396            }
2397        }else{ //filling with white
2398            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2399            @imagefill($newimg, 0, 0, $whitecolorindex);
2400        }
2401    }
2402
2403    //try resampling first
2404    if(function_exists("imagecopyresampled")){
2405        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
2406            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2407        }
2408    }else{
2409        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2410    }
2411
2412    $okay = false;
2413    if ($ext == 'jpg' || $ext == 'jpeg'){
2414        if(!function_exists('imagejpeg')){
2415            $okay = false;
2416        }else{
2417            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
2418        }
2419    }elseif($ext == 'png') {
2420        if(!function_exists('imagepng')){
2421            $okay = false;
2422        }else{
2423            $okay =  imagepng($newimg, $to);
2424        }
2425    }elseif($ext == 'gif') {
2426        if(!function_exists('imagegif')){
2427            $okay = false;
2428        }else{
2429            $okay = imagegif($newimg, $to);
2430        }
2431    }
2432
2433    // destroy GD image ressources
2434    if($image) imagedestroy($image);
2435    if($newimg) imagedestroy($newimg);
2436
2437    return $okay;
2438}
2439
2440/**
2441 * Return other media files with the same base name
2442 * but different extensions.
2443 *
2444 * @param string   $src     - ID of media file
2445 * @param string[] $exts    - alternative extensions to find other files for
2446 * @return array            - array(mime type => file ID)
2447 *
2448 * @author Anika Henke <anika@selfthinker.org>
2449 */
2450function media_alternativefiles($src, $exts){
2451
2452    $files = array();
2453    list($srcExt, /* $srcMime */) = mimetype($src);
2454    $filebase = substr($src, 0, -1 * (strlen($srcExt)+1));
2455
2456    foreach($exts as $ext) {
2457        $fileid = $filebase.'.'.$ext;
2458        $file = mediaFN($fileid);
2459        if(file_exists($file)) {
2460            list(/* $fileExt */, $fileMime) = mimetype($file);
2461            $files[$fileMime] = $fileid;
2462        }
2463    }
2464    return $files;
2465}
2466
2467/**
2468 * Check if video/audio is supported to be embedded.
2469 *
2470 * @param string $mime      - mimetype of media file
2471 * @param string $type      - type of media files to check ('video', 'audio', or null for all)
2472 * @return boolean
2473 *
2474 * @author Anika Henke <anika@selfthinker.org>
2475 */
2476function media_supportedav($mime, $type=NULL){
2477    $supportedAudio = array(
2478        'ogg' => 'audio/ogg',
2479        'mp3' => 'audio/mpeg',
2480        'wav' => 'audio/wav',
2481    );
2482    $supportedVideo = array(
2483        'webm' => 'video/webm',
2484        'ogv' => 'video/ogg',
2485        'mp4' => 'video/mp4',
2486    );
2487    if ($type == 'audio') {
2488        $supportedAv = $supportedAudio;
2489    } elseif ($type == 'video') {
2490        $supportedAv = $supportedVideo;
2491    } else {
2492        $supportedAv = array_merge($supportedAudio, $supportedVideo);
2493    }
2494    return in_array($mime, $supportedAv);
2495}
2496
2497/**
2498 * Return track media files with the same base name
2499 * but extensions that indicate kind and lang.
2500 * ie for foo.webm search foo.sub.lang.vtt, foo.cap.lang.vtt...
2501 *
2502 * @param string   $src     - ID of media file
2503 * @return array            - array(mediaID => array( kind, srclang ))
2504 *
2505 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
2506 */
2507function media_trackfiles($src){
2508    $kinds=array(
2509        'sub' => 'subtitles',
2510        'cap' => 'captions',
2511        'des' => 'descriptions',
2512        'cha' => 'chapters',
2513        'met' => 'metadata'
2514    );
2515
2516    $files = array();
2517    $re='/\\.(sub|cap|des|cha|met)\\.([^.]+)\\.vtt$/';
2518    $baseid=pathinfo($src, PATHINFO_FILENAME);
2519    $pattern=mediaFN($baseid).'.*.*.vtt';
2520    $list=glob($pattern);
2521    foreach($list as $track) {
2522        if(preg_match($re, $track, $matches)){
2523            $files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=array(
2524                $kinds[$matches[1]],
2525                $matches[2],
2526            );
2527        }
2528    }
2529    return $files;
2530}
2531
2532/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
2533