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