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