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