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