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