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