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