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