xref: /dokuwiki/inc/media.php (revision b4b31bac3276c93277a8b70368aee135b7fdde09)
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    $is_img = preg_match("/\.(jpe?g|gif|png)$/", $image);
1098
1099    if ($is_img) {
1100        $difftype = $_REQUEST['difftype'];
1101
1102        if (!$fromajax) {
1103            $form = new Doku_Form(array('action'=>media_managerURL(array(), '&'),
1104                'id' => 'mediamanager__form_diffview'));
1105            $form->addElement('<input type=hidden name=rev2[] value='.$l_rev.' ></input>');
1106            $form->addElement('<input type=hidden name=rev2[] value='.$r_rev.' ></input>');
1107            $form->addHidden('mediado', 'diff');
1108            $form->printForm();
1109
1110            echo '<div id="mediamanager__diff" >';
1111        }
1112
1113        $l_meta = new JpegMeta(mediaFN($image, $l_rev));
1114        $r_meta = new JpegMeta(mediaFN($image, $r_rev));
1115
1116        if ($difftype == 'opacity' || $difftype == 'portions') {
1117            media_image_diff($image, $l_rev, $r_rev, $l_meta, $difftype);
1118            if (!$fromajax) echo '</div>';
1119            return '';
1120        }
1121
1122        echo '<div class="mediamanager-preview">';
1123
1124    }
1125
1126    echo '<ul id="mediamanager__diff_table">';
1127
1128    echo '<li>';
1129    media_preview($image, $auth, $l_rev, $l_meta);
1130    echo '</li>';
1131
1132    echo '<li>';
1133    media_preview($image, $auth, $r_rev, $r_meta);
1134    echo '</li>';
1135
1136    echo '<li>';
1137    media_preview_buttons($image, $auth, $l_rev);
1138    echo '</li>';
1139
1140    echo '<li>';
1141    media_preview_buttons($image, $auth, $r_rev);
1142    echo '</li>';
1143
1144    $l_meta = new JpegMeta(mediaFN($image, $l_rev));
1145    $r_meta = new JpegMeta(mediaFN($image, $r_rev));
1146
1147    $l_tags = media_file_tags($l_meta);
1148    $r_tags = media_file_tags($r_meta);
1149    foreach ($l_tags as $key => $l_tag) {
1150        if ($l_tag['value'] != $r_tags[$key]['value']) {
1151            $r_tags[$key]['class'] = 'highlighted';
1152            $l_tags[$key]['class'] = 'highlighted';
1153        } else if (!$l_tag['value'] || !$r_tags[$key]['value']) {
1154            unset($r_tags[$key]);
1155            unset($l_tags[$key]);
1156        }
1157    }
1158
1159    foreach(array($l_tags,$r_tags) as $tags){
1160        echo '<li><div>';
1161
1162        echo '<dl class="img_tags">';
1163        foreach($tags as $tag){
1164            $value = cleanText($tag['value']);
1165            if (!$value) $value = '-';
1166            echo '<dt>'.$lang[$tag['tag'][1]].':</dt>';
1167            echo '<dd class="'.$tag['class'].'" >';
1168            if ($tag['tag'][2] == 'date') echo dformat($value);
1169            else echo hsc($value);
1170            echo '</dd>';
1171        }
1172        echo '</dl>';
1173
1174        echo '</div></li>';
1175    }
1176
1177    echo '</ul>';
1178
1179    if ($is_img && !$fromajax) echo '</div>';
1180    if ($is_img) echo '</div>';
1181}
1182
1183/**
1184 * Prints two images side by side
1185 * and slider
1186 *
1187 * @author Kate Arzamastseva <pshns@ukr.net>
1188 * @param string $image
1189 * @param int $l_rev
1190 * @param int $r_rev
1191 * @param JpegMeta $meta
1192 */
1193function media_image_diff($image, $l_rev, $r_rev, $meta, $type) {
1194    $l_size = media_image_preview_size($image, $l_rev, $meta);
1195    $r_size = media_image_preview_size($image, $r_rev, $meta);
1196
1197    if (!$l_size || !$r_size || $l_size != $r_size || $l_size[0] < 30) return '';
1198
1199    echo '<div class="mediamanager-preview">';
1200
1201    $l_more = 'rev='.$l_rev.'&h='.$l_size[1].'&w='.$l_size[0];
1202    $r_more = 'rev='.$r_rev.'&h='.$l_size[1].'&w='.$l_size[0];
1203
1204    $l_src = ml($image, $l_more);
1205    $r_src = ml($image, $r_more);
1206
1207    // slider
1208    echo '<div id="mediamanager__'.$type.'_slider" style="max-width: '.($l_size[0]-20).'px;" ></div>';
1209
1210    // two image's in div's
1211    echo '<div id="mediamanager__diff_layout">';
1212    echo '<div id="mediamanager__diff_'.$type.'_image1" style="max-width: '.$l_size[0].'px;">';
1213    echo '<img src="'.$l_src.'" />';
1214    echo '</div>';
1215    echo '<div id="mediamanager__diff_'.$type.'_image2" style="max-width: '.$l_size[0].'px;">';
1216    echo '<img src="'.$r_src.'" />';
1217    echo '</div>';
1218    echo '</div>';
1219
1220    echo '</div>';
1221}
1222
1223/**
1224 * Restores an old revision of a media file
1225 *
1226 * @param string $image
1227 * @param int $rev
1228 * @param int $auth
1229 * @return string - file's id
1230 * @author Kate Arzamastseva <pshns@ukr.net>
1231 */
1232function media_restore($image, $rev, $auth){
1233    global $conf;
1234    if ($auth < AUTH_DELETE || !$conf['mediarevisions']) return false;
1235    $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')));
1236    if (!$image || (!file_exists(mediaFN($image)) && !$removed)) return false;
1237    if (!$rev || !file_exists(mediaFN($image, $rev))) return false;
1238    list($iext,$imime,$dl) = mimetype($image);
1239    $res = media_upload_finish(mediaFN($image, $rev),
1240        mediaFN($image),
1241        $image,
1242        $imime,
1243        true,
1244        'copy');
1245    if (is_array($res)) {
1246        msg($res[0], $res[1]);
1247        return false;
1248    }
1249    return $res;
1250}
1251
1252/**
1253 * List all files found by the search request
1254 *
1255 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1256 * @author Andreas Gohr <gohr@cosmocode.de>
1257 * @author Kate Arzamastseva <pshns@ukr.net>
1258 * @triggers MEDIA_SEARCH
1259 */
1260function media_searchlist($query,$ns,$auth=null,$fullscreen=false){
1261    global $conf;
1262    global $lang;
1263
1264    $ns = cleanID($ns);
1265
1266    if ($query) {
1267        $evdata = array(
1268                'ns'    => $ns,
1269                'data'  => array(),
1270                'query' => $query
1271                );
1272        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
1273        if ($evt->advise_before()) {
1274            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
1275            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
1276            search($evdata['data'],
1277                    $conf['mediadir'],
1278                    'search_media',
1279                    array('showmsg'=>false,'pattern'=>$pattern),
1280                    $dir);
1281        }
1282        $evt->advise_after();
1283        unset($evt);
1284    }
1285
1286    if (!$fullscreen) {
1287        echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
1288        media_searchform($ns,$query);
1289    }
1290
1291    if(!count($evdata['data'])){
1292        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
1293    }else foreach($evdata['data'] as $item){
1294        if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
1295        else media_printfile_thumbs($item,$item['perm']);
1296    }
1297}
1298
1299/**
1300 * Print action links for a file depending on filetype
1301 * and available permissions
1302 */
1303function media_fileactions($item,$auth){
1304    global $lang;
1305
1306    // view button
1307    $link = ml($item['id'],'',true);
1308    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
1309        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
1310
1311    // no further actions if not writable
1312    if(!$item['writable']) return;
1313
1314    // delete button
1315    if($auth >= AUTH_DELETE){
1316        $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
1317            '&amp;sectok='.getSecurityToken();
1318        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
1319            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
1320            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
1321    }
1322
1323    // edit button
1324    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
1325        $link = DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']);
1326        echo ' <a href="'.$link.'">'.
1327            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
1328            'title="'.$lang['metaedit'].'" class="btn" /></a>';
1329    }
1330
1331}
1332
1333/**
1334 * Formats and prints one file in the list
1335 */
1336function media_printfile($item,$auth,$jump,$display_namespace=false){
1337    global $lang;
1338    global $conf;
1339
1340    // Prepare zebra coloring
1341    // I always wanted to use this variable name :-D
1342    static $twibble = 1;
1343    $twibble *= -1;
1344    $zebra = ($twibble == -1) ? 'odd' : 'even';
1345
1346    // Automatically jump to recent action
1347    if($jump == $item['id']) {
1348        $jump = ' id="scroll__here" ';
1349    }else{
1350        $jump = '';
1351    }
1352
1353    // Prepare fileicons
1354    list($ext,$mime,$dl) = mimetype($item['file'],false);
1355    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1356    $class = 'select mediafile mf_'.$class;
1357
1358    // Prepare filename
1359    $file = utf8_decodeFN($item['file']);
1360
1361    // Prepare info
1362    $info = '';
1363    if($item['isimg']){
1364        $info .= (int) $item['meta']->getField('File.Width');
1365        $info .= '&#215;';
1366        $info .= (int) $item['meta']->getField('File.Height');
1367        $info .= ' ';
1368    }
1369    $info .= '<i>'.dformat($item['mtime']).'</i>';
1370    $info .= ' ';
1371    $info .= filesize_h($item['size']);
1372
1373    // output
1374    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
1375    if (!$display_namespace) {
1376        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1377    } else {
1378        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1379    }
1380    echo '<span class="info">('.$info.')</span>'.NL;
1381    media_fileactions($item,$auth);
1382    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1383    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1384    echo '</div>';
1385    if($item['isimg']) media_printimgdetail($item);
1386    echo '<div class="clearer"></div>'.NL;
1387    echo '</div>'.NL;
1388}
1389
1390function media_printicon($filename){
1391    list($ext,$mime,$dl) = mimetype(mediaFN($filename),false);
1392
1393    if (@file_exists(DOKU_INC.'lib/images/fileicons/'.$ext.'.png')) {
1394        $icon = DOKU_BASE.'lib/images/fileicons/'.$ext.'.png';
1395    } else {
1396        $icon = DOKU_BASE.'lib/images/fileicons/file.png';
1397    }
1398
1399    return '<img src="'.$icon.'" alt="'.$filename.'" class="icon" />';
1400
1401}
1402
1403/**
1404 * Formats and prints one file in the list in the thumbnails view
1405 *
1406 * @author Kate Arzamastseva <pshns@ukr.net>
1407 */
1408function media_printfile_thumbs($item,$auth,$jump=false){
1409    global $lang;
1410    global $conf;
1411
1412    // Prepare filename
1413    $file = utf8_decodeFN($item['file']);
1414
1415    // output
1416    echo '<li><div>';
1417
1418    if($item['isimg']) {
1419        media_printimgdetail($item, true);
1420
1421    } else {
1422        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1423            media_managerURL(array('image' => hsc($item['id']))).'"><div>';
1424        echo media_printicon($item['id']);
1425        echo '</div></a>';
1426    }
1427    //echo '<input type=checkbox />';
1428    echo '<a href="'.media_managerURL(array('image' => hsc($item['id']))).'" name=
1429        "h_:'.$item['id'].'" class="name">'.hsc($file).'</a>';
1430    if($item['isimg']){
1431        $size = '';
1432        $size .= (int) $item['meta']->getField('File.Width');
1433        $size .= '&#215;';
1434        $size .= (int) $item['meta']->getField('File.Height');
1435        echo '<span class="size">'.$size.'</span>';
1436    } else {
1437        echo '<span class="size">&nbsp;</span>';
1438    }
1439    $date = dformat($item['mtime']);
1440    echo '<span class="date">'.$date.'</span>';
1441    $filesize = filesize_h($item['size']);
1442    echo '<span class="filesize">'.$filesize.'</span>';
1443    echo '<div class="clearer"></div>';
1444    echo '</div></li>'.NL;
1445}
1446
1447/**
1448 * Prints a thumbnail and metainfos
1449 */
1450function media_printimgdetail($item, $fullscreen=false){
1451    // prepare thumbnail
1452    if (!$fullscreen) {
1453        $size_array[] = 120;
1454    } else {
1455        $size_array = array(90, 40);
1456    }
1457    foreach ($size_array as $index => $size) {
1458        $w = (int) $item['meta']->getField('File.Width');
1459        $h = (int) $item['meta']->getField('File.Height');
1460        if($w>$size || $h>$size){
1461            if (!$fullscreen) {
1462                $ratio = $item['meta']->getResizeRatio($size);
1463            } else {
1464                $ratio = $item['meta']->getResizeRatio($size,$size);
1465            }
1466            $w = floor($w * $ratio);
1467            $h = floor($h * $ratio);
1468        }
1469        $src = ml($item['id'],array('w'=>$w,'h'=>$h,'t'=>$item['mtime']));
1470        $p = array();
1471        if (!$fullscreen) {
1472            $p['width']  = $w;
1473            $p['height'] = $h;
1474        }
1475        $p['alt']    = $item['id'];
1476        $p['class']  = 'thumb';
1477        $att = buildAttributes($p);
1478
1479        // output
1480        if ($fullscreen) {
1481            echo '<a name="d_:'.$item['id'].'" class="image'.$index.'" title="'.$item['id'].'" href="'.
1482                media_managerURL(array('image' => hsc($item['id']))).'">';
1483            echo '<div><img src="'.$src.'" '.$att.' /></div>';
1484            echo '</a>';
1485        }
1486    }
1487
1488    if ($fullscreen) return '';
1489
1490    echo '<div class="detail">';
1491    echo '<div class="thumb">';
1492    echo '<a name="d_:'.$item['id'].'" class="select">';
1493    echo '<img src="'.$src.'" '.$att.' />';
1494    echo '</a>';
1495    echo '</div>';
1496
1497    // read EXIF/IPTC data
1498    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1499    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1500                'EXIF.TIFFImageDescription',
1501                'EXIF.TIFFUserComment'));
1502    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
1503    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1504
1505    // print EXIF/IPTC data
1506    if($t || $d || $k ){
1507        echo '<p>';
1508        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
1509        if($d) echo htmlspecialchars($d).'<br />';
1510        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
1511        echo '</p>';
1512    }
1513    echo '</div>';
1514}
1515
1516/**
1517 * Build link based on the current, adding/rewriting
1518 * parameters
1519 *
1520 * @author Kate Arzamastseva <pshns@ukr.net>
1521 * @param array $params
1522 * @param string $amp - separator
1523 * @return string - link
1524 */
1525function media_managerURL($params=false, $amp='&amp;', $abs=false) {
1526    global $conf;
1527    global $ID;
1528
1529    $gets = array('do' => 'media');
1530    $media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'view');
1531    foreach ($media_manager_params as $x) {
1532        if (isset($_REQUEST[$x])) $gets[$x] = $_REQUEST[$x];
1533    }
1534
1535    if ($params) {
1536        foreach ($params as $k => $v) {
1537            $gets[$k] = $v;
1538        }
1539    }
1540    unset($gets['id']);
1541    if ($gets['delete']) {
1542        unset($gets['image']);
1543        unset($gets['tab_details']);
1544    }
1545
1546    return wl($ID,$gets,$abs,$amp);
1547}
1548
1549/**
1550 * Print the media upload form if permissions are correct
1551 *
1552 * @author Andreas Gohr <andi@splitbrain.org>
1553 * @author Kate Arzamastseva <pshns@ukr.net>
1554 */
1555function media_uploadform($ns, $auth, $fullscreen = false){
1556    global $lang, $conf;
1557
1558    if($auth < AUTH_UPLOAD) {
1559        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1560        return;
1561    }
1562    $auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
1563
1564    $update = false;
1565    $id = '';
1566    if ($auth >= $auth_ow && $fullscreen && $_REQUEST['mediado'] == 'update') {
1567        $update = true;
1568        $id = cleanID($_REQUEST['image']);
1569    }
1570
1571    // The default HTML upload form
1572    $params = array('id'      => 'dw__upload',
1573                    'enctype' => 'multipart/form-data');
1574    if (!$fullscreen) {
1575        $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1576    } else {
1577        $params['action'] = media_managerURL(array('tab_files' => 'files',
1578            'tab_details' => 'view'), '&');
1579    }
1580
1581    $form = new Doku_Form($params);
1582    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
1583    $form->addElement(formSecurityToken());
1584    $form->addHidden('ns', hsc($ns));
1585    $form->addElement(form_makeOpenTag('p'));
1586    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
1587    $form->addElement(form_makeCloseTag('p'));
1588    $form->addElement(form_makeOpenTag('p'));
1589    $form->addElement(form_makeTextField('mediaid', noNS($id), $lang['txt_filename'].':', 'upload__name'));
1590    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
1591    $form->addElement(form_makeCloseTag('p'));
1592
1593    if($auth >= $auth_ow){
1594        $form->addElement(form_makeOpenTag('p'));
1595        $attrs = array();
1596        if ($update) $attrs['checked'] = 'checked';
1597        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check', $attrs));
1598        $form->addElement(form_makeCloseTag('p'));
1599    }
1600    html_form('upload', $form);
1601
1602    if ($fullscreen) {
1603        echo '<div id="mediamanager__uploader" style="display:none"></div>';
1604        return '';
1605    }
1606
1607    // prepare flashvars for multiupload
1608    $opt = array(
1609            'L_gridname'  => $lang['mu_gridname'] ,
1610            'L_gridsize'  => $lang['mu_gridsize'] ,
1611            'L_gridstat'  => $lang['mu_gridstat'] ,
1612            'L_namespace' => $lang['mu_namespace'] ,
1613            'L_overwrite' => $lang['txt_overwrt'],
1614            'L_browse'    => $lang['mu_browse'],
1615            'L_upload'    => $lang['btn_upload'],
1616            'L_toobig'    => $lang['mu_toobig'],
1617            'L_ready'     => $lang['mu_ready'],
1618            'L_done'      => $lang['mu_done'],
1619            'L_fail'      => $lang['mu_fail'],
1620            'L_authfail'  => $lang['mu_authfail'],
1621            'L_progress'  => $lang['mu_progress'],
1622            'L_filetypes' => $lang['mu_filetypes'],
1623            'L_info'      => $lang['mu_info'],
1624            'L_lasterr'   => $lang['mu_lasterr'],
1625
1626            'O_ns'        => ":$ns",
1627            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
1628            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
1629            'O_extensions'=> join('|',array_keys(getMimeTypes())),
1630            'O_overwrite' => ($auth >= AUTH_DELETE),
1631            'O_sectok'    => getSecurityToken(),
1632            'O_authtok'   => auth_createToken(),
1633            );
1634    $var = buildURLparams($opt);
1635    // output the flash uploader
1636    ?>
1637        <div id="dw__flashupload" style="display:none">
1638        <div class="upload"><?php echo $lang['mu_intro']?></div>
1639        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
1640        </div>
1641        <?php
1642}
1643
1644/**
1645 * Print the search field form
1646 *
1647 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1648 * @author Kate Arzamastseva <pshns@ukr.net>
1649 */
1650function media_searchform($ns,$query='',$fullscreen=false){
1651    global $lang;
1652
1653    // The default HTML search form
1654    $params = array('id' => 'dw__mediasearch');
1655    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1656    else $params['action'] = media_managerURL(array(), '&');
1657    $form = new Doku_Form($params);
1658    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
1659    $form->addElement(formSecurityToken());
1660    $form->addHidden('ns', $ns);
1661    if (!$fullscreen) $form->addHidden('do', 'searchlist');
1662    else $form->addHidden('mediado', 'searchlist');
1663    $form->addElement(form_makeOpenTag('p'));
1664    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1665    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1666    $form->addElement(form_makeCloseTag('p'));
1667    html_form('searchmedia', $form);
1668}
1669
1670/**
1671 * Build a tree outline of available media namespaces
1672 *
1673 * @author Andreas Gohr <andi@splitbrain.org>
1674 */
1675function media_nstree($ns){
1676    global $conf;
1677    global $lang;
1678
1679    // currently selected namespace
1680    $ns  = cleanID($ns);
1681    if(empty($ns)){
1682        global $ID;
1683        $ns = dirname(str_replace(':','/',$ID));
1684        if($ns == '.') $ns ='';
1685    }
1686    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1687
1688    $data = array();
1689    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1690
1691    // wrap a list with the root level around the other namespaces
1692    array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
1693                               'label' => '['.$lang['mediaroot'].']'));
1694
1695    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1696}
1697
1698/**
1699 * Userfunction for html_buildlist
1700 *
1701 * Prints a media namespace tree item
1702 *
1703 * @author Andreas Gohr <andi@splitbrain.org>
1704 */
1705function media_nstree_item($item){
1706    $pos   = strrpos($item['id'], ':');
1707    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1708    if(!$item['label']) $item['label'] = $label;
1709
1710    $ret  = '';
1711    if (!($_REQUEST['do'] == 'media'))
1712    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1713    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id']), 'tab_files' => 'files'))
1714        .'" class="idx_dir">';
1715    $ret .= $item['label'];
1716    $ret .= '</a>';
1717    return $ret;
1718}
1719
1720/**
1721 * Userfunction for html_buildlist
1722 *
1723 * Prints a media namespace tree item opener
1724 *
1725 * @author Andreas Gohr <andi@splitbrain.org>
1726 */
1727function media_nstree_li($item){
1728    $class='media level'.$item['level'];
1729    if($item['open']){
1730        $class .= ' open';
1731        $img   = DOKU_BASE.'lib/images/minus.gif';
1732        $alt   = '&minus;';
1733    }else{
1734        $class .= ' closed';
1735        $img   = DOKU_BASE.'lib/images/plus.gif';
1736        $alt   = '+';
1737    }
1738    // TODO: only deliver an image if it actually has a subtree...
1739    return '<li class="'.$class.'">'.
1740        '<img src="'.$img.'" alt="'.$alt.'" />';
1741}
1742
1743/**
1744 * Resizes the given image to the given size
1745 *
1746 * @author  Andreas Gohr <andi@splitbrain.org>
1747 */
1748function media_resize_image($file, $ext, $w, $h=0){
1749    global $conf;
1750
1751    $info = @getimagesize($file); //get original size
1752    if($info == false) return $file; // that's no image - it's a spaceship!
1753
1754    if(!$h) $h = round(($w * $info[1]) / $info[0]);
1755
1756    // we wont scale up to infinity
1757    if($w > 2000 || $h > 2000) return $file;
1758
1759    //cache
1760    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1761    $mtime = @filemtime($local); // 0 if not exists
1762
1763    if( $mtime > filemtime($file) ||
1764            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1765            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1766        if($conf['fperm']) chmod($local, $conf['fperm']);
1767        return $local;
1768    }
1769    //still here? resizing failed
1770    return $file;
1771}
1772
1773/**
1774 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1775 * to the wanted size
1776 *
1777 * Crops are centered horizontally but prefer the upper third of an vertical
1778 * image because most pics are more interesting in that area (rule of thirds)
1779 *
1780 * @author  Andreas Gohr <andi@splitbrain.org>
1781 */
1782function media_crop_image($file, $ext, $w, $h=0){
1783    global $conf;
1784
1785    if(!$h) $h = $w;
1786    $info = @getimagesize($file); //get original size
1787    if($info == false) return $file; // that's no image - it's a spaceship!
1788
1789    // calculate crop size
1790    $fr = $info[0]/$info[1];
1791    $tr = $w/$h;
1792    if($tr >= 1){
1793        if($tr > $fr){
1794            $cw = $info[0];
1795            $ch = (int) $info[0]/$tr;
1796        }else{
1797            $cw = (int) $info[1]*$tr;
1798            $ch = $info[1];
1799        }
1800    }else{
1801        if($tr < $fr){
1802            $cw = (int) $info[1]*$tr;
1803            $ch = $info[1];
1804        }else{
1805            $cw = $info[0];
1806            $ch = (int) $info[0]/$tr;
1807        }
1808    }
1809    // calculate crop offset
1810    $cx = (int) ($info[0]-$cw)/2;
1811    $cy = (int) ($info[1]-$ch)/3;
1812
1813    //cache
1814    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1815    $mtime = @filemtime($local); // 0 if not exists
1816
1817    if( $mtime > filemtime($file) ||
1818            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1819            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1820        if($conf['fperm']) chmod($local, $conf['fperm']);
1821        return media_resize_image($local,$ext, $w, $h);
1822    }
1823
1824    //still here? cropping failed
1825    return media_resize_image($file,$ext, $w, $h);
1826}
1827
1828/**
1829 * Download a remote file and return local filename
1830 *
1831 * returns false if download fails. Uses cached file if available and
1832 * wanted
1833 *
1834 * @author  Andreas Gohr <andi@splitbrain.org>
1835 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
1836 */
1837function media_get_from_URL($url,$ext,$cache){
1838    global $conf;
1839
1840    // if no cache or fetchsize just redirect
1841    if ($cache==0)           return false;
1842    if (!$conf['fetchsize']) return false;
1843
1844    $local = getCacheName(strtolower($url),".media.$ext");
1845    $mtime = @filemtime($local); // 0 if not exists
1846
1847    //decide if download needed:
1848    if( ($mtime == 0) ||                           // cache does not exist
1849            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
1850      ){
1851        if(media_image_download($url,$local)){
1852            return $local;
1853        }else{
1854            return false;
1855        }
1856    }
1857
1858    //if cache exists use it else
1859    if($mtime) return $local;
1860
1861    //else return false
1862    return false;
1863}
1864
1865/**
1866 * Download image files
1867 *
1868 * @author Andreas Gohr <andi@splitbrain.org>
1869 */
1870function media_image_download($url,$file){
1871    global $conf;
1872    $http = new DokuHTTPClient();
1873    $http->max_bodysize = $conf['fetchsize'];
1874    $http->timeout = 25; //max. 25 sec
1875    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1876
1877    $data = $http->get($url);
1878    if(!$data) return false;
1879
1880    $fileexists = @file_exists($file);
1881    $fp = @fopen($file,"w");
1882    if(!$fp) return false;
1883    fwrite($fp,$data);
1884    fclose($fp);
1885    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1886
1887    // check if it is really an image
1888    $info = @getimagesize($file);
1889    if(!$info){
1890        @unlink($file);
1891        return false;
1892    }
1893
1894    return true;
1895}
1896
1897/**
1898 * resize images using external ImageMagick convert program
1899 *
1900 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1901 * @author Andreas Gohr <andi@splitbrain.org>
1902 */
1903function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1904    global $conf;
1905
1906    // check if convert is configured
1907    if(!$conf['im_convert']) return false;
1908
1909    // prepare command
1910    $cmd  = $conf['im_convert'];
1911    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1912    if ($ext == 'jpg' || $ext == 'jpeg') {
1913        $cmd .= ' -quality '.$conf['jpg_quality'];
1914    }
1915    $cmd .= " $from $to";
1916
1917    @exec($cmd,$out,$retval);
1918    if ($retval == 0) return true;
1919    return false;
1920}
1921
1922/**
1923 * crop images using external ImageMagick convert program
1924 *
1925 * @author Andreas Gohr <andi@splitbrain.org>
1926 */
1927function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1928    global $conf;
1929
1930    // check if convert is configured
1931    if(!$conf['im_convert']) return false;
1932
1933    // prepare command
1934    $cmd  = $conf['im_convert'];
1935    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1936    if ($ext == 'jpg' || $ext == 'jpeg') {
1937        $cmd .= ' -quality '.$conf['jpg_quality'];
1938    }
1939    $cmd .= " $from $to";
1940
1941    @exec($cmd,$out,$retval);
1942    if ($retval == 0) return true;
1943    return false;
1944}
1945
1946/**
1947 * resize or crop images using PHP's libGD support
1948 *
1949 * @author Andreas Gohr <andi@splitbrain.org>
1950 * @author Sebastian Wienecke <s_wienecke@web.de>
1951 */
1952function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1953    global $conf;
1954
1955    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1956
1957    // check available memory
1958    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1959        return false;
1960    }
1961
1962    // create an image of the given filetype
1963    if ($ext == 'jpg' || $ext == 'jpeg'){
1964        if(!function_exists("imagecreatefromjpeg")) return false;
1965        $image = @imagecreatefromjpeg($from);
1966    }elseif($ext == 'png') {
1967        if(!function_exists("imagecreatefrompng")) return false;
1968        $image = @imagecreatefrompng($from);
1969
1970    }elseif($ext == 'gif') {
1971        if(!function_exists("imagecreatefromgif")) return false;
1972        $image = @imagecreatefromgif($from);
1973    }
1974    if(!$image) return false;
1975
1976    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1977        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1978    }
1979    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1980    if(!$newimg){
1981        imagedestroy($image);
1982        return false;
1983    }
1984
1985    //keep png alpha channel if possible
1986    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1987        imagealphablending($newimg, false);
1988        imagesavealpha($newimg,true);
1989    }
1990
1991    //keep gif transparent color if possible
1992    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1993        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1994            $transcolorindex = @imagecolortransparent($image);
1995            if($transcolorindex >= 0 ) { //transparent color exists
1996                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1997                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1998                @imagefill($newimg, 0, 0, $transcolorindex);
1999                @imagecolortransparent($newimg, $transcolorindex);
2000            }else{ //filling with white
2001                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2002                @imagefill($newimg, 0, 0, $whitecolorindex);
2003            }
2004        }else{ //filling with white
2005            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
2006            @imagefill($newimg, 0, 0, $whitecolorindex);
2007        }
2008    }
2009
2010    //try resampling first
2011    if(function_exists("imagecopyresampled")){
2012        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
2013            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2014        }
2015    }else{
2016        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
2017    }
2018
2019    $okay = false;
2020    if ($ext == 'jpg' || $ext == 'jpeg'){
2021        if(!function_exists('imagejpeg')){
2022            $okay = false;
2023        }else{
2024            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
2025        }
2026    }elseif($ext == 'png') {
2027        if(!function_exists('imagepng')){
2028            $okay = false;
2029        }else{
2030            $okay =  imagepng($newimg, $to);
2031        }
2032    }elseif($ext == 'gif') {
2033        if(!function_exists('imagegif')){
2034            $okay = false;
2035        }else{
2036            $okay = imagegif($newimg, $to);
2037        }
2038    }
2039
2040    // destroy GD image ressources
2041    if($image) imagedestroy($image);
2042    if($newimg) imagedestroy($newimg);
2043
2044    return $okay;
2045}
2046
2047/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
2048