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