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