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