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