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