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