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