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