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