示例#1
0
function MG_exportAlbums($aid, $path, $srcRoot, $destRoot)
{
    global $_TABLES, $fp, $mvorcopy, $unix;
    $sep = '/';
    $begin = "'";
    $end = "'";
    if ($unix == 0) {
        $sep = '\\';
        $begin = '"';
        $end = '"';
    }
    if ($mvorcopy == 0) {
        $cpyCmd = $unix == 1 ? 'mv' : 'move';
    } else {
        $cpyCmd = $unix == 1 ? 'cp' : 'copy';
    }
    $album = new mgAlbum($aid);
    $children = $album->getChildren();
    $nrows = count($children);
    if ($aid != 0) {
        $file_name = stripslashes($album->title);
        $file_name = MG_replace_accents($file_name);
        if ($unix == 1) {
            $file_name = preg_replace("#[ ]#", "_", $file_name);
            // change spaces to underscore
            $file_name = preg_replace('#[^()\\.\\-,\\w]#', '_', $file_name);
            //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
        } else {
            $file_name = preg_replace('#[^()\\.\\- \',\\w]#', '_', $file_name);
            //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
        }
        $file_name = preg_replace('#(_)+#', '_', $file_name);
        //eliminate duplicate underscore
        $path = $path . $file_name . $sep;
    }
    if ($aid != 0) {
        fputs($fp, 'mkdir ' . $begin . $destRoot . $path . $end . "\n");
    }
    $sql = "SELECT * FROM {$_TABLES['mg_media_albums']} AS ma INNER JOIN {$_TABLES['mg_media']} AS m " . " ON ma.media_id=m.media_id WHERE ma.album_id=" . intval($aid);
    $result = DB_query($sql);
    while ($M = DB_fetchArray($result)) {
        if ($M['media_original_filename'] != '') {
            $destFile = $M['media_original_filename'];
        } else {
            $destFile = $M['media_filename'] . '.' . $M['media_mime_ext'];
        }
        fputs($fp, $cpyCmd . " " . $begin . $srcRoot . $M['media_filename'][0] . $sep . $M['media_filename'] . '.' . $M['media_mime_ext'] . $end . " " . $begin . $destRoot . $path . $destFile . $end . "\n");
    }
    fputs($fp, "\n\n");
    for ($i = 0; $i < $nrows; $i++) {
        MG_exportAlbums($children[$i], $path, $srcRoot, $destRoot);
    }
}
示例#2
0
function MG_getFile($filename, $file, $album_id, $opt = array())
{
    global $_CONF, $_MG_CONF, $_USER, $_TABLES, $LANG_MG00, $LANG_MG01, $LANG_MG02, $_SPECIAL_IMAGES_MIMETYPE, $new_media_id;
    $caption = isset($opt['caption']) ? $opt['caption'] : '';
    $description = isset($opt['description']) ? $opt['description'] : '';
    $upload = isset($opt['upload']) ? $opt['upload'] : 1;
    $purgefiles = isset($opt['purgefiles']) ? $opt['purgefiles'] : 0;
    $filetype = isset($opt['filetype']) ? $opt['filetype'] : '';
    $atttn = isset($opt['atttn']) ? $opt['atttn'] : 0;
    $thumbnail = isset($opt['thumbnail']) ? $opt['thumbnail'] : '';
    $keywords = isset($opt['keywords']) ? $opt['keywords'] : '';
    $category = isset($opt['category']) ? $opt['category'] : 0;
    $dnc = isset($opt['dnc']) ? $opt['dnc'] : 0;
    $replace = isset($opt['replace']) ? $opt['replace'] : 0;
    $artist = '';
    $musicAlbum = '';
    $genre = '';
    $video_attached_thumbnail = 0;
    $successfulWatermark = 0;
    $dnc = 1;
    // What is this?
    $errors = 0;
    $errMsg = '';
    require_once $_CONF['path'] . 'plugins/mediagallery/include/classAlbum.php';
    $album = new mgAlbum($album_id);
    $root_album = new mgAlbum(0);
    if ($_MG_CONF['verbose']) {
        COM_errorLog("MG Upload: *********** Beginning media upload process...");
        COM_errorLog("Filename to process: " . $filename);
        COM_errorLog("UID=" . $_USER['uid']);
        COM_errorLog("album access=" . $album->access);
        COM_errorLog("album owner_id=" . $album->owner_id);
        COM_errorLog("member_uploads=" . $album->member_uploads);
    }
    clearstatcache();
    if (!file_exists($filename)) {
        $errMsg = $LANG_MG02['upload_not_found'];
        return array(false, $errMsg);
    }
    if (!is_readable($filename)) {
        $errMsg = $LANG_MG02['upload_not_readable'];
        return array(false, $errMsg);
    }
    // make sure we have the proper permissions to upload to this album....
    if (!isset($album->id)) {
        $errMsg = $LANG_MG02['album_nonexist'];
        // "Album does not exist, unable to process uploads";
        return array(false, $errMsg);
    }
    if ($album->access != 3 && !$root_album->owner_id && $album->member_uploads == 0) {
        COM_errorLog("Someone has tried to illegally upload to an album in Media Gallery. " . "User id: {$_USER['uid']}, Username: {$_USER['username']}, IP: " . $_SERVER['REMOTE_ADDR'], 1);
        return array(false, $LANG_MG00['access_denied_msg']);
    }
    sleep(0.1);
    // We do this to make sure we don't get dupe sid's
    /*
     * The following section of code will generate a unique name for a temporary
     * file and copy the uploaded file to the Media Gallery temp directory.
     * We do this to prevent any SAFE MODE issues when we later open the
     * file to determine the mime type.
     */
    if (empty($_USER['username'])) {
        $_USER['username'] = '******';
    }
    $tmpPath = $_MG_CONF['tmp_path'] . $_USER['username'] . COM_makesid() . '.tmp';
    if ($upload) {
        $rc = @move_uploaded_file($filename, $tmpPath);
    } else {
        $rc = @copy($filename, $tmpPath);
        $importSource = $filename;
    }
    if ($rc != 1) {
        COM_errorLog("Media Upload - Error moving uploaded file in generic processing....");
        COM_errorLog("Media Upload - Unable to copy file to: " . $tmpPath);
        $errors++;
        $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
        @unlink($tmpPath);
        COM_errorLog("MG Upload: Problem uploading a media object");
        return array(false, $errMsg);
    }
    $filename = $tmpPath;
    $new_media_id = $replace > 0 ? $replace : COM_makesid();
    $media_time = time();
    $media_upload_time = $media_time;
    if (!isset($_USER['uid']) || $_USER['uid'] < 1) {
        $media_user_id = 1;
    } else {
        $media_user_id = $_USER['uid'];
    }
    $mimeInfo = MG_getMediaMetaData($filename);
    $mimeExt = strtolower(substr(strrchr($file, '.'), 1));
    $mimeInfo['type'] = $mimeExt;
    // override the determination for some filetypes
    $filetype = MG_getFileTypeFromExt($mimeExt, $filetype);
    if (empty($mimeInfo['mime_type'])) {
        COM_errorLog("MG Upload: getID3 was unable to detect mime type - using PHP detection");
        $mimeInfo['mime_type'] = $filetype;
    }
    $gotTN = 0;
    if ($mimeInfo['id3v2']['APIC'][0]['mime'] == 'image/jpeg') {
        $mp3AttachdedThumbnail = $mimeInfo['id3v2']['APIC'][0]['data'];
        $gotTN = 1;
    }
    if ($_MG_CONF['verbose']) {
        COM_errorLog("MG Upload: found mime type of " . $mimeInfo['type']);
    }
    if ($mimeExt == '' || $mimeInfo['mime_type'] == 'application/octet-stream' || $mimeInfo['mime_type'] == '') {
        // assume format based on file upload info...
        switch ($filetype) {
            case 'audio/mpeg':
                $mimeInfo['type'] = 'mp3';
                $mimeInfo['mime_type'] = 'audio/mpeg';
                $mimeExt = 'mp3';
                break;
            case 'image/tga':
                $mimeInfo['type'] = 'tga';
                $mimeInfo['mime_type'] = 'image/tga';
                $mimeExt = 'tga';
                break;
            case 'image/psd':
                $mimeInfo['type'] = 'psd';
                $mimeInfo['mime_type'] = 'image/psd';
                $mimeExt = 'psd';
                break;
            case 'image/gif':
                $mimeInfo['type'] = 'gif';
                $mimeInfo['mime_type'] = 'image/gif';
                $mimeExt = 'gif';
                break;
            case 'image/jpeg':
            case 'image/jpg':
                $mimeInfo['type'] = 'jpg';
                $mimeInfo['mime_type'] = 'image/jpeg';
                $mimeExt = 'jpg';
                break;
            case 'image/png':
                $mimeInfo['type'] = 'png';
                $mimeInfo['mime_type'] = 'image/png';
                $mimeExt = 'png';
                break;
            case 'image/bmp':
                $mimeInfo['type'] = 'bmp';
                $mimeInfo['mime_type'] = 'image/bmp';
                $mimeExt = 'bmp';
                break;
            case 'application/x-shockwave-flash':
                $mimeInfo['type'] = 'swf';
                $mimeInfo['mime_type'] = 'application/x-shockwave-flash';
                $mimeExt = 'swf';
                break;
            case 'application/zip':
                $mimeInfo['type'] = 'zip';
                $mimeInfo['mime_type'] = 'application/zip';
                $mimeExt = 'zip';
                break;
            case 'audio/mpeg':
                $mimeInfo['type'] = 'mp3';
                $mimeInfo['mime_type'] = 'audio/mpeg';
                $mimeExt = 'mp3';
                break;
            case 'video/quicktime':
                $mimeInfo['type'] = 'mov';
                $mimeInfo['mime_type'] = 'video/quicktime';
                $mimeExt = 'mov';
                break;
            case 'video/x-m4v':
                $mimeInfo['type'] = 'mov';
                $mimeInfo['mime_type'] = 'video/x-m4v';
                $mimeExt = 'mov';
                break;
            case 'video/x-flv':
                $mimeInfo['type'] = 'flv';
                $mimeInfo['mime_type'] = 'video/x-flv';
                $mimeExt = 'flv';
                break;
            case 'audio/x-ms-wma':
                $mimeInfo['type'] = 'wma';
                $mimeInfo['mime_type'] = 'audio/x-ms-wma';
                $mimeExt = 'wma';
                break;
            default:
                switch ($mimeExt) {
                    case 'flv':
                        $mimeInfo['type'] = 'flv';
                        $mimeInfo['mime_type'] = 'video/x-flv';
                        break;
                    case 'wma':
                        $mimeInfo['type'] = 'wma';
                        $mimeInfo['mime_type'] = 'audio/x-ms-wma';
                        break;
                    default:
                        $mimeInfo['type'] = 'file';
                        $mimeInfo['mime_type'] = 'application/octet-stream';
                        if ($filetype != '') {
                            $mimeInfo['mime_type'] = $filetype;
                        }
                        break;
                }
                break;
        }
        if ($_MG_CONF['verbose']) {
            COM_errorLog("MG Upload: override mime type to: " . $mimeInfo['type'] . ' based upon file extension of: ' . $filetype);
        }
    }
    switch ($mimeInfo['mime_type']) {
        case 'audio/mpeg':
            $format_type = MG_MP3;
            break;
        case 'image/gif':
            $format_type = MG_GIF;
            break;
        case 'image/jpeg':
        case 'image/jpg':
            $format_type = MG_JPG;
            break;
        case 'image/png':
            $format_type = MG_PNG;
            break;
        case 'image/bmp':
            $format_type = MG_BMP;
            break;
        case 'application/x-shockwave-flash':
            $format_type = MG_SWF;
            break;
        case 'application/zip':
            $format_type = MG_ZIP;
            break;
        case 'video/mpeg':
        case 'video/x-motion-jpeg':
        case 'video/quicktime':
        case 'video/mpeg':
        case 'video/x-mpeg':
        case 'video/x-mpeq2a':
        case 'video/x-qtc':
        case 'video/x-m4v':
            $format_type = MG_MOV;
            break;
        case 'video/x-flv':
            $format_type = MG_FLV;
            break;
        case 'image/tiff':
            $format_type = MG_TIF;
            break;
        case 'image/x-targa':
        case 'image/tga':
            $format_type = MG_TGA;
            break;
        case 'image/psd':
            $format_type = MG_PSD;
            break;
        case 'application/ogg':
            $format_type = MG_OGG;
            break;
        case 'audio/x-ms-wma':
        case 'audio/x-ms-wax':
        case 'audio/x-ms-wmv':
        case 'video/x-ms-asf':
        case 'video/x-ms-asf-plugin':
        case 'video/avi':
        case 'video/msvideo':
        case 'video/x-msvideo':
        case 'video/avs-video':
        case 'video/x-ms-wmv':
        case 'video/x-ms-wvx':
        case 'video/x-ms-wm':
        case 'application/x-troff-msvideo':
        case 'application/x-ms-wmz':
        case 'application/x-ms-wmd':
            $format_type = MG_ASF;
            break;
        case 'application/pdf':
            $format_type = MG_OTHER;
            break;
        default:
            $format_type = MG_OTHER;
            break;
    }
    if (!($album->valid_formats & $format_type)) {
        return array(false, $LANG_MG02['format_not_allowed']);
    }
    $mimeType = $mimeInfo['mime_type'];
    if ($_MG_CONF['verbose']) {
        COM_errorLog("MG Upload: PHP detected mime type is : " . $filetype);
    }
    if ($filetype == 'video/x-m4v') {
        $mimeType = 'video/x-m4v';
        $mimeInfo['mime_type'] = 'video/x-m4v';
    }
    if ($replace > 0) {
        $sql = "SELECT * FROM {$_TABLES['mg_media']} WHERE media_id='" . addslashes($replace) . "'";
        $result = DB_query($sql);
        $row = DB_fetchArray($result);
        $media_filename = $row['media_filename'];
    } else {
        if ($_MG_CONF['preserve_filename'] == 1) {
            $loopCounter = 0;
            $digitCounter = 1;
            $file_name = stripslashes($file);
            $file_name = MG_replace_accents($file_name);
            $file_name = preg_replace("#[ ]#", "_", $file_name);
            // change spaces to underscore
            $file_name = preg_replace('#[^\\.\\-,\\w]#', '_', $file_name);
            //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
            $file_name = preg_replace('#(_)+#', '_', $file_name);
            //eliminate duplicate underscore
            $pos = strrpos($file_name, '.');
            if ($pos === false) {
                $basefilename = $file_name;
            } else {
                $basefilename = strtolower(substr($file_name, 0, $pos));
            }
            do {
                clearstatcache();
                $media_filename = substr(md5(uniqid(rand())), 0, $digitCounter) . '_' . $basefilename;
                $loopCounter++;
                if ($loopCounter > 16) {
                    $digitCounter++;
                    $loopCounter = 0;
                }
            } while (MG_file_exists($media_filename));
        } else {
            do {
                clearstatcache();
                $media_filename = md5(uniqid(rand()));
            } while (MG_file_exists($media_filename));
        }
    }
    // replace a few mime extentions here...
    //
    if ($mimeExt == 'php') {
        $mimeExt = 'phps';
    }
    if (in_array($mimeExt, array('pl', 'cgi', 'py', 'sh', 'rb'))) {
        $mimeExt = 'txt';
    }
    $disp_media_filename = $media_filename . '.' . $mimeExt;
    if ($_MG_CONF['verbose']) {
        COM_errorLog("MG Upload: Stored filename is : " . $disp_media_filename);
        COM_errorLog("MG Upload: Mime Type: " . $mimeType);
    }
    switch ($mimeType) {
        case 'image/psd':
        case 'image/x-targa':
        case 'image/tga':
        case 'image/photoshop':
        case 'image/x-photoshop':
        case 'image/psd':
        case 'application/photoshop':
        case 'application/psd':
        case 'image/tiff':
        case 'image/gif':
        case 'image/jpeg':
        case 'image/jpg':
        case 'image/png':
        case 'image/bmp':
            $dispExt = $mimeExt;
            if (in_array($mimeType, $_SPECIAL_IMAGES_MIMETYPE)) {
                $dispExt = 'jpg';
            }
            $media_orig = MG_getFilePath('orig', $media_filename, $mimeExt);
            $media_disp = MG_getFilePath('disp', $media_filename, $dispExt);
            $media_tn = MG_getFilePath('tn', $media_filename, $dispExt);
            $mimeType = $mimeInfo['mime_type'];
            // process image file
            $media_time = getOriginationTimestamp($filename);
            if ($media_time == null || $media_time < 0) {
                $media_time = time();
            }
            if ($_MG_CONF['verbose']) {
                COM_errorLog("MG Upload: About to move/copy file");
            }
            $rc = @copy($filename, $media_orig);
            if ($rc != 1) {
                COM_errorLog("Media Upload - Error moving uploaded file....");
                COM_errorLog("Media Upload - Unable to copy file to: " . $media_orig);
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                @chmod($media_orig, 0644);
                list($rc, $msg) = MG_convertImage($media_orig, $media_tn, $media_disp, $mimeExt, $mimeType, $album_id, $media_filename, $dnc);
                if ($rc == false) {
                    $errors++;
                    $errMsg .= $msg;
                    // sprintf($LANG_MG02['convert_error'],$filename);
                } else {
                    $mediaType = 0;
                    if ($_MG_CONF['discard_original'] == 1 && ($mimeType == 'image/jpeg' || $mimeType == 'image/jpg' || $mimeType == 'image/png' || $mimeType == 'image/bmp' || $mimeType == 'image/gif')) {
                        if ($_MG_CONF['jhead_enabled'] && ($mimeType == 'image/jpeg' || $mimeType == 'image/jpg')) {
                            $rc = MG_execWrapper('"' . $_MG_CONF['jhead_path'] . "/jhead" . '"' . " -te " . $media_orig . " " . $media_disp);
                        }
                        @unlink($media_orig);
                    }
                    if ($album->wm_auto) {
                        if ($_MG_CONF['discard_original'] == 1) {
                            $rc = MG_watermark($media_disp, $album_id, 1);
                            if ($rc == true) {
                                $successfulWatermark = 1;
                            }
                        } else {
                            $rc1 = MG_watermark($media_orig, $album_id, 1);
                            $rc2 = MG_watermark($media_disp, $album_id, 0);
                            if ($rc1 == ture && $rc2 == true) {
                                $successfulWatermark = 1;
                            }
                        }
                    }
                    if ($dnc != 1) {
                        if (!in_array($mimeType, $_SPECIAL_IMAGES_MIMETYPE)) {
                            $mimeExt = 'jpg';
                            $mimeType = 'image/jpeg';
                        }
                    }
                }
            }
            break;
        case 'video/quicktime':
        case 'video/mpeg':
        case 'video/x-flv':
        case 'video/x-ms-asf':
        case 'video/x-ms-asf-plugin':
        case 'video/avi':
        case 'video/msvideo':
        case 'video/x-msvideo':
        case 'video/avs-video':
        case 'video/x-ms-wmv':
        case 'video/x-ms-wvx':
        case 'video/x-ms-wm':
        case 'application/x-troff-msvideo':
        case 'application/x-shockwave-flash':
        case 'video/mp4':
        case 'video/x-m4v':
            $mimeType = $mimeInfo['mime_type'];
            if ($filetype == 'video/mp4') {
                $mimeExt = 'mp4';
            }
            // process video format
            $media_orig = MG_getFilePath('orig', $media_filename, $mimeExt);
            $rc = @copy($filename, $media_orig);
            if ($rc != 1) {
                COM_errorLog("MG Upload: Error moving uploaded file in video processing....");
                COM_errorLog("Media Upload - Unable to copy file to: " . $media_orig);
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                @chmod($media_orig, 0644);
                $mediaType = 1;
            }
            $video_attached_thumbnail = MG_videoThumbnail($album_id, $media_orig, $media_filename);
            break;
        case 'application/ogg':
        case 'audio/mpeg':
        case 'audio/x-ms-wma':
        case 'audio/x-ms-wax':
        case 'audio/x-ms-wmv':
            $mimeType = $mimeInfo['mime_type'];
            // process audio format
            $media_orig = MG_getFilePath('orig', $media_filename, $mimeExt);
            $rc = @copy($filename, $media_orig);
            COM_errorLog("MG Upload: Extracting audio meta data");
            if (isset($mimeInfo['tags']['id3v1']['title'][0])) {
                if ($caption == '') {
                    $caption = $mimeInfo['tags']['id3v1']['title'][0];
                }
            }
            if (isset($mimeInfo['tags']['id3v1']['artist'][0])) {
                $artist = addslashes($mimeInfo['tags']['id3v1']['artist'][0]);
            }
            if (isset($mimeInfo['tags']['id3v2']['genre'][0])) {
                $genre = addslashes($mimeInfo['tags']['id3v2']['genre'][0]);
            }
            if (isset($mimeInfo['tags']['id3v1']['album'][0])) {
                $musicAlbum = addslashes($mimeInfo['tags']['id3v1']['album'][0]);
            }
            if ($rc != 1) {
                COM_errorLog("Media Upload - Error moving uploaded file in audio processing....");
                COM_errorLog("Media Upload - Unable to copy file to: " . $media_orig);
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                $mediaType = 2;
            }
            break;
        case 'zip':
        case 'application/zip':
            if ($_MG_CONF['zip_enabled']) {
                $errMsg .= MG_processZip($filename, $album_id, $purgefiles, $media_filename);
                break;
            }
            // NO BREAK HERE, fall through if enable zip isn't allowed
        // NO BREAK HERE, fall through if enable zip isn't allowed
        default:
            $media_orig = MG_getFilePath('orig', $media_filename, $mimeExt);
            $mimeType = $mimeInfo['mime_type'];
            $rc = @copy($filename, $media_orig);
            if ($rc != 1) {
                COM_errorLog("Media Upload - Error moving uploaded file in generic processing....");
                COM_errorLog("Media Upload - Unable to copy file to: " . $media_orig);
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                $mediaType = 4;
            }
            $mediaType = 4;
            break;
    }
    // update quota
    $quota = $album->album_disk_usage;
    $quota += @filesize(MG_getFilePath('orig', $media_filename, $mimeExt));
    if ($_MG_CONF['discard_original'] == 1) {
        $quota += @filesize(MG_getFilePath('disp', $media_filename, 'jpg'));
    }
    DB_change($_TABLES['mg_albums'], 'album_disk_usage', $quota, 'album_id', intval($album_id));
    if ($errors) {
        @unlink($tmpPath);
        COM_errorLog("MG Upload: Problem uploading a media object");
        return array(false, $errMsg);
    }
    if (($mimeType != 'application/zip' || $_MG_CONF['zip_enabled'] == 0) && $errors == 0) {
        // Now we need to process an uploaded thumbnail
        if ($gotTN == 1) {
            $mp3TNFilename = $_MG_CONF['tmp_path'] . 'mp3tn' . time() . '.jpg';
            $fn = fopen($mp3TNFilename, "w");
            fwrite($fn, $mp3AttachdedThumbnail);
            fclose($fn);
            $saveThumbnailName = $_MG_CONF['path_mediaobjects'] . 'tn/' . $media_filename[0] . '/tn_' . $media_filename;
            MG_attachThumbnail($album_id, $mp3TNFilename, $saveThumbnailName);
            @unlink($mp3TNFilename);
            $atttn = 1;
        } else {
            if ($atttn == 1) {
                $saveThumbnailName = $_MG_CONF['path_mediaobjects'] . 'tn/' . $media_filename[0] . '/tn_' . $media_filename;
                MG_attachThumbnail($album_id, $thumbnail, $saveThumbnailName);
            }
        }
        if ($video_attached_thumbnail) {
            $atttn = 1;
        }
        if ($_MG_CONF['verbose']) {
            COM_errorLog("MG Upload: Building SQL and preparing to enter database");
        }
        if ($_MG_CONF['htmlallowed'] != 1) {
            $media_desc = addslashes(htmlspecialchars(strip_tags(COM_checkWords(COM_killJS($description)))));
            $media_caption = addslashes(htmlspecialchars(strip_tags(COM_checkWords(COM_killJS($caption)))));
            $media_keywords = addslashes(htmlspecialchars(strip_tags(COM_checkWords(COM_killJS($keywords)))));
        } else {
            $media_desc = addslashes(COM_checkHTML(COM_killJS($description)));
            $media_caption = addslashes(COM_checkHTML(COM_killJS($caption)));
            $media_keywords = addslashes(COM_checkHTML(COM_killJS($keywords)));
        }
        // Check and see if moderation is on.  If yes, place in mediasubmission
        if ($album->moderate == 1 && !$root_album->owner_id) {
            $tableMedia = $_TABLES['mg_mediaqueue'];
            $tableMediaAlbum = $_TABLES['mg_media_album_queue'];
            $queue = 1;
        } else {
            $tableMedia = $_TABLES['mg_media'];
            $tableMediaAlbum = $_TABLES['mg_media_albums'];
            $queue = 0;
        }
        $original_filename = addslashes($file);
        if ($album->filename_title) {
            if ($media_caption == '') {
                $pos = strrpos($original_filename, '.');
                if ($pos === false) {
                    $media_caption = $original_filename;
                } else {
                    $media_caption = substr($original_filename, 0, $pos);
                }
            }
        }
        if ($_MG_CONF['verbose']) {
            COM_errorLog("MG Upload: Inserting media record into mg_media");
        }
        $resolution_x = 0;
        $resolution_y = 0;
        // try to find a resolution if video...
        if ($mediaType == 1) {
            switch ($mimeType) {
                case 'application/x-shockwave-flash':
                case 'video/quicktime':
                case 'video/mpeg':
                case 'video/x-m4v':
                    $resolution_x = -1;
                    $resolution_y = -1;
                    if (isset($mimeInfo['video']['resolution_x']) && isset($mimeInfo['video']['resolution_x'])) {
                        $resolution_x = $mimeInfo['video']['resolution_x'];
                        $resolution_y = $mimeInfo['video']['resolution_y'];
                    }
                    break;
                case 'video/x-flv':
                    if ($mimeInfo['video']['resolution_x'] < 1 || $mimeInfo['video']['resolution_y'] < 1) {
                        $resolution_x = -1;
                        $resolution_y = -1;
                        if (isset($mimeInfo['meta']['onMetaData']['width']) && isset($mimeInfo['meta']['onMetaData']['height'])) {
                            $resolution_x = $mimeInfo['meta']['onMetaData']['width'];
                            $resolution_y = $mimeInfo['meta']['onMetaData']['height'];
                        }
                    } else {
                        $resolution_x = $mimeInfo['video']['resolution_x'];
                        $resolution_y = $mimeInfo['video']['resolution_y'];
                    }
                    break;
                case 'video/x-ms-asf':
                case 'video/x-ms-asf-plugin':
                case 'video/avi':
                case 'video/msvideo':
                case 'video/x-msvideo':
                case 'video/avs-video':
                case 'video/x-ms-wmv':
                case 'video/x-ms-wvx':
                case 'video/x-ms-wm':
                case 'application/x-troff-msvideo':
                    $resolution_x = -1;
                    $resolution_y = -1;
                    if (isset($mimeInfo['video']['streams']['2']['resolution_x']) && isset($mimeInfo['video']['streams']['2']['resolution_y'])) {
                        $resolution_x = $mimeInfo['video']['streams']['2']['resolution_x'];
                        $resolution_y = $mimeInfo['video']['streams']['2']['resolution_y'];
                    }
                    break;
            }
        }
        if ($replace > 0) {
            $sql = "UPDATE " . $tableMedia . " SET " . "media_filename='" . addslashes($media_filename) . "'," . "media_original_filename='" . $original_filename . "'," . "media_mime_ext='" . addslashes($mimeExt) . "'," . "mime_type='" . addslashes($mimeType) . "'," . "media_time='" . addslashes($media_time) . "'," . "media_user_id='" . addslashes($media_user_id) . "'," . "media_type='" . addslashes($mediaType) . "'," . "media_upload_time='" . addslashes($media_upload_time) . "'," . "media_watermarked='" . addslashes($successfulWatermark) . "'," . "media_resolution_x='" . intval($resolution_x) . "'," . "media_resolution_y='" . intval($resolution_y) . "' " . "WHERE media_id='" . addslashes($replace) . "'";
            DB_query($sql);
        } else {
            $sql = "INSERT INTO " . $tableMedia . " (media_id,media_filename,media_original_filename,media_mime_ext," . "media_exif,mime_type,media_title,media_desc,media_keywords,media_time," . "media_views,media_comments,media_votes,media_rating,media_tn_attached," . "media_tn_image,include_ss,media_user_id,media_user_ip,media_approval," . "media_type,media_upload_time,media_category,media_watermarked,v100," . "maint,media_resolution_x,media_resolution_y,remote_media,remote_url," . "artist,album,genre) " . "VALUES ('" . addslashes($new_media_id) . "','" . addslashes($media_filename) . "','" . $original_filename . "','" . addslashes($mimeExt) . "','1','" . addslashes($mimeType) . "','" . addslashes($media_caption) . "','" . addslashes($media_desc) . "','" . addslashes($media_keywords) . "','" . addslashes($media_time) . "','0','0','0','0.00','" . addslashes($atttn) . "','','1','" . addslashes($media_user_id) . "','','0','" . addslashes($mediaType) . "','" . addslashes($media_upload_time) . "','" . addslashes($category) . "','" . addslashes($successfulWatermark) . "','0','0'," . intval($resolution_x) . "," . intval($resolution_y) . ",0,'','" . addslashes($artist) . "','" . addslashes($musicAlbum) . "','" . addslashes($genre) . "');";
            DB_query($sql);
            if ($_MG_CONF['verbose']) {
                COM_errorLog("MG Upload: Updating Album information");
            }
            $x = 0;
            $sql = "SELECT MAX(media_order) + 10 AS media_seq FROM {$_TABLES['mg_media_albums']} WHERE album_id = " . intval($album_id);
            $result = DB_query($sql);
            $row = DB_fetchArray($result);
            $media_seq = $row['media_seq'];
            if ($media_seq < 10) {
                $media_seq = 10;
            }
            $sql = "INSERT INTO " . $tableMediaAlbum . " (media_id, album_id, media_order) " . "VALUES ('" . addslashes($new_media_id) . "', " . intval($album_id) . ", " . intval($media_seq) . ")";
            DB_query($sql);
            if ($mediaType == 1 && $resolution_x > 0 && $resolution_y > 0 && $_MG_CONF['use_default_resolution'] == 0) {
                DB_save($_TABLES['mg_playback_options'], 'media_id,option_name,option_value', "'{$new_media_id}','width', '{$resolution_x}'");
                DB_save($_TABLES['mg_playback_options'], 'media_id,option_name,option_value', "'{$new_media_id}','height','{$resolution_y}'");
            }
            PLG_itemSaved($new_media_id, 'mediagallery');
            // update the media count for the album, only if no moderation...
            if ($queue == 0) {
                $album->media_count++;
                DB_change($_TABLES['mg_albums'], 'media_count', $album->media_count, 'album_id', $album->id);
                MG_updateAlbumLastUpdate($album->id);
                if ($album->cover == -1 && ($mediaType == 0 || $atttn == 1)) {
                    if ($atttn == 1) {
                        $covername = 'tn_' . $media_filename;
                    } else {
                        $covername = $media_filename;
                    }
                    DB_change($_TABLES['mg_albums'], 'album_cover_filename', $covername, 'album_id', $album->id);
                }
                //                MG_resetAlbumCover($album->id);
            }
            $x++;
        }
    }
    if ($queue) {
        $errMsg .= $LANG_MG01['successful_upload_queue'];
        // ' successfully placed in Moderation queue';
    } else {
        $errMsg .= $LANG_MG01['successful_upload'];
        // ' successfully uploaded to album';
    }
    if ($queue == 0) {
        require_once $_CONF['path'] . 'plugins/mediagallery/include/rssfeed.php';
        MG_buildFullRSS();
        MG_buildAlbumRSS($album_id);
    }
    COM_errorLog("MG Upload: Successfully uploaded a media object");
    @unlink($tmpPath);
    return array(true, $errMsg);
}
示例#3
0
/**
 * Continues a session - handles timeout, looping, etc.
 *
 * @parm    char    session id to continue
 * @parm    int     number of items to process per run
 *                  0 indicates initial run
 * @return  char    HTML of status screen
 */
