xref: /dokuwiki/inc/media.php (revision 0489c64b7de1b71fdd124114dd18525156f26327)
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\Utf8\Sort;
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 = ft_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 = ft_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                ($data[$pos]['level'] <= $level+1 && Sort::strcmp($data[$pos]['id'], $tmp_ns) > 0)
1986            ) {
1987                array_splice($data, $pos, 0, array(array('level' => $level+1, 'id' => $tmp_ns, 'open' => 'true')));
1988                break;
1989            }
1990            ++$pos;
1991        }
1992    }
1993
1994    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1995}
1996
1997/**
1998 * Userfunction for html_buildlist
1999 *
2000 * Prints a media namespace tree item
2001 *
2002 * @author Andreas Gohr <andi@splitbrain.org>
2003 *
2004 * @param array $item
2005 * @return string html
2006 */
2007function media_nstree_item($item){
2008    global $INPUT;
2009    $pos   = strrpos($item['id'], ':');
2010    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
2011    if(empty($item['label'])) $item['label'] = $label;
2012
2013    $ret  = '';
2014    if (!($INPUT->str('do') == 'media'))
2015    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
2016    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id'], false), 'tab_files' => 'files'))
2017        .'" class="idx_dir">';
2018    $ret .= $item['label'];
2019    $ret .= '</a>';
2020    return $ret;
2021}
2022
2023/**
2024 * Userfunction for html_buildlist
2025 *
2026 * Prints a media namespace tree item opener
2027 *
2028 * @author Andreas Gohr <andi@splitbrain.org>
2029 *
2030 * @param array $item
2031 * @return string html
2032 */
2033function media_nstree_li($item){
2034    $class='media level'.$item['level'];
2035    if($item['open']){
2036        $class .= ' open';
2037        $img   = DOKU_BASE.'lib/images/minus.gif';
2038        $alt   = '−';
2039    }else{
2040        $class .= ' closed';
2041        $img   = DOKU_BASE.'lib/images/plus.gif';
2042        $alt   = '+';
2043    }
2044    // TODO: only deliver an image if it actually has a subtree...
2045    return '<li class="'.$class.'">'.
2046        '<img src="'.$img.'" alt="'.$alt.'" />';
2047}
2048
2049/**
2050 * Resizes the given image to the given size
2051 *
2052 * @author  Andreas Gohr <andi@splitbrain.org>
2053 *
2054 * @param string $file filename, path to file
2055 * @param string $ext  extension
2056 * @param int    $w    desired width
2057 * @param int    $h    desired height
2058 * @return string path to resized or original size if failed
2059 */
2060function media_resize_image($file, $ext, $w, $h=0){
2061    global $conf;
2062
2063    $info = @getimagesize($file); //get original size
2064    if($info == false) return $file; // that's no image - it's a spaceship!
2065
2066    if(!$h) $h = round(($w * $info[1]) / $info[0]);
2067    if(!$w) $w = round(($h * $info[0]) / $info[1]);
2068
2069    // we wont scale up to infinity
2070    if($w > 2000 || $h > 2000) return $file;
2071
2072    // resize necessary? - (w,h) = native dimensions
2073    if(($w == $info[0]) && ($h == $info[1])) return $file;
2074
2075    //cache
2076    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
2077    $mtime = @filemtime($local); // 0 if not exists
2078
2079    if($mtime > filemtime($file) ||
2080        media_resize_imageIM($ext, $file, $info[0], $info[1], $local, $w, $h) ||
2081        media_resize_imageGD($ext, $file, $info[0], $info[1], $local, $w, $h)
2082    ) {
2083        if($conf['fperm']) @chmod($local, $conf['fperm']);
2084        return $local;
2085    }
2086    //still here? resizing failed
2087    return $file;
2088}
2089
2090/**
2091 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
2092 * to the wanted size
2093 *
2094 * Crops are centered horizontally but prefer the upper third of an vertical
2095 * image because most pics are more interesting in that area (rule of thirds)
2096 *
2097 * @author  Andreas Gohr <andi@splitbrain.org>
2098 *
2099 * @param string $file filename, path to file
2100 * @param string $ext  extension
2101 * @param int    $w    desired width
2102 * @param int    $h    desired height
2103 * @return string path to resized or original size if failed
2104 */
2105function media_crop_image($file, $ext, $w, $h=0){
2106    global $conf;
2107
2108    if(!$h) $h = $w;
2109    $info = @getimagesize($file); //get original size
2110    if($info == false) return $file; // that's no image - it's a spaceship!
2111
2112    // calculate crop size
2113    $fr = $info[0]/$info[1];
2114    $tr = $w/$h;
2115
2116    // check if the crop can be handled completely by resize,
2117    // i.e. the specified width & height match the aspect ratio of the source image
2118    if ($w == round($h*$fr)) {
2119        return media_resize_image($file, $ext, $w);
2120    }
2121
2122    if($tr >= 1){
2123        if($tr > $fr){
2124            $cw = $info[0];
2125            $ch = (int) ($info[0]/$tr);
2126        }else{
2127            $cw = (int) ($info[1]*$tr);
2128            $ch = $info[1];
2129        }
2130    }else{
2131        if($tr < $fr){
2132            $cw = (int) ($info[1]*$tr);
2133            $ch = $info[1];
2134        }else{
2135            $cw = $info[0];
2136            $ch = (int) ($info[0]/$tr);
2137        }
2138    }
2139    // calculate crop offset
2140    $cx = (int) (($info[0]-$cw)/2);
2141    $cy = (int) (($info[1]-$ch)/3);
2142
2143    //cache
2144    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
2145    $mtime = @filemtime($local); // 0 if not exists
2146
2147    if( $mtime > @filemtime($file) ||
2148            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
2149            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
2150        if($conf['fperm']) @chmod($local, $conf['fperm']);
2151        return media_resize_image($local,$ext, $w, $h);
2152    }
2153
2154    //still here? cropping failed
2155    return media_resize_image($file,$ext, $w, $h);
2156}
2157
2158/**
2159 * Calculate a token to be used to verify fetch requests for resized or
2160 * cropped images have been internally generated - and prevent external
2161 * DDOS attacks via fetch
2162 *
2163 * @author Christopher Smith <chris@jalakai.co.uk>
2164 *
2165 * @param string  $id    id of the image
2166 * @param int     $w     resize/crop width
2167 * @param int     $h     resize/crop height
2168 * @return string token or empty string if no token required
2169 */
2170function media_get_token($id,$w,$h){
2171    // token is only required for modified images
2172    if ($w || $h || media_isexternal($id)) {
2173        $token = $id;
2174        if ($w) $token .= '.'.$w;
2175        if ($h) $token .= '.'.$h;
2176
2177        return substr(\dokuwiki\PassHash::hmac('md5', $token, auth_cookiesalt()),0,6);
2178    }
2179
2180    return '';
2181}
2182
2183/**
2184 * Download a remote file and return local filename
2185 *
2186 * returns false if download fails. Uses cached file if available and
2187 * wanted
2188 *
2189 * @author  Andreas Gohr <andi@splitbrain.org>
2190 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
2191 *
2192 * @param string $url
2193 * @param string $ext   extension
2194 * @param int    $cache cachetime in seconds
2195 * @return false|string path to cached file
2196 */
2197function media_get_from_URL($url,$ext,$cache){
2198    global $conf;
2199
2200    // if no cache or fetchsize just redirect
2201    if ($cache==0)           return false;
2202    if (!$conf['fetchsize']) return false;
2203
2204    $local = getCacheName(strtolower($url),".media.$ext");
2205    $mtime = @filemtime($local); // 0 if not exists
2206
2207    //decide if download needed:
2208    if(($mtime == 0) || // cache does not exist
2209        ($cache != -1 && $mtime < time() - $cache) // 'recache' and cache has expired
2210    ) {
2211        if(media_image_download($url, $local)) {
2212            return $local;
2213        } else {
2214            return false;
2215        }
2216    }
2217
2218    //if cache exists use it else
2219    if($mtime) return $local;
2220
2221    //else return false
2222    return false;
2223}
2224
2225/**
2226 * Download image files
2227 *
2228 * @author Andreas Gohr <andi@splitbrain.org>
2229 *
2230 * @param string $url
2231 * @param string $file path to file in which to put the downloaded content
2232 * @return bool
2233 */
2234function media_image_download($url,$file){
2235    global $conf;
2236    $http = new DokuHTTPClient();
2237    $http->keep_alive = false; // we do single ops here, no need for keep-alive
2238
2239    $http->max_bodysize = $conf['fetchsize'];
2240    $http->timeout = 25; //max. 25 sec
2241    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
2242
2243    $data = $http->get($url);
2244    if(!$data) return false;
2245
2246    $fileexists = file_exists($file);
2247    $fp = @fopen($file,"w");
2248    if(!$fp) return false;
2249    fwrite($fp,$data);
2250    fclose($fp);
2251    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
2252
2253    // check if it is really an image
2254    $info = @getimagesize($file);
2255    if(!$info){
2256        @unlink($file);
2257        return false;
2258    }
2259
2260    return true;
2261}
2262
2263/**
2264 * resize images using external ImageMagick convert program
2265 *
2266 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
2267 * @author Andreas Gohr <andi@splitbrain.org>
2268 *
2269 * @param string $ext     extension
2270 * @param string $from    filename path to file
2271 * @param int    $from_w  original width
2272 * @param int    $from_h  original height
2273 * @param string $to      path to resized file
2274 * @param int    $to_w    desired width
2275 * @param int    $to_h    desired height
2276 * @return bool
2277 */
2278function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
2279    global $conf;
2280
2281    // check if convert is configured
2282    if(!$conf['im_convert']) return false;
2283
2284    // prepare command
2285    $cmd  = $conf['im_convert'];
2286    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
2287    if ($ext == 'jpg' || $ext == 'jpeg') {
2288        $cmd .= ' -quality '.$conf['jpg_quality'];
2289    }
2290    $cmd .= " $from $to";
2291
2292    @exec($cmd,$out,$retval);
2293    if ($retval == 0) return true;
2294    return false;
2295}
2296
2297/**
2298 * crop images using external ImageMagick convert program
2299 *
2300 * @author Andreas Gohr <andi@splitbrain.org>
2301 *
2302 * @param string $ext     extension
2303 * @param string $from    filename path to file
2304 * @param int    $from_w  original width
2305 * @param int    $from_h  original height
2306 * @param string $to      path to resized file
2307 * @param int    $to_w    desired width
2308 * @param int    $to_h    desired height
2309 * @param int    $ofs_x   offset of crop centre
2310 * @param int    $ofs_y   offset of crop centre
2311 * @return bool
2312 */
2313function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
2314    global $conf;
2315
2316    // check if convert is configured
2317    if(!$conf['im_convert']) return false;
2318
2319    // prepare command
2320    $cmd  = $conf['im_convert'];
2321    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
2322    if ($ext == 'jpg' || $ext == 'jpeg') {
2323        $cmd .= ' -quality '.$conf['jpg_quality'];
2324    }
2325    $cmd .= " $from $to";
2326
2327    @exec($cmd,$out,$retval);
2328    if ($retval == 0) return true;
2329    return false;
2330}
2331
2332/**
2333 * resize or crop images using PHP's libGD support
2334 *
2335 * @author Andreas Gohr <andi@splitbrain.org>
2336 * @author Sebastian Wienecke <s_wienecke@web.de>
2337 *
2338 * @param string $ext     extension
2339 * @param string $from    filename path to file
2340 * @param int    $from_w  original width
2341 * @param int    $from_h  original height
2342 * @param string $to      path to resized file
2343 * @param int    $to_w    desired width
2344 * @param int    $to_h    desired height
2345 * @param int    $ofs_x   offset of crop centre
2346 * @param int    $ofs_y   offset of crop centre
2347 * @return bool
2348 */
2349function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
2350    global $conf;
2351
2352    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
2353
2354    // check available memory
2355    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
2356        return false;
2357    }
2358
2359    // create an image of the given filetype
2360    $image = false;
2361    if ($ext == 'jpg' || $ext == 'jpeg'){
2362        if(!function_exists("imagecreatefromjpeg")) return false;
2363        $image = @imagecreatefromjpeg($from);
2364    }elseif($ext == 'png') {
2365        if(!function_exists("imagecreatefrompng")) return false;
2366        $image = @imagecreatefrompng($from);
2367
2368    }elseif($ext == 'gif') {
2369        if(!function_exists("imagecreatefromgif")) return false;
2370        $image = @imagecreatefromgif($from);
2371    }
2372    if(!$image) return false;
2373
2374    $newimg = false;
2375    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
2376        $newimg = @imagecreatetruecolor ($to_w, $to_h);
2377    }
2378    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
2379    if(!$newimg){
2380        imagedestroy($image);
2381        return false;
2382    }
2383
2384    //keep png alpha channel if possible
2385    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
2386        imagealphablending($newimg, false);
2387        imagesavealpha($newimg,true);
2388    }
2389
2390    //keep gif transparent color if possible
2391    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
2392        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
2393            $transcolorindex = @imagecolortransparent($image);
2394            if($transcolorindex >= 0 ) { //transparent color exists
2395                $transcolor = @imagecolorsforindex($image, $transcolorindex);
2396                $transcolorindex = @imagecolorallocate(
2397                    $newimg,
2398                    $transcolor['red'],
2399                    $transcolor['green'],
2400                    $transcolor['blue']
2401                );
2402                @imagefill($newimg, 0, 0, $transcolorindex);
2403                @imagecolortransparent($newimg, $transcolorindex);
2404            }else{ //filling with white
2405                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2406                @imagefill($newimg, 0, 0, $whitecolorindex);
2407            }
2408        }else{ //filling with white
2409            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2410            @imagefill($newimg, 0, 0, $whitecolorindex);
2411        }
2412    }
2413
2414    //try resampling first
2415    if(function_exists("imagecopyresampled")){
2416        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
2417            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2418        }
2419    }else{
2420        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2421    }
2422
2423    $okay = false;
2424    if ($ext == 'jpg' || $ext == 'jpeg'){
2425        if(!function_exists('imagejpeg')){
2426            $okay = false;
2427        }else{
2428            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
2429        }
2430    }elseif($ext == 'png') {
2431        if(!function_exists('imagepng')){
2432            $okay = false;
2433        }else{
2434            $okay =  imagepng($newimg, $to);
2435        }
2436    }elseif($ext == 'gif') {
2437        if(!function_exists('imagegif')){
2438            $okay = false;
2439        }else{
2440            $okay = imagegif($newimg, $to);
2441        }
2442    }
2443
2444    // destroy GD image ressources
2445    if($image) imagedestroy($image);
2446    if($newimg) imagedestroy($newimg);
2447
2448    return $okay;
2449}
2450
2451/**
2452 * Return other media files with the same base name
2453 * but different extensions.
2454 *
2455 * @param string   $src     - ID of media file
2456 * @param string[] $exts    - alternative extensions to find other files for
2457 * @return array            - array(mime type => file ID)
2458 *
2459 * @author Anika Henke <anika@selfthinker.org>
2460 */
2461function media_alternativefiles($src, $exts){
2462
2463    $files = array();
2464    list($srcExt, /* $srcMime */) = mimetype($src);
2465    $filebase = substr($src, 0, -1 * (strlen($srcExt)+1));
2466
2467    foreach($exts as $ext) {
2468        $fileid = $filebase.'.'.$ext;
2469        $file = mediaFN($fileid);
2470        if(file_exists($file)) {
2471            list(/* $fileExt */, $fileMime) = mimetype($file);
2472            $files[$fileMime] = $fileid;
2473        }
2474    }
2475    return $files;
2476}
2477
2478/**
2479 * Check if video/audio is supported to be embedded.
2480 *
2481 * @param string $mime      - mimetype of media file
2482 * @param string $type      - type of media files to check ('video', 'audio', or null for all)
2483 * @return boolean
2484 *
2485 * @author Anika Henke <anika@selfthinker.org>
2486 */
2487function media_supportedav($mime, $type=NULL){
2488    $supportedAudio = array(
2489        'ogg' => 'audio/ogg',
2490        'mp3' => 'audio/mpeg',
2491        'wav' => 'audio/wav',
2492    );
2493    $supportedVideo = array(
2494        'webm' => 'video/webm',
2495        'ogv' => 'video/ogg',
2496        'mp4' => 'video/mp4',
2497    );
2498    if ($type == 'audio') {
2499        $supportedAv = $supportedAudio;
2500    } elseif ($type == 'video') {
2501        $supportedAv = $supportedVideo;
2502    } else {
2503        $supportedAv = array_merge($supportedAudio, $supportedVideo);
2504    }
2505    return in_array($mime, $supportedAv);
2506}
2507
2508/**
2509 * Return track media files with the same base name
2510 * but extensions that indicate kind and lang.
2511 * ie for foo.webm search foo.sub.lang.vtt, foo.cap.lang.vtt...
2512 *
2513 * @param string   $src     - ID of media file
2514 * @return array            - array(mediaID => array( kind, srclang ))
2515 *
2516 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
2517 */
2518function media_trackfiles($src){
2519    $kinds=array(
2520        'sub' => 'subtitles',
2521        'cap' => 'captions',
2522        'des' => 'descriptions',
2523        'cha' => 'chapters',
2524        'met' => 'metadata'
2525    );
2526
2527    $files = array();
2528    $re='/\\.(sub|cap|des|cha|met)\\.([^.]+)\\.vtt$/';
2529    $baseid=pathinfo($src, PATHINFO_FILENAME);
2530    $pattern=mediaFN($baseid).'.*.*.vtt';
2531    $list=glob($pattern);
2532    foreach($list as $track) {
2533        if(preg_match($re, $track, $matches)){
2534            $files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=array(
2535                $kinds[$matches[1]],
2536                $matches[2],
2537            );
2538        }
2539    }
2540    return $files;
2541}
2542
2543/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
2544