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