xref: /dokuwiki/inc/media.php (revision 23735ba4c5021df9ab8c1b4a0e8322cebdaf5931)
1<?php
2/**
3 * All output and handler function needed for the media management popup
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10if(!defined('NL')) define('NL',"\n");
11
12/**
13 * Lists pages which currently use a media file selected for deletion
14 *
15 * References uses the same visual as search results and share
16 * their CSS tags except pagenames won't be links.
17 *
18 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
19 */
20function media_filesinuse($data,$id){
21    global $lang;
22    echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
23    echo '<p>'.hsc($lang['ref_inuse']).'</p>';
24
25    $hidden=0; //count of hits without read permission
26    foreach($data as $row){
27        if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
28            echo '<div class="search_result">';
29            echo '<span class="mediaref_ref">'.hsc($row).'</span>';
30            echo '</div>';
31        }else
32            $hidden++;
33    }
34    if ($hidden){
35        print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
36    }
37}
38
39/**
40 * Handles the saving of image meta data
41 *
42 * @author Andreas Gohr <andi@splitbrain.org>
43 * @author Kate Arzamastseva <pshns@ukr.net>
44 */
45function media_metasave($id,$auth,$data){
46    if($auth < AUTH_UPLOAD) return false;
47    if(!checkSecurityToken()) return false;
48    global $lang;
49    global $conf;
50    $src = mediaFN($id);
51
52    $meta = new JpegMeta($src);
53    $meta->_parseAll();
54
55    foreach($data as $key => $val){
56        $val=trim($val);
57        if(empty($val)){
58            $meta->deleteField($key);
59        }else{
60            $meta->setField($key,$val);
61        }
62    }
63
64    $old = @filemtime($src);
65    if(!@file_exists(mediaFN($id, $old)) && @file_exists($src)) {
66        // add old revision to the attic
67        media_saveOldRevision($id);
68    }
69
70    if($meta->save()){
71        if($conf['fperm']) chmod($src, $conf['fperm']);
72
73        $new = @filemtime($src);
74        // add a log entry to the media changelog
75        addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, $lang['media_meta_edited']);
76
77        msg($lang['metasaveok'],1);
78        return $id;
79    }else{
80        msg($lang['metasaveerr'],-1);
81        return false;
82    }
83}
84
85/**
86 * Display the form to edit image meta data
87 *
88 * @author Andreas Gohr <andi@splitbrain.org>
89 * @author Kate Arzamastseva <pshns@ukr.net>
90 */
91function media_metaform($id,$auth){
92    global $lang, $config_cascade;
93
94    if($auth < AUTH_UPLOAD) {
95        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
96        return false;
97    }
98
99    // load the field descriptions
100    static $fields = null;
101    if(is_null($fields)){
102        $config_files = getConfigFiles('mediameta');
103        foreach ($config_files as $config_file) {
104            if(@file_exists($config_file)) include($config_file);
105        }
106    }
107
108    $src = mediaFN($id);
109
110    // output
111    $form = new Doku_Form(array('action' => media_managerURL(array('tab_details' => 'view'), '&'),
112                                'class' => 'meta'));
113    $form->addHidden('img', $id);
114    $form->addHidden('mediado', 'save');
115    foreach($fields as $key => $field){
116        // get current value
117        if (empty($field[0])) continue;
118        $tags = array($field[0]);
119        if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
120        $value = tpl_img_getTag($tags,'',$src);
121        $value = cleanText($value);
122
123        // prepare attributes
124        $p = array();
125        $p['class'] = 'edit';
126        $p['id']    = 'meta__'.$key;
127        $p['name']  = 'meta['.$field[0].']';
128        $p_attrs    = array('class' => 'edit');
129
130        $form->addElement('<div class="row">');
131        if($field[2] == 'text'){
132            $form->addElement(form_makeField('text', $p['name'], $value, ($lang[$field[1]]) ? $lang[$field[1]] : $field[1] . ':', $p['id'], $p['class'], $p_attrs));
133        }else{
134            $att = buildAttributes($p);
135            $form->addElement('<label for="meta__'.$key.'">'.$lang[$field[1]].'</label>');
136            $form->addElement("<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>');
137        }
138        $form->addElement('</div>'.NL);
139    }
140    $form->addElement('<div class="buttons">');
141    $form->addElement(form_makeButton('submit', '', $lang['btn_save'], array('accesskey' => 's', 'name' => 'mediado[save]')));
142    $form->addElement('</div>'.NL);
143    $form->printForm();
144}
145
146/**
147 * Convenience function to check if a media file is still in use
148 *
149 * @author Michael Klier <chi@chimeric.de>
150 */
151function media_inuse($id) {
152    global $conf;
153    $mediareferences = array();
154    if($conf['refcheck']){
155        $mediareferences = ft_mediause($id,$conf['refshow']);
156        if(!count($mediareferences)) {
157            return false;
158        } else {
159            return $mediareferences;
160        }
161    } else {
162        return false;
163    }
164}
165
166define('DOKU_MEDIA_DELETED', 1);
167define('DOKU_MEDIA_NOT_AUTH', 2);
168define('DOKU_MEDIA_INUSE', 4);
169define('DOKU_MEDIA_EMPTY_NS', 8);
170
171/**
172 * Handles media file deletions
173 *
174 * If configured, checks for media references before deletion
175 *
176 * @author Andreas Gohr <andi@splitbrain.org>
177 * @return int One of: 0,
178                       DOKU_MEDIA_DELETED,
179                       DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
180                       DOKU_MEDIA_NOT_AUTH,
181                       DOKU_MEDIA_INUSE
182 */
183function media_delete($id,$auth){
184    global $lang;
185    if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
186    if(media_inuse($id)) return DOKU_MEDIA_INUSE;
187
188    $file = mediaFN($id);
189
190    // trigger an event - MEDIA_DELETE_FILE
191    $data['id']   = $id;
192    $data['name'] = basename($file);
193    $data['path'] = $file;
194    $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
195
196    $data['unl'] = false;
197    $data['del'] = false;
198    $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
199    if ($evt->advise_before()) {
200        $old = @filemtime($file);
201        if(!@file_exists(mediaFN($id, $old)) && @file_exists($file)) {
202            // add old revision to the attic
203            media_saveOldRevision($id);
204        }
205
206        $data['unl'] = @unlink($file);
207        if($data['unl']){
208            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted']);
209            $data['del'] = io_sweepNS($id,'mediadir');
210        }
211    }
212    $evt->advise_after();
213    unset($evt);
214
215    if($data['unl'] && $data['del']){
216        return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
217    }
218
219    return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
220}
221
222/**
223 * Handle file uploads via XMLHttpRequest
224 *
225 * @return mixed false on error, id of the new file on success
226 */
227function media_upload_xhr($ns,$auth){
228    if(!checkSecurityToken()) return false;
229
230    $id = $_GET['qqfile'];
231    list($ext,$mime,$dl) = mimetype($id);
232    $input = fopen("php://input", "r");
233    if (!($tmp = io_mktmpdir())) return false;
234    $path = $tmp.'/'.md5($id);
235    $target = fopen($path, "w");
236    $realSize = stream_copy_to_stream($input, $target);
237    fclose($target);
238    fclose($input);
239    if ($realSize != (int)$_SERVER["CONTENT_LENGTH"]){
240        unlink($target);
241        unlink($path);
242        return false;
243    }
244
245    $res = media_save(
246        array('name' => $path,
247            'mime' => $mime,
248            'ext'  => $ext),
249        $ns.':'.$id,
250        (($_REQUEST['ow'] == 'checked') ? true : false),
251        $auth,
252        'copy'
253    );
254    unlink($path);
255    if ($tmp) dir_delete($tmp);
256    if (is_array($res)) {
257        msg($res[0], $res[1]);
258        return false;
259    }
260    return $res;
261}
262
263/**
264 * Handles media file uploads
265 *
266 * @author Andreas Gohr <andi@splitbrain.org>
267 * @author Michael Klier <chi@chimeric.de>
268 * @return mixed false on error, id of the new file on success
269 */
270function media_upload($ns,$auth,$file=false){
271    if(!checkSecurityToken()) return false;
272    global $lang;
273
274    // get file and id
275    $id   = $_POST['mediaid'];
276    if (!$file) $file = $_FILES['upload'];
277    if(empty($id)) $id = $file['name'];
278
279    // check for errors (messages are done in lib/exe/mediamanager.php)
280    if($file['error']) return false;
281
282    // check extensions
283    list($fext,$fmime,$dl) = mimetype($file['name']);
284    list($iext,$imime,$dl) = mimetype($id);
285    if($fext && !$iext){
286        // no extension specified in id - read original one
287        $id   .= '.'.$fext;
288        $imime = $fmime;
289    }elseif($fext && $fext != $iext){
290        // extension was changed, print warning
291        msg(sprintf($lang['mediaextchange'],$fext,$iext));
292    }
293
294    $res = media_save(array('name' => $file['tmp_name'],
295                            'mime' => $imime,
296                            'ext'  => $iext), $ns.':'.$id,
297                      $_REQUEST['ow'], $auth, 'move_uploaded_file');
298    if (is_array($res)) {
299        msg($res[0], $res[1]);
300        return false;
301    }
302    return $res;
303}
304
305/**
306 * This generates an action event and delegates to _media_upload_action().
307 * Action plugins are allowed to pre/postprocess the uploaded file.
308 * (The triggered event is preventable.)
309 *
310 * Event data:
311 * $data[0]     fn_tmp: the temporary file name (read from $_FILES)
312 * $data[1]     fn: the file name of the uploaded file
313 * $data[2]     id: the future directory id of the uploaded file
314 * $data[3]     imime: the mimetype of the uploaded file
315 * $data[4]     overwrite: if an existing file is going to be overwritten
316 *
317 * @triggers MEDIA_UPLOAD_FINISH
318 */
319function media_save($file, $id, $ow, $auth, $move) {
320    if($auth < AUTH_UPLOAD) {
321        return array("You don't have permissions to upload files.", -1);
322    }
323
324    if (!isset($file['mime']) || !isset($file['ext'])) {
325        list($ext, $mime) = mimetype($id);
326        if (!isset($file['mime'])) {
327            $file['mime'] = $mime;
328        }
329        if (!isset($file['ext'])) {
330            $file['ext'] = $ext;
331        }
332    }
333
334    global $lang, $conf;
335
336    // get filename
337    $id   = cleanID($id);
338    $fn   = mediaFN($id);
339
340    // get filetype regexp
341    $types = array_keys(getMimeTypes());
342    $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
343    $regex = join('|',$types);
344
345    // because a temp file was created already
346    if(!preg_match('/\.('.$regex.')$/i',$fn)) {
347        return array($lang['uploadwrong'],-1);
348    }
349
350    //check for overwrite
351    $overwrite = @file_exists($fn);
352    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
353    if($overwrite && (!$ow || $auth < $auth_ow)) {
354        return array($lang['uploadexist'], 0);
355    }
356    // check for valid content
357    $ok = media_contentcheck($file['name'], $file['mime']);
358    if($ok == -1){
359        return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
360    }elseif($ok == -2){
361        return array($lang['uploadspam'],-1);
362    }elseif($ok == -3){
363        return array($lang['uploadxss'],-1);
364    }
365
366    // prepare event data
367    $data[0] = $file['name'];
368    $data[1] = $fn;
369    $data[2] = $id;
370    $data[3] = $file['mime'];
371    $data[4] = $overwrite;
372    $data[5] = $move;
373
374    // trigger event
375    return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
376}
377
378/**
379 * Callback adapter for media_upload_finish()
380 * @author Michael Klier <chi@chimeric.de>
381 */
382function _media_upload_action($data) {
383    // fixme do further sanity tests of given data?
384    if(is_array($data) && count($data)===6) {
385        return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
386    } else {
387        return false; //callback error
388    }
389}
390
391/**
392 * Saves an uploaded media file
393 *
394 * @author Andreas Gohr <andi@splitbrain.org>
395 * @author Michael Klier <chi@chimeric.de>
396 * @author Kate Arzamastseva <pshns@ukr.net>
397 */
398function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
399    global $conf;
400    global $lang;
401    global $REV;
402
403    $old = @filemtime($fn);
404    if(!@file_exists(mediaFN($id, $old)) && @file_exists($fn)) {
405        // add old revision to the attic if missing
406        media_saveOldRevision($id);
407    }
408
409    // prepare directory
410    io_createNamespace($id, 'media');
411
412    if($move($fn_tmp, $fn)) {
413        @clearstatcache(true,$fn);
414        $new = @filemtime($fn);
415        // Set the correct permission here.
416        // Always chmod media because they may be saved with different permissions than expected from the php umask.
417        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
418        chmod($fn, $conf['fmode']);
419        msg($lang['uploadsucc'],1);
420        media_notify($id,$fn,$imime,$old);
421        // add a log entry to the media changelog
422        if ($REV){
423            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_REVERT, $lang['restored'], $REV);
424        } elseif ($overwrite) {
425            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT);
426        } else {
427            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created']);
428        }
429        return $id;
430    }else{
431        return array($lang['uploadfail'],-1);
432    }
433}
434
435/**
436 * Moves the current version of media file to the media_attic
437 * directory
438 *
439 * @author Kate Arzamastseva <pshns@ukr.net>
440 * @param string $id
441 * @return int - revision date
442 */
443function media_saveOldRevision($id){
444    global $conf, $lang;
445
446    $oldf = mediaFN($id);
447    if(!@file_exists($oldf)) return '';
448    $date = filemtime($oldf);
449    if (!$conf['mediarevisions']) return $date;
450
451    if (!getRevisionInfo($id, $date, 8192, true)) {
452        // there was an external edit,
453        // there is no log entry for current version of file
454        if (!@file_exists(mediaMetaFN($id,'.changes'))) {
455            addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created']);
456        } else {
457            addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_EDIT);
458        }
459    }
460
461    $newf = mediaFN($id,$date);
462    io_makeFileDir($newf);
463    if(copy($oldf, $newf)) {
464        // Set the correct permission here.
465        // Always chmod media because they may be saved with different permissions than expected from the php umask.
466        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
467        chmod($newf, $conf['fmode']);
468    }
469    return $date;
470}
471
472/**
473 * This function checks if the uploaded content is really what the
474 * mimetype says it is. We also do spam checking for text types here.
475 *
476 * We need to do this stuff because we can not rely on the browser
477 * to do this check correctly. Yes, IE is broken as usual.
478 *
479 * @author Andreas Gohr <andi@splitbrain.org>
480 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
481 * @fixme  check all 26 magic IE filetypes here?
482 */
483function media_contentcheck($file,$mime){
484    global $conf;
485    if($conf['iexssprotect']){
486        $fh = @fopen($file, 'rb');
487        if($fh){
488            $bytes = fread($fh, 256);
489            fclose($fh);
490            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
491                return -3;
492            }
493        }
494    }
495    if(substr($mime,0,6) == 'image/'){
496        $info = @getimagesize($file);
497        if($mime == 'image/gif' && $info[2] != 1){
498            return -1;
499        }elseif($mime == 'image/jpeg' && $info[2] != 2){
500            return -1;
501        }elseif($mime == 'image/png' && $info[2] != 3){
502            return -1;
503        }
504        # fixme maybe check other images types as well
505    }elseif(substr($mime,0,5) == 'text/'){
506        global $TEXT;
507        $TEXT = io_readFile($file);
508        if(checkwordblock()){
509            return -2;
510        }
511    }
512    return 0;
513}
514
515/**
516 * Send a notify mail on uploads
517 *
518 * @author Andreas Gohr <andi@splitbrain.org>
519 */
520function media_notify($id,$file,$mime,$old_rev=false){
521    global $lang;
522    global $conf;
523    global $INFO;
524    if(empty($conf['notify'])) return; //notify enabled?
525
526    $ip = clientIP();
527
528    $text = rawLocale('uploadmail');
529    $text = str_replace('@DATE@',dformat(),$text);
530    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
531    $text = str_replace('@IPADDRESS@',$ip,$text);
532    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
533    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
534    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
535    $text = str_replace('@MIME@',$mime,$text);
536    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
537    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
538    if ($old_rev && $conf['mediarevisions']) {
539        $text = str_replace('@OLD@', ml($id, "rev=$old_rev", true, '&', true), $text);
540    } else {
541        $text = str_replace('@OLD@', '', $text);
542    }
543
544    if(empty($conf['mailprefix'])) {
545        $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
546    } else {
547        $subject = '['.$conf['mailprefix'].'] '.$lang['mail_upload'].' '.$id;
548    }
549
550    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
551}
552
553/**
554 * List all files in a given Media namespace
555 */
556function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=false){
557    global $conf;
558    global $lang;
559    $ns = cleanID($ns);
560
561    // check auth our self if not given (needed for ajax calls)
562    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
563
564    if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
565
566    if($auth < AUTH_READ){
567        // FIXME: print permission warning here instead?
568        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
569    }else{
570        if (!$fullscreenview) media_uploadform($ns, $auth);
571
572        $dir = utf8_encodeFN(str_replace(':','/',$ns));
573        $data = array();
574        search($data,$conf['mediadir'],'search_media',
575                array('showmsg'=>true,'depth'=>1),$dir,1,$sort);
576
577        if(!count($data)){
578            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
579        }else {
580            if ($fullscreenview) {
581                echo '<ul class="' . _media_get_list_type() . '">';
582            }
583            foreach($data as $item){
584                if (!$fullscreenview) {
585                    media_printfile($item,$auth,$jump);
586                } else {
587                    media_printfile_thumbs($item,$auth,$jump);
588                }
589            }
590            if ($fullscreenview) echo '</ul>'.NL;
591        }
592    }
593    if (!$fullscreenview) media_searchform($ns);
594}
595
596/**
597 * Prints tabs for files list actions
598 *
599 * @author Kate Arzamastseva <pshns@ukr.net>
600 * @author Adrian Lang <mail@adrianlang.de>
601 *
602 * @param string $selected_tab - opened tab
603 */
604
605function media_tabs_files($selected_tab = ''){
606    global $lang;
607    $tabs = array();
608    foreach(array('files'  => 'mediaselect',
609                  'upload' => 'media_uploadtab',
610                  'search' => 'media_searchtab') as $tab => $caption) {
611        $tabs[$tab] = array('href'    => media_managerURL(array('tab_files' => $tab), '&'),
612                            'caption' => $lang[$caption]);
613    }
614
615    html_tabs($tabs, $selected_tab);
616}
617
618/**
619 * Prints tabs for files details actions
620 *
621 * @author Kate Arzamastseva <pshns@ukr.net>
622 * @param string $selected_tab - opened tab
623 */
624function media_tabs_details($image, $selected_tab = ''){
625    global $lang, $conf;
626
627    $tabs = array();
628    $tabs['view'] = array('href'    => media_managerURL(array('tab_details' => 'view'), '&'),
629                          'caption' => $lang['media_viewtab']);
630
631    list($ext, $mime) = mimetype($image);
632    if ($mime == 'image/jpeg' && @file_exists(mediaFN($image))) {
633        $tabs['edit'] = array('href'    => media_managerURL(array('tab_details' => 'edit'), '&'),
634                              'caption' => $lang['media_edittab']);
635    }
636    if ($conf['mediarevisions']) {
637        $tabs['history'] = array('href'    => media_managerURL(array('tab_details' => 'history'), '&'),
638                                 'caption' => $lang['media_historytab']);
639    }
640
641    html_tabs($tabs, $selected_tab);
642}
643
644/**
645 * Prints options for the tab that displays a list of all files
646 *
647 * @author Kate Arzamastseva <pshns@ukr.net>
648 */
649function media_tab_files_options(){
650    global $lang, $NS;
651    $form = new Doku_Form(array('class' => 'options', 'method' => 'get',
652                                'action' => wl($ID)));
653    $media_manager_params = media_managerURL(array(), '', false, true);
654    foreach($media_manager_params as $pKey => $pVal){
655        $form->addHidden($pKey, $pVal);
656    }
657    $form->addHidden('sectok', null);
658    if (isset($_REQUEST['q'])) {
659        $form->addHidden('q', $_REQUEST['q']);
660    }
661    $form->addElement('<ul>'.NL);
662    foreach(array('list' => array('listType', array('thumbs', 'rows')),
663                  'sort' => array('sortBy', array('name', 'date')))
664            as $group => $content) {
665        $checked = "_media_get_${group}_type";
666        $checked = $checked();
667
668        $form->addElement('<li class="' . $content[0] . '">');
669        foreach($content[1] as $option) {
670            $attrs = array();
671            if ($checked == $option) {
672                $attrs['checked'] = 'checked';
673            }
674            $form->addElement(form_makeRadioField($group, $option,
675                                       $lang['media_' . $group . '_' . $option],
676                                                  $content[0] . '__' . $option,
677                                                  $option, $attrs));
678        }
679        $form->addElement('</li>'.NL);
680    }
681    $form->addElement('<li>');
682    $form->addElement(form_makeButton('submit', '', $lang['btn_apply']));
683    $form->addElement('</li>'.NL);
684    $form->addElement('</ul>'.NL);
685    $form->printForm();
686}
687
688/**
689 * Returns type of sorting for the list of files in media manager
690 *
691 * @author Kate Arzamastseva <pshns@ukr.net>
692 * @return string - sort type
693 */
694function _media_get_sort_type() {
695    return _media_get_display_param('sort', array('default' => 'name', 'date'));
696}
697
698function _media_get_list_type() {
699    return _media_get_display_param('list', array('default' => 'thumbs', 'rows'));
700}
701
702function _media_get_display_param($param, $values) {
703    if (isset($_REQUEST[$param]) && in_array($_REQUEST[$param], $values)) {
704        // FIXME: Set cookie
705        return $_REQUEST[$param];
706    } else {
707        $val = get_doku_pref($param, $values['default']);
708        if (!in_array($val, $values)) {
709            $val = $values['default'];
710        }
711        return $val;
712    }
713}
714
715/**
716 * Prints tab that displays a list of all files
717 *
718 * @author Kate Arzamastseva <pshns@ukr.net>
719 */
720function media_tab_files($ns,$auth=null,$jump='') {
721    global $lang;
722    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
723
724    if($auth < AUTH_READ){
725        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
726    }else{
727        media_filelist($ns,$auth,$jump,true,_media_get_sort_type());
728    }
729}
730
731/**
732 * Prints tab that displays uploading form
733 *
734 * @author Kate Arzamastseva <pshns@ukr.net>
735 */
736function media_tab_upload($ns,$auth=null,$jump='') {
737    global $lang;
738    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
739
740    echo '<div class="upload">'.NL;
741    if ($auth >= AUTH_UPLOAD) {
742        echo '<p>' . $lang['mediaupload'] . '</p>';
743    }
744    media_uploadform($ns, $auth, true);
745    echo '</div>'.NL;
746}
747
748/**
749 * Prints tab that displays search form
750 *
751 * @author Kate Arzamastseva <pshns@ukr.net>
752 */
753function media_tab_search($ns,$auth=null) {
754    global $lang;
755
756    $do = $_REQUEST['mediado'];
757    $query = $_REQUEST['q'];
758    if (!$query) $query = '';
759    echo '<div class="search">'.NL;
760
761    media_searchform($ns, $query, true);
762    if ($do == 'searchlist' || $query) {
763        media_searchlist($query,$ns,$auth,true,_media_get_sort_type());
764    }
765    echo '</div>'.NL;
766}
767
768/**
769 * Prints tab that displays mediafile details
770 *
771 * @author Kate Arzamastseva <pshns@ukr.net>
772 */
773function media_tab_view($image, $ns, $auth=null, $rev=false) {
774    global $lang, $conf;
775    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
776
777    if ($image && $auth >= AUTH_READ) {
778        $meta = new JpegMeta(mediaFN($image, $rev));
779        media_preview($image, $auth, $rev, $meta);
780        media_preview_buttons($image, $auth, $rev);
781        media_details($image, $auth, $rev, $meta);
782
783    } else {
784        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
785    }
786}
787
788/**
789 * Prints tab that displays form for editing mediafile metadata
790 *
791 * @author Kate Arzamastseva <pshns@ukr.net>
792 */
793function media_tab_edit($image, $ns, $auth=null) {
794    global $lang;
795    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
796
797    if ($image) {
798        list($ext, $mime) = mimetype($image);
799        if ($mime == 'image/jpeg') media_metaform($image,$auth);
800    }
801}
802
803/**
804 * Prints tab that displays mediafile revisions
805 *
806 * @author Kate Arzamastseva <pshns@ukr.net>
807 */
808function media_tab_history($image, $ns, $auth=null) {
809    global $lang;
810    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
811    $do = $_REQUEST['mediado'];
812
813    if ($auth >= AUTH_READ && $image) {
814        if ($do == 'diff'){
815            media_diff($image, $ns, $auth);
816        } else {
817            $first = isset($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
818            html_revisions($first, $image);
819        }
820    } else {
821        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
822    }
823}
824
825/**
826 * Prints mediafile details
827 *
828 * @author Kate Arzamastseva <pshns@ukr.net>
829 */
830function media_preview($image, $auth, $rev=false, $meta=false) {
831
832    $size = media_image_preview_size($image, $rev, $meta);
833
834    if ($size) {
835        echo '<div class="image">';
836
837        $more = array();
838        if ($rev) {
839            $more['rev'] = $rev;
840        } else {
841            $t = @filemtime(mediaFN($image));
842            $more['t'] = $t;
843        }
844
845        $more['w'] = $size[0];
846        $more['h'] = $size[1];
847        $src = ml($image, $more);
848        echo '<img src="'.$src.'" alt="" style="max-width: '.$size[0].'px;" />';
849
850        echo '</div>'.NL;
851    }
852}
853
854/**
855 * Prints mediafile action buttons
856 *
857 * @author Kate Arzamastseva <pshns@ukr.net>
858 */
859function media_preview_buttons($image, $auth, $rev=false) {
860    global $lang, $conf;
861
862    echo '<ul class="actions">'.NL;
863
864    if($auth >= AUTH_DELETE && !$rev && @file_exists(mediaFN($image))){
865
866        // delete button
867        $form = new Doku_Form(array('id' => 'mediamanager__btn_delete',
868            'action'=>media_managerURL(array('delete' => $image), '&')));
869        $form->addElement(form_makeButton('submit','',$lang['btn_delete']));
870        echo '<li>';
871        $form->printForm();
872        echo '</li>'.NL;
873    }
874
875    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
876    if($auth >= $auth_ow && !$rev){
877
878        // upload new version button
879        $form = new Doku_Form(array('id' => 'mediamanager__btn_update',
880            'action'=>media_managerURL(array('image' => $image, 'mediado' => 'update'), '&')));
881        $form->addElement(form_makeButton('submit','',$lang['media_update']));
882        echo '<li>';
883        $form->printForm();
884        echo '</li>'.NL;
885    }
886
887    if($auth >= AUTH_UPLOAD && $rev && $conf['mediarevisions'] && @file_exists(mediaFN($image, $rev))){
888
889        // restore button
890        $form = new Doku_Form(array('id' => 'mediamanager__btn_restore',
891            'action'=>media_managerURL(array('image' => $image), '&')));
892        $form->addHidden('mediado','restore');
893        $form->addHidden('rev',$rev);
894        $form->addElement(form_makeButton('submit','',$lang['media_restore']));
895        echo '<li>';
896        $form->printForm();
897        echo '</li>'.NL;
898    }
899
900    echo '</ul>'.NL;
901}
902
903/**
904 * Returns image width and height for mediamanager preview panel
905 *
906 * @author Kate Arzamastseva <pshns@ukr.net>
907 * @param string $image
908 * @param int $rev
909 * @param JpegMeta $meta
910 * @return array
911 */
912function media_image_preview_size($image, $rev, $meta, $size = 500) {
913    if (!preg_match("/\.(jpe?g|gif|png)$/", $image) || !file_exists(mediaFN($image, $rev))) return false;
914
915    $info = getimagesize(mediaFN($image, $rev));
916    $w = (int) $info[0];
917    $h = (int) $info[1];
918
919    if($meta && ($w > $size || $h > $size)){
920        $ratio = $meta->getResizeRatio($size, $size);
921        $w = floor($w * $ratio);
922        $h = floor($h * $ratio);
923    }
924    return array($w, $h);
925}
926
927/**
928 * Returns the requested EXIF/IPTC tag from the image meta
929 *
930 * @author Kate Arzamastseva <pshns@ukr.net>
931 * @param array $tags
932 * @param JpegMeta $meta
933 * @param string $alt
934 * @return string
935 */
936function media_getTag($tags,$meta,$alt=''){
937    if($meta === false) return $alt;
938    $info = $meta->getField($tags);
939    if($info == false) return $alt;
940    return $info;
941}
942
943/**
944 * Returns mediafile tags
945 *
946 * @author Kate Arzamastseva <pshns@ukr.net>
947 * @param JpegMeta $meta
948 * @return array
949 */
950function media_file_tags($meta) {
951    global $config_cascade;
952
953    // load the field descriptions
954    static $fields = null;
955    if(is_null($fields)){
956        $config_files = getConfigFiles('mediameta');
957        foreach ($config_files as $config_file) {
958            if(@file_exists($config_file)) include($config_file);
959        }
960    }
961
962    $tags = array();
963
964    foreach($fields as $key => $tag){
965        $t = array();
966        if (!empty($tag[0])) $t = array($tag[0]);
967        if(is_array($tag[3])) $t = array_merge($t,$tag[3]);
968        $value = media_getTag($t, $meta);
969        $tags[] = array('tag' => $tag, 'value' => $value);
970    }
971
972    return $tags;
973}
974
975/**
976 * Prints mediafile tags
977 *
978 * @author Kate Arzamastseva <pshns@ukr.net>
979 */
980function media_details($image, $auth, $rev=false, $meta=false) {
981    global $lang;
982
983    if (!$meta) $meta = new JpegMeta(mediaFN($image, $rev));
984    $tags = media_file_tags($meta);
985
986    echo '<dl>'.NL;
987    foreach($tags as $tag){
988        if ($tag['value']) {
989            $value = cleanText($tag['value']);
990            echo '<dt>'.$lang[$tag['tag'][1]].':</dt><dd>';
991            if ($tag['tag'][2] == 'date') echo dformat($value);
992            else echo hsc($value);
993            echo '</dd>'.NL;
994        }
995    }
996    echo '</dl>'.NL;
997}
998
999/**
1000 * Shows difference between two revisions of file
1001 *
1002 * @author Kate Arzamastseva <pshns@ukr.net>
1003 */
1004function media_diff($image, $ns, $auth, $fromajax = false) {
1005    global $lang;
1006    global $conf;
1007
1008    if ($auth < AUTH_READ || !$image || !$conf['mediarevisions']) return '';
1009
1010    $rev1 = (int) $_REQUEST['rev'];
1011
1012    if(is_array($_REQUEST['rev2'])){
1013        $rev1 = (int) $_REQUEST['rev2'][0];
1014        $rev2 = (int) $_REQUEST['rev2'][1];
1015
1016        if(!$rev1){
1017            $rev1 = $rev2;
1018            unset($rev2);
1019        }
1020    }else{
1021        $rev2 = (int) $_REQUEST['rev2'];
1022    }
1023
1024    if ($rev1 && !file_exists(mediaFN($image, $rev1))) $rev1 = false;
1025    if ($rev2 && !file_exists(mediaFN($image, $rev2))) $rev2 = false;
1026
1027    if($rev1 && $rev2){            // two specific revisions wanted
1028        // make sure order is correct (older on the left)
1029        if($rev1 < $rev2){
1030            $l_rev = $rev1;
1031            $r_rev = $rev2;
1032        }else{
1033            $l_rev = $rev2;
1034            $r_rev = $rev1;
1035        }
1036    }elseif($rev1){                // single revision given, compare to current
1037        $r_rev = '';
1038        $l_rev = $rev1;
1039    }else{                        // no revision was given, compare previous to current
1040        $r_rev = '';
1041        $revs = getRevisions($image, 0, 1, 8192, true);
1042        if (file_exists(mediaFN($image, $revs[0]))) {
1043            $l_rev = $revs[0];
1044        } else {
1045            $l_rev = '';
1046        }
1047    }
1048
1049    // prepare event data
1050    $data[0] = $image;
1051    $data[1] = $l_rev;
1052    $data[2] = $r_rev;
1053    $data[3] = $ns;
1054    $data[4] = $auth;
1055    $data[5] = $fromajax;
1056
1057    // trigger event
1058    return trigger_event('MEDIA_DIFF', $data, '_media_file_diff', true);
1059
1060}
1061
1062function _media_file_diff($data) {
1063    if(is_array($data) && count($data)===6) {
1064        return media_file_diff($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
1065    } else {
1066        return false;
1067    }
1068}
1069
1070/**
1071 * Shows difference between two revisions of image
1072 *
1073 * @author Kate Arzamastseva <pshns@ukr.net>
1074 */
1075function media_file_diff($image, $l_rev, $r_rev, $ns, $auth, $fromajax){
1076    global $lang, $config_cascade;
1077
1078    $l_meta = new JpegMeta(mediaFN($image, $l_rev));
1079    $r_meta = new JpegMeta(mediaFN($image, $r_rev));
1080
1081    $is_img = preg_match("/\.(jpe?g|gif|png)$/", $image);
1082    if ($is_img) {
1083        $l_size = media_image_preview_size($image, $l_rev, $l_meta);
1084        $r_size = media_image_preview_size($image, $r_rev, $r_meta);
1085        $is_img = ($l_size && $r_size && ($l_size[0] >= 30 || $r_size[0] >= 30));
1086
1087        $difftype = $_REQUEST['difftype'];
1088
1089        if (!$fromajax) {
1090            $form = new Doku_Form(array(
1091                'action' => media_managerURL(array(), '&'),
1092                'method' => 'get',
1093                'id' => 'mediamanager__form_diffview',
1094                'class' => 'diffView'
1095            ));
1096            $form->addHidden('sectok', null);
1097            $form->addElement('<input type="hidden" name="rev2[]" value="'.$l_rev.'" ></input>');
1098            $form->addElement('<input type="hidden" name="rev2[]" value="'.$r_rev.'" ></input>');
1099            $form->addHidden('mediado', 'diff');
1100            $form->printForm();
1101
1102            echo NL.'<div id="mediamanager__diff" >'.NL;
1103        }
1104
1105        if ($difftype == 'opacity' || $difftype == 'portions') {
1106            media_image_diff($image, $l_rev, $r_rev, $l_size, $r_size, $difftype);
1107            if (!$fromajax) echo '</div>';
1108            return '';
1109        }
1110    }
1111
1112    list($l_head, $r_head) = html_diff_head($l_rev, $r_rev, $image, true);
1113
1114    ?>
1115    <table>
1116      <tr>
1117        <th><?php echo $l_head; ?></th>
1118        <th><?php echo $r_head; ?></th>
1119      </tr>
1120    <?php
1121
1122    echo '<tr class="image">';
1123    echo '<td>';
1124    media_preview($image, $auth, $l_rev, $l_meta);
1125    echo '</td>';
1126
1127    echo '<td>';
1128    media_preview($image, $auth, $r_rev, $r_meta);
1129    echo '</td>';
1130    echo '</tr>'.NL;
1131
1132    echo '<tr class="actions">';
1133    echo '<td>';
1134    media_preview_buttons($image, $auth, $l_rev);
1135    echo '</td>';
1136
1137    echo '<td>';
1138    media_preview_buttons($image, $auth, $r_rev);
1139    echo '</td>';
1140    echo '</tr>'.NL;
1141
1142    $l_tags = media_file_tags($l_meta);
1143    $r_tags = media_file_tags($r_meta);
1144    // FIXME r_tags-only stuff
1145    foreach ($l_tags as $key => $l_tag) {
1146        if ($l_tag['value'] != $r_tags[$key]['value']) {
1147            $r_tags[$key]['highlighted'] = true;
1148            $l_tags[$key]['highlighted'] = true;
1149        } else if (!$l_tag['value'] || !$r_tags[$key]['value']) {
1150            unset($r_tags[$key]);
1151            unset($l_tags[$key]);
1152        }
1153    }
1154
1155    echo '<tr>';
1156    foreach(array($l_tags,$r_tags) as $tags){
1157        echo '<td>'.NL;
1158
1159        echo '<dl class="img_tags">';
1160        foreach($tags as $tag){
1161            $value = cleanText($tag['value']);
1162            if (!$value) $value = '-';
1163            echo '<dt>'.$lang[$tag['tag'][1]].':</dt>';
1164            echo '<dd>';
1165            if ($tag['highlighted']) {
1166                echo '<strong>';
1167            }
1168            if ($tag['tag'][2] == 'date') echo dformat($value);
1169            else echo hsc($value);
1170            if ($tag['highlighted']) {
1171                echo '</strong>';
1172            }
1173            echo '</dd>';
1174        }
1175        echo '</dl>'.NL;
1176
1177        echo '</td>';
1178    }
1179    echo '</tr>'.NL;
1180
1181    echo '</table>'.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    echo '</div>'.NL;
1606}
1607
1608/**
1609 * Print the search field form
1610 *
1611 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1612 * @author Kate Arzamastseva <pshns@ukr.net>
1613 */
1614function media_searchform($ns,$query='',$fullscreen=false){
1615    global $lang;
1616
1617    // The default HTML search form
1618    $params = array('id' => 'dw__mediasearch');
1619    if (!$fullscreen) {
1620        $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1621    } else {
1622        $params['action'] = media_managerURL(array(), '&');
1623    }
1624    $form = new Doku_Form($params);
1625    $form->addHidden('ns', $ns);
1626    $form->addHidden($fullscreen ? 'mediado' : 'do', 'searchlist');
1627
1628    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>'.NL);
1629    $form->addElement(form_makeOpenTag('p'));
1630    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1631    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1632    $form->addElement(form_makeCloseTag('p'));
1633    html_form('searchmedia', $form);
1634}
1635
1636/**
1637 * Build a tree outline of available media namespaces
1638 *
1639 * @author Andreas Gohr <andi@splitbrain.org>
1640 */
1641function media_nstree($ns){
1642    global $conf;
1643    global $lang;
1644
1645    // currently selected namespace
1646    $ns  = cleanID($ns);
1647    if(empty($ns)){
1648        global $ID;
1649        $ns = dirname(str_replace(':','/',$ID));
1650        if($ns == '.') $ns ='';
1651    }
1652    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1653
1654    $data = array();
1655    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1656
1657    // wrap a list with the root level around the other namespaces
1658    array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
1659                               'label' => '['.$lang['mediaroot'].']'));
1660
1661    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1662}
1663
1664/**
1665 * Userfunction for html_buildlist
1666 *
1667 * Prints a media namespace tree item
1668 *
1669 * @author Andreas Gohr <andi@splitbrain.org>
1670 */
1671function media_nstree_item($item){
1672    $pos   = strrpos($item['id'], ':');
1673    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1674    if(!$item['label']) $item['label'] = $label;
1675
1676    $ret  = '';
1677    if (!($_REQUEST['do'] == 'media'))
1678    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1679    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id'], false), 'tab_files' => 'files'))
1680        .'" class="idx_dir">';
1681    $ret .= $item['label'];
1682    $ret .= '</a>';
1683    return $ret;
1684}
1685
1686/**
1687 * Userfunction for html_buildlist
1688 *
1689 * Prints a media namespace tree item opener
1690 *
1691 * @author Andreas Gohr <andi@splitbrain.org>
1692 */
1693function media_nstree_li($item){
1694    $class='media level'.$item['level'];
1695    if($item['open']){
1696        $class .= ' open';
1697        $img   = DOKU_BASE.'lib/images/minus.gif';
1698        $alt   = '&minus;';
1699    }else{
1700        $class .= ' closed';
1701        $img   = DOKU_BASE.'lib/images/plus.gif';
1702        $alt   = '+';
1703    }
1704    // TODO: only deliver an image if it actually has a subtree...
1705    return '<li class="'.$class.'">'.
1706        '<img src="'.$img.'" alt="'.$alt.'" />';
1707}
1708
1709/**
1710 * Resizes the given image to the given size
1711 *
1712 * @author  Andreas Gohr <andi@splitbrain.org>
1713 */
1714function media_resize_image($file, $ext, $w, $h=0){
1715    global $conf;
1716
1717    $info = @getimagesize($file); //get original size
1718    if($info == false) return $file; // that's no image - it's a spaceship!
1719
1720    if(!$h) $h = round(($w * $info[1]) / $info[0]);
1721
1722    // we wont scale up to infinity
1723    if($w > 2000 || $h > 2000) return $file;
1724
1725    //cache
1726    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1727    $mtime = @filemtime($local); // 0 if not exists
1728
1729    if( $mtime > filemtime($file) ||
1730            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1731            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1732        if($conf['fperm']) chmod($local, $conf['fperm']);
1733        return $local;
1734    }
1735    //still here? resizing failed
1736    return $file;
1737}
1738
1739/**
1740 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1741 * to the wanted size
1742 *
1743 * Crops are centered horizontally but prefer the upper third of an vertical
1744 * image because most pics are more interesting in that area (rule of thirds)
1745 *
1746 * @author  Andreas Gohr <andi@splitbrain.org>
1747 */
1748function media_crop_image($file, $ext, $w, $h=0){
1749    global $conf;
1750
1751    if(!$h) $h = $w;
1752    $info = @getimagesize($file); //get original size
1753    if($info == false) return $file; // that's no image - it's a spaceship!
1754
1755    // calculate crop size
1756    $fr = $info[0]/$info[1];
1757    $tr = $w/$h;
1758    if($tr >= 1){
1759        if($tr > $fr){
1760            $cw = $info[0];
1761            $ch = (int) $info[0]/$tr;
1762        }else{
1763            $cw = (int) $info[1]*$tr;
1764            $ch = $info[1];
1765        }
1766    }else{
1767        if($tr < $fr){
1768            $cw = (int) $info[1]*$tr;
1769            $ch = $info[1];
1770        }else{
1771            $cw = $info[0];
1772            $ch = (int) $info[0]/$tr;
1773        }
1774    }
1775    // calculate crop offset
1776    $cx = (int) ($info[0]-$cw)/2;
1777    $cy = (int) ($info[1]-$ch)/3;
1778
1779    //cache
1780    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1781    $mtime = @filemtime($local); // 0 if not exists
1782
1783    if( $mtime > @filemtime($file) ||
1784            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1785            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1786        if($conf['fperm']) chmod($local, $conf['fperm']);
1787        return media_resize_image($local,$ext, $w, $h);
1788    }
1789
1790    //still here? cropping failed
1791    return media_resize_image($file,$ext, $w, $h);
1792}
1793
1794/**
1795 * Download a remote file and return local filename
1796 *
1797 * returns false if download fails. Uses cached file if available and
1798 * wanted
1799 *
1800 * @author  Andreas Gohr <andi@splitbrain.org>
1801 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
1802 */
1803function media_get_from_URL($url,$ext,$cache){
1804    global $conf;
1805
1806    // if no cache or fetchsize just redirect
1807    if ($cache==0)           return false;
1808    if (!$conf['fetchsize']) return false;
1809
1810    $local = getCacheName(strtolower($url),".media.$ext");
1811    $mtime = @filemtime($local); // 0 if not exists
1812
1813    //decide if download needed:
1814    if( ($mtime == 0) ||                           // cache does not exist
1815            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
1816      ){
1817        if(media_image_download($url,$local)){
1818            return $local;
1819        }else{
1820            return false;
1821        }
1822    }
1823
1824    //if cache exists use it else
1825    if($mtime) return $local;
1826
1827    //else return false
1828    return false;
1829}
1830
1831/**
1832 * Download image files
1833 *
1834 * @author Andreas Gohr <andi@splitbrain.org>
1835 */
1836function media_image_download($url,$file){
1837    global $conf;
1838    $http = new DokuHTTPClient();
1839    $http->max_bodysize = $conf['fetchsize'];
1840    $http->timeout = 25; //max. 25 sec
1841    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1842
1843    $data = $http->get($url);
1844    if(!$data) return false;
1845
1846    $fileexists = @file_exists($file);
1847    $fp = @fopen($file,"w");
1848    if(!$fp) return false;
1849    fwrite($fp,$data);
1850    fclose($fp);
1851    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1852
1853    // check if it is really an image
1854    $info = @getimagesize($file);
1855    if(!$info){
1856        @unlink($file);
1857        return false;
1858    }
1859
1860    return true;
1861}
1862
1863/**
1864 * resize images using external ImageMagick convert program
1865 *
1866 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1867 * @author Andreas Gohr <andi@splitbrain.org>
1868 */
1869function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1870    global $conf;
1871
1872    // check if convert is configured
1873    if(!$conf['im_convert']) return false;
1874
1875    // prepare command
1876    $cmd  = $conf['im_convert'];
1877    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1878    if ($ext == 'jpg' || $ext == 'jpeg') {
1879        $cmd .= ' -quality '.$conf['jpg_quality'];
1880    }
1881    $cmd .= " $from $to";
1882
1883    @exec($cmd,$out,$retval);
1884    if ($retval == 0) return true;
1885    return false;
1886}
1887
1888/**
1889 * crop images using external ImageMagick convert program
1890 *
1891 * @author Andreas Gohr <andi@splitbrain.org>
1892 */
1893function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1894    global $conf;
1895
1896    // check if convert is configured
1897    if(!$conf['im_convert']) return false;
1898
1899    // prepare command
1900    $cmd  = $conf['im_convert'];
1901    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1902    if ($ext == 'jpg' || $ext == 'jpeg') {
1903        $cmd .= ' -quality '.$conf['jpg_quality'];
1904    }
1905    $cmd .= " $from $to";
1906
1907    @exec($cmd,$out,$retval);
1908    if ($retval == 0) return true;
1909    return false;
1910}
1911
1912/**
1913 * resize or crop images using PHP's libGD support
1914 *
1915 * @author Andreas Gohr <andi@splitbrain.org>
1916 * @author Sebastian Wienecke <s_wienecke@web.de>
1917 */
1918function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1919    global $conf;
1920
1921    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1922
1923    // check available memory
1924    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1925        return false;
1926    }
1927
1928    // create an image of the given filetype
1929    if ($ext == 'jpg' || $ext == 'jpeg'){
1930        if(!function_exists("imagecreatefromjpeg")) return false;
1931        $image = @imagecreatefromjpeg($from);
1932    }elseif($ext == 'png') {
1933        if(!function_exists("imagecreatefrompng")) return false;
1934        $image = @imagecreatefrompng($from);
1935
1936    }elseif($ext == 'gif') {
1937        if(!function_exists("imagecreatefromgif")) return false;
1938        $image = @imagecreatefromgif($from);
1939    }
1940    if(!$image) return false;
1941
1942    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1943        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1944    }
1945    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1946    if(!$newimg){
1947        imagedestroy($image);
1948        return false;
1949    }
1950
1951    //keep png alpha channel if possible
1952    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1953        imagealphablending($newimg, false);
1954        imagesavealpha($newimg,true);
1955    }
1956
1957    //keep gif transparent color if possible
1958    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1959        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1960            $transcolorindex = @imagecolortransparent($image);
1961            if($transcolorindex >= 0 ) { //transparent color exists
1962                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1963                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1964                @imagefill($newimg, 0, 0, $transcolorindex);
1965                @imagecolortransparent($newimg, $transcolorindex);
1966            }else{ //filling with white
1967                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1968                @imagefill($newimg, 0, 0, $whitecolorindex);
1969            }
1970        }else{ //filling with white
1971            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1972            @imagefill($newimg, 0, 0, $whitecolorindex);
1973        }
1974    }
1975
1976    //try resampling first
1977    if(function_exists("imagecopyresampled")){
1978        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
1979            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1980        }
1981    }else{
1982        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1983    }
1984
1985    $okay = false;
1986    if ($ext == 'jpg' || $ext == 'jpeg'){
1987        if(!function_exists('imagejpeg')){
1988            $okay = false;
1989        }else{
1990            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1991        }
1992    }elseif($ext == 'png') {
1993        if(!function_exists('imagepng')){
1994            $okay = false;
1995        }else{
1996            $okay =  imagepng($newimg, $to);
1997        }
1998    }elseif($ext == 'gif') {
1999        if(!function_exists('imagegif')){
2000            $okay = false;
2001        }else{
2002            $okay = imagegif($newimg, $to);
2003        }
2004    }
2005
2006    // destroy GD image ressources
2007    if($image) imagedestroy($image);
2008    if($newimg) imagedestroy($newimg);
2009
2010    return $okay;
2011}
2012
2013/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
2014