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