function MG_continueSession($session_id, $item_limit, $refresh_rate)
{
    global $MG_albums, $_CONF, $_MG_CONF, $_TABLES, $_USER, $LANG_MG00, $LANG_MG01, $LANG_MG02, $HTTP_SERVER_VARS;
    global $new_media_id, $_GKCONST;
    $retval = '';
    $cycle_start_time = time();
    $temp_time = array();
    $timer_expired = false;
    $num_rows = 0;
    $session_id = COM_applyFilter($session_id);
    // Pull the session status info
    $sql = "SELECT * FROM {$_TABLES['mg_sessions']} WHERE session_id='" . DB_escapeString($session_id) . "'";
    $result = DB_query($sql, 1);
    if (DB_error()) {
        COM_errorLog("MediaGallery:  Error - Unable to retrieve batch session data");
        return '';
    }
    $nRows = DB_numRows($result);
    if ($nRows > 0) {
        $session = DB_fetchArray($result);
    } else {
        COM_errorLog("MediaGallery: Error - Unable to find batch session id");
        return '';
        // no session found
    }
    // security check - make sure we are continuing a session that we own...
    if ($session['session_uid'] != $_USER['uid'] && !$MG_albums[0]->owner_id) {
        $display .= COM_startBlock('', '', COM_getBlockTemplate('_admin_block', 'header'));
        $T = new Template(MG_getTemplatePath(0));
        $T->set_file('admin', 'error.thtml');
        $T->set_var('site_url', $_CONF['site_url']);
        $T->set_var('site_admin_url', $_CONF['site_admin_url']);
        $T->set_var('errormessage', $LANG_MG00['access_denied_msg']);
        $T->parse('output', 'admin');
        $display .= $T->finish($T->get_var('output'));
        $display .= COM_endBlock(COM_getBlockTemplate('_admin_block', 'footer'));
        $display .= MG_siteFooter();
        return $display;
    }
    // Setup timer information
    $time_limit = $_MG_CONF['def_time_limit'];
    @set_time_limit($time_limit + 20);
    // get execution time
    $max_execution_time = ini_get('max_execution_time');
    if ($time_limit > $max_execution_time) {
        $time_limit = $max_execution_time;
    }
    $label = $session['session_description'];
    // Pull the detail data from the sessions_items table...
    $sql = "SELECT * FROM {$_TABLES['mg_session_items']} WHERE session_id='" . DB_escapeString($session_id) . "' AND status=0 LIMIT " . $item_limit;
    $result = DB_query($sql);
    while (($row = DB_fetchArray($result)) && $timer_expired == false) {
        // used for calculating loop duration and changing the timer condition
        $start_temp_time = time();
        switch ($session['session_action']) {
            case 'watermark':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-watermark.php';
                MG_watermarkBatchProcess($row['aid'], $row['mid']);
                break;
            case 'rebuildthumb':
                $makeSquare = 0;
                $aid = $row['aid'];
                $srcImage = $row['data'];
                $imageThumb = $row['data2'];
                $mimeExt = $row['data3'];
                $mimeType = $row['mid'];
                if ($MG_albums[$aid]->tn_size == 3 || $MG_albums[$aid]->tn_size == 4) {
                    $tnHeight = $MG_albums[$aid]->tnHeight;
                    $tnWidth = $MG_albums[$aid]->tnWidth;
                    if ($MG_albums[$aid]->tn_size == 4) {
                        $makeSquare = 1;
                    }
                } else {
                    if ($_MG_CONF['thumbnail_actual_size'] == 1) {
                        switch ($MG_albums[$aid]->tn_size) {
                            case 0:
                                $tnHeight = 100;
                                $tnWidth = 100;
                                break;
                            case 1:
                                $tnHeight = 150;
                                $tnWidth = 150;
                                break;
                            default:
                                $tnHeight = 200;
                                $tnWidth = 200;
                                break;
                        }
                    } else {
                        $tnHeight = 200;
                        $tnWidth = 200;
                    }
                }
                $tmpImage = '';
                if ($mimeType == 'image/x-targa' || $mimeType == 'image/tga' || $mimeType == 'image/photoshop' || $mimeType == 'image/x-photoshop' || $mimeType == 'image/psd' || $mimeType == 'application/photoshop' || $mimeType == 'application/psd') {
                    $tmpImage = $_MG_CONF['tmp_path'] . '/wip' . rand() . '.jpg';
                    $rc = IMG_convertImageFormat($srcImage, $tmpImage, 'image/jpeg', 0);
                    if ($rc == false) {
                        COM_errorLog("MG_convertImage: Error converting uploaded image to jpeg format.");
                        @unlink($srcImage);
                        return false;
                    }
                    if ($makeSquare == 1) {
                        $rc = IMG_squareThumbnail($tmpImage, $imageThumb, $tnWidth, $mimeType, 0);
                    } else {
                        $rc = IMG_resizeImage($tmpImage, $imageThumb, $tnHeight, $tnWidth, $mimeType, 0);
                    }
                } else {
                    if ($makeSquare == 1) {
                        $rc = IMG_squareThumbnail($srcImage, $imageThumb, $tnWidth, $mimeType, 0);
                    } else {
                        $rc = IMG_resizeImage($srcImage, $imageThumb, $tnHeight, $tnWidth, $mimeType, 0);
                    }
                }
                if ($rc == false) {
                    COM_errorLog("MG_convertImage: Error resizing uploaded image to thumbnail size.");
                    @unlink($srcImage);
                }
                break;
            case 'rebuilddisplay':
                $srcImage = $row['data'];
                $imageDisplay = $row['data2'];
                $mimeExt = $row['data3'];
                $mimeType = $row['mid'];
                $aid = $row['aid'];
                $imgsize = @getimagesize("{$srcImage}");
                $imgwidth = $imgsize[0];
                $imgheight = $imgsize[1];
                $tmpImage = '';
                if ($mimeType == 'image/x-targa' || $mimeType == 'image/tga' || $mimeType == 'image/photoshop' || $mimeType == 'image/x-photoshop' || $mimeType == 'image/psd' || $mimeType == 'application/photoshop' || $mimeType == 'application/psd' || $mimeType == 'image/tiff') {
                    $tmpImage = $_MG_CONF['tmp_path'] . '/wip' . rand() . '.jpg';
                    list($rc, $msg) = IMG_convertImageFormat($srcImage, $tmpImage, 'image/jpeg', 0);
                    if ($rc == false) {
                        COM_errorLog("MG_libBatch: Error converting uploaded image to jpeg format.");
                    }
                }
                switch ($MG_albums[$aid]->display_image_size) {
                    case 0:
                        $dImageWidth = 500;
                        $dImageHeight = 375;
                        break;
                    case 1:
                        $dImageWidth = 600;
                        $dImageHeight = 450;
                        break;
                    case 2:
                        $dImageWidth = 620;
                        $dImageHeight = 465;
                        break;
                    case 3:
                        $dImageWidth = 720;
                        $dImageHeight = 540;
                        break;
                    case 4:
                        $dImageWidth = 800;
                        $dImageHeight = 600;
                        break;
                    case 5:
                        $dImageWidth = 912;
                        $dImageHeight = 684;
                        break;
                    case 6:
                        $dImageWidth = 1024;
                        $dImageHeight = 768;
                        break;
                    case 7:
                        $dImageWidth = 1152;
                        $dImageHeight = 804;
                        break;
                    case 8:
                        $dImageWidth = 1280;
                        $dImageHeight = 1024;
                        break;
                    case 9:
                        $dImageWidth = $_MG_CONF['custom_image_width'];
                        $dImageHeight = $_MG_CONF['custom_image_height'];
                        break;
                    default:
                        $dImageWidth = 620;
                        $dImageHeight = 465;
                        break;
                }
                if ($imgsize == false || $imgwidth == 0 || $imgheight == 0) {
                    $imgwidth = $dImageWidth;
                    $imgheight = $dImageHeight;
                }
                if ($mimeType == 'image/x-targa' || $mimeType == 'image/tga') {
                    $fp = @fopen($srcImage, 'rb');
                    if ($fp == false) {
                        $imgwidth = 0;
                        $imgheight = 0;
                    } else {
                        $data = fread($fp, filesize($srcImage));
                        fclose($fp);
                        $imgwidth = base_convert(bin2hex(strrev(substr($data, 12, 2))), 16, 10);
                        $imgheight = base_convert(bin2hex(strrev(substr($data, 12, 2))), 16, 10);
                    }
                }
                if ($tmpImage != '') {
                    list($rc, $msg) = IMG_resizeImage($tmpImage, $imageDisplay, $dImageHeight, $dImageWidth, $mimeType, 0);
                } else {
                    list($rc, $msg) = IMG_resizeImage($srcImage, $imageDisplay, $dImageHeight, $dImageWidth, $mimeType, 0);
                }
                if ($tmpImage != '') {
                    @unlink($tmpImage);
                }
                break;
            case 'droporiginal':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                if ($_MG_CONF['jhead_enabled'] == 1) {
                    UTL_execWrapper('"' . $_MG_CONF['jhead_path'] . "/jhead" . '"' . " -te " . $row['data'] . " " . $row['data2']);
                }
                @unlink($row['data']);
                break;
            case 'rotate':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/rotate.php';
                MG_rotateMedia($row['aid'], $row['mid'], $row['data'], -1);
                break;
            case 'delete':
                break;
            case 'upgrade':
                break;
            case 'import':
                break;
            case 'ftpimport2':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                $srcFile = $row['data'];
                // full path
                $album_id = $row['aid'];
                $purgefiles = intval($row['data2']);
                $baseSrcFile = $row['data3'];
                // basefilename
                $directory = $row['mid'];
                if ($directory == 1) {
                    require_once $_CONF['path'] . 'plugins/mediagallery/include/albumedit.php';
                    $new_aid = MG_quickCreate($album_id, $baseSrcFile);
                    $dir = $srcFile;
                    if (!($dh = @opendir($dir))) {
                        COM_errorLog("Media Gallery: Error - unable process FTP import directory " . $dir);
                    } else {
                        while (($file = readdir($dh)) != false) {
                            if ($file == '..' || $file == '.') {
                                continue;
                            }
                            if ($file == 'Thumbs.db' || $file == 'thumbs.db') {
                                continue;
                            }
                            $filetmp = $dir . '/' . $file;
                            if (is_dir($filetmp)) {
                                $mid = 1;
                            } else {
                                $mid = 0;
                            }
                            $filename = basename($file);
                            $file_extension = strtolower(substr(strrchr($filename, "."), 1));
                            DB_query("INSERT INTO {$_TABLES['mg_session_items']} (session_id,mid,aid,data,data2,data3,status)\n                                      VALUES('" . DB_escapeString($session_id) . "','" . DB_escapeString($mid) . "',{$new_aid},'" . DB_escapeString($filetmp) . "','" . DB_escapeString($purgefiles) . "','" . DB_escapeString($filename) . "',0)");
                            if (DB_error()) {
                                COM_errorLog("Media Gallery: Error - SQL error on inserting record into session_items table");
                            }
                        }
                    }
                } else {
                    $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                    if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                        COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                        $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                        DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                        continue;
                    }
                    //This will set the Content-Type to the appropriate setting for the file
                    switch ($file_extension) {
                        case "exe":
                            $filetype = "application/octet-stream";
                            break;
                        case "zip":
                            $filetype = "application/zip";
                            break;
                        case "mp3":
                            $filetype = "audio/mpeg";
                            break;
                        case "mpg":
                            $filetype = "video/mpeg";
                            break;
                        case "avi":
                            $filetype = "video/x-msvideo";
                            break;
                        default:
                            $filetype = "application/force-download";
                    }
                    list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, '', '', 0, $purgefiles, $filetype, 0, '', '', 0, 0, 0);
                    $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                    MG_SortMedia($album_id);
                    @set_time_limit($time_limit + 20);
                }
                break;
            case 'galleryimport':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                $srcFile = $row['data'];
                // full path
                $album_id = $row['aid'];
                $purgefiles = 0;
                $baseSrcFile = $row['data2'];
                // basefilename
                $views = (int) $row['mid'];
                $caption = $row['data3'];
                $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                    COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                    $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                    continue;
                }
                //This will set the Content-Type to the appropriate setting for the file
                switch ($file_extension) {
                    case "exe":
                        $filetype = "application/octet-stream";
                        break;
                    case "zip":
                        $filetype = "application/zip";
                        break;
                    case "mp3":
                        $filetype = "audio/mpeg";
                        break;
                    case "mpg":
                        $filetype = "video/mpeg";
                        break;
                    case "avi":
                        $filetype = "video/x-msvideo";
                        break;
                    default:
                        $filetype = "application/force-download";
                }
                list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $caption, '', 0, $purgefiles, $filetype, 0, '', '', 0, 0, 0);
                DB_query("UPDATE {$_TABLES['mg_media']} SET media_views=" . (int) $views . ",media_user_id='" . $MG_albums[$album_id]->owner_id . "' WHERE media_id='" . $new_media_id . "'");
                $sql = "SELECT * FROM {$_TABLES['mg_session_items2']} WHERE id=" . $row['id'];
                $gcmtResult2 = DB_query($sql);
                $cRows = DB_numRows($gcmtResult2);
                for ($z = 0; $z < $cRows; $z++) {
                    $row2 = DB_fetchArray($gcmtResult2);
                    $row2['sid'] = $new_media_id;
                    $row2['type'] = 'mediagallery';
                    $cmtTitle = 'Gallery Comment';
                    $cmtText = $row2['data3'];
                    $cmtDate = (int) $row2['data4'];
                    $cmtIP = $row2['data5'];
                    $cmtUid = 1;
                    if ($row2['data1'] != '' && $row2['data1'] != 'everyone') {
                        $sql = "SELECT uid FROM {$_TABLES['users']} WHERE username='******'data1'])) . "'";
                        $uResult = DB_query($sql);
                        $uRows = DB_numRows($uResult);
                        if ($uRows > 0) {
                            $uRow = DB_fetchArray($uResult);
                            $cmtUid = $uRow['uid'];
                        }
                    }
                    $cmtDate = gmdate("Y-m-d H:i:s", $row2['data4']);
                    MG_saveComment($cmtTitle, $cmtText, $row2['sid'], 0, $row2['type'], 'plain', $cmtUid, $cmtDate, $cmtIP);
                }
                $comments = DB_count($_TABLES['comments'], array('sid', 'type'), array($new_media_id, 'mediagallery'));
                DB_change($_TABLES['mg_media'], 'media_comments', $comments, 'media_id', $new_media_id);
                DB_query("DELETE FROM {$_TABLES['mg_session_items2']} WHERE id=" . $row['id']);
                $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                MG_SortMedia($album_id);
                @set_time_limit($time_limit + 20);
                break;
            case 'coppermineimport':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                $srcFile = $row['data'];
                // full path
                $album_id = $row['aid'];
                $sdata = unserialize($row['mid']);
                $views = (int) $sdata[0];
                $uid = (int) $sdata[1];
                $purgefiles = 0;
                $file = basename($row['data']);
                $baseSrcFile = $file;
                $baseSrcFile = MG_replace_accents($baseSrcFile);
                $baseSrcFile = preg_replace("#[ ]#", "_", $baseSrcFile);
                // change spaces to underscore
                $baseSrcFile = preg_replace('#[^()\\.\\-,\\w]#', '_', $baseSrcFile);
                //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
                $baseSrcFile = preg_replace('#(_)+#', '_', $baseSrcFile);
                //eliminate duplicate underscore
                $caption = $row['data3'];
                $description = $row['data2'];
                $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                    COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                    $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('{$session_id}','{$statusMsg}')");
                    continue;
                }
                //This will set the Content-Type to the appropriate setting for the file
                switch ($file_extension) {
                    case "exe":
                        $filetype = "application/octet-stream";
                        break;
                    case "zip":
                        $filetype = "application/zip";
                        break;
                    case "mp3":
                        $filetype = "audio/mpeg";
                        break;
                    case "mpg":
                        $filetype = "video/mpeg";
                        break;
                    case "avi":
                        $filetype = "video/x-msvideo";
                        break;
                    default:
                        $filetype = "application/force-download";
                }
                list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $caption, $description, 0, $purgefiles, $filetype, 0, '', '', 0, 0, 0);
                if ($rc == true) {
                    $sql = "SELECT uid FROM {$_TABLES['users']} WHERE username='******'";
                    $userResult = DB_query($sql);
                    $userRows = DB_numRows($userResult);
                    if ($userRows > 0) {
                        $userRow = DB_fetchArray($userResult);
                        $glUid = $userRow['uid'];
                    } else {
                        $glUid = 1;
                    }
                    DB_query("UPDATE {$_TABLES['mg_media']} SET media_views=" . (int) $views . ",media_user_id='" . $glUid . "' WHERE media_id='" . $new_media_id . "'");
                    $sql = "SELECT * FROM {$_TABLES['mg_session_items2']} WHERE id=" . $row['id'];
                    $gcmtResult2 = DB_query($sql);
                    $cRows = DB_numRows($gcmtResult2);
                    for ($z = 0; $z < $cRows; $z++) {
                        $row2 = DB_fetchArray($gcmtResult2);
                        $row2['sid'] = $new_media_id;
                        $row2['type'] = 'mediagallery';
                        $cmtTitle = 'Coppermine Comment';
                        $cmtText = $row2['data3'];
                        $cmtDate = (int) $row2['data4'];
                        $cmtIP = $row2['data5'];
                        $cmtUid = 1;
                        if ($row2['data1'] != '' && $row2['data1'] != 'everyone') {
                            $sql = "SELECT uid FROM {$_TABLES['users']} WHERE username='******'data1']))) . "'";
                            $uResult = DB_query($sql);
                            $uRows = DB_numRows($uResult);
                            if ($uRows > 0) {
                                $uRow = DB_fetchArray($uResult);
                                $cmtUid = $uRow['uid'];
                            }
                        }
                        $cmtDate = $row2['data4'];
                        // gmdate("Y-m-d H:i:s", $row2['data4']);
                        MG_saveComment($cmtTitle, $cmtText, $row2['sid'], 0, $row2['type'], 'plain', $cmtUid, $cmtDate, $cmtIP);
                    }
                    $comments = DB_count($_TABLES['comments'], array('sid', 'type'), array($new_media_id, 'mediagallery'));
                    DB_change($_TABLES['mg_media'], 'media_comments', $comments, 'media_id', $new_media_id);
                }
                DB_query("DELETE FROM {$_TABLES['mg_session_items2']} WHERE id=" . $row['id']);
                $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                MG_SortMedia($album_id);
                @set_time_limit($time_limit + 20);
                break;
            case 'gallery2import':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                $srcFile = $row['data'];
                // full path
                $album_id = $row['aid'];
                $purgefiles = 0;
                $baseSrcFile = $row['data2'];
                // basefilename
                $views = 0;
                // $row['mid'];
                $caption = $row['data3'];
                $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                    COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                    $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('{$session_id}','{$statusMsg}')");
                    continue;
                }
                //This will set the Content-Type to the appropriate setting for the file
                switch ($file_extension) {
                    case "exe":
                        $filetype = "application/octet-stream";
                        break;
                    case "zip":
                        $filetype = "application/zip";
                        break;
                    case "mp3":
                        $filetype = "audio/mpeg";
                        break;
                    case "mpg":
                        $filetype = "video/mpeg";
                        break;
                    case "avi":
                        $filetype = "video/x-msvideo";
                        break;
                    default:
                        $filetype = "application/force-download";
                }
                list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $caption, '', 0, $purgefiles, $filetype, 0, '', '', 0, 0, 0);
                DB_query("UPDATE {$_TABLES['mg_media']} SET media_views=" . (int) $views . " WHERE media_id='" . $new_media_id . "'");
                $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                MG_SortMedia($album_id);
                @set_time_limit($time_limit + 20);
                break;
            case '4imagesimport':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                $srcFile = $row['data'];
                // full path
                $album_id = $row['aid'];
                $purgefiles = 0;
                $title = $row['data2'];
                $baseSrcFile = basename($row['data']);
                $views = (int) $row['mid'];
                $caption = $row['data3'];
                $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                    COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                    $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                    continue;
                }
                //This will set the Content-Type to the appropriate setting for the file
                switch ($file_extension) {
                    case "exe":
                        $filetype = "application/octet-stream";
                        break;
                    case "zip":
                        $filetype = "application/zip";
                        break;
                    case "mp3":
                        $filetype = "audio/mpeg";
                        break;
                    case "mpg":
                        $filetype = "video/mpeg";
                        break;
                    case "avi":
                        $filetype = "video/x-msvideo";
                        break;
                    default:
                        $filetype = "application/force-download";
                }
                list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $title, $caption, 0, $purgefiles, $filetype, 0, '', '', 0, 0, 0);
                DB_query("UPDATE {$_TABLES['mg_media']} SET media_views=" . (int) $views . " WHERE media_id='" . DB_escapeString($new_media_id) . "'");
                $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                MG_SortMedia($album_id);
                @set_time_limit($time_limit + 20);
                break;
            case 'inmemoriamimport':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                global $INM_TABLES;
                $album_id = $row['aid'];
                $inm_mid = $row['mid'];
                $album_path = $row['data'];
                $inmResult = DB_query("SELECT * FROM {$INM_TABLES['media']} WHERE mid='" . DB_escapeString($inm_mid) . "'");
                $inmNumRows = DB_numRows($inmResult);
                if ($inmNumRows > 0) {
                    $M = DB_fetchArray($inmResult);
                    $srcFile = $album_path . $M['filename'];
                    $baseSrcFile = $M['filename'];
                    $views = (int) $M['hits'];
                    $caption = $M['caption'];
                    $keywords = $M['keywords'];
                    $date = $M['date'];
                    $title = $M['title'];
                    $purgefiles = 0;
                    $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                    if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                        COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                        $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                        DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                        continue;
                    }
                    //This will set the Content-Type to the appropriate setting for the file
                    switch ($file_extension) {
                        case "exe":
                            $filetype = "application/octet-stream";
                            break;
                        case "zip":
                            $filetype = "application/zip";
                            break;
                        case "mp3":
                            $filetype = "audio/mpeg";
                            break;
                        case "mpg":
                            $filetype = "video/mpeg";
                            break;
                        case "avi":
                            $filetype = "video/x-msvideo";
                            break;
                        default:
                            $filetype = "application/force-download";
                    }
                    list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $title, $caption, 0, $purgefiles, $filetype, 0, '', $keywords, 0, 0, 0);
                    DB_query("UPDATE {$_TABLES['mg_media']} SET media_views=" . (int) $views . " WHERE media_id='" . DB_escapeString($new_media_id) . "'");
                    $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                    MG_SortMedia($album_id);
                    @set_time_limit($time_limit + 20);
                    $sql = "SELECT * FROM {$_TABLES['comments']} WHERE sid='" . $row['mid'] . "' AND type='inmemoriam'";
                    $inmResult2 = DB_query($sql);
                    $cRows = DB_numRows($inmResult2);
                    for ($z = 0; $z < $cRows; $z++) {
                        $row2 = DB_fetchArray($inmResult2);
                        $row2['sid'] = $new_media_id;
                        $row2['type'] = 'mediagallery';
                        MG_saveComment($row2['title'], $row2['comment'], $row2['sid'], 0, $row2['type'], 'plain', $row2['uid'], $row2['date']);
                        $comments = DB_count($_TABLES['comments'], array('sid', 'type'), array($new_media_id, 'mediagallery'));
                        DB_change($_TABLES['mg_media'], 'media_comments', $comments, 'media_id', $new_media_id);
                    }
                    // now do the rating...
                    if ($row['totalrating'] > 0) {
                        $rating = $row['totalrating'] / $row['numvotes'];
                        $new_rating = sprintf("%.2f", $rating);
                        $votes = $row['numvotes'];
                        $sql = "UPDATE {$_TABLES['mg_media']} SET media_votes = {$votes}, media_rating = '{$rating}'\n                                        WHERE media_id='" . DB_escapeString($new_media_id) . "'";
                        DB_query($sql);
                    }
                }
                break;
            case 'geekaryimport':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                $album_id = $row['aid'];
                $inm_mid = $row['mid'];
                $gk_album_id = $row['data2'];
                $album_path = $_GKCONST['full_geekage'];
                $inmResult = DB_query("SELECT * FROM {$_TABLES['geekary_images']} WHERE id='" . DB_escapeString($inm_mid) . "'");
                $inmNumRows = DB_numRows($inmResult);
                if ($inmNumRows > 0) {
                    $M = DB_fetchArray($inmResult);
                    $srcFile = $album_path . '/' . $gk_album_id . '/' . $M['file_name'];
                    $baseSrcFile = $M['file_name'];
                    $views = (int) $M['hits'];
                    $caption = $M['description'];
                    $title = $M['name'];
                    $purgefiles = 0;
                    $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                    if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                        COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                        $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                        DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                        continue;
                    }
                    //This will set the Content-Type to the appropriate setting for the file
                    switch ($file_extension) {
                        case "exe":
                            $filetype = "application/octet-stream";
                            break;
                        case "zip":
                            $filetype = "application/zip";
                            break;
                        case "mp3":
                            $filetype = "audio/mpeg";
                            break;
                        case "mpg":
                            $filetype = "video/mpeg";
                            break;
                        case "avi":
                            $filetype = "video/x-msvideo";
                            break;
                        default:
                            $filetype = "application/force-download";
                    }
                    list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $title, $caption, 0, $purgefiles, $filetype, 0, '', $keywords, 0, 0, 0);
                    DB_query("UPDATE {$_TABLES['mg_media']} SET media_views=" . (int) $views . " WHERE media_id='" . DB_escapeString($new_media_id) . "'");
                    $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                    MG_SortMedia($album_id);
                    @set_time_limit($time_limit + 20);
                }
                break;
            case 'gl_storyimport':
                require_once $_CONF['path'] . 'plugins/mediagallery/include/lib-upload.php';
                require_once $_CONF['path'] . 'plugins/mediagallery/include/sort.php';
                require_once $_CONF['path_system'] . 'lib-story.php';
                require_once $_CONF['path_system'] . 'classes/story.class.php';
                $album_id = $row['aid'];
                $srcFile = $row['data'];
                $baseSrcFile = basename($row['data']);
                $sid = $row['data3'];
                $purgefiles = 0;
                $caption = '';
                $imageNumber = $row['data2'];
                $file_extension = strtolower(substr(strrchr($baseSrcFile, "."), 1));
                if ($MG_albums[$album_id]->max_filesize != 0 && filesize($srcFile) > $MG_albums[$album_id]->max_filesize) {
                    COM_errorLog("MediaGallery: File " . $baseSrcFile . " exceeds maximum filesize for this album.");
                    $statusMsg = DB_escapeString(sprintf($LANG_MG02['upload_exceeds_max_filesize'], $baseSrcFile));
                    DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                    continue;
                }
                //This will set the Content-Type to the appropriate setting for the file
                switch ($file_extension) {
                    case "exe":
                        $filetype = "application/octet-stream";
                        break;
                    case "zip":
                        $filetype = "application/zip";
                        break;
                    case "mp3":
                        $filetype = "audio/mpeg";
                        break;
                    case "mpg":
                        $filetype = "video/mpeg";
                        break;
                    case "avi":
                        $filetype = "video/x-msvideo";
                        break;
                    default:
                        $filetype = "application/force-download";
                }
                list($rc, $msg) = MG_getFile($srcFile, $baseSrcFile, $album_id, $caption, '', 0, $purgefiles, $filetype, 0, '', $mid, 0, 0, 0);
                $mid = $new_media_id;
                $statusMsg = DB_escapeString($baseSrcFile . " " . $msg);
                DB_query("INSERT INTO {$_TABLES['mg_session_log']} (session_id,session_log) VALUES ('" . DB_escapeString($session_id) . "','{$statusMsg}')");
                MG_SortMedia($album_id);
                // now update the tag in the article...
                $sResult = DB_query("SELECT * FROM {$_TABLES['stories']} WHERE sid='" . DB_escapeString($sid) . "'");
                $howmany = DB_numRows($sResult);
                $S = DB_fetchArray($sResult);
                $story = new Story();
                $story->loadFromArray($S);
                $intro = $story->replaceImages($S['introtext']);
                $body = $story->replaceImages($S['bodytext']);
                $atag = $session['session_var0'];
                $align = $session['session_var1'];
                $delete = $session['session_var2'];
                $norm = '[image' . $imageNumber . ']';
                $left = '[image' . $imageNumber . '_left]';
                $right = '[image' . $imageNumber . '_right]';
                $mg_norm = '[' . $atag . ':' . $mid . ' align:' . $align . ']';
                $mg_left = '[' . $atag . ':' . $mid . ' align:left]';
                $mg_right = '[' . $atag . ':' . $mid . ' align:right]';
                $intro = str_replace($norm, $mg_norm, $intro);
                $body = str_replace($norm, $mg_norm, $body);
                $intro = str_replace($left, $mg_left, $intro);
                $body = str_replace($left, $mg_left, $body);
                $intro = str_replace($right, $mg_right, $intro);
                $body = str_replace($right, $mg_right, $body);
                $norm = '[unscaled' . $imageNumber . ']';
                $left = '[unscaled' . $imageNumber . '_left]';
                $right = '[unscaled' . $imageNumber . '_right]';
                $mg_norm = '[oimage:' . $mid . ' align:' . $align . ']';
                $mg_left = '[oimage:' . $mid . ' align:left]';
                $mg_right = '[oimage:' . $mid . ' align:right]';
                $intro = str_replace($norm, $mg_norm, $intro);
                $body = str_replace($norm, $mg_norm, $body);
                $intro = str_replace($left, $mg_left, $intro);
                $body = str_replace($left, $mg_left, $body);
                $intro = str_replace($right, $mg_right, $intro);
                $body = str_replace($right, $mg_right, $body);
                DB_query("UPDATE {$_TABLES['stories']} SET introtext='" . DB_escapeString($intro) . "', bodytext='" . DB_escapeString($body) . "' WHERE sid='" . $sid . "'");
                if ($delete == 1) {
                    $sql = "DELETE FROM {$_TABLES['article_images']} WHERE ai_sid='" . DB_escapeString($sid) . "'";
                    DB_query($sql);
                }
                @set_time_limit($time_limit + 20);
                break;
            default:
                // no valid action defined...
                break;
        }
        DB_query("UPDATE {$_TABLES['mg_session_items']} SET status=1 WHERE id=" . $row['id']);
        // calculate time for each loop iteration
        $temp_time[$num_rows] = time() - $start_temp_time;
        // get the max
        $timer_time = max($temp_time);
        $num_rows++;
        // check if timer is about to expire
        if (time() - $cycle_start_time >= $time_limit - $timer_time) {
            $timer_expired_secs = time() - $cycle_start_time;
            $timer_expired = true;
        }
    }
    // end the timer
    $cycle_end_time = time();
    // find how much time the last cycle took
    $last_cycle_time = $cycle_end_time - $cycle_start_time;
    $T = new Template(MG_getTemplatePath(0));
    $T->set_file('batch', 'batch_progress.thtml');
    $processing_messages = '<span style="font-weight:bold;">';
    $processing_messages .= $timer_expired ? sprintf($LANG_MG01['timer_expired'], $timer_expired_secs) : '';
    $processing_messages .= '</span>';
    $sql = "SELECT COUNT(*) as processed FROM {$_TABLES['mg_session_items']} WHERE session_id='" . $session_id . "' AND status=1";
    $result = DB_query($sql);
    $row = DB_fetchArray($result);
    $session_items_processed = $row['processed'];
    $sql = "SELECT COUNT(*) as processing FROM {$_TABLES['mg_session_items']} WHERE session_id='" . $session_id . "'";
    $result = DB_query($sql);
    $row = DB_fetchArray($result);
    $session_items_processing = $row['processing'];
    $items_remaining = $session_items_processing - $session_items_processed;
    if ($items_remaining > 0) {
        if ($item_limit == 0) {
            $processing_messages .= '<b>' . $LANG_MG01['begin_processing'] . '</b>';
            $item_limit = $_MG_CONF['def_item_limit'];
        } else {
            $processing_messages .= sprintf('<b>' . $LANG_MG01['processing_next_items'] . '</b>', $item_limit);
        }
        $form_action = $_MG_CONF['site_url'] . '/batch.php?mode=continue&amp;sid=' . $session_id . '&amp;refresh=' . $refresh_rate . '&amp;limit=' . $item_limit;
        $next_button = $LANG_MG01['next'];
        // create the meta tag for refresh
        $T->set_var(array("META" => '<meta http-equiv="refresh" content="' . $refresh_rate . ';url=' . $form_action . '"/>'));
    } else {
        if ($item_limit == 0) {
            echo COM_refresh($session['session_origin']);
            exit;
        }
        $next_button = $LANG_MG01['finished'];
        $processing_messages .= '<b>' . $LANG_MG01['all_done'] . '</b><br /><br />';
        $T->set_var(array("META" => ''));
        $refresh_rate = -1;
        $form_action = $session['session_origin'];
        $result = DB_query("SELECT * FROM {$_TABLES['mg_session_log']} WHERE session_id='" . $session_id . "'");
        $nRows = DB_numRows($result);
        for ($i = 0; $i < $nRows; $i++) {
            $row = DB_fetchArray($result);
            $processing_messages .= $row['session_log'] . '<br />';
        }
        MG_endSession($session_id);
    }
    $session_percent = $session_items_processed / $session_items_processing * 100;
    $session_time = $cycle_end_time - $session['session_start_time'];
    // create the percent boxes
    $pct_box = _mg_create_percent_box('session', _mg_create_percent_color($session_percent), $session_percent);
    $T->set_var(array('L_BATCH_PROCESS' => $label, 'L_BATCH' => $LANG_MG01['batch_processor'], 'L_NEXT' => $next_button, 'L_PROCESSING' => $LANG_MG01['processing'], 'L_CANCEL' => $LANG_MG01['cancel'], 'L_PROCESSING_DETAILS' => $LANG_MG01['processing_details'], 'L_STATUS' => $LANG_MG01['status'], 'L_TOTAL_ITEMS' => $LANG_MG01['total_items'], 'L_ITEMS_PROCESSED' => $LANG_MG01['processed_items'], 'L_ITEMS_REMAINING' => $LANG_MG01['items_remaining'], 'L_POSTS_LAST_CYCLE' => $LANG_MG01['items_last_cycle'], 'L_TIME_LIMIT' => $LANG_MG01['time_limit'], 'L_REFRESH_RATE' => $LANG_MG01['refresh_rate'], 'L_ITEM_RATE' => $LANG_MG01['item_rate'], 'L_ACTIVE_PARAMETERS' => $LANG_MG01['batch_parameters'], 'L_ITEMS_PER_CYCLE' => $LANG_MG01['items_per_cycle'], 'TOTAL_ITEMS' => $session_items_processing, 'ITEMS_PROCESSED' => $session_items_processed, 'ITEMS_REMAINING' => $session_items_processing - $session_items_processed, 'ITEM_RATE' => sprintf($LANG_MG01['seconds_per_item'], round(@($last_cycle_time / $num_rows))), 'PROCESSING_MESSAGES' => $processing_messages, 'SESSION_PERCENT_BOX' => $pct_box, 'SESSION_PERCENT' => sprintf($LANG_MG01['percent_completed'], round($session_percent, 2)), 'POST_LIMIT' => $num_rows, 'ITEM_LIMIT' => $item_limit, 'TIME_LIMIT' => $time_limit, 'REFRESH_RATE' => $refresh_rate, 'PERCENT_COMPLETE' => $session_percent, 'S_BATCH_ACTION' => $form_action));
    $T->parse('output', 'batch');
    $retval .= $T->finish($T->get_var('output'));
    return $retval;
}
示例#4
0
function _MG_getFile($filename, $file, $albums, $caption = '', $description = '', $upload = 1, $purgefiles = 0, $filetype, $atttn, $thumbnail, $keywords = '', $category = 0, $dnc = 0, $replace = 0, $userid)
{
    global $MG_albums, $_CONF, $_MG_CONF, $_USER, $_TABLES, $LANG_MG00, $LANG_MG01, $LANG_MG02, $new_media_id;
    $artist = '';
    $musicAlbum = '';
    $genre = '';
    $video_attached_thumbnail = 0;
    $successfulWatermark = 0;
    $dnc = 1;
    $errors = 0;
    $errMsg = '';
    clearstatcache();
    if (!file_exists($filename)) {
        $errMsg = $LANG_MG02['upload_not_found'];
        return array(false, $errMsg);
    }
    clearstatcache();
    if (!is_readable($filename)) {
        $errMsg = $LANG_MG02['upload_not_readable'];
        return array(false, $errMsg);
    }
    // make sure we have the proper permissions to upload to this album....
    if (!isset($MG_albums[$albums]->id)) {
        $errMsg = $LANG_MG02['album_nonexist'];
        // "Album does not exist, unable to process uploads";
        return array(false, $errMsg);
    }
    sleep(1);
    // We do this to make sure we don't get dupe sid's
    /*
     * The following section of code will generate a unique name for a temporary
     * file and copy the uploaded file to the Media Gallery temp directory.
     * We do this to prevent any SAFE MODE issues when we later open the
     * file to determine the mime type.
     */
    if (empty($_USER['username']) || $_USER['username'] == '') {
        $_USER['username'] = '******';
    }
    $tmpPath = $_MG_CONF['tmp_path'] . '/' . $_USER['username'] . COM_makesid() . '.tmp';
    if ($upload) {
        $rc = @move_uploaded_file($filename, $tmpPath);
    } else {
        $rc = @copy($filename, $tmpPath);
        $importSource = $filename;
    }
    if ($rc != 1) {
        $errors++;
        $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
        @unlink($tmpPath);
        return array(false, $errMsg);
    }
    $filename = $tmpPath;
    if ($replace > 0) {
        $new_media_id = $replace;
    } else {
        $new_media_id = COM_makesid();
    }
    $media_time = time();
    $media_upload_time = time();
    $media_user_id = $userid;
    $mimeInfo = IMG_getMediaMetaData($filename);
    $mimeExt = strtolower(substr(strrchr($file, "."), 1));
    $mimeInfo['type'] = $mimeExt;
    if (!isset($mimeInfo['mime_type']) || $mimeInfo['mime_type'] == '') {
        $mimeInfo['mime_type'] = $filetype;
    }
    $gotTN = 0;
    if (isset($mimeInfo['id3v2']['APIC'][0]['mime']) && $mimeInfo['id3v2']['APIC'][0]['mime'] == 'image/jpeg') {
        $mp3AttachdedThumbnail = $mimeInfo['id3v2']['APIC'][0]['data'];
        $gotTN = 1;
    }
    if ($mimeExt == '' || $mimeInfo['mime_type'] == 'application/octet-stream' || $mimeInfo['mime_type'] == '') {
        // assume format based on file upload info...
        switch ($filetype) {
            case 'audio/mpeg':
                $mimeInfo['type'] = 'mp3';
                $mimeInfo['mime_type'] = 'audio/mpeg';
                $mimeExt = 'mp3';
                break;
            case 'image/tga':
                $mimeInfo['type'] = 'tga';
                $mimeInfo['mime_type'] = 'image/tga';
                $mimeExt = 'tga';
                break;
            case 'image/psd':
                $mimeInfo['type'] = 'psd';
                $mimeInfo['mime_type'] = 'image/psd';
                $mimeExt = 'psd';
                break;
            case 'image/gif':
                $mimeInfo['type'] = 'gif';
                $mimeInfo['mime_type'] = 'image/gif';
                $mimeExt = 'gif';
                break;
            case 'image/jpeg':
            case 'image/jpg':
                $mimeInfo['type'] = 'jpg';
                $mimeInfo['mime_type'] = 'image/jpeg';
                $mimeExt = 'jpg';
                break;
            case 'image/png':
                $mimeInfo['type'] = 'png';
                $mimeInfo['mime_type'] = 'image/png';
                $mimeExt = 'png';
                break;
            case 'image/bmp':
                $mimeInfo['type'] = 'bmp';
                $mimeInfo['mime_type'] = 'image/bmp';
                $mimeExt = 'bmp';
                break;
            case 'application/x-shockwave-flash':
                $mimeInfo['type'] = 'swf';
                $mimeInfo['mime_type'] = 'application/x-shockwave-flash';
                $mimeExt = 'swf';
                break;
            case 'application/zip':
                $mimeInfo['type'] = 'zip';
                $mimeInfo['mime_type'] = 'application/zip';
                $mimeExt = 'zip';
                break;
            case 'audio/mpeg':
                $mimeInfo['type'] = 'mp3';
                $mimeInfo['mime_type'] = 'audio/mpeg';
                $mimeExt = 'mp3';
                break;
            case 'video/quicktime':
                $mimeInfo['type'] = 'mov';
                $mimeInfo['mime_type'] = 'video/quicktime';
                $mimeExt = 'mov';
                break;
            case 'video/x-m4v':
                $mimeInfo['type'] = 'mov';
                $mimeInfo['mime_type'] = 'video/x-m4v';
                $mimeExt = 'mov';
                break;
            case 'video/x-flv':
                $mimeInfo['type'] = 'flv';
                $mimeInfo['mime_type'] = 'video/x-flv';
                $mimeExt = 'flv';
                break;
            case 'audio/x-ms-wma':
                $mimeInfo['type'] = 'wma';
                $mimeInfo['mime_type'] = 'audio/x-ms-wma';
                $mimeExt = 'wma';
                break;
            default:
                $file_extension = strtolower(substr(strrchr($file, "."), 1));
                switch ($file_extension) {
                    case 'flv':
                        $mimeInfo['type'] = 'flv';
                        $mimeInfo['mime_type'] = 'video/x-flv';
                        $mimeExt = 'flv';
                        break;
                    case 'wma':
                        $mimeInfo['type'] = 'wma';
                        $mimeInfo['mime_type'] = 'audio/x-ms-wma';
                        $mimeExt = 'wma';
                        break;
                    default:
                        $mimeInfo['type'] = 'file';
                        if ($filetype != '') {
                            $mimeInfo['mime_type'] = $filetype;
                        } else {
                            $mimeInfo['mime_type'] = 'application/octet-stream';
                        }
                        $mimeExt = $file_extension;
                        break;
                }
        }
    }
    switch ($mimeInfo['mime_type']) {
        case 'audio/mpeg':
            $format_type = MG_MP3;
            break;
        case 'image/gif':
            $format_type = MG_GIF;
            break;
        case 'image/jpeg':
        case 'image/jpg':
            $format_type = MG_JPG;
            break;
        case 'image/png':
            $format_type = MG_PNG;
            break;
        case 'image/bmp':
            $format_type = MG_BMP;
            break;
        case 'application/x-shockwave-flash':
            $format_type = MG_SWF;
            break;
        case 'application/zip':
            $format_type = MG_ZIP;
            break;
        case 'video/mpeg':
        case 'video/x-motion-jpeg':
        case 'video/quicktime':
        case 'video/mpeg':
        case 'video/x-mpeg':
        case 'video/x-mpeq2a':
        case 'video/x-qtc':
        case 'video/x-m4v':
            $format_type = MG_MOV;
            break;
        case 'video/x-flv':
            $format_type = MG_FLV;
            break;
        case 'image/tiff':
            $format_type = MG_TIF;
            break;
        case 'image/x-targa':
        case 'image/tga':
            $format_type = MG_TGA;
            break;
        case 'image/psd':
            $format_type = MG_PSD;
            break;
        case 'application/ogg':
            $format_type = MG_OGG;
            break;
        case 'audio/x-ms-wma':
        case 'audio/x-ms-wax':
        case 'audio/x-ms-wmv':
        case 'video/x-ms-asf':
        case 'video/x-ms-asf-plugin':
        case 'video/avi':
        case 'video/msvideo':
        case 'video/x-msvideo':
        case 'video/avs-video':
        case 'video/x-ms-wmv':
        case 'video/x-ms-wvx':
        case 'video/x-ms-wm':
        case 'application/x-troff-msvideo':
        case 'application/x-ms-wmz':
        case 'application/x-ms-wmd':
            $format_type = MG_ASF;
            break;
        case 'application/pdf':
            $format_type = MG_OTHER;
            break;
        default:
            $format_type = MG_OTHER;
            break;
    }
    $mimeType = $mimeInfo['mime_type'];
    if ($filetype == 'video/x-m4v') {
        $mimeType = 'video/x-m4v';
        $mimeInfo['mime_type'] = 'video/x-m4v';
    }
    if (!($MG_albums[$albums]->valid_formats & $format_type)) {
        return array(false, $LANG_MG02['format_not_allowed']);
    }
    if ($replace > 0) {
        $sql = "SELECT * FROM {$_TABLES['mg_media']} WHERE media_id='" . DB_escapeString($replace) . "'";
        $result = DB_query($sql);
        $row = DB_fetchArray($result);
        $media_filename = $row['media_filename'];
    } else {
        if ($_MG_CONF['preserve_filename'] == 1) {
            $loopCounter = 0;
            $digitCounter = 1;
            $file_name = stripslashes($file);
            $file_name = MG_replace_accents($file_name);
            $file_name = preg_replace("#[ ]#", "_", $file_name);
            // change spaces to underscore
            $file_name = preg_replace('#[^\\.\\-,\\w]#', '_', $file_name);
            //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
            $file_name = preg_replace('#(_)+#', '_', $file_name);
            //eliminate duplicate underscore
            $pos = strrpos($file_name, '.');
            if ($pos === false) {
                $basefilename = $file_name;
            } else {
                $basefilename = strtolower(substr($file_name, 0, $pos));
            }
            do {
                clearstatcache();
                $media_filename = substr(md5(uniqid(rand())), 0, $digitCounter) . '_' . $basefilename;
                $loopCounter++;
                if ($loopCounter > 16) {
                    $digitCounter++;
                    $loopCounter = 0;
                }
            } while (MG_file_exists($media_filename));
        } else {
            do {
                clearstatcache();
                $media_filename = md5(uniqid(rand()));
            } while (MG_file_exists($media_filename));
        }
    }
    // replace a few mime extentions here...
    //
    $mimeExtLower = strtolower($mimeExt);
    if ($mimeExtLower == 'php') {
        $mimeExt = 'phps';
    } else {
        if ($mimeExtLower == 'pl') {
            $mimeExt = 'txt';
        } else {
            if ($mimeExtLower == 'cgi') {
                $mimeExt = 'txt';
            } else {
                if ($mimeExtLower == 'py') {
                    $mimeExt = 'txt';
                } else {
                    if ($mimeExtLower == 'sh') {
                        $mimeExt = 'txt';
                    } else {
                        if ($mimeExtLower == 'rb') {
                            $mimeExt = 'txt';
                        }
                    }
                }
            }
        }
    }
    $disp_media_filename = $media_filename . '.' . $mimeExt;
    switch ($mimeType) {
        case 'image/psd':
        case 'image/x-targa':
        case 'image/tga':
        case 'image/photoshop':
        case 'image/x-photoshop':
        case 'image/psd':
        case 'application/photoshop':
        case 'application/psd':
        case 'image/tiff':
        case 'image/gif':
        case 'image/jpeg':
        case 'image/jpg':
        case 'image/png':
        case 'image/bmp':
            if ($mimeType == 'image/psd' || $mimeType == 'image/x-targa' || $mimeType == 'image/tga' || $mimeType == 'image/photoshop' || $mimeType == 'image/x-photoshop' || $mimeType == 'image/psd' || $mimeType == 'application/photoshop' || $mimeType == 'application/psd' || $mimeType == 'image/tiff') {
                $media_orig = $_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . "." . $mimeExt;
                $media_disp = $_MG_CONF['path_mediaobjects'] . 'disp/' . $media_filename[0] . '/' . $media_filename . ".jpg";
                $media_tn = $_MG_CONF['path_mediaobjects'] . 'tn/' . $media_filename[0] . '/' . $media_filename . ".jpg";
            } else {
                $media_orig = $_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . "." . $mimeExt;
                $media_disp = $_MG_CONF['path_mediaobjects'] . 'disp/' . $media_filename[0] . '/' . $media_filename . "." . $mimeExt;
                $media_tn = $_MG_CONF['path_mediaobjects'] . 'tn/' . $media_filename[0] . '/' . $media_filename . "." . $mimeExt;
            }
            $mimeType = $mimeInfo['mime_type'];
            // process image file
            $media_time = getOriginationTimestamp($filename);
            if ($media_time == null || $media_time < 0) {
                $media_time = time();
            }
            $rc = @copy($filename, $media_orig);
            if ($rc != 1) {
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                @chmod($media_orig, 0644);
                list($rc, $msg) = MG_convertImage($media_orig, $media_tn, $media_disp, $mimeExt, $mimeType, $albums, $media_filename, $dnc);
                if ($rc == false) {
                    $errors++;
                    $errMsg .= $msg;
                    // sprintf($LANG_MG02['convert_error'],$filename);
                } else {
                    $mediaType = 0;
                    if ($_MG_CONF['discard_original'] == 1 && ($mimeType == 'image/jpeg' || $mimeType == 'image/jpg' || $mimeType == 'image/png' || $mimeType == 'image/bmp' || $mimeType == 'image/gif')) {
                        if ($_MG_CONF['jhead_enabled'] && ($mimeType == 'image/jpeg' || $mimeType == 'image/jpg')) {
                            $rc = MG_execWrapper('"' . $_MG_CONF['jhead_path'] . "/jhead" . '"' . " -te " . $media_orig . " " . $media_disp);
                        }
                        @unlink($media_orig);
                    }
                    if ($MG_albums[$albums]->wm_auto) {
                        if ($_MG_CONF['discard_original'] == 1) {
                            $rc = MG_watermark($media_disp, $albums, 1);
                            if ($rc == TRUE) {
                                $successfulWatermark = 1;
                            }
                        } else {
                            $rc1 = MG_watermark($media_orig, $albums, 1);
                            $rc2 = MG_watermark($media_disp, $albums, 0);
                            if ($rc1 == TRUE && $rc2 == TRUE) {
                                $successfulWatermark = 1;
                            }
                        }
                    }
                    if ($dnc != 1) {
                        if ($mimeType != 'image/tga' && $mimeType != 'image/x-targa' && $mimeType != 'image/tiff') {
                            if ($mimeType != 'image/photoshop' && $mimeType != 'image/x-photoshop' && $mimeType != 'image/psd' && $mimeType != 'application/photoshop' && $mimeType != 'application/psd') {
                                $mimeExt = 'jpg';
                                $mimeType = 'image/jpeg';
                            }
                        }
                    }
                }
            }
            break;
        case 'video/quicktime':
        case 'video/mpeg':
        case 'video/x-flv':
        case 'video/x-ms-asf':
        case 'video/x-ms-asf-plugin':
        case 'video/avi':
        case 'video/msvideo':
        case 'video/x-msvideo':
        case 'video/avs-video':
        case 'video/x-ms-wmv':
        case 'video/x-ms-wvx':
        case 'video/x-ms-wm':
        case 'application/x-troff-msvideo':
        case 'application/x-shockwave-flash':
        case 'video/mp4':
        case 'video/x-m4v':
            $mimeType = $mimeInfo['mime_type'];
            if ($filetype == 'video/mp4') {
                $mimeExt = 'mp4';
            }
            // process video format
            $media_orig = $_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . '.' . $mimeExt;
            $rc = @copy($filename, $media_orig);
            if ($rc != 1) {
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                @chmod($media_orig, 0644);
                $mediaType = 1;
            }
            $video_attached_thumbnail = MG_videoThumbnail($albums, $media_orig, $media_filename);
            break;
        case 'application/ogg':
        case 'audio/mpeg':
        case 'audio/x-ms-wma':
        case 'audio/x-ms-wax':
        case 'audio/x-ms-wmv':
            $mimeType = $mimeInfo['mime_type'];
            // process audio format
            $media_orig = $_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . '.' . $mimeExt;
            $rc = @copy($filename, $media_orig);
            if (isset($mimeInfo['tags']['id3v1']['title'][0])) {
                if ($caption == '') {
                    $caption = $mimeInfo['tags']['id3v1']['title'][0];
                }
            }
            if (isset($mimeInfo['tags']['id3v1']['artist'][0])) {
                $artist = DB_escapeString($mimeInfo['tags']['id3v1']['artist'][0]);
            }
            if (isset($mimeInfo['tags']['id3v2']['genre'][0])) {
                $genre = DB_escapeString($mimeInfo['tags']['id3v2']['genre'][0]);
            }
            if (isset($mimeInfo['tags']['id3v1']['album'][0])) {
                $musicAlbum = DB_escapeString($mimeInfo['tags']['id3v1']['album'][0]);
            }
            if ($rc != 1) {
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                $mediaType = 2;
            }
            break;
        case 'zip':
        case 'application/zip':
            if ($_MG_CONF['zip_enabled']) {
                $errMsg .= MG_processZip($filename, $albums, $purgefiles, $media_filename);
                break;
            }
            // NO BREAK HERE, fall through if enable zip isn't allowed
        // NO BREAK HERE, fall through if enable zip isn't allowed
        default:
            $media_orig = $_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . "." . $mimeExt;
            $mimeType = $mimeInfo['mime_type'];
            $rc = @copy($filename, $media_orig);
            if ($rc != 1) {
                $errors++;
                $errMsg .= sprintf($LANG_MG02['move_error'], $filename);
            } else {
                if ($purgefiles) {
                    @unlink($importSource);
                }
                $mediaType = 4;
            }
            $mediaType = 4;
            break;
    }
    // update quota
    $quota = $MG_albums[$albums]->album_disk_usage;
    if ($_MG_CONF['discard_original'] == 1) {
        $quota += @filesize($_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . '.' . $mimeExt);
        $quota += @filesize($_MG_CONF['path_mediaobjects'] . 'disp/' . $media_filename[0] . '/' . $media_filename . '.jpg');
    } else {
        $quota += @filesize($_MG_CONF['path_mediaobjects'] . 'orig/' . $media_filename[0] . '/' . $media_filename . '.' . $mimeExt);
    }
    DB_query("UPDATE {$_TABLES['mg_albums']} SET album_disk_usage=" . $quota . " WHERE album_id=" . $albums);
    if ($errors) {
        @unlink($tmpPath);
        return array(false, $errMsg);
    }
    if (($mimeType != 'application/zip' || $_MG_CONF['zip_enabled'] == 0) && $errors == 0) {
        // Now we need to process an uploaded thumbnail
        if ($gotTN == 1) {
            $mp3TNFilename = $_MG_CONF['tmp_path'] . '/mp3tn' . time() . '.jpg';
            $fn = fopen($mp3TNFilename, "w");
            fwrite($fn, $mp3AttachdedThumbnail);
            fclose($fn);
            $saveThumbnailName = $_MG_CONF['path_mediaobjects'] . 'tn/' . $media_filename[0] . '/tn_' . $media_filename;
            MG_attachThumbnail($albums, $mp3TNFilename, $saveThumbnailName);
            @unlink($mp3TNFilename);
            $atttn = 1;
        } else {
            if ($atttn == 1) {
                $saveThumbnailName = $_MG_CONF['path_mediaobjects'] . 'tn/' . $media_filename[0] . '/tn_' . $media_filename;
                MG_attachThumbnail($albums, $thumbnail, $saveThumbnailName);
            }
        }
        if ($video_attached_thumbnail) {
            $atttn = 1;
        }
        if ($MG_albums[$albums]->enable_html != 1) {
            //        if ($_MG_CONF['htmlallowed'] != 1 ) {
            $media_desc = DB_escapeString(htmlspecialchars(strip_tags(COM_checkWords(COM_killJS($description)))));
            $media_caption = DB_escapeString(htmlspecialchars(strip_tags(COM_checkWords(COM_killJS($caption)))));
            $media_keywords = DB_escapeString(htmlspecialchars(strip_tags(COM_checkWords(COM_killJS($keywords)))));
        } else {
            $media_desc = DB_escapeString(COM_checkHTML(COM_killJS($description)));
            $media_caption = DB_escapeString(COM_checkHTML(COM_killJS($caption)));
            $media_keywords = DB_escapeString(COM_checkHTML(COM_killJS($keywords)));
        }
        // Check and see if moderation is on.  If yes, place in mediasubmission
        if ($MG_albums[$albums]->moderate == 1 && !$MG_albums[0]->owner_id) {
            $tableMedia = $_TABLES['mg_mediaqueue'];
            $tableMediaAlbum = $_TABLES['mg_media_album_queue'];
            $queue = 1;
        } else {
            $tableMedia = $_TABLES['mg_media'];
            $tableMediaAlbum = $_TABLES['mg_media_albums'];
            $queue = 0;
        }
        $original_filename = DB_escapeString($file);
        if ($MG_albums[$albums]->filename_title) {
            if ($media_caption == '') {
                $pos = strrpos($original_filename, '.');
                if ($pos === false) {
                    $media_caption = $original_filename;
                } else {
                    $media_caption = substr($original_filename, 0, $pos);
                }
            }
        }
        $resolution_x = 0;
        $resolution_y = 0;
        // try to find a resolution if video...
        if ($mediaType == 1) {
            switch ($mimeType) {
                case 'application/x-shockwave-flash':
                case 'video/quicktime':
                case 'video/mpeg':
                case 'video/x-m4v':
                    if (isset($mimeInfo['video']['resolution_x']) && isset($mimeInfo['video']['resolution_x'])) {
                        $resolution_x = $mimeInfo['video']['resolution_x'];
                        $resolution_y = $mimeInfo['video']['resolution_y'];
                    } else {
                        $resolution_x = -1;
                        $resolution_y = -1;
                    }
                    break;
                case 'video/x-flv':
                    if ($mimeInfo['video']['resolution_x'] < 1 || $mimeInfo['video']['resolution_y'] < 1) {
                        if (isset($mimeInfo['meta']['onMetaData']['width']) && isset($mimeInfo['meta']['onMetaData']['height'])) {
                            $resolution_x = $mimeInfo['meta']['onMetaData']['width'];
                            $resolution_y = $mimeInfo['meta']['onMetaData']['height'];
                        } else {
                            $resolution_x = -1;
                            $resolution_y = -1;
                        }
                    } else {
                        $resolution_x = $mimeInfo['video']['resolution_x'];
                        $resolution_y = $mimeInfo['video']['resolution_y'];
                    }
                    break;
                case 'video/x-ms-asf':
                case 'video/x-ms-asf-plugin':
                case 'video/avi':
                case 'video/msvideo':
                case 'video/x-msvideo':
                case 'video/avs-video':
                case 'video/x-ms-wmv':
                case 'video/x-ms-wvx':
                case 'video/x-ms-wm':
                case 'application/x-troff-msvideo':
                    if (isset($mimeInfo['video']['streams']['2']['resolution_x']) && isset($mimeInfo['video']['streams']['2']['resolution_y'])) {
                        $resolution_x = $mimeInfo['video']['streams']['2']['resolution_x'];
                        $resolution_y = $mimeInfo['video']['streams']['2']['resolution_y'];
                    } else {
                        $resolution_x = -1;
                        $resolution_y = -1;
                    }
                    break;
            }
        }
        if ($replace > 0) {
            $sql = "UPDATE " . $tableMedia . " SET\n\t        \t\t\t\t\tmedia_filename='" . DB_escapeString($media_filename) . "',\n\t        \t\t\t\t\tmedia_original_filename='{$original_filename}',\n\t        \t\t\t\t\tmedia_mime_ext='" . DB_escapeString($mimeExt) . "',\n\t        \t\t\t\t\tmime_type='" . DB_escapeString($mimeType) . "',\n\t        \t\t\t\t\tmedia_time='" . DB_escapeString($media_time) . "',\n\t        \t\t\t\t\tmedia_user_id='" . DB_escapeString($media_user_id) . "',\n\t        \t\t\t\t\tmedia_type='" . DB_escapeString($mediaType) . "',\n\t        \t\t\t\t\tmedia_upload_time='" . DB_escapeString($media_upload_time) . "',\n\t        \t\t\t\t\tmedia_watermarked='" . DB_escapeString($successfulWatermark) . "',\n\t        \t\t\t\t\tmedia_resolution_x='" . DB_escapeString($resolution_x) . "',\n\t        \t\t\t\t\tmedia_resolution_y='" . DB_escapeString($resolution_y) . "'\n\t        \t\t\t\t\tWHERE media_id='" . DB_escapeString($replace) . "'";
            DB_query($sql);
        } else {
            $sql = "INSERT INTO " . $tableMedia . " (media_id,media_filename,media_original_filename,media_mime_ext,media_exif,mime_type,media_title,media_desc,media_keywords,media_time,media_views,media_comments,media_votes,media_rating,media_tn_attached,media_tn_image,include_ss,media_user_id,media_user_ip,media_approval,media_type,media_upload_time,media_category,media_watermarked,v100,maint,media_resolution_x,media_resolution_y,remote_media,remote_url,artist,album,genre)\n\t                VALUES ('{$new_media_id}','{$media_filename}','{$original_filename}','{$mimeExt}','1','{$mimeType}','{$media_caption}','{$media_desc}','{$media_keywords}','{$media_time}','0','0','0','0.00','{$atttn}','','1','{$media_user_id}','','0','{$mediaType}','{$media_upload_time}','{$category}','{$successfulWatermark}','0','0',{$resolution_x},{$resolution_y},0,'','{$artist}','{$musicAlbum}','{$genre}');";
            DB_query($sql);
            $x = 0;
            $sql = "SELECT MAX(media_order) + 10 AS media_seq FROM " . $_TABLES['mg_media_albums'] . " WHERE album_id = " . $albums;
            $result = DB_query($sql);
            $row = DB_fetchArray($result);
            $media_seq = $row['media_seq'];
            if ($media_seq < 10) {
                $media_seq = 10;
            }
            $sql = "INSERT INTO " . $tableMediaAlbum . " (media_id, album_id, media_order) VALUES ('{$new_media_id}', {$albums}, {$media_seq} )";
            DB_query($sql);
            if ($mediaType == 1 && $resolution_x > 0 && $resolution_y > 0 && $_MG_CONF['use_default_resolution'] == 0) {
                DB_save($_TABLES['mg_playback_options'], 'media_id,option_name,option_value', "'{$new_media_id}','width',       '{$resolution_x}'");
                DB_save($_TABLES['mg_playback_options'], 'media_id,option_name,option_value', "'{$new_media_id}','height',      '{$resolution_y}'");
            }
            // update the media count for the album, only if no moderation...
            if ($queue == 0) {
                $MG_albums[$albums]->media_count++;
                DB_query("UPDATE " . $_TABLES['mg_albums'] . " SET media_count=" . $MG_albums[$albums]->media_count . ",last_update=" . $media_upload_time . " WHERE album_id='" . $MG_albums[$albums]->id . "'");
                if ($_MG_CONF['update_parent_lastupdated'] == 1) {
                    $currentAID = $MG_albums[$albums]->parent;
                    while ($MG_albums[$currentAID]->id != 0) {
                        DB_query("UPDATE " . $_TABLES['mg_albums'] . " SET last_update=" . $media_upload_time . " WHERE album_id='" . $MG_albums[$currentAID]->id . "'");
                        $currentAID = $MG_albums[$currentAID]->parent;
                    }
                }
                if ($MG_albums[$albums]->cover == -1 && ($mediaType == 0 || $atttn == 1)) {
                    if ($atttn == 1) {
                        $covername = 'tn_' . $media_filename;
                    } else {
                        $covername = $media_filename;
                    }
                    DB_query("UPDATE {$_TABLES['mg_albums']} SET album_cover_filename='" . $covername . "'" . " WHERE album_id='" . $MG_albums[$albums]->id . "'");
                }
            }
            $x++;
        }
    }
    if ($queue) {
        $errMsg .= $LANG_MG01['successful_upload_queue'];
        // ' successfully placed in Moderation queue';
    } else {
        $errMsg .= $LANG_MG01['successful_upload'];
        // ' successfully uploaded to album';
    }
    if ($queue == 0) {
        require_once $_CONF['path'] . 'plugins/mediagallery/include/rssfeed.php';
        MG_buildFullRSS();
        MG_buildAlbumRSS($albums);
        CACHE_remove_instance('whatsnew');
    }
    @unlink($tmpPath);
    return array(true, $errMsg);
}