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