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