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