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