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