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