xref: /dokuwiki/inc/media.php (revision 87deddfa454164964c2fb71481cf480b3d2d92df)
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        if ($sort == 'date') {
1336            $data = array();
1337            foreach ($evdata['data'] as $k => $v) {
1338                $data[$k]  = $v['mtime'];
1339            }
1340            array_multisort($data, SORT_DESC, SORT_NUMERIC, $evdata['data']);
1341        }
1342
1343        $evt->advise_after();
1344        unset($evt);
1345    }
1346
1347    if (!$fullscreen) {
1348        echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
1349        media_searchform($ns,$query);
1350    }
1351
1352    if(!count($evdata['data'])){
1353        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
1354    }else {
1355        if ($fullscreen) {
1356            $view = $_REQUEST['view'];
1357            if ($view == 'list') {
1358                echo '<ul class="mediamanager-list" id="mediamanager__file_list">';
1359            } else {
1360                echo '<ul class="mediamanager-thumbs" id="mediamanager__file_list">';
1361            }
1362        }
1363        foreach($evdata['data'] as $item){
1364            if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
1365            else media_printfile_thumbs($item,$item['perm'],false,true);
1366        }
1367        if ($fullscreen) echo '</ul>';
1368    }
1369}
1370
1371/**
1372 * Print action links for a file depending on filetype
1373 * and available permissions
1374 */
1375function media_fileactions($item,$auth){
1376    global $lang;
1377
1378    // view button
1379    $link = ml($item['id'],'',true);
1380    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
1381        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
1382
1383    // no further actions if not writable
1384    if(!$item['writable']) return;
1385
1386    // delete button
1387    if($auth >= AUTH_DELETE){
1388        $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
1389            '&amp;sectok='.getSecurityToken();
1390        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
1391            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
1392            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
1393    }
1394
1395    // edit button
1396    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
1397        $link = DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']);
1398        echo ' <a href="'.$link.'">'.
1399            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
1400            'title="'.$lang['metaedit'].'" class="btn" /></a>';
1401    }
1402
1403}
1404
1405/**
1406 * Formats and prints one file in the list
1407 */
1408function media_printfile($item,$auth,$jump,$display_namespace=false){
1409    global $lang;
1410    global $conf;
1411
1412    // Prepare zebra coloring
1413    // I always wanted to use this variable name :-D
1414    static $twibble = 1;
1415    $twibble *= -1;
1416    $zebra = ($twibble == -1) ? 'odd' : 'even';
1417
1418    // Automatically jump to recent action
1419    if($jump == $item['id']) {
1420        $jump = ' id="scroll__here" ';
1421    }else{
1422        $jump = '';
1423    }
1424
1425    // Prepare fileicons
1426    list($ext,$mime,$dl) = mimetype($item['file'],false);
1427    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1428    $class = 'select mediafile mf_'.$class;
1429
1430    // Prepare filename
1431    $file = utf8_decodeFN($item['file']);
1432
1433    // Prepare info
1434    $info = '';
1435    if($item['isimg']){
1436        $info .= (int) $item['meta']->getField('File.Width');
1437        $info .= '&#215;';
1438        $info .= (int) $item['meta']->getField('File.Height');
1439        $info .= ' ';
1440    }
1441    $info .= '<i>'.dformat($item['mtime']).'</i>';
1442    $info .= ' ';
1443    $info .= filesize_h($item['size']);
1444
1445    // output
1446    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
1447    if (!$display_namespace) {
1448        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1449    } else {
1450        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1451    }
1452    echo '<span class="info">('.$info.')</span>'.NL;
1453    media_fileactions($item,$auth);
1454    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1455    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1456    echo '</div>';
1457    if($item['isimg']) media_printimgdetail($item);
1458    echo '<div class="clearer"></div>'.NL;
1459    echo '</div>'.NL;
1460}
1461
1462function media_printicon($filename){
1463    list($ext,$mime,$dl) = mimetype(mediaFN($filename),false);
1464
1465    if (@file_exists(DOKU_INC.'lib/images/fileicons/'.$ext.'.png')) {
1466        $icon = DOKU_BASE.'lib/images/fileicons/'.$ext.'.png';
1467    } else {
1468        $icon = DOKU_BASE.'lib/images/fileicons/file.png';
1469    }
1470
1471    return '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />';
1472
1473}
1474
1475/**
1476 * Formats and prints one file in the list in the thumbnails view
1477 *
1478 * @author Kate Arzamastseva <pshns@ukr.net>
1479 */
1480function media_printfile_thumbs($item,$auth,$jump=false,$display_namespace=false){
1481    global $lang;
1482    global $conf;
1483
1484    // Prepare filename
1485    $file = utf8_decodeFN($item['file']);
1486
1487    // output
1488    echo '<li><div>';
1489
1490    if($item['isimg']) {
1491        media_printimgdetail($item, true);
1492
1493    } else {
1494        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1495            media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']))).'"><span>';
1496        echo media_printicon($item['id']);
1497        echo '</span></a>';
1498    }
1499    //echo '<input type=checkbox />';
1500    if (!$display_namespace) {
1501        $name = hsc($file);
1502    } else {
1503        $name = hsc($item['id']);
1504    }
1505    echo '<a href="'.media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']))).'" name=
1506        "h_:'.$item['id'].'" class="name">'.$name.'</a>';
1507
1508    if($item['isimg']){
1509        $size = '';
1510        $size .= (int) $item['meta']->getField('File.Width');
1511        $size .= '&#215;';
1512        $size .= (int) $item['meta']->getField('File.Height');
1513        echo '<span class="size">'.$size.'</span>';
1514    } else {
1515        echo '<span class="size">&nbsp;</span>';
1516    }
1517    $date = dformat($item['mtime']);
1518    echo '<span class="date">'.$date.'</span>';
1519    $filesize = filesize_h($item['size']);
1520    echo '<span class="filesize">'.$filesize.'</span>';
1521    echo '<div class="clearer"></div>';
1522    echo '</div></li>'.NL;
1523}
1524
1525/**
1526 * Prints a thumbnail and metainfos
1527 */
1528function media_printimgdetail($item, $fullscreen=false){
1529    // prepare thumbnail
1530    if (!$fullscreen) {
1531        $size_array[] = 120;
1532    } else {
1533        $size_array = array(90, 40);
1534    }
1535    foreach ($size_array as $index => $size) {
1536        $w = (int) $item['meta']->getField('File.Width');
1537        $h = (int) $item['meta']->getField('File.Height');
1538        if($w>$size || $h>$size){
1539            if (!$fullscreen) {
1540                $ratio = $item['meta']->getResizeRatio($size);
1541            } else {
1542                $ratio = $item['meta']->getResizeRatio($size,$size);
1543            }
1544            $w = floor($w * $ratio);
1545            $h = floor($h * $ratio);
1546        }
1547        $src = ml($item['id'],array('w'=>$w,'h'=>$h,'t'=>$item['mtime']));
1548        $p = array();
1549        if (!$fullscreen) {
1550            $p['width']  = $w;
1551            $p['height'] = $h;
1552        }
1553        $p['alt']    = $item['id'];
1554        $p['class']  = 'thumb';
1555        $att = buildAttributes($p);
1556
1557        // output
1558        if ($fullscreen) {
1559            echo '<a name="'.($index ? 'd' : 'l').'_:'.$item['id'].'" class="image'.$index.'" title="'.$item['id'].'" href="'.
1560                media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']))).'">';
1561            echo '<span><img src="'.$src.'" '.$att.' /></span>';
1562            echo '</a>';
1563        }
1564    }
1565
1566    if ($fullscreen) return '';
1567
1568    echo '<div class="detail">';
1569    echo '<div class="thumb">';
1570    echo '<a name="d_:'.$item['id'].'" class="select">';
1571    echo '<img src="'.$src.'" '.$att.' />';
1572    echo '</a>';
1573    echo '</div>';
1574
1575    // read EXIF/IPTC data
1576    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1577    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1578                'EXIF.TIFFImageDescription',
1579                'EXIF.TIFFUserComment'));
1580    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
1581    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1582
1583    // print EXIF/IPTC data
1584    if($t || $d || $k ){
1585        echo '<p>';
1586        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
1587        if($d) echo htmlspecialchars($d).'<br />';
1588        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
1589        echo '</p>';
1590    }
1591    echo '</div>';
1592}
1593
1594/**
1595 * Build link based on the current, adding/rewriting
1596 * parameters
1597 *
1598 * @author Kate Arzamastseva <pshns@ukr.net>
1599 * @param array $params
1600 * @param string $amp - separator
1601 * @return string - link
1602 */
1603function media_managerURL($params=false, $amp='&amp;', $abs=false, $params_array=false) {
1604    global $conf;
1605    global $ID;
1606
1607    $gets = array('do' => 'media');
1608    $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'view');
1609    foreach ($media_manager_params as $x) {
1610        if (isset($_REQUEST[$x])) $gets[$x] = $_REQUEST[$x];
1611    }
1612
1613    if ($params) {
1614        foreach ($params as $k => $v) {
1615            $gets[$k] = $v;
1616        }
1617    }
1618    unset($gets['id']);
1619    if ($gets['delete']) {
1620        unset($gets['image']);
1621        unset($gets['tab_details']);
1622    }
1623
1624    if ($params_array) return $gets;
1625
1626    return wl($ID,$gets,$abs,$amp);
1627}
1628
1629/**
1630 * Print the media upload form if permissions are correct
1631 *
1632 * @author Andreas Gohr <andi@splitbrain.org>
1633 * @author Kate Arzamastseva <pshns@ukr.net>
1634 */
1635function media_uploadform($ns, $auth, $fullscreen = false){
1636    global $lang, $conf;
1637
1638    if($auth < AUTH_UPLOAD) {
1639        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1640        return;
1641    }
1642    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
1643
1644    $update = false;
1645    $id = '';
1646    if ($auth >= $auth_ow && $fullscreen && $_REQUEST['mediado'] == 'update') {
1647        $update = true;
1648        $id = cleanID($_REQUEST['image']);
1649    }
1650
1651    // The default HTML upload form
1652    $params = array('id'      => 'dw__upload',
1653                    'enctype' => 'multipart/form-data');
1654    if (!$fullscreen) {
1655        $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1656    } else {
1657        $params['action'] = media_managerURL(array('tab_files' => 'files',
1658            'tab_details' => 'view'), '&');
1659    }
1660
1661    $form = new Doku_Form($params);
1662    if (!$fullscreen) echo '<div class="upload">' . $lang['mediaupload'] . '</div>';
1663    $form->addElement(formSecurityToken());
1664    $form->addHidden('ns', hsc($ns));
1665    $form->addElement(form_makeOpenTag('p'));
1666    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
1667    $form->addElement(form_makeCloseTag('p'));
1668    $form->addElement(form_makeOpenTag('p'));
1669    $form->addElement(form_makeTextField('mediaid', noNS($id), $lang['txt_filename'].':', 'upload__name'));
1670    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
1671    $form->addElement(form_makeCloseTag('p'));
1672
1673    if($auth >= $auth_ow){
1674        $form->addElement(form_makeOpenTag('p'));
1675        $attrs = array();
1676        if ($update) $attrs['checked'] = 'checked';
1677        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check', $attrs));
1678        $form->addElement(form_makeCloseTag('p'));
1679    }
1680
1681    echo '<div id="mediamanager__uploader">';
1682    html_form('upload', $form);
1683    echo '</div>';
1684}
1685
1686/**
1687 * Print the search field form
1688 *
1689 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1690 * @author Kate Arzamastseva <pshns@ukr.net>
1691 */
1692function media_searchform($ns,$query='',$fullscreen=false){
1693    global $lang;
1694
1695    // The default HTML search form
1696    $params = array('id' => 'dw__mediasearch');
1697    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1698    else $params['action'] = media_managerURL(array(), '&');
1699    $form = new Doku_Form($params);
1700    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
1701    $form->addElement(formSecurityToken());
1702    $form->addHidden('ns', $ns);
1703    if (!$fullscreen) $form->addHidden('do', 'searchlist');
1704    else $form->addHidden('mediado', 'searchlist');
1705    $form->addElement(form_makeOpenTag('p'));
1706    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'mediamanager__sort_textfield','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1707    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1708    $form->addElement(form_makeCloseTag('p'));
1709    html_form('searchmedia', $form);
1710}
1711
1712/**
1713 * Build a tree outline of available media namespaces
1714 *
1715 * @author Andreas Gohr <andi@splitbrain.org>
1716 */
1717function media_nstree($ns){
1718    global $conf;
1719    global $lang;
1720
1721    // currently selected namespace
1722    $ns  = cleanID($ns);
1723    if(empty($ns)){
1724        global $ID;
1725        $ns = dirname(str_replace(':','/',$ID));
1726        if($ns == '.') $ns ='';
1727    }
1728    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1729
1730    $data = array();
1731    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1732
1733    // wrap a list with the root level around the other namespaces
1734    array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
1735                               'label' => '['.$lang['mediaroot'].']'));
1736
1737    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1738}
1739
1740/**
1741 * Userfunction for html_buildlist
1742 *
1743 * Prints a media namespace tree item
1744 *
1745 * @author Andreas Gohr <andi@splitbrain.org>
1746 */
1747function media_nstree_item($item){
1748    $pos   = strrpos($item['id'], ':');
1749    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1750    if(!$item['label']) $item['label'] = $label;
1751
1752    $ret  = '';
1753    if (!($_REQUEST['do'] == 'media'))
1754    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1755    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id']), 'tab_files' => 'files'))
1756        .'" class="idx_dir">';
1757    $ret .= $item['label'];
1758    $ret .= '</a>';
1759    return $ret;
1760}
1761
1762/**
1763 * Userfunction for html_buildlist
1764 *
1765 * Prints a media namespace tree item opener
1766 *
1767 * @author Andreas Gohr <andi@splitbrain.org>
1768 */
1769function media_nstree_li($item){
1770    $class='media level'.$item['level'];
1771    if($item['open']){
1772        $class .= ' open';
1773        $img   = DOKU_BASE.'lib/images/minus.gif';
1774        $alt   = '&minus;';
1775    }else{
1776        $class .= ' closed';
1777        $img   = DOKU_BASE.'lib/images/plus.gif';
1778        $alt   = '+';
1779    }
1780    // TODO: only deliver an image if it actually has a subtree...
1781    return '<li class="'.$class.'">'.
1782        '<img src="'.$img.'" alt="'.$alt.'" />';
1783}
1784
1785/**
1786 * Resizes the given image to the given size
1787 *
1788 * @author  Andreas Gohr <andi@splitbrain.org>
1789 */
1790function media_resize_image($file, $ext, $w, $h=0){
1791    global $conf;
1792
1793    $info = @getimagesize($file); //get original size
1794    if($info == false) return $file; // that's no image - it's a spaceship!
1795
1796    if(!$h) $h = round(($w * $info[1]) / $info[0]);
1797
1798    // we wont scale up to infinity
1799    if($w > 2000 || $h > 2000) return $file;
1800
1801    //cache
1802    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1803    $mtime = @filemtime($local); // 0 if not exists
1804
1805    if( $mtime > filemtime($file) ||
1806            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1807            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1808        if($conf['fperm']) chmod($local, $conf['fperm']);
1809        return $local;
1810    }
1811    //still here? resizing failed
1812    return $file;
1813}
1814
1815/**
1816 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1817 * to the wanted size
1818 *
1819 * Crops are centered horizontally but prefer the upper third of an vertical
1820 * image because most pics are more interesting in that area (rule of thirds)
1821 *
1822 * @author  Andreas Gohr <andi@splitbrain.org>
1823 */
1824function media_crop_image($file, $ext, $w, $h=0){
1825    global $conf;
1826
1827    if(!$h) $h = $w;
1828    $info = @getimagesize($file); //get original size
1829    if($info == false) return $file; // that's no image - it's a spaceship!
1830
1831    // calculate crop size
1832    $fr = $info[0]/$info[1];
1833    $tr = $w/$h;
1834    if($tr >= 1){
1835        if($tr > $fr){
1836            $cw = $info[0];
1837            $ch = (int) $info[0]/$tr;
1838        }else{
1839            $cw = (int) $info[1]*$tr;
1840            $ch = $info[1];
1841        }
1842    }else{
1843        if($tr < $fr){
1844            $cw = (int) $info[1]*$tr;
1845            $ch = $info[1];
1846        }else{
1847            $cw = $info[0];
1848            $ch = (int) $info[0]/$tr;
1849        }
1850    }
1851    // calculate crop offset
1852    $cx = (int) ($info[0]-$cw)/2;
1853    $cy = (int) ($info[1]-$ch)/3;
1854
1855    //cache
1856    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1857    $mtime = @filemtime($local); // 0 if not exists
1858
1859    if( $mtime > filemtime($file) ||
1860            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1861            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1862        if($conf['fperm']) chmod($local, $conf['fperm']);
1863        return media_resize_image($local,$ext, $w, $h);
1864    }
1865
1866    //still here? cropping failed
1867    return media_resize_image($file,$ext, $w, $h);
1868}
1869
1870/**
1871 * Download a remote file and return local filename
1872 *
1873 * returns false if download fails. Uses cached file if available and
1874 * wanted
1875 *
1876 * @author  Andreas Gohr <andi@splitbrain.org>
1877 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
1878 */
1879function media_get_from_URL($url,$ext,$cache){
1880    global $conf;
1881
1882    // if no cache or fetchsize just redirect
1883    if ($cache==0)           return false;
1884    if (!$conf['fetchsize']) return false;
1885
1886    $local = getCacheName(strtolower($url),".media.$ext");
1887    $mtime = @filemtime($local); // 0 if not exists
1888
1889    //decide if download needed:
1890    if( ($mtime == 0) ||                           // cache does not exist
1891            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
1892      ){
1893        if(media_image_download($url,$local)){
1894            return $local;
1895        }else{
1896            return false;
1897        }
1898    }
1899
1900    //if cache exists use it else
1901    if($mtime) return $local;
1902
1903    //else return false
1904    return false;
1905}
1906
1907/**
1908 * Download image files
1909 *
1910 * @author Andreas Gohr <andi@splitbrain.org>
1911 */
1912function media_image_download($url,$file){
1913    global $conf;
1914    $http = new DokuHTTPClient();
1915    $http->max_bodysize = $conf['fetchsize'];
1916    $http->timeout = 25; //max. 25 sec
1917    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1918
1919    $data = $http->get($url);
1920    if(!$data) return false;
1921
1922    $fileexists = @file_exists($file);
1923    $fp = @fopen($file,"w");
1924    if(!$fp) return false;
1925    fwrite($fp,$data);
1926    fclose($fp);
1927    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1928
1929    // check if it is really an image
1930    $info = @getimagesize($file);
1931    if(!$info){
1932        @unlink($file);
1933        return false;
1934    }
1935
1936    return true;
1937}
1938
1939/**
1940 * resize images using external ImageMagick convert program
1941 *
1942 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1943 * @author Andreas Gohr <andi@splitbrain.org>
1944 */
1945function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1946    global $conf;
1947
1948    // check if convert is configured
1949    if(!$conf['im_convert']) return false;
1950
1951    // prepare command
1952    $cmd  = $conf['im_convert'];
1953    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1954    if ($ext == 'jpg' || $ext == 'jpeg') {
1955        $cmd .= ' -quality '.$conf['jpg_quality'];
1956    }
1957    $cmd .= " $from $to";
1958
1959    @exec($cmd,$out,$retval);
1960    if ($retval == 0) return true;
1961    return false;
1962}
1963
1964/**
1965 * crop images using external ImageMagick convert program
1966 *
1967 * @author Andreas Gohr <andi@splitbrain.org>
1968 */
1969function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1970    global $conf;
1971
1972    // check if convert is configured
1973    if(!$conf['im_convert']) return false;
1974
1975    // prepare command
1976    $cmd  = $conf['im_convert'];
1977    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1978    if ($ext == 'jpg' || $ext == 'jpeg') {
1979        $cmd .= ' -quality '.$conf['jpg_quality'];
1980    }
1981    $cmd .= " $from $to";
1982
1983    @exec($cmd,$out,$retval);
1984    if ($retval == 0) return true;
1985    return false;
1986}
1987
1988/**
1989 * resize or crop images using PHP's libGD support
1990 *
1991 * @author Andreas Gohr <andi@splitbrain.org>
1992 * @author Sebastian Wienecke <s_wienecke@web.de>
1993 */
1994function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1995    global $conf;
1996
1997    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1998
1999    // check available memory
2000    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
2001        return false;
2002    }
2003
2004    // create an image of the given filetype
2005    if ($ext == 'jpg' || $ext == 'jpeg'){
2006        if(!function_exists("imagecreatefromjpeg")) return false;
2007        $image = @imagecreatefromjpeg($from);
2008    }elseif($ext == 'png') {
2009        if(!function_exists("imagecreatefrompng")) return false;
2010        $image = @imagecreatefrompng($from);
2011
2012    }elseif($ext == 'gif') {
2013        if(!function_exists("imagecreatefromgif")) return false;
2014        $image = @imagecreatefromgif($from);
2015    }
2016    if(!$image) return false;
2017
2018    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
2019        $newimg = @imagecreatetruecolor ($to_w, $to_h);
2020    }
2021    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
2022    if(!$newimg){
2023        imagedestroy($image);
2024        return false;
2025    }
2026
2027    //keep png alpha channel if possible
2028    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
2029        imagealphablending($newimg, false);
2030        imagesavealpha($newimg,true);
2031    }
2032
2033    //keep gif transparent color if possible
2034    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
2035        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
2036            $transcolorindex = @imagecolortransparent($image);
2037            if($transcolorindex >= 0 ) { //transparent color exists
2038                $transcolor = @imagecolorsforindex($image, $transcolorindex);
2039                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
2040                @imagefill($newimg, 0, 0, $transcolorindex);
2041                @imagecolortransparent($newimg, $transcolorindex);
2042            }else{ //filling with white
2043                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2044                @imagefill($newimg, 0, 0, $whitecolorindex);
2045            }
2046        }else{ //filling with white
2047            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2048            @imagefill($newimg, 0, 0, $whitecolorindex);
2049        }
2050    }
2051
2052    //try resampling first
2053    if(function_exists("imagecopyresampled")){
2054        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
2055            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2056        }
2057    }else{
2058        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2059    }
2060
2061    $okay = false;
2062    if ($ext == 'jpg' || $ext == 'jpeg'){
2063        if(!function_exists('imagejpeg')){
2064            $okay = false;
2065        }else{
2066            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
2067        }
2068    }elseif($ext == 'png') {
2069        if(!function_exists('imagepng')){
2070            $okay = false;
2071        }else{
2072            $okay =  imagepng($newimg, $to);
2073        }
2074    }elseif($ext == 'gif') {
2075        if(!function_exists('imagegif')){
2076            $okay = false;
2077        }else{
2078            $okay = imagegif($newimg, $to);
2079        }
2080    }
2081
2082    // destroy GD image ressources
2083    if($image) imagedestroy($image);
2084    if($newimg) imagedestroy($newimg);
2085
2086    return $okay;
2087}
2088
2089/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
2090