xref: /dokuwiki/inc/media.php (revision cbe26ad6152c998c9a3290b0d321030c61dc7f1b)
13df72098SAndreas Gohr<?php
23df72098SAndreas Gohr/**
33df72098SAndreas Gohr * All output and handler function needed for the media management popup
43df72098SAndreas Gohr *
53df72098SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
63df72098SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
73df72098SAndreas Gohr */
83df72098SAndreas Gohr
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
103df72098SAndreas Gohrif(!defined('NL')) define('NL',"\n");
113df72098SAndreas Gohr
123df72098SAndreas Gohr/**
133df72098SAndreas Gohr * Lists pages which currently use a media file selected for deletion
143df72098SAndreas Gohr *
153df72098SAndreas Gohr * References uses the same visual as search results and share
163df72098SAndreas Gohr * their CSS tags except pagenames won't be links.
173df72098SAndreas Gohr *
183df72098SAndreas Gohr * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
193df72098SAndreas Gohr */
203df72098SAndreas Gohrfunction media_filesinuse($data,$id){
213df72098SAndreas Gohr    global $lang;
223df72098SAndreas Gohr    echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
233df72098SAndreas Gohr    echo '<p>'.hsc($lang['ref_inuse']).'</p>';
243df72098SAndreas Gohr
253df72098SAndreas Gohr    $hidden=0; //count of hits without read permission
263df72098SAndreas Gohr    foreach($data as $row){
27a05e297aSAndreas Gohr        if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
283df72098SAndreas Gohr            echo '<div class="search_result">';
29a05e297aSAndreas Gohr            echo '<span class="mediaref_ref">'.hsc($row).'</span>';
303df72098SAndreas Gohr            echo '</div>';
313df72098SAndreas Gohr        }else
323df72098SAndreas Gohr            $hidden++;
333df72098SAndreas Gohr    }
343df72098SAndreas Gohr    if ($hidden){
353df72098SAndreas Gohr        print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
363df72098SAndreas Gohr    }
373df72098SAndreas Gohr}
383df72098SAndreas Gohr
393df72098SAndreas Gohr/**
403df72098SAndreas Gohr * Handles the saving of image meta data
413df72098SAndreas Gohr *
423df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
433df72098SAndreas Gohr */
443df72098SAndreas Gohrfunction media_metasave($id,$auth,$data){
453df72098SAndreas Gohr    if($auth < AUTH_UPLOAD) return false;
46f2ea8432SAndreas Gohr    if(!checkSecurityToken()) return false;
473df72098SAndreas Gohr    global $lang;
480b308644SOtto Vainio    global $conf;
493df72098SAndreas Gohr    $src = mediaFN($id);
503df72098SAndreas Gohr
513df72098SAndreas Gohr    $meta = new JpegMeta($src);
523df72098SAndreas Gohr    $meta->_parseAll();
533df72098SAndreas Gohr
543df72098SAndreas Gohr    foreach($data as $key => $val){
553df72098SAndreas Gohr        $val=trim($val);
563df72098SAndreas Gohr        if(empty($val)){
573df72098SAndreas Gohr            $meta->deleteField($key);
583df72098SAndreas Gohr        }else{
593df72098SAndreas Gohr            $meta->setField($key,$val);
603df72098SAndreas Gohr        }
613df72098SAndreas Gohr    }
623df72098SAndreas Gohr
633df72098SAndreas Gohr    if($meta->save()){
640b308644SOtto Vainio        if($conf['fperm']) chmod($src, $conf['fperm']);
653df72098SAndreas Gohr        msg($lang['metasaveok'],1);
663df72098SAndreas Gohr        return $id;
673df72098SAndreas Gohr    }else{
683df72098SAndreas Gohr        msg($lang['metasaveerr'],-1);
693df72098SAndreas Gohr        return false;
703df72098SAndreas Gohr    }
713df72098SAndreas Gohr}
723df72098SAndreas Gohr
733df72098SAndreas Gohr/**
743df72098SAndreas Gohr * Display the form to edit image meta data
753df72098SAndreas Gohr *
763df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
773df72098SAndreas Gohr */
783df72098SAndreas Gohrfunction media_metaform($id,$auth){
793df72098SAndreas Gohr    if($auth < AUTH_UPLOAD) return false;
80f8121585SChris Smith    global $lang, $config_cascade;
813df72098SAndreas Gohr
823df72098SAndreas Gohr    // load the field descriptions
833df72098SAndreas Gohr    static $fields = null;
843df72098SAndreas Gohr    if(is_null($fields)){
85f8121585SChris Smith
86f8121585SChris Smith        foreach (array('default','local') as $config_group) {
87f8121585SChris Smith            if (empty($config_cascade['mediameta'][$config_group])) continue;
88f8121585SChris Smith            foreach ($config_cascade['mediameta'][$config_group] as $config_file) {
89f8121585SChris Smith                if(@file_exists($config_file)){
90f8121585SChris Smith                    include($config_file);
91d578eae7SAndreas Gohr                }
92f8121585SChris Smith            }
933df72098SAndreas Gohr        }
943df72098SAndreas Gohr    }
953df72098SAndreas Gohr
963df72098SAndreas Gohr    $src = mediaFN($id);
973df72098SAndreas Gohr
983df72098SAndreas Gohr    // output
993df72098SAndreas Gohr    echo '<h1>'.hsc(noNS($id)).'</h1>'.NL;
1003df72098SAndreas Gohr    echo '<form action="'.DOKU_BASE.'lib/exe/mediamanager.php" accept-charset="utf-8" method="post" class="meta">'.NL;
101f2ea8432SAndreas Gohr    formSecurityToken();
1023df72098SAndreas Gohr    foreach($fields as $key => $field){
1033df72098SAndreas Gohr        // get current value
1043df72098SAndreas Gohr        $tags = array($field[0]);
1053df72098SAndreas Gohr        if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
1063df72098SAndreas Gohr        $value = tpl_img_getTag($tags,'',$src);
107ca6a0701SAndreas Gohr        $value = cleanText($value);
1083df72098SAndreas Gohr
1093df72098SAndreas Gohr        // prepare attributes
1103df72098SAndreas Gohr        $p = array();
1113df72098SAndreas Gohr        $p['class'] = 'edit';
1123df72098SAndreas Gohr        $p['id']    = 'meta__'.$key;
1133df72098SAndreas Gohr        $p['name']  = 'meta['.$field[0].']';
1143df72098SAndreas Gohr
1153df72098SAndreas Gohr        // put label
1163df72098SAndreas Gohr        echo '<div class="metafield">';
1173df72098SAndreas Gohr        echo '<label for="meta__'.$key.'">';
1183df72098SAndreas Gohr        echo ($lang[$field[1]]) ? $lang[$field[1]] : $field[1];
119cf6894dfSAndreas Gohr        echo ':</label>';
1203df72098SAndreas Gohr
1213df72098SAndreas Gohr        // put input field
1223df72098SAndreas Gohr        if($field[2] == 'text'){
1233df72098SAndreas Gohr            $p['value'] = $value;
1243df72098SAndreas Gohr            $p['type']  = 'text';
1253df72098SAndreas Gohr            $att = buildAttributes($p);
1263df72098SAndreas Gohr            echo "<input $att/>".NL;
1273df72098SAndreas Gohr        }else{
1283df72098SAndreas Gohr            $att = buildAttributes($p);
1291440e523SAnika Henke            echo "<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'.NL;
1303df72098SAndreas Gohr        }
1313df72098SAndreas Gohr        echo '</div>'.NL;
1323df72098SAndreas Gohr    }
1333df72098SAndreas Gohr    echo '<div class="buttons">'.NL;
1341440e523SAnika Henke    echo '<input type="hidden" name="img" value="'.hsc($id).'" />'.NL;
1353df72098SAndreas Gohr    echo '<input name="do[save]" type="submit" value="'.$lang['btn_save'].
13607493d05SAnika Henke        '" title="'.$lang['btn_save'].' [S]" accesskey="s" class="button" />'.NL;
1373df72098SAndreas Gohr    echo '<input name="do[cancel]" type="submit" value="'.$lang['btn_cancel'].
13807493d05SAnika Henke        '" title="'.$lang['btn_cancel'].' [C]" accesskey="c" class="button" />'.NL;
1394868e1c6SAndreas Gohr    echo '</div>'.NL;
1403df72098SAndreas Gohr    echo '</form>'.NL;
1413df72098SAndreas Gohr}
1423df72098SAndreas Gohr
143666cdec5SMichael Klier/**
14487229c84SAdrian Lang * Convenience function to check if a media file is still in use
145666cdec5SMichael Klier *
146666cdec5SMichael Klier * @author Michael Klier <chi@chimeric.de>
147666cdec5SMichael Klier */
148666cdec5SMichael Klierfunction media_inuse($id) {
149666cdec5SMichael Klier    global $conf;
150666cdec5SMichael Klier    $mediareferences = array();
151666cdec5SMichael Klier    if($conf['refcheck']){
152666cdec5SMichael Klier        $mediareferences = ft_mediause($id,$conf['refshow']);
153666cdec5SMichael Klier        if(!count($mediareferences)) {
1546dae2464SAndreas Gohr            return false;
155666cdec5SMichael Klier        } else {
156666cdec5SMichael Klier            return $mediareferences;
157666cdec5SMichael Klier        }
158666cdec5SMichael Klier    } else {
159666cdec5SMichael Klier        return false;
160666cdec5SMichael Klier    }
161666cdec5SMichael Klier}
162a05e297aSAndreas Gohr
16387229c84SAdrian Langdefine('DOKU_MEDIA_DELETED', 1);
16487229c84SAdrian Langdefine('DOKU_MEDIA_NOT_AUTH', 2);
16587229c84SAdrian Langdefine('DOKU_MEDIA_INUSE', 4);
16687229c84SAdrian Langdefine('DOKU_MEDIA_EMPTY_NS', 8);
16787229c84SAdrian Lang
1683df72098SAndreas Gohr/**
1693df72098SAndreas Gohr * Handles media file deletions
1703df72098SAndreas Gohr *
1713df72098SAndreas Gohr * If configured, checks for media references before deletion
1723df72098SAndreas Gohr *
1733df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17487229c84SAdrian Lang * @return int One of: 0,
17587229c84SAdrian Lang                       DOKU_MEDIA_DELETED,
17687229c84SAdrian Lang                       DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
17787229c84SAdrian Lang                       DOKU_MEDIA_NOT_AUTH,
17887229c84SAdrian Lang                       DOKU_MEDIA_INUSE
1793df72098SAndreas Gohr */
1803df72098SAndreas Gohrfunction media_delete($id,$auth){
18187229c84SAdrian Lang    if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
18287229c84SAdrian Lang    if(media_inuse($id)) return DOKU_MEDIA_INUSE;
1833df72098SAndreas Gohr
1843df72098SAndreas Gohr    $file = mediaFN($id);
1854a961e72SMichal Kolodziejski
1864a961e72SMichal Kolodziejski    // trigger an event - MEDIA_DELETE_FILE
187666cdec5SMichael Klier    $data['id']   = $id;
1884a961e72SMichal Kolodziejski    $data['name'] = basename($file);
1894a961e72SMichal Kolodziejski    $data['path'] = $file;
1904a961e72SMichal Kolodziejski    $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
191666cdec5SMichael Klier
192666cdec5SMichael Klier    $data['unl'] = false;
193666cdec5SMichael Klier    $data['del'] = false;
1944a961e72SMichal Kolodziejski    $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
1954a961e72SMichal Kolodziejski    if ($evt->advise_before()) {
196666cdec5SMichael Klier        $data['unl'] = @unlink($file);
197666cdec5SMichael Klier        if($data['unl']){
19899c8d7f2Smichael            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE);
199666cdec5SMichael Klier            $data['del'] = io_sweepNS($id,'mediadir');
2003df72098SAndreas Gohr        }
2014a961e72SMichal Kolodziejski    }
2024a961e72SMichal Kolodziejski    $evt->advise_after();
2034a961e72SMichal Kolodziejski    unset($evt);
2044a961e72SMichal Kolodziejski
205666cdec5SMichael Klier    if($data['unl'] && $data['del']){
20687229c84SAdrian Lang        return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
2073df72098SAndreas Gohr    }
2083df72098SAndreas Gohr
20987229c84SAdrian Lang    return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
2103df72098SAndreas Gohr}
2113df72098SAndreas Gohr
2123df72098SAndreas Gohr/**
2133df72098SAndreas Gohr * Handles media file uploads
2143df72098SAndreas Gohr *
2153df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
21611d9dfa5SMichael Klier * @author Michael Klier <chi@chimeric.de>
2173df72098SAndreas Gohr * @return mixed false on error, id of the new file on success
2183df72098SAndreas Gohr */
2193df72098SAndreas Gohrfunction media_upload($ns,$auth){
220f2ea8432SAndreas Gohr    if(!checkSecurityToken()) return false;
2213df72098SAndreas Gohr    global $lang;
2223df72098SAndreas Gohr
22344409c3dSAndreas Gohr    // get file and id
2243df72098SAndreas Gohr    $id   = $_POST['id'];
2253df72098SAndreas Gohr    $file = $_FILES['upload'];
2263df72098SAndreas Gohr    if(empty($id)) $id = $file['name'];
22744409c3dSAndreas Gohr
22899766eefSAndreas Gohr    // check for errors (messages are done in lib/exe/mediamanager.php)
22999766eefSAndreas Gohr    if($file['error']) return false;
2309676dc23SAndreas Gohr
23144409c3dSAndreas Gohr    // check extensions
232ecebf3a8SAndreas Gohr    list($fext,$fmime,$dl) = mimetype($file['name']);
233ecebf3a8SAndreas Gohr    list($iext,$imime,$dl) = mimetype($id);
23444409c3dSAndreas Gohr    if($fext && !$iext){
2358cb1eb01SAndreas Gohr        // no extension specified in id - read original one
23644409c3dSAndreas Gohr        $id   .= '.'.$fext;
2378cb1eb01SAndreas Gohr        $imime = $fmime;
23844409c3dSAndreas Gohr    }elseif($fext && $fext != $iext){
23944409c3dSAndreas Gohr        // extension was changed, print warning
24044409c3dSAndreas Gohr        msg(sprintf($lang['mediaextchange'],$fext,$iext));
24144409c3dSAndreas Gohr    }
24244409c3dSAndreas Gohr
243ffb291f2SAdrian Lang    $res = media_save(array('name' => $file['tmp_name'],
244ffb291f2SAdrian Lang                            'mime' => $imime,
245ffb291f2SAdrian Lang                            'ext'  => $iext), $ns.':'.$id,
246ffb291f2SAdrian Lang                      $_REQUEST['ow'], $auth, 'move_uploaded_file');
247ffb291f2SAdrian Lang    if (is_array($res)) {
248ffb291f2SAdrian Lang        msg($res[0], $res[1]);
249ffb291f2SAdrian Lang        return false;
250ffb291f2SAdrian Lang    }
251ffb291f2SAdrian Lang    return $res;
252ffb291f2SAdrian Lang}
253ffb291f2SAdrian Lang
254ffb291f2SAdrian Lang/**
255ffb291f2SAdrian Lang * This generates an action event and delegates to _media_upload_action().
256ffb291f2SAdrian Lang * Action plugins are allowed to pre/postprocess the uploaded file.
257ffb291f2SAdrian Lang * (The triggered event is preventable.)
258ffb291f2SAdrian Lang *
259ffb291f2SAdrian Lang * Event data:
260ffb291f2SAdrian Lang * $data[0]     fn_tmp: the temporary file name (read from $_FILES)
261ffb291f2SAdrian Lang * $data[1]     fn: the file name of the uploaded file
262ffb291f2SAdrian Lang * $data[2]     id: the future directory id of the uploaded file
263ffb291f2SAdrian Lang * $data[3]     imime: the mimetype of the uploaded file
264ffb291f2SAdrian Lang * $data[4]     overwrite: if an existing file is going to be overwritten
265ffb291f2SAdrian Lang *
266ffb291f2SAdrian Lang * @triggers MEDIA_UPLOAD_FINISH
267ffb291f2SAdrian Lang */
268ffb291f2SAdrian Langfunction media_save($file, $id, $ow, $auth, $move) {
269ffb291f2SAdrian Lang    if($auth < AUTH_UPLOAD) {
270ffb291f2SAdrian Lang        return array("You don't have permissions to upload files.", -1);
271ffb291f2SAdrian Lang    }
272ffb291f2SAdrian Lang
273ffb291f2SAdrian Lang    if (!isset($file['mime']) || !isset($file['ext'])) {
274ffb291f2SAdrian Lang        list($ext, $mime) = mimetype($id);
275ffb291f2SAdrian Lang        if (!isset($file['mime'])) {
276ffb291f2SAdrian Lang            $file['mime'] = $mime;
277ffb291f2SAdrian Lang        }
278ffb291f2SAdrian Lang        if (!isset($file['ext'])) {
279ffb291f2SAdrian Lang            $file['ext'] = $ext;
280ffb291f2SAdrian Lang        }
281ffb291f2SAdrian Lang    }
282ffb291f2SAdrian Lang
283ffb291f2SAdrian Lang    global $lang;
284ffb291f2SAdrian Lang
2853df72098SAndreas Gohr    // get filename
286ffb291f2SAdrian Lang    $id   = cleanID($id,false,true);
2873df72098SAndreas Gohr    $fn   = mediaFN($id);
2883df72098SAndreas Gohr
2893df72098SAndreas Gohr    // get filetype regexp
2903df72098SAndreas Gohr    $types = array_keys(getMimeTypes());
2913df72098SAndreas Gohr    $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
2923df72098SAndreas Gohr    $regex = join('|',$types);
2933df72098SAndreas Gohr
2943df72098SAndreas Gohr    // because a temp file was created already
295ffb291f2SAdrian Lang    if(!preg_match('/\.('.$regex.')$/i',$fn)) {
296ffb291f2SAdrian Lang        return array($lang['uploadwrong'],-1);
297ffb291f2SAdrian Lang    }
298ffb291f2SAdrian Lang
2993df72098SAndreas Gohr    //check for overwrite
30099c8d7f2Smichael    $overwrite = @file_exists($fn);
301ffb291f2SAdrian Lang    if($overwrite && (!$ow || $auth < AUTH_DELETE)) {
302ffb291f2SAdrian Lang        return array($lang['uploadexist'], 0);
3033df72098SAndreas Gohr    }
3048cb1eb01SAndreas Gohr    // check for valid content
305ffb291f2SAdrian Lang    $ok = media_contentcheck($file['name'], $file['mime']);
3068cb1eb01SAndreas Gohr    if($ok == -1){
307ffb291f2SAdrian Lang        return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
3088cb1eb01SAndreas Gohr    }elseif($ok == -2){
309ffb291f2SAdrian Lang        return array($lang['uploadspam'],-1);
31026ceae18SAndreas Gohr    }elseif($ok == -3){
311ffb291f2SAdrian Lang        return array($lang['uploadxss'],-1);
3128cb1eb01SAndreas Gohr    }
3138cb1eb01SAndreas Gohr
31411d9dfa5SMichael Klier    // prepare event data
315ffb291f2SAdrian Lang    $data[0] = $file['name'];
31611d9dfa5SMichael Klier    $data[1] = $fn;
31711d9dfa5SMichael Klier    $data[2] = $id;
318ffb291f2SAdrian Lang    $data[3] = $file['mime'];
31999c8d7f2Smichael    $data[4] = $overwrite;
320ffb291f2SAdrian Lang    $data[5] = $move;
32111d9dfa5SMichael Klier
32211d9dfa5SMichael Klier    // trigger event
32311d9dfa5SMichael Klier    return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
32411d9dfa5SMichael Klier}
32511d9dfa5SMichael Klier
32611d9dfa5SMichael Klier/**
32711d9dfa5SMichael Klier * Callback adapter for media_upload_finish()
32811d9dfa5SMichael Klier * @author Michael Klier <chi@chimeric.de>
32911d9dfa5SMichael Klier */
33011d9dfa5SMichael Klierfunction _media_upload_action($data) {
33111d9dfa5SMichael Klier    // fixme do further sanity tests of given data?
332ffb291f2SAdrian Lang    if(is_array($data) && count($data)===6) {
333ffb291f2SAdrian Lang        return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
33411d9dfa5SMichael Klier    } else {
33511d9dfa5SMichael Klier        return false; //callback error
33611d9dfa5SMichael Klier    }
33711d9dfa5SMichael Klier}
33811d9dfa5SMichael Klier
33911d9dfa5SMichael Klier/**
34011d9dfa5SMichael Klier * Saves an uploaded media file
34111d9dfa5SMichael Klier *
34211d9dfa5SMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
34311d9dfa5SMichael Klier * @author Michael Klier <chi@chimeric.de>
344*cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
34511d9dfa5SMichael Klier */
346ffb291f2SAdrian Langfunction media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
34711d9dfa5SMichael Klier    global $conf;
34811d9dfa5SMichael Klier    global $lang;
34911d9dfa5SMichael Klier
350e4f389efSKate Arzamastseva    $old = @filemtime($fn);
351*cbe26ad6SKate Arzamastseva    $oldRev = getRevisions($id, -1, 1, 1024, true); // from changelog
352*cbe26ad6SKate Arzamastseva    $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
353*cbe26ad6SKate Arzamastseva    if(!@file_exists(mediaFN($id, $old)) && @file_exists($fn) && $old>=$oldRev) {
354e4f389efSKate Arzamastseva        // add old revision to the attic if missing
355*cbe26ad6SKate Arzamastseva        media_saveOldRevision($id);
356e4f389efSKate Arzamastseva    }
357e4f389efSKate Arzamastseva
3583df72098SAndreas Gohr    // prepare directory
359cc7d0c94SBen Coburn    io_createNamespace($id, 'media');
36011d9dfa5SMichael Klier
361ffb291f2SAdrian Lang    if($move($fn_tmp, $fn)) {
36274400ea5SBen Coburn        // Set the correct permission here.
36374400ea5SBen Coburn        // Always chmod media because they may be saved with different permissions than expected from the php umask.
36474400ea5SBen Coburn        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
36574400ea5SBen Coburn        chmod($fn, $conf['fmode']);
3663df72098SAndreas Gohr        msg($lang['uploadsucc'],1);
36775030359SAndreas Gohr        media_notify($id,$fn,$imime);
36899c8d7f2Smichael        // add a log entry to the media changelog
36999c8d7f2Smichael        if ($overwrite) {
37099c8d7f2Smichael            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_EDIT);
37199c8d7f2Smichael        } else {
37299c8d7f2Smichael            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_CREATE);
37399c8d7f2Smichael        }
3743df72098SAndreas Gohr        return $id;
3753df72098SAndreas Gohr    }else{
376ffb291f2SAdrian Lang        return array($lang['uploadfail'],-1);
3773df72098SAndreas Gohr    }
3783df72098SAndreas Gohr}
3793df72098SAndreas Gohr
3808cb1eb01SAndreas Gohr/**
381*cbe26ad6SKate Arzamastseva * Moves the current version of media file to the media_attic
382*cbe26ad6SKate Arzamastseva * directory
383*cbe26ad6SKate Arzamastseva *
384*cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
385*cbe26ad6SKate Arzamastseva * @param string $id
386*cbe26ad6SKate Arzamastseva * @return int - revision date
387e4f389efSKate Arzamastseva */
388*cbe26ad6SKate Arzamastsevafunction media_saveOldRevision($id){
389e4f389efSKate Arzamastseva    global $conf;
390e4f389efSKate Arzamastseva    $oldf = mediaFN($id);
391e4f389efSKate Arzamastseva    if(!@file_exists($oldf)) return '';
392e4f389efSKate Arzamastseva    $date = filemtime($oldf);
393e4f389efSKate Arzamastseva    $newf = mediaFN($id,$date);
394e4f389efSKate Arzamastseva    io_makeFileDir($newf);
395*cbe26ad6SKate Arzamastseva    if(copy($oldf, $newf)) {
396e4f389efSKate Arzamastseva        // Set the correct permission here.
397e4f389efSKate Arzamastseva        // Always chmod media because they may be saved with different permissions than expected from the php umask.
398e4f389efSKate Arzamastseva        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
399e4f389efSKate Arzamastseva        chmod($newf, $conf['fmode']);
400e4f389efSKate Arzamastseva    }
401e4f389efSKate Arzamastseva    return $date;
402e4f389efSKate Arzamastseva}
403e4f389efSKate Arzamastseva
404e4f389efSKate Arzamastseva/**
4058cb1eb01SAndreas Gohr * This function checks if the uploaded content is really what the
40626ceae18SAndreas Gohr * mimetype says it is. We also do spam checking for text types here.
4078cb1eb01SAndreas Gohr *
4088cb1eb01SAndreas Gohr * We need to do this stuff because we can not rely on the browser
4098cb1eb01SAndreas Gohr * to do this check correctly. Yes, IE is broken as usual.
4108cb1eb01SAndreas Gohr *
4118cb1eb01SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
41226ceae18SAndreas Gohr * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
4138cb1eb01SAndreas Gohr * @fixme  check all 26 magic IE filetypes here?
4148cb1eb01SAndreas Gohr */
4158cb1eb01SAndreas Gohrfunction media_contentcheck($file,$mime){
41626ceae18SAndreas Gohr    global $conf;
41726ceae18SAndreas Gohr    if($conf['iexssprotect']){
41826ceae18SAndreas Gohr        $fh = @fopen($file, 'rb');
41926ceae18SAndreas Gohr        if($fh){
42026ceae18SAndreas Gohr            $bytes = fread($fh, 256);
42126ceae18SAndreas Gohr            fclose($fh);
42226ceae18SAndreas Gohr            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
42326ceae18SAndreas Gohr                return -3;
42426ceae18SAndreas Gohr            }
42526ceae18SAndreas Gohr        }
42626ceae18SAndreas Gohr    }
4278cb1eb01SAndreas Gohr    if(substr($mime,0,6) == 'image/'){
4288cb1eb01SAndreas Gohr        $info = @getimagesize($file);
4298cb1eb01SAndreas Gohr        if($mime == 'image/gif' && $info[2] != 1){
4308cb1eb01SAndreas Gohr            return -1;
4318cb1eb01SAndreas Gohr        }elseif($mime == 'image/jpeg' && $info[2] != 2){
4328cb1eb01SAndreas Gohr            return -1;
4338cb1eb01SAndreas Gohr        }elseif($mime == 'image/png' && $info[2] != 3){
4348cb1eb01SAndreas Gohr            return -1;
4358cb1eb01SAndreas Gohr        }
4368cb1eb01SAndreas Gohr        # fixme maybe check other images types as well
4378cb1eb01SAndreas Gohr    }elseif(substr($mime,0,5) == 'text/'){
4388cb1eb01SAndreas Gohr        global $TEXT;
4398cb1eb01SAndreas Gohr        $TEXT = io_readFile($file);
4408cb1eb01SAndreas Gohr        if(checkwordblock()){
4418cb1eb01SAndreas Gohr            return -2;
4428cb1eb01SAndreas Gohr        }
4438cb1eb01SAndreas Gohr    }
4448cb1eb01SAndreas Gohr    return 0;
4458cb1eb01SAndreas Gohr}
4463df72098SAndreas Gohr
4473df72098SAndreas Gohr/**
44875030359SAndreas Gohr * Send a notify mail on uploads
44975030359SAndreas Gohr *
45075030359SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
45175030359SAndreas Gohr */
45275030359SAndreas Gohrfunction media_notify($id,$file,$mime){
45375030359SAndreas Gohr    global $lang;
45475030359SAndreas Gohr    global $conf;
455de3eb1d7SAdrian Lang    global $INFO;
45675030359SAndreas Gohr    if(empty($conf['notify'])) return; //notify enabled?
45775030359SAndreas Gohr
4582f9daf16SAndreas Gohr    $ip = clientIP();
4592f9daf16SAndreas Gohr
46075030359SAndreas Gohr    $text = rawLocale('uploadmail');
461f2263577SAndreas Gohr    $text = str_replace('@DATE@',dformat(),$text);
46275030359SAndreas Gohr    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
4632f9daf16SAndreas Gohr    $text = str_replace('@IPADDRESS@',$ip,$text);
4642f9daf16SAndreas Gohr    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
46575030359SAndreas Gohr    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
46675030359SAndreas Gohr    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
46775030359SAndreas Gohr    $text = str_replace('@MIME@',$mime,$text);
46855b2b31bSAndreas Gohr    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
46975030359SAndreas Gohr    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
47075030359SAndreas Gohr
47175030359SAndreas Gohr    $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
47275030359SAndreas Gohr
4735ec3fefcSAndreas Gohr    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
47475030359SAndreas Gohr}
47575030359SAndreas Gohr
47675030359SAndreas Gohr/**
4773df72098SAndreas Gohr * List all files in a given Media namespace
4783df72098SAndreas Gohr */
4793df72098SAndreas Gohrfunction media_filelist($ns,$auth=null,$jump=''){
4803df72098SAndreas Gohr    global $conf;
4813df72098SAndreas Gohr    global $lang;
4823df72098SAndreas Gohr    $ns = cleanID($ns);
4833df72098SAndreas Gohr
4843df72098SAndreas Gohr    // check auth our self if not given (needed for ajax calls)
4853df72098SAndreas Gohr    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
4863df72098SAndreas Gohr
4876c48a22eSAndreas Gohr    echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
4883df72098SAndreas Gohr
4893df72098SAndreas Gohr    if($auth < AUTH_READ){
4903df72098SAndreas Gohr        // FIXME: print permission warning here instead?
4913df72098SAndreas Gohr        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
49256fe6664SAndreas Gohr    }else{
4933df72098SAndreas Gohr        media_uploadform($ns, $auth);
4943df72098SAndreas Gohr
4953df72098SAndreas Gohr        $dir = utf8_encodeFN(str_replace(':','/',$ns));
4963df72098SAndreas Gohr        $data = array();
4971a7f560eSAndreas Gohr        search($data,$conf['mediadir'],'search_media',
4981a7f560eSAndreas Gohr                array('showmsg'=>true,'depth'=>1),$dir);
4993df72098SAndreas Gohr
5003df72098SAndreas Gohr        if(!count($data)){
5013df72098SAndreas Gohr            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
50256fe6664SAndreas Gohr        }else foreach($data as $item){
5033df72098SAndreas Gohr            media_printfile($item,$auth,$jump);
5043df72098SAndreas Gohr        }
50556fe6664SAndreas Gohr    }
506c9f56829SAndreas Gohr    media_searchform($ns);
5073df72098SAndreas Gohr}
5083df72098SAndreas Gohr
5093df72098SAndreas Gohr/**
510bf1f3ac4Ssarnowski * List all files found by the search request
511c9f56829SAndreas Gohr *
512c9f56829SAndreas Gohr * @author Tobias Sarnowski <sarnowski@cosmocode.de>
513c9f56829SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
514c9f56829SAndreas Gohr * @triggers MEDIA_SEARCH
515bf1f3ac4Ssarnowski */
516c9f56829SAndreas Gohrfunction media_searchlist($query,$ns,$auth=null){
517bf1f3ac4Ssarnowski    global $conf;
518bf1f3ac4Ssarnowski    global $lang;
519bf1f3ac4Ssarnowski    $ns = cleanID($ns);
520bf1f3ac4Ssarnowski
521c9f56829SAndreas Gohr    if ($query) {
52256fe6664SAndreas Gohr        $evdata = array(
52356fe6664SAndreas Gohr                'ns'    => $ns,
52456fe6664SAndreas Gohr                'data'  => array(),
52556fe6664SAndreas Gohr                'query' => $query
52656fe6664SAndreas Gohr                );
52756fe6664SAndreas Gohr        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
528bf1f3ac4Ssarnowski        if ($evt->advise_before()) {
52956fe6664SAndreas Gohr            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
53056fe6664SAndreas Gohr            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
53156fe6664SAndreas Gohr            search($evdata['data'],
53256fe6664SAndreas Gohr                    $conf['mediadir'],
53356fe6664SAndreas Gohr                    'search_media',
53456fe6664SAndreas Gohr                    array('showmsg'=>false,'pattern'=>$pattern),
53556fe6664SAndreas Gohr                    $dir);
536bf1f3ac4Ssarnowski        }
537bf1f3ac4Ssarnowski        $evt->advise_after();
538bf1f3ac4Ssarnowski        unset($evt);
53956fe6664SAndreas Gohr    }
540bf1f3ac4Ssarnowski
54156fe6664SAndreas Gohr    echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
54256fe6664SAndreas Gohr    media_searchform($ns,$query);
54356fe6664SAndreas Gohr
54456fe6664SAndreas Gohr    if(!count($evdata['data'])){
545bf1f3ac4Ssarnowski        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
54656fe6664SAndreas Gohr    }else foreach($evdata['data'] as $item){
54756fe6664SAndreas Gohr        media_printfile($item,$item['perm'],'',true);
548bf1f3ac4Ssarnowski    }
549bf1f3ac4Ssarnowski}
550bf1f3ac4Ssarnowski
551bf1f3ac4Ssarnowski/**
5523df72098SAndreas Gohr * Print action links for a file depending on filetype
5533df72098SAndreas Gohr * and available permissions
5543df72098SAndreas Gohr */
5553df72098SAndreas Gohrfunction media_fileactions($item,$auth){
5563df72098SAndreas Gohr    global $lang;
5573df72098SAndreas Gohr
558cf6894dfSAndreas Gohr    // view button
559cf6894dfSAndreas Gohr    $link = ml($item['id'],'',true);
560cf6894dfSAndreas Gohr    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
561cf6894dfSAndreas Gohr        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
562cf6894dfSAndreas Gohr
563cf6894dfSAndreas Gohr    // no further actions if not writable
5643df72098SAndreas Gohr    if(!$item['writable']) return;
5653df72098SAndreas Gohr
5663df72098SAndreas Gohr    // delete button
5673df72098SAndreas Gohr    if($auth >= AUTH_DELETE){
568f2ea8432SAndreas Gohr        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
569c55fac47SMichael Klier            '&amp;sectok='.getSecurityToken().'" class="btn_media_delete" title="'.$item['id'].'">'.
5703df72098SAndreas Gohr            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
5713df72098SAndreas Gohr            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
5723df72098SAndreas Gohr    }
5733df72098SAndreas Gohr
5743df72098SAndreas Gohr    // edit button
5753df72098SAndreas Gohr    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
5763df72098SAndreas Gohr        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']).'">'.
5773df72098SAndreas Gohr            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
5783df72098SAndreas Gohr            'title="'.$lang['metaedit'].'" class="btn" /></a>';
5793df72098SAndreas Gohr    }
5803df72098SAndreas Gohr
5813df72098SAndreas Gohr}
5823df72098SAndreas Gohr
5833df72098SAndreas Gohr/**
5843df72098SAndreas Gohr * Formats and prints one file in the list
5853df72098SAndreas Gohr */
586bf1f3ac4Ssarnowskifunction media_printfile($item,$auth,$jump,$display_namespace=false){
58764c9cfd5SAndreas Gohr    global $lang;
5885e7fa82eSAndreas Gohr    global $conf;
58964c9cfd5SAndreas Gohr
5903df72098SAndreas Gohr    // Prepare zebra coloring
5913df72098SAndreas Gohr    // I always wanted to use this variable name :-D
5923df72098SAndreas Gohr    static $twibble = 1;
5933df72098SAndreas Gohr    $twibble *= -1;
5943df72098SAndreas Gohr    $zebra = ($twibble == -1) ? 'odd' : 'even';
5953df72098SAndreas Gohr
5963df72098SAndreas Gohr    // Automatically jump to recent action
5973df72098SAndreas Gohr    if($jump == $item['id']) {
5983df72098SAndreas Gohr        $jump = ' id="scroll__here" ';
5993df72098SAndreas Gohr    }else{
6003df72098SAndreas Gohr        $jump = '';
6013df72098SAndreas Gohr    }
6023df72098SAndreas Gohr
6033df72098SAndreas Gohr    // Prepare fileicons
60427bf7924STom N Harris    list($ext,$mime,$dl) = mimetype($item['file'],false);
6053df72098SAndreas Gohr    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
6063df72098SAndreas Gohr    $class = 'select mediafile mf_'.$class;
6073df72098SAndreas Gohr
6083df72098SAndreas Gohr    // Prepare filename
6093df72098SAndreas Gohr    $file = utf8_decodeFN($item['file']);
6103df72098SAndreas Gohr
6113df72098SAndreas Gohr    // Prepare info
6123df72098SAndreas Gohr    $info = '';
6133df72098SAndreas Gohr    if($item['isimg']){
6143df72098SAndreas Gohr        $info .= (int) $item['meta']->getField('File.Width');
6153df72098SAndreas Gohr        $info .= '&#215;';
6163df72098SAndreas Gohr        $info .= (int) $item['meta']->getField('File.Height');
6173df72098SAndreas Gohr        $info .= ' ';
6183df72098SAndreas Gohr    }
619f2263577SAndreas Gohr    $info .= '<i>'.dformat($item['mtime']).'</i>';
6205e7fa82eSAndreas Gohr    $info .= ' ';
6213df72098SAndreas Gohr    $info .= filesize_h($item['size']);
6223df72098SAndreas Gohr
623c9f56829SAndreas Gohr    // output
6243df72098SAndreas Gohr    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
625c9f56829SAndreas Gohr    if (!$display_namespace) {
626c9f56829SAndreas Gohr        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
627c9f56829SAndreas Gohr    } else {
628c9f56829SAndreas Gohr        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
629c9f56829SAndreas Gohr    }
6303df72098SAndreas Gohr    echo '<span class="info">('.$info.')</span>'.NL;
6313df72098SAndreas Gohr    media_fileactions($item,$auth);
632f495da32SAnika Henke    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
6330b173dceSAndreas Gohr    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
63464c9cfd5SAndreas Gohr    echo '</div>';
6353df72098SAndreas Gohr    if($item['isimg']) media_printimgdetail($item);
6363df72098SAndreas Gohr    echo '<div class="clearer"></div>'.NL;
6373df72098SAndreas Gohr    echo '</div>'.NL;
6383df72098SAndreas Gohr}
6393df72098SAndreas Gohr
6403df72098SAndreas Gohr/**
6413df72098SAndreas Gohr * Prints a thumbnail and metainfos
6423df72098SAndreas Gohr */
6433df72098SAndreas Gohrfunction media_printimgdetail($item){
6443df72098SAndreas Gohr    // prepare thumbnail
6453df72098SAndreas Gohr    $w = (int) $item['meta']->getField('File.Width');
6463df72098SAndreas Gohr    $h = (int) $item['meta']->getField('File.Height');
6473df72098SAndreas Gohr    if($w>120 || $h>120){
6483df72098SAndreas Gohr        $ratio = $item['meta']->getResizeRatio(120);
6493df72098SAndreas Gohr        $w = floor($w * $ratio);
6503df72098SAndreas Gohr        $h = floor($h * $ratio);
6513df72098SAndreas Gohr    }
6523df72098SAndreas Gohr    $src = ml($item['id'],array('w'=>$w,'h'=>$h));
6533df72098SAndreas Gohr    $p = array();
6543df72098SAndreas Gohr    $p['width']  = $w;
6553df72098SAndreas Gohr    $p['height'] = $h;
6563df72098SAndreas Gohr    $p['alt']    = $item['id'];
6573df72098SAndreas Gohr    $p['class']  = 'thumb';
6583df72098SAndreas Gohr    $att = buildAttributes($p);
6593df72098SAndreas Gohr
6603df72098SAndreas Gohr    // output
6613df72098SAndreas Gohr    echo '<div class="detail">';
6623df72098SAndreas Gohr    echo '<div class="thumb">';
663b166ccbcSAndreas Gohr    echo '<a name="d_:'.$item['id'].'" class="select">';
6643df72098SAndreas Gohr    echo '<img src="'.$src.'" '.$att.' />';
6653df72098SAndreas Gohr    echo '</a>';
6663df72098SAndreas Gohr    echo '</div>';
6673df72098SAndreas Gohr
6683df72098SAndreas Gohr    // read EXIF/IPTC data
66949ac3837Shakan.sandell    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
6700b173dceSAndreas Gohr    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
6713df72098SAndreas Gohr                'EXIF.TIFFImageDescription',
6723df72098SAndreas Gohr                'EXIF.TIFFUserComment'));
6730b173dceSAndreas Gohr    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
67449ac3837Shakan.sandell    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
6753df72098SAndreas Gohr
6760b173dceSAndreas Gohr    // print EXIF/IPTC data
6770b173dceSAndreas Gohr    if($t || $d || $k ){
6780b173dceSAndreas Gohr        echo '<p>';
6790b173dceSAndreas Gohr        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
6800b173dceSAndreas Gohr        if($d) echo htmlspecialchars($d).'<br />';
6810b173dceSAndreas Gohr        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
6823df72098SAndreas Gohr        echo '</p>';
6830b173dceSAndreas Gohr    }
6843df72098SAndreas Gohr    echo '</div>';
6853df72098SAndreas Gohr}
6863df72098SAndreas Gohr
6873df72098SAndreas Gohr/**
6883df72098SAndreas Gohr * Print the media upload form if permissions are correct
6893df72098SAndreas Gohr *
6903df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6913df72098SAndreas Gohr */
6923df72098SAndreas Gohrfunction media_uploadform($ns, $auth){
6933df72098SAndreas Gohr    global $lang;
6943df72098SAndreas Gohr
6953df72098SAndreas Gohr    if($auth < AUTH_UPLOAD) return; //fixme print info on missing permissions?
6963df72098SAndreas Gohr
697d00ec455SAndreas Gohr    // The default HTML upload form
698e351c80dSAdrian Lang    $form = new Doku_Form(array('id'      => 'dw__upload',
699e351c80dSAdrian Lang                                'action'  => DOKU_BASE.'lib/exe/mediamanager.php',
700e351c80dSAdrian Lang                                'enctype' => 'multipart/form-data'));
701d00ec455SAndreas Gohr    $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
7029f5dde7fSMichael Klier    $form->addElement(formSecurityToken());
7039f5dde7fSMichael Klier    $form->addHidden('ns', hsc($ns));
7049f5dde7fSMichael Klier    $form->addElement(form_makeOpenTag('p'));
7059f5dde7fSMichael Klier    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
7069f5dde7fSMichael Klier    $form->addElement(form_makeCloseTag('p'));
7079f5dde7fSMichael Klier    $form->addElement(form_makeOpenTag('p'));
7089f5dde7fSMichael Klier    $form->addElement(form_makeTextField('id', '', $lang['txt_filename'].':', 'upload__name'));
7099f5dde7fSMichael Klier    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
7109f5dde7fSMichael Klier    $form->addElement(form_makeCloseTag('p'));
711cf6894dfSAndreas Gohr
7129f5dde7fSMichael Klier    if($auth >= AUTH_DELETE){
7139f5dde7fSMichael Klier        $form->addElement(form_makeOpenTag('p'));
7149f5dde7fSMichael Klier        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check'));
7159f5dde7fSMichael Klier        $form->addElement(form_makeCloseTag('p'));
7163df72098SAndreas Gohr    }
7179f5dde7fSMichael Klier    html_form('upload', $form);
718d00ec455SAndreas Gohr
719d00ec455SAndreas Gohr    // prepare flashvars for multiupload
720d00ec455SAndreas Gohr    $opt = array(
721d00ec455SAndreas Gohr            'L_gridname'  => $lang['mu_gridname'] ,
722d00ec455SAndreas Gohr            'L_gridsize'  => $lang['mu_gridsize'] ,
723d00ec455SAndreas Gohr            'L_gridstat'  => $lang['mu_gridstat'] ,
724d00ec455SAndreas Gohr            'L_namespace' => $lang['mu_namespace'] ,
725d00ec455SAndreas Gohr            'L_overwrite' => $lang['txt_overwrt'],
726d00ec455SAndreas Gohr            'L_browse'    => $lang['mu_browse'],
727d00ec455SAndreas Gohr            'L_upload'    => $lang['btn_upload'],
728d00ec455SAndreas Gohr            'L_toobig'    => $lang['mu_toobig'],
729d00ec455SAndreas Gohr            'L_ready'     => $lang['mu_ready'],
730d00ec455SAndreas Gohr            'L_done'      => $lang['mu_done'],
731d00ec455SAndreas Gohr            'L_fail'      => $lang['mu_fail'],
732d00ec455SAndreas Gohr            'L_authfail'  => $lang['mu_authfail'],
733d00ec455SAndreas Gohr            'L_progress'  => $lang['mu_progress'],
734d00ec455SAndreas Gohr            'L_filetypes' => $lang['mu_filetypes'],
73558b091deSAndreas Gohr            'L_info'      => $lang['mu_info'],
73658b091deSAndreas Gohr            'L_lasterr'   => $lang['mu_lasterr'],
737d00ec455SAndreas Gohr
738d00ec455SAndreas Gohr            'O_ns'        => ":$ns",
739d00ec455SAndreas Gohr            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
74058b091deSAndreas Gohr            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
741d00ec455SAndreas Gohr            'O_extensions'=> join('|',array_keys(getMimeTypes())),
742d00ec455SAndreas Gohr            'O_overwrite' => ($auth >= AUTH_DELETE),
743d00ec455SAndreas Gohr            'O_sectok'    => getSecurityToken(),
744d00ec455SAndreas Gohr            'O_authtok'   => auth_createToken(),
745d00ec455SAndreas Gohr            );
7468c8dd6eaSAndreas Gohr    $var = buildURLparams($opt);
747d00ec455SAndreas Gohr    // output the flash uploader
748d00ec455SAndreas Gohr    ?>
749d00ec455SAndreas Gohr        <div id="dw__flashupload" style="display:none">
750d00ec455SAndreas Gohr        <div class="upload"><?php echo $lang['mu_intro']?></div>
751d4c61e61SAndreas Gohr        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
752d00ec455SAndreas Gohr        </div>
753d00ec455SAndreas Gohr        <?php
7549f5dde7fSMichael Klier}
7553df72098SAndreas Gohr
7563df72098SAndreas Gohr/**
757bf1f3ac4Ssarnowski * Print the search field form
758bf1f3ac4Ssarnowski *
759bf1f3ac4Ssarnowski * @author Tobias Sarnowski <sarnowski@cosmocode.de>
760bf1f3ac4Ssarnowski */
761c9f56829SAndreas Gohrfunction media_searchform($ns,$query=''){
762bf1f3ac4Ssarnowski    global $lang;
763bf1f3ac4Ssarnowski
764bf1f3ac4Ssarnowski    // The default HTML search form
765e351c80dSAdrian Lang    $form = new Doku_Form(array('id' => 'dw__mediasearch', 'action' => DOKU_BASE.'lib/exe/mediamanager.php'));
766bf1f3ac4Ssarnowski    $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
767bf1f3ac4Ssarnowski    $form->addElement(formSecurityToken());
768c9f56829SAndreas Gohr    $form->addHidden('ns', $ns);
769c9f56829SAndreas Gohr    $form->addHidden('do', 'searchlist');
770bf1f3ac4Ssarnowski    $form->addElement(form_makeOpenTag('p'));
77156fe6664SAndreas Gohr    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
772bf1f3ac4Ssarnowski    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
773bf1f3ac4Ssarnowski    $form->addElement(form_makeCloseTag('p'));
774bf1f3ac4Ssarnowski    html_form('searchmedia', $form);
775bf1f3ac4Ssarnowski}
776bf1f3ac4Ssarnowski
777bf1f3ac4Ssarnowski/**
7783df72098SAndreas Gohr * Build a tree outline of available media namespaces
7793df72098SAndreas Gohr *
7803df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7813df72098SAndreas Gohr */
7823df72098SAndreas Gohrfunction media_nstree($ns){
7833df72098SAndreas Gohr    global $conf;
784256ca81eSAndreas Gohr    global $lang;
7853df72098SAndreas Gohr
7863df72098SAndreas Gohr    // currently selected namespace
7873df72098SAndreas Gohr    $ns  = cleanID($ns);
7883df72098SAndreas Gohr    if(empty($ns)){
789de3eb1d7SAdrian Lang        global $ID;
7903df72098SAndreas Gohr        $ns = dirname(str_replace(':','/',$ID));
7913df72098SAndreas Gohr        if($ns == '.') $ns ='';
7923df72098SAndreas Gohr    }
7933df72098SAndreas Gohr    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
7943df72098SAndreas Gohr
7953df72098SAndreas Gohr    $data = array();
796ee7b5a62SAndreas Gohr    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
7973df72098SAndreas Gohr
7983df72098SAndreas Gohr    // wrap a list with the root level around the other namespaces
799256ca81eSAndreas Gohr    $item = array( 'level' => 0, 'id' => '',
800256ca81eSAndreas Gohr            'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
8013df72098SAndreas Gohr
8023df72098SAndreas Gohr    echo '<ul class="idx">';
8033df72098SAndreas Gohr    echo media_nstree_li($item);
8043df72098SAndreas Gohr    echo media_nstree_item($item);
8053df72098SAndreas Gohr    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
8063df72098SAndreas Gohr    echo '</li>';
8073df72098SAndreas Gohr    echo '</ul>';
8083df72098SAndreas Gohr}
8093df72098SAndreas Gohr
8103df72098SAndreas Gohr/**
8113df72098SAndreas Gohr * Userfunction for html_buildlist
8123df72098SAndreas Gohr *
8133df72098SAndreas Gohr * Prints a media namespace tree item
8143df72098SAndreas Gohr *
8153df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8163df72098SAndreas Gohr */
8173df72098SAndreas Gohrfunction media_nstree_item($item){
8183df72098SAndreas Gohr    $pos   = strrpos($item['id'], ':');
8193df72098SAndreas Gohr    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
8203df72098SAndreas Gohr    if(!$item['label']) $item['label'] = $label;
8213df72098SAndreas Gohr
8223df72098SAndreas Gohr    $ret  = '';
8233df72098SAndreas Gohr    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
8243df72098SAndreas Gohr    $ret .= $item['label'];
8253df72098SAndreas Gohr    $ret .= '</a>';
8263df72098SAndreas Gohr    return $ret;
8273df72098SAndreas Gohr}
8283df72098SAndreas Gohr
8293df72098SAndreas Gohr/**
8303df72098SAndreas Gohr * Userfunction for html_buildlist
8313df72098SAndreas Gohr *
8323df72098SAndreas Gohr * Prints a media namespace tree item opener
8333df72098SAndreas Gohr *
8343df72098SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8353df72098SAndreas Gohr */
8363df72098SAndreas Gohrfunction media_nstree_li($item){
8373df72098SAndreas Gohr    $class='media level'.$item['level'];
8383df72098SAndreas Gohr    if($item['open']){
8393df72098SAndreas Gohr        $class .= ' open';
8403df72098SAndreas Gohr        $img   = DOKU_BASE.'lib/images/minus.gif';
8417af1b404SAnika Henke        $alt   = '&minus;';
8423df72098SAndreas Gohr    }else{
8433df72098SAndreas Gohr        $class .= ' closed';
8443df72098SAndreas Gohr        $img   = DOKU_BASE.'lib/images/plus.gif';
8457af1b404SAnika Henke        $alt   = '+';
8463df72098SAndreas Gohr    }
847231b8c34SPierre Spring    // TODO: only deliver an image if it actually has a subtree...
8483df72098SAndreas Gohr    return '<li class="'.$class.'">'.
8497af1b404SAnika Henke        '<img src="'.$img.'" alt="'.$alt.'" />';
8503df72098SAndreas Gohr}
85113c08e2fSMichael Klier
85213c08e2fSMichael Klier/**
85313c08e2fSMichael Klier * Resizes the given image to the given size
85413c08e2fSMichael Klier *
85513c08e2fSMichael Klier * @author  Andreas Gohr <andi@splitbrain.org>
85613c08e2fSMichael Klier */
85713c08e2fSMichael Klierfunction media_resize_image($file, $ext, $w, $h=0){
85813c08e2fSMichael Klier    global $conf;
85913c08e2fSMichael Klier
86013c08e2fSMichael Klier    $info = @getimagesize($file); //get original size
86113c08e2fSMichael Klier    if($info == false) return $file; // that's no image - it's a spaceship!
86213c08e2fSMichael Klier
86313c08e2fSMichael Klier    if(!$h) $h = round(($w * $info[1]) / $info[0]);
86413c08e2fSMichael Klier
86513c08e2fSMichael Klier    // we wont scale up to infinity
86613c08e2fSMichael Klier    if($w > 2000 || $h > 2000) return $file;
86713c08e2fSMichael Klier
86813c08e2fSMichael Klier    //cache
86913c08e2fSMichael Klier    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
87013c08e2fSMichael Klier    $mtime = @filemtime($local); // 0 if not exists
87113c08e2fSMichael Klier
87213c08e2fSMichael Klier    if( $mtime > filemtime($file) ||
87313c08e2fSMichael Klier            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
87413c08e2fSMichael Klier            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
87513c08e2fSMichael Klier        if($conf['fperm']) chmod($local, $conf['fperm']);
87613c08e2fSMichael Klier        return $local;
87713c08e2fSMichael Klier    }
87813c08e2fSMichael Klier    //still here? resizing failed
87913c08e2fSMichael Klier    return $file;
88013c08e2fSMichael Klier}
88113c08e2fSMichael Klier
88213c08e2fSMichael Klier/**
88313c08e2fSMichael Klier * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
88413c08e2fSMichael Klier * to the wanted size
88513c08e2fSMichael Klier *
88613c08e2fSMichael Klier * Crops are centered horizontally but prefer the upper third of an vertical
88713c08e2fSMichael Klier * image because most pics are more interesting in that area (rule of thirds)
88813c08e2fSMichael Klier *
88913c08e2fSMichael Klier * @author  Andreas Gohr <andi@splitbrain.org>
89013c08e2fSMichael Klier */
89113c08e2fSMichael Klierfunction media_crop_image($file, $ext, $w, $h=0){
89213c08e2fSMichael Klier    global $conf;
89313c08e2fSMichael Klier
89413c08e2fSMichael Klier    if(!$h) $h = $w;
89513c08e2fSMichael Klier    $info = @getimagesize($file); //get original size
89613c08e2fSMichael Klier    if($info == false) return $file; // that's no image - it's a spaceship!
89713c08e2fSMichael Klier
89813c08e2fSMichael Klier    // calculate crop size
89913c08e2fSMichael Klier    $fr = $info[0]/$info[1];
90013c08e2fSMichael Klier    $tr = $w/$h;
90113c08e2fSMichael Klier    if($tr >= 1){
90213c08e2fSMichael Klier        if($tr > $fr){
90313c08e2fSMichael Klier            $cw = $info[0];
90413c08e2fSMichael Klier            $ch = (int) $info[0]/$tr;
90513c08e2fSMichael Klier        }else{
90613c08e2fSMichael Klier            $cw = (int) $info[1]*$tr;
90713c08e2fSMichael Klier            $ch = $info[1];
90813c08e2fSMichael Klier        }
90913c08e2fSMichael Klier    }else{
91013c08e2fSMichael Klier        if($tr < $fr){
91113c08e2fSMichael Klier            $cw = (int) $info[1]*$tr;
91213c08e2fSMichael Klier            $ch = $info[1];
91313c08e2fSMichael Klier        }else{
91413c08e2fSMichael Klier            $cw = $info[0];
91513c08e2fSMichael Klier            $ch = (int) $info[0]/$tr;
91613c08e2fSMichael Klier        }
91713c08e2fSMichael Klier    }
91813c08e2fSMichael Klier    // calculate crop offset
91913c08e2fSMichael Klier    $cx = (int) ($info[0]-$cw)/2;
92013c08e2fSMichael Klier    $cy = (int) ($info[1]-$ch)/3;
92113c08e2fSMichael Klier
92213c08e2fSMichael Klier    //cache
92313c08e2fSMichael Klier    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
92413c08e2fSMichael Klier    $mtime = @filemtime($local); // 0 if not exists
92513c08e2fSMichael Klier
92613c08e2fSMichael Klier    if( $mtime > filemtime($file) ||
92713c08e2fSMichael Klier            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
92813c08e2fSMichael Klier            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
92913c08e2fSMichael Klier        if($conf['fperm']) chmod($local, $conf['fperm']);
93013c08e2fSMichael Klier        return media_resize_image($local,$ext, $w, $h);
93113c08e2fSMichael Klier    }
93213c08e2fSMichael Klier
93313c08e2fSMichael Klier    //still here? cropping failed
93413c08e2fSMichael Klier    return media_resize_image($file,$ext, $w, $h);
93513c08e2fSMichael Klier}
93613c08e2fSMichael Klier
93713c08e2fSMichael Klier/**
93813c08e2fSMichael Klier * Download a remote file and return local filename
93913c08e2fSMichael Klier *
94013c08e2fSMichael Klier * returns false if download fails. Uses cached file if available and
94113c08e2fSMichael Klier * wanted
94213c08e2fSMichael Klier *
94313c08e2fSMichael Klier * @author  Andreas Gohr <andi@splitbrain.org>
94413c08e2fSMichael Klier * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
94513c08e2fSMichael Klier */
94613c08e2fSMichael Klierfunction media_get_from_URL($url,$ext,$cache){
94713c08e2fSMichael Klier    global $conf;
94813c08e2fSMichael Klier
94913c08e2fSMichael Klier    // if no cache or fetchsize just redirect
95013c08e2fSMichael Klier    if ($cache==0)           return false;
95113c08e2fSMichael Klier    if (!$conf['fetchsize']) return false;
95213c08e2fSMichael Klier
95313c08e2fSMichael Klier    $local = getCacheName(strtolower($url),".media.$ext");
95413c08e2fSMichael Klier    $mtime = @filemtime($local); // 0 if not exists
95513c08e2fSMichael Klier
95613c08e2fSMichael Klier    //decide if download needed:
95713c08e2fSMichael Klier    if( ($mtime == 0) ||                           // cache does not exist
95813c08e2fSMichael Klier            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
95913c08e2fSMichael Klier      ){
96013c08e2fSMichael Klier        if(media_image_download($url,$local)){
96113c08e2fSMichael Klier            return $local;
96213c08e2fSMichael Klier        }else{
96313c08e2fSMichael Klier            return false;
96413c08e2fSMichael Klier        }
96513c08e2fSMichael Klier    }
96613c08e2fSMichael Klier
96713c08e2fSMichael Klier    //if cache exists use it else
96813c08e2fSMichael Klier    if($mtime) return $local;
96913c08e2fSMichael Klier
97013c08e2fSMichael Klier    //else return false
97113c08e2fSMichael Klier    return false;
97213c08e2fSMichael Klier}
97313c08e2fSMichael Klier
97413c08e2fSMichael Klier/**
97513c08e2fSMichael Klier * Download image files
97613c08e2fSMichael Klier *
97713c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
97813c08e2fSMichael Klier */
97913c08e2fSMichael Klierfunction media_image_download($url,$file){
98013c08e2fSMichael Klier    global $conf;
98113c08e2fSMichael Klier    $http = new DokuHTTPClient();
98213c08e2fSMichael Klier    $http->max_bodysize = $conf['fetchsize'];
98313c08e2fSMichael Klier    $http->timeout = 25; //max. 25 sec
98413c08e2fSMichael Klier    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
98513c08e2fSMichael Klier
98613c08e2fSMichael Klier    $data = $http->get($url);
98713c08e2fSMichael Klier    if(!$data) return false;
98813c08e2fSMichael Klier
98913c08e2fSMichael Klier    $fileexists = @file_exists($file);
99013c08e2fSMichael Klier    $fp = @fopen($file,"w");
99113c08e2fSMichael Klier    if(!$fp) return false;
99213c08e2fSMichael Klier    fwrite($fp,$data);
99313c08e2fSMichael Klier    fclose($fp);
99413c08e2fSMichael Klier    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
99513c08e2fSMichael Klier
99613c08e2fSMichael Klier    // check if it is really an image
99713c08e2fSMichael Klier    $info = @getimagesize($file);
99813c08e2fSMichael Klier    if(!$info){
99913c08e2fSMichael Klier        @unlink($file);
100013c08e2fSMichael Klier        return false;
100113c08e2fSMichael Klier    }
100213c08e2fSMichael Klier
100313c08e2fSMichael Klier    return true;
100413c08e2fSMichael Klier}
100513c08e2fSMichael Klier
100613c08e2fSMichael Klier/**
100713c08e2fSMichael Klier * resize images using external ImageMagick convert program
100813c08e2fSMichael Klier *
100913c08e2fSMichael Klier * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
101013c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
101113c08e2fSMichael Klier */
101213c08e2fSMichael Klierfunction media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
101313c08e2fSMichael Klier    global $conf;
101413c08e2fSMichael Klier
101513c08e2fSMichael Klier    // check if convert is configured
101613c08e2fSMichael Klier    if(!$conf['im_convert']) return false;
101713c08e2fSMichael Klier
101813c08e2fSMichael Klier    // prepare command
101913c08e2fSMichael Klier    $cmd  = $conf['im_convert'];
102013c08e2fSMichael Klier    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
102113c08e2fSMichael Klier    if ($ext == 'jpg' || $ext == 'jpeg') {
102213c08e2fSMichael Klier        $cmd .= ' -quality '.$conf['jpg_quality'];
102313c08e2fSMichael Klier    }
102413c08e2fSMichael Klier    $cmd .= " $from $to";
102513c08e2fSMichael Klier
102613c08e2fSMichael Klier    @exec($cmd,$out,$retval);
102713c08e2fSMichael Klier    if ($retval == 0) return true;
102813c08e2fSMichael Klier    return false;
102913c08e2fSMichael Klier}
103013c08e2fSMichael Klier
103113c08e2fSMichael Klier/**
103213c08e2fSMichael Klier * crop images using external ImageMagick convert program
103313c08e2fSMichael Klier *
103413c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
103513c08e2fSMichael Klier */
103613c08e2fSMichael Klierfunction media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
103713c08e2fSMichael Klier    global $conf;
103813c08e2fSMichael Klier
103913c08e2fSMichael Klier    // check if convert is configured
104013c08e2fSMichael Klier    if(!$conf['im_convert']) return false;
104113c08e2fSMichael Klier
104213c08e2fSMichael Klier    // prepare command
104313c08e2fSMichael Klier    $cmd  = $conf['im_convert'];
104413c08e2fSMichael Klier    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
104513c08e2fSMichael Klier    if ($ext == 'jpg' || $ext == 'jpeg') {
104613c08e2fSMichael Klier        $cmd .= ' -quality '.$conf['jpg_quality'];
104713c08e2fSMichael Klier    }
104813c08e2fSMichael Klier    $cmd .= " $from $to";
104913c08e2fSMichael Klier
105013c08e2fSMichael Klier    @exec($cmd,$out,$retval);
105113c08e2fSMichael Klier    if ($retval == 0) return true;
105213c08e2fSMichael Klier    return false;
105313c08e2fSMichael Klier}
105413c08e2fSMichael Klier
105513c08e2fSMichael Klier/**
105613c08e2fSMichael Klier * resize or crop images using PHP's libGD support
105713c08e2fSMichael Klier *
105813c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
105913c08e2fSMichael Klier * @author Sebastian Wienecke <s_wienecke@web.de>
106013c08e2fSMichael Klier */
106113c08e2fSMichael Klierfunction media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
106213c08e2fSMichael Klier    global $conf;
106313c08e2fSMichael Klier
106413c08e2fSMichael Klier    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
106513c08e2fSMichael Klier
106613c08e2fSMichael Klier    // check available memory
106713c08e2fSMichael Klier    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
106813c08e2fSMichael Klier        return false;
106913c08e2fSMichael Klier    }
107013c08e2fSMichael Klier
107113c08e2fSMichael Klier    // create an image of the given filetype
107213c08e2fSMichael Klier    if ($ext == 'jpg' || $ext == 'jpeg'){
107313c08e2fSMichael Klier        if(!function_exists("imagecreatefromjpeg")) return false;
107413c08e2fSMichael Klier        $image = @imagecreatefromjpeg($from);
107513c08e2fSMichael Klier    }elseif($ext == 'png') {
107613c08e2fSMichael Klier        if(!function_exists("imagecreatefrompng")) return false;
107713c08e2fSMichael Klier        $image = @imagecreatefrompng($from);
107813c08e2fSMichael Klier
107913c08e2fSMichael Klier    }elseif($ext == 'gif') {
108013c08e2fSMichael Klier        if(!function_exists("imagecreatefromgif")) return false;
108113c08e2fSMichael Klier        $image = @imagecreatefromgif($from);
108213c08e2fSMichael Klier    }
108313c08e2fSMichael Klier    if(!$image) return false;
108413c08e2fSMichael Klier
108513c08e2fSMichael Klier    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
108613c08e2fSMichael Klier        $newimg = @imagecreatetruecolor ($to_w, $to_h);
108713c08e2fSMichael Klier    }
108813c08e2fSMichael Klier    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
108913c08e2fSMichael Klier    if(!$newimg){
109013c08e2fSMichael Klier        imagedestroy($image);
109113c08e2fSMichael Klier        return false;
109213c08e2fSMichael Klier    }
109313c08e2fSMichael Klier
109413c08e2fSMichael Klier    //keep png alpha channel if possible
109513c08e2fSMichael Klier    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
109613c08e2fSMichael Klier        imagealphablending($newimg, false);
109713c08e2fSMichael Klier        imagesavealpha($newimg,true);
109813c08e2fSMichael Klier    }
109913c08e2fSMichael Klier
110013c08e2fSMichael Klier    //keep gif transparent color if possible
110113c08e2fSMichael Klier    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
110213c08e2fSMichael Klier        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
110313c08e2fSMichael Klier            $transcolorindex = @imagecolortransparent($image);
110413c08e2fSMichael Klier            if($transcolorindex >= 0 ) { //transparent color exists
110513c08e2fSMichael Klier                $transcolor = @imagecolorsforindex($image, $transcolorindex);
110613c08e2fSMichael Klier                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
110713c08e2fSMichael Klier                @imagefill($newimg, 0, 0, $transcolorindex);
110813c08e2fSMichael Klier                @imagecolortransparent($newimg, $transcolorindex);
110913c08e2fSMichael Klier            }else{ //filling with white
111013c08e2fSMichael Klier                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
111113c08e2fSMichael Klier                @imagefill($newimg, 0, 0, $whitecolorindex);
111213c08e2fSMichael Klier            }
111313c08e2fSMichael Klier        }else{ //filling with white
111413c08e2fSMichael Klier            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
111513c08e2fSMichael Klier            @imagefill($newimg, 0, 0, $whitecolorindex);
111613c08e2fSMichael Klier        }
111713c08e2fSMichael Klier    }
111813c08e2fSMichael Klier
111913c08e2fSMichael Klier    //try resampling first
112013c08e2fSMichael Klier    if(function_exists("imagecopyresampled")){
112113c08e2fSMichael Klier        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
112213c08e2fSMichael Klier            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
112313c08e2fSMichael Klier        }
112413c08e2fSMichael Klier    }else{
112513c08e2fSMichael Klier        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
112613c08e2fSMichael Klier    }
112713c08e2fSMichael Klier
112813c08e2fSMichael Klier    $okay = false;
112913c08e2fSMichael Klier    if ($ext == 'jpg' || $ext == 'jpeg'){
113013c08e2fSMichael Klier        if(!function_exists('imagejpeg')){
113113c08e2fSMichael Klier            $okay = false;
113213c08e2fSMichael Klier        }else{
113313c08e2fSMichael Klier            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
113413c08e2fSMichael Klier        }
113513c08e2fSMichael Klier    }elseif($ext == 'png') {
113613c08e2fSMichael Klier        if(!function_exists('imagepng')){
113713c08e2fSMichael Klier            $okay = false;
113813c08e2fSMichael Klier        }else{
113913c08e2fSMichael Klier            $okay =  imagepng($newimg, $to);
114013c08e2fSMichael Klier        }
114113c08e2fSMichael Klier    }elseif($ext == 'gif') {
114213c08e2fSMichael Klier        if(!function_exists('imagegif')){
114313c08e2fSMichael Klier            $okay = false;
114413c08e2fSMichael Klier        }else{
114513c08e2fSMichael Klier            $okay = imagegif($newimg, $to);
114613c08e2fSMichael Klier        }
114713c08e2fSMichael Klier    }
114813c08e2fSMichael Klier
114913c08e2fSMichael Klier    // destroy GD image ressources
115013c08e2fSMichael Klier    if($image) imagedestroy($image);
115113c08e2fSMichael Klier    if($newimg) imagedestroy($newimg);
115213c08e2fSMichael Klier
115313c08e2fSMichael Klier    return $okay;
115413c08e2fSMichael Klier}
115513c08e2fSMichael Klier
1156365be586SAndreas Gohr/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1157