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