コード例 #1
0
ファイル: qrdecode.php プロジェクト: RazorMarx/izend
function qrdecode($file)
{
    $url = 'http://zxing.org/w/decode';
    $args = array('full' => 'true');
    $files = array('f' => array('name' => basename($file), 'tmp_name' => $file, 'type' => file_mime_type($file)));
    $response = sendpost($url, $args, $files, false);
    // DON'T encode data in base64
    if (!$response or $response[0] != 200) {
        return false;
    }
    if (!preg_match('#<tr><td>Parsed Result</td><td><pre.*>(.*)</pre></td></tr>#', $response[2], $r)) {
        // extract data - adapt when response format changes
        return false;
    }
    return strip_tags($r[1]);
}
コード例 #2
0
ファイル: download.php プロジェクト: RazorMarx/izend
function download($lang, $arglist = false)
{
    $node_id = $download_name = false;
    if (is_array($arglist)) {
        if (isset($arglist[0])) {
            $node_id = $arglist[0];
        }
        if (isset($arglist[1])) {
            $download_name = $arglist[1];
        }
    }
    if (!$node_id) {
        return run('error/badrequest', $lang);
    }
    if (!$download_name) {
        return run('error/badrequest', $lang);
    }
    $sqllang = db_sql_arg($lang, false);
    $sqlname = db_sql_arg($download_name, true);
    $tabnodecontent = db_prefix_table('node_content');
    $tabcontentdownload = db_prefix_table('content_download');
    $sql = "SELECT cd.path FROM {$tabnodecontent} nc JOIN {$tabcontentdownload} cd ON nc.content_type='download' AND cd.content_id=nc.content_id AND cd.locale={$sqllang} WHERE nc.node_id={$node_id} AND cd.name={$sqlname}";
    $r = db_query($sql);
    if (!$r) {
        return run('error/notfound', $lang);
    }
    $path = $r[0]['path'];
    $filepath = ROOT_DIR . DIRECTORY_SEPARATOR . $path;
    if (!file_exists($filepath)) {
        return run('error/internalerror', $lang);
    }
    $filename = $download_name;
    $filesize = filesize($filepath);
    $filetype = file_mime_type($filepath);
    if (!$filetype) {
        $filetype = 'application/octet-stream';
    }
    header('HTTP/1.1 200 OK');
    // make sure status code is OK in case URL pointed to a file not found like an image
    header('Content-Description: File Transfer');
    header("Content-Type: {$filetype}");
    header("Content-Disposition: attachment; filename={$filename}");
    header("Content-Length: {$filesize}");
    readfile($filepath);
    return false;
}
コード例 #3
0
ファイル: bulkimport.php プロジェクト: rboyatt/mahara
function import_next_user($filename, $username, $authinstance)
{
    global $ADDEDUSERS, $FAILEDUSERS;
    log_debug('adding user ' . $username . ' from ' . $filename);
    $authobj = get_record('auth_instance', 'id', $authinstance);
    $institution = new Institution($authobj->institution);
    $date = time();
    $nicedate = date('Y/m/d h:i:s', $date);
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $username);
    $uploaddir = get_config('dataroot') . 'import/' . $niceuser . '-' . $date . '/';
    check_dir_exists($uploaddir);
    // Unzip the file
    $archive = new ZipArchive();
    if ($archive->open($filename) && $archive->extractTo($uploaddir)) {
        // successfully extracted
        $archive->close();
    } else {
        $FAILEDUSERS[$username] = get_string('unzipfailed', 'admin', hsc($filename));
        return;
    }
    $leap2afilename = $uploaddir . 'leap2a.xml';
    if (!is_file($leap2afilename)) {
        $FAILEDUSERS[$username] = get_string('noleap2axmlfiledetected', 'admin');
        log_debug($FAILEDUSERS[$username]);
        return;
    }
    // If the username is already taken, append something to the end
    while (get_record('usr', 'username', $username)) {
        $username .= "_";
    }
    $user = (object) array('authinstance' => $authinstance, 'username' => $username, 'firstname' => 'Imported', 'lastname' => 'User', 'password' => get_random_key(6), 'passwordchange' => 1);
    db_begin();
    try {
        $user->id = create_user($user, array(), $institution, $authobj);
    } catch (EmailException $e) {
        // Suppress any emails (e.g. new institution membership) sent out
        // during user creation, becuase the user doesn't have an email
        // address until we've imported them from the Leap2A file.
        log_debug("Failed sending email during user import");
    }
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $user->username);
    $record = (object) array('token' => '', 'usr' => $user->id, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'data' => array('importfile' => $filename, 'importfilename' => $filename, 'importid' => $niceuser . time(), 'mimetype' => file_mime_type($filename)), 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_FILE, 'profile' => true);
    $tr = new LocalImporterTransport($record);
    $tr->extract_file();
    $importer = PluginImport::create_importer(null, $tr, $record);
    unset($record, $tr);
    try {
        $importer->process();
        log_info("Imported user account {$user->id} from Leap2A file, see" . $importer->get('logfile') . 'for a full log');
    } catch (ImportException $e) {
        log_info("Leap2A import failed: " . $e->getMessage());
        $FAILEDUSERS[$username] = get_string("leap2aimportfailed");
        db_rollback();
    }
    db_commit();
    if (empty($FAILEDUSERS[$username])) {
        // Reload the user details, as various fields are changed by the
        // importer when importing (e.g. firstname/lastname)
        $newuser = get_record('usr', 'id', $user->id);
        $newuser->clearpasswd = $user->password;
        $ADDEDUSERS[] = $newuser;
    }
    return;
}
コード例 #4
0
ファイル: upgrade.php プロジェクト: sarahjcotton/mahara
function xmldb_artefact_file_upgrade($oldversion = 0)
{
    $status = true;
    if ($oldversion < 2009033000) {
        if (!get_record('artefact_config', 'plugin', 'file', 'field', 'uploadagreement')) {
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'uploadagreement', 'value' => 1));
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'usecustomagreement', 'value' => 1));
        }
    }
    if ($oldversion < 2009091700) {
        execute_sql("DELETE FROM {artefact_file_files} WHERE artefact IN (SELECT id FROM {artefact} WHERE artefacttype = 'folder')");
    }
    if ($oldversion < 2009091701) {
        $table = new XMLDBTable('artefact_file_files');
        $key = new XMLDBKey('artefactpk');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('artefact'));
        add_key($table, $key);
        $table = new XMLDBTable('artefact_file_image');
        $key = new XMLDBKey('artefactpk');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('artefact'));
        add_key($table, $key);
    }
    if ($oldversion < 2009092300) {
        insert_record('artefact_installed_type', (object) array('plugin' => 'file', 'name' => 'archive'));
        // update old files
        if (function_exists('zip_open')) {
            $files = get_records_select_array('artefact_file_files', "filetype IN ('application/zip', 'application/x-zip')");
            if ($files) {
                $checked = array();
                foreach ($files as $file) {
                    $path = get_config('dataroot') . 'artefact/file/originals/' . $file->fileid % 256 . '/' . $file->fileid;
                    $zip = zip_open($path);
                    if (is_resource($zip)) {
                        $checked[] = $file->artefact;
                        zip_close($zip);
                    }
                }
                if (!empty($checked)) {
                    set_field_select('artefact', 'artefacttype', 'archive', "artefacttype = 'file' AND id IN (" . join(',', $checked) . ')', array());
                }
            }
        }
    }
    if ($oldversion < 2010012702) {
        if ($records = get_records_sql_array("SELECT * FROM {artefact_file_files} WHERE filetype='application/octet-stream'", array())) {
            require_once 'file.php';
            foreach ($records as &$r) {
                $path = get_config('dataroot') . 'artefact/file/originals/' . $r->fileid % 256 . '/' . $r->fileid;
                set_field('artefact_file_files', 'filetype', file_mime_type($path), 'fileid', $r->fileid, 'artefact', $r->artefact);
            }
        }
    }
    if ($oldversion < 2011052500) {
        // Set default quota to 50MB
        set_config_plugin('artefact', 'file', 'defaultgroupquota', 52428800);
    }
    if ($oldversion < 2011070700) {
        // Create an images folder for everyone with a profile icon
        $imagesdir = get_string('imagesdir', 'artefact.file');
        $imagesdirdesc = get_string('imagesdirdesc', 'artefact.file');
        execute_sql("\n            INSERT INTO {artefact} (artefacttype, container, owner, ctime, mtime, atime, title, description, author)\n            SELECT 'folder', 1, owner, current_timestamp, current_timestamp, current_timestamp, ?, ?, owner\n            FROM {artefact} WHERE owner IS NOT NULL AND artefacttype = 'profileicon'\n            GROUP BY owner", array($imagesdir, $imagesdirdesc));
        // Put profileicons into the images folder and update the description
        $profileicondesc = get_string('uploadedprofileicon', 'artefact.file');
        if (is_postgres()) {
            execute_sql("\n                UPDATE {artefact}\n                SET parent = f.folderid, description = ?\n                FROM (\n                    SELECT owner, MAX(id) AS folderid\n                    FROM {artefact}\n                    WHERE artefacttype = 'folder' AND title = ? AND description = ?\n                    GROUP BY owner\n                ) f\n                WHERE artefacttype = 'profileicon' AND {artefact}.owner = f.owner", array($profileicondesc, $imagesdir, $imagesdirdesc));
        } else {
            execute_sql("\n                UPDATE {artefact}, (\n                    SELECT owner, MAX(id) AS folderid\n                    FROM {artefact}\n                    WHERE artefacttype = 'folder' AND title = ? AND description = ?\n                    GROUP BY owner\n                ) f\n                SET parent = f.folderid, description = ?\n                WHERE artefacttype = 'profileicon' AND {artefact}.owner = f.owner", array($imagesdir, $imagesdirdesc, $profileicondesc));
        }
    }
    if ($oldversion < 2011082200) {
        // video file type
        if (!get_record('artefact_installed_type', 'plugin', 'file', 'name', 'video')) {
            insert_record('artefact_installed_type', (object) array('plugin' => 'file', 'name' => 'video'));
        }
        // update existing records
        $videotypes = get_records_sql_array('
            SELECT DISTINCT description
            FROM {artefact_file_mime_types}
            WHERE mimetype ' . db_ilike() . ' \'%video%\'', array());
        if ($videotypes) {
            $mimetypes = array();
            foreach ($videotypes as $type) {
                $mimetypes[] = $type->description;
            }
            $files = get_records_sql_array('
                SELECT *
                FROM {artefact_file_files}
                WHERE filetype IN (
                    SELECT mimetype
                    FROM {artefact_file_mime_types}
                    WHERE description IN (' . join(',', array_map('db_quote', array_values($mimetypes))) . ')
                )', array());
            if ($files) {
                $checked = array();
                foreach ($files as $file) {
                    $checked[] = $file->artefact;
                }
                if (!empty($checked)) {
                    set_field_select('artefact', 'artefacttype', 'video', "artefacttype = 'file' AND id IN (" . join(',', $checked) . ')', array());
                }
            }
        }
        // audio file type
        if (!get_record('artefact_installed_type', 'plugin', 'file', 'name', 'audio')) {
            insert_record('artefact_installed_type', (object) array('plugin' => 'file', 'name' => 'audio'));
        }
        // update existing records
        $audiotypes = get_records_sql_array('
            SELECT DISTINCT description
            FROM {artefact_file_mime_types}
            WHERE mimetype ' . db_ilike() . ' \'%audio%\'', array());
        if ($audiotypes) {
            $mimetypes = array();
            foreach ($audiotypes as $type) {
                $mimetypes[] = $type->description;
            }
            $files = get_records_sql_array('
                SELECT *
                FROM {artefact_file_files}
                WHERE filetype IN (
                    SELECT mimetype
                    FROM {artefact_file_mime_types}
                    WHERE description IN (' . join(',', array_map('db_quote', array_values($mimetypes))) . ')
                 )', array());
            if ($files) {
                $checked = array();
                foreach ($files as $file) {
                    $checked[] = $file->artefact;
                }
                if (!empty($checked)) {
                    set_field_select('artefact', 'artefacttype', 'audio', "artefacttype = 'file' AND id IN (" . join(',', $checked) . ')', array());
                }
            }
        }
    }
    if ($oldversion < 2012050400) {
        if (!get_record('artefact_config', 'plugin', 'file', 'field', 'resizeonuploadenable')) {
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'resizeonuploadenable', 'value' => 0));
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'resizeonuploaduseroption', 'value' => 0));
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'resizeonuploadmaxheight', 'value' => get_config('imagemaxheight')));
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'resizeonuploadmaxwidth', 'value' => get_config('imagemaxwidth')));
        }
    }
    if ($oldversion < 2012092400) {
        $basepath = get_config('dataroot') . "artefact/file/originals/";
        try {
            check_dir_exists($basepath, true);
        } catch (Exception $e) {
            throw new SystemException("Failed to create " . $basepath);
        }
        $baseiter = new DirectoryIterator($basepath);
        foreach ($baseiter as $dir) {
            if ($dir->isDot()) {
                continue;
            }
            $dirpath = $dir->getPath() . '/' . $dir->getFilename();
            $fileiter = new DirectoryIterator($dirpath);
            foreach ($fileiter as $file) {
                if ($file->isDot()) {
                    continue;
                }
                if (!$file->isFile()) {
                    log_error("Something was wrong about the dataroot in artefact/file/originals/{$dir}. Unexpected folder {$file}");
                    continue;
                }
                chmod($file->getPathname(), $file->getPerms() & 0666);
            }
        }
    }
    if ($oldversion < 2013031200) {
        // Update MIME types for Microsoft video files: avi, asf, wm, and wmv
        update_record('artefact_file_mime_types', (object) array('mimetype' => 'video/x-ms-asf', 'description' => 'asf'), (object) array('mimetype' => 'video/x-ms-asf'));
        update_record('artefact_file_mime_types', (object) array('mimetype' => 'video/x-ms-wm', 'description' => 'wm'), (object) array('mimetype' => 'video/x-ms-wm'));
        update_record('artefact_file_mime_types', (object) array('mimetype' => 'video/x-ms-wmv', 'description' => 'wmv'), (object) array('mimetype' => 'video/x-ms-wmv'));
    }
    if ($oldversion < 2014040800) {
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'audio/aac'), (object) array('mimetype' => 'audio/aac', 'description' => 'aac'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/msaccess'), (object) array('mimetype' => 'application/msaccess', 'description' => 'accdb'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'shockwave/director'), (object) array('mimetype' => 'shockwave/director', 'description' => 'cct'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-csh'), (object) array('mimetype' => 'application/x-csh', 'description' => 'cs'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'text/css'), (object) array('mimetype' => 'text/css', 'description' => 'css'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'text/csv'), (object) array('mimetype' => 'text/csv', 'description' => 'csv'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'video/x-dv'), (object) array('mimetype' => 'video/x-dv', 'description' => 'dv'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'description' => 'docx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-word.document.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-word.document.macroEnabled.12', 'description' => 'docm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'description' => 'dotx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-word.template.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-word.template.macroEnabled.12', 'description' => 'dotm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-director'), (object) array('mimetype' => 'application/x-director', 'description' => 'dcr'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/epub+zip'), (object) array('mimetype' => 'application/epub+zip', 'description' => 'epub'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-smarttech-notebook'), (object) array('mimetype' => 'application/x-smarttech-notebook', 'description' => 'gallery'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/mac-binhex40'), (object) array('mimetype' => 'application/mac-binhex40', 'description' => 'hqx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'text/x-component'), (object) array('mimetype' => 'text/x-component', 'description' => 'htc'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/xhtml+xml'), (object) array('mimetype' => 'application/xhtml+xml', 'description' => 'xhtml'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'image/vnd.microsoft.icon'), (object) array('mimetype' => 'image/vnd.microsoft.icon', 'description' => 'ico'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'text/calendar'), (object) array('mimetype' => 'text/calendar', 'description' => 'ics'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/inspiration'), (object) array('mimetype' => 'application/inspiration', 'description' => 'isf'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/inspiration.template'), (object) array('mimetype' => 'application/inspiration.template', 'description' => 'ist'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/java-archive'), (object) array('mimetype' => 'application/java-archive', 'description' => 'jar'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-java-jnlp-file'), (object) array('mimetype' => 'application/x-java-jnlp-file', 'description' => 'jnlp'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.moodle.backup'), (object) array('mimetype' => 'application/vnd.moodle.backup', 'description' => 'mbz'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-msaccess'), (object) array('mimetype' => 'application/x-msaccess', 'description' => 'mdb'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'message/rfc822'), (object) array('mimetype' => 'message/rfc822', 'description' => 'mht'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.moodle.profiling'), (object) array('mimetype' => 'application/vnd.moodle.profiling', 'description' => 'mpr'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.oasis.opendocument.graphics-template'), (object) array('mimetype' => 'application/vnd.oasis.opendocument.graphics-template', 'description' => 'otg'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.oasis.opendocument.presentation-template'), (object) array('mimetype' => 'application/vnd.oasis.opendocument.presentation-template', 'description' => 'otp'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.oasis.opendocument.spreadsheet-template'), (object) array('mimetype' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'description' => 'ots'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'audio/ogg'), (object) array('mimetype' => 'audio/ogg', 'description' => 'oga'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'video/ogg'), (object) array('mimetype' => 'video/ogg', 'description' => 'ogv'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'image/pict'), (object) array('mimetype' => 'image/pict', 'description' => 'pct'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'description' => 'pptx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'description' => 'pptm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.presentationml.template'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'description' => 'potx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-powerpoint.template.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-powerpoint.template.macroEnabled.12', 'description' => 'potm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'description' => 'ppam'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'description' => 'ppsx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'description' => 'ppsm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'audio/x-realaudio-plugin'), (object) array('mimetype' => 'audio/x-realaudio-plugin', 'description' => 'ra'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'audio/x-pn-realaudio-plugin'), (object) array('mimetype' => 'audio/x-pn-realaudio-plugin', 'description' => 'ram'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.rn-realmedia-vbr'), (object) array('mimetype' => 'application/vnd.rn-realmedia-vbr', 'description' => 'rmvb'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'text/richtext'), (object) array('mimetype' => 'text/richtext', 'description' => 'rtx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-stuffit'), (object) array('mimetype' => 'application/x-stuffit', 'description' => 'sit'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/smil'), (object) array('mimetype' => 'application/smil', 'description' => 'smi'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'image/svg+xml'), (object) array('mimetype' => 'image/svg+xml', 'description' => 'svg'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.writer'), (object) array('mimetype' => 'application/vnd.sun.xml.writer', 'description' => 'sxw'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.writer.template'), (object) array('mimetype' => 'application/vnd.sun.xml.writer.template', 'description' => 'stw'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.calc'), (object) array('mimetype' => 'application/vnd.sun.xml.calc', 'description' => 'sxc'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.calc.template'), (object) array('mimetype' => 'application/vnd.sun.xml.calc.template', 'description' => 'stc'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.draw'), (object) array('mimetype' => 'application/vnd.sun.xml.draw', 'description' => 'sxd'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.draw.template'), (object) array('mimetype' => 'application/vnd.sun.xml.draw.template', 'description' => 'std'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.impress'), (object) array('mimetype' => 'application/vnd.sun.xml.impress', 'description' => 'sxi'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.impress.template'), (object) array('mimetype' => 'application/vnd.sun.xml.impress.template', 'description' => 'sti'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.writer.global'), (object) array('mimetype' => 'application/vnd.sun.xml.writer.global', 'description' => 'sxg'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.sun.xml.math'), (object) array('mimetype' => 'application/vnd.sun.xml.math', 'description' => 'sxm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'image/tiff'), (object) array('mimetype' => 'image/tiff', 'description' => 'tif'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-tex'), (object) array('mimetype' => 'application/x-tex', 'description' => 'tex'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/x-texinfo'), (object) array('mimetype' => 'application/x-texinfo', 'description' => 'texi'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'text/tab-separated-values'), (object) array('mimetype' => 'text/tab-separated-values', 'description' => 'tsv'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'video/webm'), (object) array('mimetype' => 'video/webm', 'description' => 'webm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-excel'), (object) array('mimetype' => 'application/vnd.ms-excel', 'description' => 'xls'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'description' => 'xlsx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-excel.sheet.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-excel.sheet.macroEnabled.12', 'description' => 'xlsm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'), (object) array('mimetype' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'description' => 'xltx'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-excel.template.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-excel.template.macroEnabled.12', 'description' => 'xltm'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'description' => 'xlsb'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/vnd.ms-excel.addin.macroEnabled.12'), (object) array('mimetype' => 'application/vnd.ms-excel.addin.macroEnabled.12', 'description' => 'xlam'));
        ensure_record_exists('artefact_file_mime_types', (object) array('mimetype' => 'application/xml'), (object) array('mimetype' => 'application/xml', 'description' => 'xml'));
    }
    if ($oldversion < 2014051200) {
        require_once get_config('docroot') . '/lib/file.php';
        $mimetypes = get_records_assoc('artefact_file_mime_types', '', '', '', 'description,mimetype');
        // Re-examine only those files where their current identified mimetype is
        // different from how we would identify their mimetype based on file extension
        $rs = get_recordset_sql('
            select a.id, aff.oldextension, aff.filetype
            from
                {artefact} a
                inner join {artefact_file_files} aff
                    on a.id = aff.artefact
            where a.artefacttype = \'archive\'
                and not exists (
                    select 1 from {artefact_file_mime_types} afmt
                    where afmt.description = aff.oldextension
                    and afmt.mimetype = aff.filetype
                )
            order by a.id
        ');
        $total = 0;
        $done = 0;
        while ($zf = $rs->FetchRow()) {
            if ($done % 100 == 0) {
                log_debug('Verifying filetypes: ' . $done . '/' . $rs->RecordCount());
            }
            $done++;
            $file = artefact_instance_from_id($zf['id']);
            $path = $file->get_path();
            // Check what our improved file detection system thinks it is
            $guess = file_mime_type($path, 'foo.' . $zf['oldextension']);
            if ($guess != 'application/octet-stream') {
                $data = new stdClass();
                $data->filetype = $data->guess = $guess;
                foreach (array('video', 'audio', 'archive') as $artefacttype) {
                    $classname = 'ArtefactType' . ucfirst($artefacttype);
                    if (call_user_func_array(array($classname, 'is_valid_file'), array($file->get_path(), &$data))) {
                        set_field('artefact', 'artefacttype', $artefacttype, 'id', $zf['id']);
                        set_field('artefact_file_files', 'filetype', $data->filetype, 'artefact', $zf['id']);
                        continue 2;
                    }
                }
                // It wasn't any of those special ones, so just make it a normal file artefact
                set_field('artefact', 'artefacttype', 'file', 'id', $zf['id']);
                set_field('artefact_file_files', 'filetype', $data->filetype, 'artefact', $zf['id']);
            }
        }
        log_debug('Verifying filetypes: ' . $done . '/' . $rs->RecordCount());
        $rs->Close();
    }
    if ($oldversion < 2014060900) {
        $events = array((object) array('plugin' => 'file', 'event' => 'saveartefact', 'callfunction' => 'eventlistener_savedeleteartefact'), (object) array('plugin' => 'file', 'event' => 'deleteartefact', 'callfunction' => 'eventlistener_savedeleteartefact'), (object) array('plugin' => 'file', 'event' => 'deleteartefacts', 'callfunction' => 'eventlistener_savedeleteartefact'), (object) array('plugin' => 'file', 'event' => 'updateuser', 'callfunction' => 'eventlistener_savedeleteartefact'));
        foreach ($events as $event) {
            ensure_record_exists('artefact_event_subscription', $event, $event);
        }
        PluginArtefactFile::set_quota_triggers();
    }
    if ($oldversion < 2014061000) {
        // Remove the not needed quota notify on update config trigger from previous update
        if (is_postgres()) {
            $sql = 'DROP TRIGGER IF EXISTS {unmark_quota_exeed_notified_on_update_setting_trigger} ON {artefact_config};';
        } else {
            $sql = 'DROP TRIGGER IF EXISTS {unmark_quota_exeed_notified_on_update_setting_trigger};';
        }
        execute_sql($sql);
    }
    if ($oldversion < 2014111200) {
        // Create embedded images table
        $table = new XMLDBTable('artefact_file_embedded');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('fileid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL);
        $table->addFieldInfo('resourcetype', XMLDB_TYPE_CHAR, '100', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('resourceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('artefactfk', XMLDB_KEY_FOREIGN, array('fileid'), 'artefact', array('id'));
        $status = $status && create_table($table);
    }
    if ($oldversion < 2015101900) {
        log_debug('Need to consolidate "textbox" and "editnote" embedded resource types as they are in fact the same thing');
        if ($records = get_records_sql_array('SELECT * FROM {artefact_file_embedded} WHERE resourcetype IN (?, ?)', array('editnote', 'textbox'))) {
            $newrecords = array();
            // Turn the results into something easier to check against
            foreach ($records as $k => $v) {
                $newrecords[$v->resourcetype . '_' . $v->resourceid . '_' . $v->fileid] = $v;
            }
            foreach ($newrecords as $nk => $nv) {
                // need to sort out the 'editnote' options
                if (preg_match('/^editnote_(.*)$/', $nk, $match)) {
                    // Check to see if there is a corresponding 'textbox' one - if not we need to make one
                    if (!array_key_exists('textbox_' . $match[1], $newrecords)) {
                        insert_record('artefact_file_embedded', (object) array('fileid' => $nv->fileid, 'resourcetype' => 'textbox', 'resourceid' => $nv->resourceid));
                    }
                    // now delete the 'editnote' one
                    delete_records('artefact_file_embedded', 'id', $nv->id);
                }
            }
        }
    }
    return $status;
}
コード例 #5
0
ファイル: functions.upload.php プロジェクト: ungc0/three5six
function make_thumb($name, $path, $thumbs_dir)
{
    $height = 200;
    $width = 200;
    $exlong = $extiny = false;
    $return = array('generated' => false);
    if (file_mime_type(ABSPATH . '/' . $path) == 'image/svg+xml') {
        $svg = file_get_contents(ABSPATH . '/' . $path);
        if (preg_match('/<svg.*?width="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?height="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?>/', $svg, $match)) {
            $width = $match[1];
            $height = $match[3];
        } else {
            if (preg_match('/<svg.*?height="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?width="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?>/', $svg, $match)) {
                $width = $match[3];
                $height = $match[1];
            } else {
                $width = $height = 200;
            }
        }
        $ratio = $width / $height;
        $exlong = $ratio > 3 || $ratio < 0.33;
        if ($ratio < 0.33 || $ratio >= 1 && $ratio <= 3) {
            $width = 200;
            $height = $width / $ratio;
        } else {
            if ($ratio >= 0.33 && $ratio < 1 || $ratio > 3) {
                $height = 200;
                $width = $height * $ratio;
            }
        }
        $return['width'] = $width;
        $return['height'] = $height;
    } else {
        if (!($imgInfo = getimagesize(ABSPATH . '/' . $path))) {
            return $return;
        }
        $notype = false;
        list($width_orig, $height_orig, $type) = $imgInfo;
        switch ($type) {
            case IMAGETYPE_GIF:
                $readf = "imagecreatefromgif";
                $writef = "imagegif";
                break;
            case IMAGETYPE_JPEG:
                $readf = "imagecreatefromjpeg";
                $writef = "imagejpeg";
                break;
            case IMAGETYPE_PNG:
                $readf = "imagecreatefrompng";
                $writef = "imagepng";
                break;
            default:
                $notype = true;
        }
        $ratio_orig = $width_orig / $height_orig;
        $exlong = $ratio_orig < 0.33 || $ratio_orig > 3;
        $extiny = $width_orig < 67 || $height_orig < 67;
        if ($height_orig <= $height && $width_orig <= $width || $extiny || $exlong && ($height_orig <= $height || $width_orig <= $width)) {
            $return['width'] = $width_orig;
            $return['height'] = $height_orig;
        } else {
            if ($ratio_orig < 0.33 || $ratio_orig >= 1 && $ratio_orig <= 3) {
                $height = $width / $ratio_orig;
            } else {
                if ($ratio_orig >= 0.33 && $ratio_orig < 1 || $ratio_orig > 3) {
                    $width = $height * $ratio_orig;
                }
            }
            $return['width'] = $width;
            $return['height'] = $height;
            if ($notype || !($image_p = imagecreatetruecolor($width, $height))) {
                return $return;
            }
            $image = $readf(ABSPATH . '/' . $path);
            // Create alpha channel for png
            if ($type == IMAGETYPE_PNG) {
                if (!imagealphablending($image_p, false) || !imagesavealpha($image_p, true) || !($transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127)) || !imagefill($image_p, 0, 0, $transparent)) {
                    return $return;
                }
            }
            // Make transparent for gif
            if ($type == IMAGETYPE_GIF) {
                $transparent_index = imagecolortransparent($image);
                if ($transparent_index != -1) {
                    $bgcolor = imagecolorsforindex($image, $transparent_index);
                    $bgcolor = imagecolorallocate($image_p, $bgcolor['red'], $bgcolor['green'], $bgcolor['blue']);
                    $bgcolor_index = imagecolortransparent($image_p, $bgcolor);
                    imagefill($image_p, 0, 0, $bgcolor_index);
                }
            }
            // Resize image
            if (!imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig)) {
                return $return;
            }
            if (!$writef($image_p, ABSPATH . "/{$thumbs_dir}/{$name}")) {
                return $return;
            }
            imagedestroy($image);
            imagedestroy($image_p);
            $return['generated'] = true;
            $return['path'] = "{$thumbs_dir}/{$name}";
        }
    }
    $return['exlong'] = $exlong ? 'long' : '';
    $return['extiny'] = $extiny ? 'tiny' : '';
    return $return;
}
コード例 #6
0
 /**
  * retrieves the files from the remote host
  */
 public function prepare_files()
 {
     if (empty($this->importer)) {
         throw new ImportException(null, 'Failed to initialise XMLRPC file retrieval - no importer object');
     }
     $this->prepare_tempdir();
     $this->token = $this->importer->get('token');
     require_once get_config('docroot') . 'api/xmlrpc/client.php';
     $client = new Client();
     try {
         $client->set_method('portfolio/mahara/lib.php/fetch_file')->add_param($this->token)->send($this->host->wwwroot);
     } catch (XmlrpcClientException $e) {
         throw new ImportException($this->importer, 'Failed to retrieve zipfile from remote server: ' . $e->getMessage());
     }
     if (!($filecontents = base64_decode($client->response))) {
         throw new ImportException($this->importer, 'Failed to retrieve zipfile from remote server');
     }
     $this->importfilename = 'import.zip';
     $this->importfile = $this->tempdir . $this->importfilename;
     if (!file_put_contents($this->tempdir . $this->importfilename, $filecontents)) {
         throw new ImportException($this->importer, 'Failed to write out the zipfile to local temporary storage');
     }
     // detect the filetype and bail if it's not a zip file
     safe_require('artefact', 'file');
     require_once 'file.php';
     $ziptypes = PluginArtefactFile::get_mimetypes_from_description('zip');
     $this->mimetype = file_mime_type($this->tempdir . $this->importfilename);
     if (!in_array($this->mimetype, $ziptypes)) {
         throw new ImportException($this->importer, 'Not a valid zipfile - mimetype was ' . $this->mimetype);
     }
 }
コード例 #7
0
ファイル: lib.php プロジェクト: vohung96/mahara
 /**
  * Test file type and return a new Image or File.
  */
 public static function new_file($path, $data)
 {
     require_once 'file.php';
     if (is_image_file($path)) {
         // If it's detected as an image, overwrite the browser mime type
         $imageinfo = getimagesize($path);
         $data->filetype = $imageinfo['mime'];
         $data->width = $imageinfo[0];
         $data->height = $imageinfo[1];
         return new ArtefactTypeImage(0, $data);
     }
     $data->guess = file_mime_type($path, "foo.{$data->oldextension}");
     // The guessed mimetype tends to be more accurate than what the browser tells us.
     // Use the guess, unless it failed to find a match.
     // But if it failed to find a match *and* there is no browser-supplied mimetype,
     // then just use the guess.
     if ($data->guess != 'application/octet-stream' || empty($data->filetype)) {
         $data->filetype = $data->guess;
     }
     foreach (array('video', 'audio', 'archive') as $artefacttype) {
         $classname = 'ArtefactType' . ucfirst($artefacttype);
         if (call_user_func_array(array($classname, 'is_valid_file'), array($path, &$data))) {
             return new $classname(0, $data);
         }
     }
     return new ArtefactTypeFile(0, $data);
 }
コード例 #8
0
ファイル: install.php プロジェクト: kienv/mahara
function addfontform_validate(Pieform $form, $values)
{
    global $USER, $SESSION;
    require_once 'file.php';
    require_once 'uploadmanager.php';
    $foldername = preg_replace(Skin::FONTNAME_FILTER_CHARACTERS, '', $values['fonttitle']);
    if (!$foldername) {
        $form->set_error('fonttitle', get_string('invalidfonttitle', 'skin'));
    }
    // If we are uploading a zip file we need to extract things before we can validate them
    if (!empty($values['fontfileZip'])) {
        safe_require('artefact', 'file');
        $ziptypes = PluginArtefactFile::get_mimetypes_from_description('zip');
        $zipmimetype = file_mime_type($values['fontfileZip']['name']);
        $zipmimetype = $zipmimetype || (substr($values['fontfileZip']['name'], -4) == '.zip' ? 'application/zip' : null);
        if (in_array($zipmimetype, $ziptypes)) {
            // we are dealing with a zip file
            // First pass it through the virus checker
            $um = new upload_manager('fontfileZip');
            if ($error = $um->preprocess_file()) {
                $form->set_error('fontfileZip', $error);
            }
            $zip = new ZipArchive();
            if ($zip->open($values['fontfileZip']['tmp_name'])) {
                $check = uploadfiles_info();
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $fontname = dirname($zip->getNameIndex($i));
                    $filename = basename($zip->getNameIndex($i));
                    if (empty($fontname) || $fontname == '.') {
                        $fontname = substr($values['fontfileZip']['name'], 0, -1 * strlen('.zip'));
                    }
                    // Check that all the needed files exist in the zip file
                    foreach ($check as $key => $item) {
                        if (end(explode('.', $zip->getNameIndex($i))) == $item['suffix']) {
                            $check[$key]['found'] = true;
                        }
                    }
                }
                // now examine our $check array to make sure at least one of each of the required files was found
                foreach ($check as $key => $item) {
                    if ($item['required'] == true && $item['found'] == false) {
                        $form->set_error('fontfileZip', get_string('fontfilemissing', 'skin', $item['suffix']));
                    }
                }
            } else {
                $form->set_error('fontfileZip', get_string('archivereadingerror', 'skin'));
            }
        } else {
            $form->set_error('fontfileZip', get_string('notvalidzipfile', 'skin'));
        }
    } else {
        foreach (uploadfiles_info() as $inputname => $details) {
            $um = new upload_manager($inputname, false, null, !$details['required']);
            if ($error = $um->preprocess_file()) {
                $form->set_error($inputname, $error);
            }
            if (!$um->optionalandnotsupplied && $details['suffix']) {
                $reqext = ".{$details['suffix']}";
                $fileext = substr($values[$inputname]['name'], -1 * strlen($reqext));
                if ($fileext != $reqext) {
                    $form->set_error($inputname, get_string('notvalidfontfile', 'skin', strtoupper($details['suffix'])));
                }
            }
        }
    }
}
コード例 #9
0
 /**
  * Attaches a file to a blogpost entry that was just linked directly, rather than having a Leap2a entry
  * See http://wiki.leapspecs.org/2A/files
  *
  * @param SimpleXMLElement $blogpostentry
  * @param SimpleXMLElement $blogpostlink
  * @param PluginImportLeap $importer
  */
 private static function attach_linked_file($blogpostentry, $blogpostlink, PluginImportLeap $importer)
 {
     $importer->trace($blogpostlink);
     $pathname = urldecode((string) $blogpostlink['href']);
     $dir = dirname($importer->get('filename'));
     $pathname = $dir . DIRECTORY_SEPARATOR . $pathname;
     if (!file_exists($pathname)) {
         return false;
     }
     // Note: this data is passed (eventually) to ArtefactType->__construct,
     // which calls strtotime on the dates for us
     require_once 'file.php';
     $data = (object) array('title' => (string) $blogpostentry->title . ' ' . get_string('attachment', 'artefact.blog'), 'owner' => $importer->get('usr'), 'filetype' => file_mime_type($pathname));
     return ArtefactTypeFile::save_file($pathname, $data, $importer->get('usrobj'), true);
 }
コード例 #10
0
ファイル: functions.php プロジェクト: ungc0/three5six
function get_image_size($file)
{
    $geterror = false;
    if (file_mime_type($file) == 'image/svg+xml') {
        $svg = file_get_contents($file);
        if (preg_match('/<svg.+width="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?".+height="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?"/', $svg, $matches)) {
            $width = $matches[1];
            $height = $matches[3];
        } else {
            if (preg_match('/<svg.+height="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?".+width="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?"/', $svg, $matches)) {
                $width = $matches[3];
                $height = $matches[1];
            } else {
                $width = 200;
                $height = 200;
            }
        }
        $ratio = $width / $height;
        if ($ratio < 0.33 || $ratio >= 1 && $ratio <= 3) {
            $width = 200;
            $height = $width / $ratio;
        } else {
            if ($ratio >= 0.33 && $ratio < 1 || $ratio > 3) {
                $height = 200;
                $width = $height * $ratio;
            }
        }
    } else {
        if (!($imgInfo = @getimagesize($file))) {
            list($width, $height) = array(200, 200);
            $geterror = true;
        } else {
            list($width, $height, , ) = $imgInfo;
        }
    }
    return array($width, $height, $geterror);
}
コード例 #11
0
 /**
  * Processes a newly uploaded file, copies it to disk, and creates
  * a new artefact object.
  * Takes the name of a file input.
  * Returns false for no errors, or a string describing the error.
  */
 public static function save_uploaded_file($inputname, $data)
 {
     require_once 'uploadmanager.php';
     $um = new upload_manager($inputname);
     if ($error = $um->preprocess_file()) {
         throw new UploadException($error);
     }
     $size = $um->file['size'];
     if (!empty($data->owner)) {
         global $USER;
         if ($data->owner == $USER->get('id')) {
             $owner = $USER;
             $owner->quota_refresh();
         } else {
             $owner = new User();
             $owner->find_by_id($data->owner);
         }
         if (!$owner->quota_allowed($size)) {
             throw new QuotaExceededException(get_string('uploadexceedsquota', 'artefact.file'));
         }
     }
     $data->size = $size;
     if ($um->file['type'] == 'application/octet-stream') {
         // the browser wasn't sure, so use file_mime_type to guess
         require_once 'file.php';
         $data->filetype = file_mime_type($um->file['tmp_name']);
     } else {
         $data->filetype = $um->file['type'];
     }
     $data->oldextension = $um->original_filename_extension();
     $f = self::new_file($um->file['tmp_name'], $data);
     $f->commit();
     $id = $f->get('id');
     // Save the file using its id as the filename, and use its id modulo
     // the number of subdirectories as the directory name.
     if ($error = $um->save_file(self::get_file_directory($id), $id)) {
         $f->delete();
         throw new UploadException($error);
     } else {
         if (isset($owner)) {
             $owner->quota_add($size);
             $owner->commit();
         }
     }
     return $id;
 }
コード例 #12
0
 private function genPostdata()
 {
     if (count($this->files) == 0 && !$this->multipart) {
         if (count($this->posts) != 0) {
             $query = '';
             foreach ($this->posts as $post) {
                 $query .= rawurlencode($post['key']) . '=' . rawurlencode($post['value']) . '&';
             }
             $query = substr($query, 0, -1);
             if ($this->method == 'POST') {
                 $this->setHeader(array('name' => 'Content-Type', 'value' => 'application/x-www-form-urlencoded'));
                 $this->postdata = $query;
             } else {
                 if ($this->query == '') {
                     $this->query = '?' . $query;
                 } else {
                     $this->query .= '&' . $query;
                 }
             }
         }
     } else {
         // 设置分割标识
         srand((double) microtime() * 1000000);
         $boundary = '---------------------------' . substr(md5(rand(0, 32000)), 0, 10);
         $this->setHeader(array('name' => 'Content-Type', 'value' => 'multipart/form-data; boundary=' . $boundary));
         $this->postdata = '--' . $boundary . HTTPRequest::HTTP_EOL;
         if (count($this->posts) != 0) {
             foreach ($this->posts as $post) {
                 $this->postdata .= 'Content-Disposition: form-data; name="' . $post['key'] . '"' . HTTPRequest::HTTP_EOL . HTTPRequest::HTTP_EOL;
                 $this->postdata .= $post['value'] . HTTPRequest::HTTP_EOL;
                 $this->postdata .= '--' . $boundary . HTTPRequest::HTTP_EOL;
             }
         }
         foreach ($this->files as $file) {
             if (file_exists($file['path'])) {
                 $this->postdata .= 'Content-Disposition: form-data; name="' . $file['name'] . '"; filename="' . $file['filename'] . '"' . HTTPRequest::HTTP_EOL;
                 $mime = file_mime_type($file['path']);
                 if ($mime) {
                     $this->postdata .= 'Content-Type: ' . $mime . HTTPRequest::HTTP_EOL;
                 }
                 $this->postdata .= HTTPRequest::HTTP_EOL;
                 $contents = file_get_contents($file['path']);
                 $this->postdata .= $contents . HTTPRequest::HTTP_EOL;
                 $this->postdata .= '--' . $boundary . HTTPRequest::HTTP_EOL;
             }
         }
         $this->postdata = substr($this->postdata, 0, -2) . '--' . HTTPRequest::HTTP_EOL;
         $this->setHeader(array('name' => 'Content-Length', 'value' => strlen($this->postdata)));
     }
 }
コード例 #13
0
ファイル: emailhtml.php プロジェクト: RazorMarx/izend
function emailhtml($text, $html, $css, $to, $subject, $sender = false)
{
    global $mailer, $webmaster, $sitename;
    if (!$sender) {
        $sender = $webmaster;
    }
    $textheader = $textbody = $htmlheader = $htmlbody = false;
    if ($text) {
        $textheader = 'Content-Type: text/plain; charset=utf-8';
        $textbody = <<<_SEP_
{$text}

_SEP_;
    }
    $related = false;
    if ($html) {
        $related = array();
        if (preg_match_all('#<img[^>]+src="([^"]*)"[^>]*>#is', $html, $matches)) {
            $pattern = array();
            $replacement = array();
            foreach ($matches[1] as $url) {
                if ($url[0] != '/') {
                    continue;
                }
                if (array_key_exists($url, $related)) {
                    continue;
                }
                $fname = ROOT_DIR . $url;
                $filetype = file_mime_type($fname, false);
                if (!$filetype or strpos($filetype, 'image') !== 0) {
                    continue;
                }
                $data = file_get_contents($fname);
                if (get_magic_quotes_runtime()) {
                    $data = stripslashes($data);
                }
                if (!$data) {
                    continue;
                }
                $base64 = chunk_split(base64_encode($data));
                $cid = md5(uniqid('cid', true));
                $qfname = preg_quote($url);
                $pattern[] = '#(<img[^>]+src=)"' . $qfname . '"([^>]*>)#is';
                $replacement[] = '${1}"cid:' . $cid . '"${2}';
                $related[$url] = array(basename($fname), $filetype, $cid, $base64);
            }
            $html = preg_replace($pattern, $replacement, $html);
        }
        $title = htmlspecialchars($sitename, ENT_COMPAT, 'UTF-8');
        $htmlheader = 'Content-Type: text/html; charset=utf-8';
        $htmlbody = <<<_SEP_
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>{$title}</title>
<style type="text/css">
{$css}
</style>
</head>
<body>
{$html}
</body>
</html>

_SEP_;
    }
    $headers = <<<_SEP_
From: {$sender}
Return-Path: {$sender}
X-Mailer: {$mailer}

_SEP_;
    $body = '';
    if ($related) {
        if ($textbody) {
            $sep = md5(uniqid('sep', true));
            $body .= <<<_SEP_
Content-Type: multipart/alternative; boundary="{$sep}"

--{$sep}
{$textheader}

{$textbody}
--{$sep}
{$htmlheader}

{$htmlbody}
--{$sep}--


_SEP_;
        } else {
            $body .= <<<_SEP_
{$htmlheader}

{$htmlbody}

_SEP_;
        }
        $sep = md5(uniqid('sep', true));
        $headers .= <<<_SEP_
Content-Type: multipart/related; boundary="{$sep}"
_SEP_;
        foreach ($related as $url => $r) {
            list($filename, $filetype, $cid, $base64) = $r;
            $body .= <<<_SEP_
--{$sep}
Content-Type: {$filetype}
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="{$filename}"
Content-ID: <{$cid}>

{$base64}

_SEP_;
        }
        $body = <<<_SEP_
--{$sep}
{$body}
--{$sep}--
_SEP_;
    } else {
        if ($textbody and $htmlbody) {
            $sep = md5(uniqid('sep', true));
            $headers .= <<<_SEP_
Content-Type: multipart/alternative; boundary="{$sep}"
_SEP_;
            $body .= <<<_SEP_
--{$sep}
{$textheader}

{$textbody}
--{$sep}
{$htmlheader}

{$htmlbody}
--{$sep}--
_SEP_;
        } else {
            if ($textbody) {
                $headers .= $textheader;
                $body = $textbody;
            } else {
                if ($htmlbody) {
                    $headers .= $htmlheader;
                    $body = $htmlbody;
                }
            }
        }
    }
    return @mail($to, $subject, $body, $headers);
}
コード例 #14
0
function adduser_validate(Pieform $form, $values)
{
    global $USER, $TRANSPORTER;
    $authobj = AuthFactory::create($values['authinstance']);
    $institution = $authobj->institution;
    // Institutional admins can only set their own institutions' authinstances
    if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
        $form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
        return;
    }
    $institution = new Institution($authobj->institution);
    // Don't exceed max user accounts for the institution
    if ($institution->isFull()) {
        $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
        return;
    }
    $username = $values['username'];
    $firstname = $values['firstname'];
    $lastname = $values['lastname'];
    $email = $values['email'];
    $password = $values['password'];
    if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($username)) {
        $form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
    }
    if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($username))) {
        $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
    }
    if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
        $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
    }
    if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
        $form->set_error('firstname', null);
        $form->set_error('lastname', null);
        $form->set_error('email', null);
        if (!$values['leap2afile']) {
            $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
            return;
        }
        if ($values['leap2afile']['type'] == 'application/octet-stream') {
            require_once 'file.php';
            $mimetype = file_mime_type($values['leap2afile']['tmp_name']);
        } else {
            $mimetype = $values['leap2afile']['type'];
        }
        $date = time();
        $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
        safe_require('import', 'leap');
        $fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
        $TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
        try {
            $TRANSPORTER->extract_file();
            PluginImportLeap::validate_transported_data($TRANSPORTER);
        } catch (Exception $e) {
            $form->set_error('leap2afile', $e->getMessage());
        }
    } else {
        if (!$form->get_error('firstname') && !preg_match('/\\S/', $firstname)) {
            $form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('lastname') && !preg_match('/\\S/', $lastname)) {
            $form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('email')) {
            require_once 'phpmailer/class.phpmailer.php';
            if (!$form->get_error('email') && !PHPMailer::ValidateAddress($email)) {
                $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
            }
            if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
                $form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
            }
        }
    }
}
コード例 #15
0
ファイル: add.php プロジェクト: rboyatt/mahara
function adduser_validate(Pieform $form, $values)
{
    global $USER, $TRANSPORTER;
    $authobj = AuthFactory::create($values['authinstance']);
    $institution = $authobj->institution;
    // Institutional admins can only set their own institutions' authinstances
    if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
        $form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
        return;
    }
    $institution = new Institution($authobj->institution);
    // Don't exceed max user accounts for the institution
    if ($institution->isFull()) {
        $institution->send_admin_institution_is_full_message();
        $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
        return;
    }
    $username = $values['username'];
    $firstname = sanitize_firstname($values['firstname']);
    $lastname = sanitize_lastname($values['lastname']);
    $email = sanitize_email($values['email']);
    $password = $values['password'];
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
        $maxquota = get_config_plugin('artefact', 'file', 'maxquota');
        if ($maxquotaenabled && $values['quota'] > $maxquota) {
            $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
        }
    }
    if (method_exists($authobj, 'is_username_valid_admin')) {
        if (!$authobj->is_username_valid_admin($username)) {
            $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal'));
        }
    } else {
        if (method_exists($authobj, 'is_username_valid')) {
            if (!$authobj->is_username_valid($username)) {
                $form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
            }
        }
    }
    if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
        $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
    }
    if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
        $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
    }
    if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
        $form->set_error('firstname', null);
        $form->set_error('lastname', null);
        $form->set_error('email', null);
        if (!$values['leap2afile'] && ($_FILES['leap2afile']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['leap2afile']['error'] == UPLOAD_ERR_FORM_SIZE)) {
            $form->reply(PIEFORM_ERR, array('message' => get_string('uploadedfiletoobig'), 'goto' => '/admin/users/add.php'));
            $form->set_error('leap2afile', get_string('uploadedfiletoobig'));
            return;
        } else {
            if (!$values['leap2afile']) {
                $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
                return;
            }
        }
        if ($values['leap2afile']['type'] == 'application/octet-stream') {
            require_once 'file.php';
            $mimetype = file_mime_type($values['leap2afile']['tmp_name']);
        } else {
            $mimetype = trim($values['leap2afile']['type'], '"');
        }
        $date = time();
        $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
        safe_require('import', 'leap');
        $fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
        $TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
        try {
            $TRANSPORTER->extract_file();
            PluginImportLeap::validate_transported_data($TRANSPORTER);
        } catch (Exception $e) {
            $form->set_error('leap2afile', $e->getMessage());
        }
    } else {
        if (!$form->get_error('firstname') && empty($firstname)) {
            $form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('lastname') && empty($lastname)) {
            $form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('email')) {
            if (!$form->get_error('email') && empty($email)) {
                $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
            }
            if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
                $form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
            }
        }
    }
}
コード例 #16
0
 /**
  * Attaches a file to a blogpost entry that was just linked directly, rather than having a Leap2a entry
  * See http://wiki.leapspecs.org/2A/files
  *
  * @param SimpleXMLElement $entry
  * @param SimpleXMLElement $link
  */
 private function create_linked_file(SimpleXMLElement $entry, SimpleXMLElement $link)
 {
     $this->trace($link);
     $pathname = urldecode((string) $link['href']);
     $dir = dirname($this->get('filename'));
     $pathname = $dir . DIRECTORY_SEPARATOR . $pathname;
     if (!file_exists($pathname)) {
         return false;
     }
     // Note: this data is passed (eventually) to ArtefactType->__construct,
     // which calls strtotime on the dates for us
     require_once 'file.php';
     $data = (object) array('title' => (string) $entry->title . ' ' . get_string('attachment'), 'owner' => $this->get('usr'), 'filetype' => file_mime_type($pathname));
     return ArtefactTypeFile::save_file($pathname, $data, $this->get('usrobj'), true);
 }
コード例 #17
0
ファイル: index.php プロジェクト: vohung96/mahara
function import_validate(Pieform $form, $values)
{
    global $USER, $TRANSPORTER;
    if (!isset($values['leap2afile'])) {
        $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
        return;
    }
    if ($values['leap2afile']['type'] == 'application/octet-stream') {
        require_once 'file.php';
        $mimetype = file_mime_type($values['leap2afile']['tmp_name']);
    } else {
        $mimetype = trim($values['leap2afile']['type'], '"');
    }
    $date = time();
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $USER->get('username'));
    safe_require('import', 'leap');
    $fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
    $TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
    try {
        $TRANSPORTER->extract_file();
        PluginImportLeap::validate_transported_data($TRANSPORTER);
    } catch (Exception $e) {
        $form->set_error('leap2afile', $e->getMessage());
        $TRANSPORTER->cleanup();
    }
    // Check if import data may exceed the user's file quota
    $importdata = $TRANSPORTER->files_info();
    require_once 'function.dirsize.php';
    $importdatasize = dirsize($importdata['tempdir'] . 'extract/files');
    if ($USER->get('quotaused') + $importdatasize > $USER->get('quota')) {
        $form->set_error('leap2afile', get_string('importexceedquota', 'import'));
        $TRANSPORTER->cleanup();
    }
}
コード例 #18
0
function xmldb_artefact_file_upgrade($oldversion = 0)
{
    $status = true;
    if ($oldversion < 2007010900) {
        $table = new XMLDBTable('artefact_file_files');
        $field = new XMLDBField('adminfiles');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, false, true, false, null, null, 0);
        add_field($table, $field);
        set_field('artefact_file_files', 'adminfiles', 0);
        // Put all folders into artefact_file_files
        $folders = get_column_sql("\n            SELECT a.id\n            FROM {artefact} a\n            LEFT OUTER JOIN {artefact_file_files} f ON a.id = f.artefact\n            WHERE a.artefacttype = 'folder' AND f.artefact IS NULL");
        if ($folders) {
            foreach ($folders as $folderid) {
                $data = (object) array('artefact' => $folderid, 'adminfiles' => 0);
                insert_record('artefact_file_files', $data);
            }
        }
    }
    if ($oldversion < 2007011800) {
        // Make sure the default quota is set
        set_config_plugin('artefact', 'file', 'defaultquota', 10485760);
    }
    if ($oldversion < 2007011801) {
        // Create image table
        $table = new XMLDBTable('artefact_file_image');
        $table->addFieldInfo('artefact', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('width', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('height', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null);
        $table->addKeyInfo('artefactfk', XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
        $status = $status && create_table($table);
        $images = get_column('artefact', 'id', 'artefacttype', 'image');
        log_debug(count($images));
        require_once get_config('docroot') . 'artefact/lib.php';
        foreach ($images as $imageid) {
            $image = artefact_instance_from_id($imageid);
            $path = $image->get_path();
            $image->set('dirty', false);
            $data = new StdClass();
            $data->artefact = $imageid;
            if (file_exists($path)) {
                list($data->width, $data->height) = getimagesize($path);
            }
            if (empty($data->width) || empty($data->height)) {
                $data->width = 0;
                $data->height = 0;
            }
            insert_record('artefact_file_image', $data);
        }
    }
    if ($oldversion < 2007013100) {
        // Add new tables for file/mime types
        $table = new XMLDBTable('artefact_file_file_types');
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 128, null, XMLDB_NOTNULL);
        $table->addFieldInfo('enabled', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('description'));
        create_table($table);
        $table = new XMLDBTable('artefact_file_mime_types');
        $table->addFieldInfo('mimetype', XMLDB_TYPE_TEXT, 128, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('mimetype'));
        $table->addKeyInfo('descriptionfk', XMLDB_KEY_FOREIGN, array('description'), 'artefact_file_file_types', array('description'));
        create_table($table);
        safe_require('artefact', 'file');
        PluginArtefactFile::resync_filetype_list();
    }
    if ($oldversion < 2007021400) {
        $table = new XMLDBTable('artefact_file_files');
        $field = new XMLDBField('oldextension');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2007042500) {
        // migrate everything we had to change to  make mysql happy
        execute_sql("ALTER TABLE {artefact_file_file_types} ALTER COLUMN description TYPE varchar(32)");
        execute_sql("ALTER TABLE {artefact_file_mime_types} ALTER COLUMN mimetype TYPE varchar(128)");
        execute_sql("ALTER TABLE {artefact_file_mime_types} ALTER COLUMN description TYPE varchar(32)");
    }
    if ($oldversion < 2008091100) {
        $table = new XMLDBTable('artefact_file_files');
        $field = new XMLDBField('fileid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null);
        add_field($table, $field);
        execute_sql("UPDATE {artefact_file_files} SET fileid = artefact WHERE NOT size IS NULL");
    }
    if ($oldversion < 2008101602) {
        $table = new XMLDBTable('artefact_file_files');
        $field = new XMLDBField('filetype');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
        // Guess mime type for existing files
        $fileartefacts = get_records_sql_array('
            SELECT
                a.artefacttype, f.artefact, f.oldextension, f.fileid
            FROM
                {artefact} a,
                {artefact_file_files} f
            WHERE
                a.id = f.artefact
        ', array());
        require_once get_config('libroot') . 'file.php';
        if ($fileartefacts) {
            foreach ($fileartefacts as $a) {
                $type = null;
                if ($a->artefacttype == 'image') {
                    $size = getimagesize(get_config('dataroot') . 'artefact/file/originals/' . $a->fileid % 256 . '/' . $a->fileid);
                    $type = $size['mime'];
                } else {
                    if ($a->artefacttype == 'profileicon') {
                        $size = getimagesize(get_config('dataroot') . 'artefact/file/profileicons/originals/' . $a->fileid % 256 . '/' . $a->fileid);
                        $type = $size['mime'];
                    } else {
                        if ($a->artefacttype == 'file') {
                            $type = get_mime_type(get_config('dataroot') . 'artefact/file/originals/' . $a->fileid % 256 . '/' . $a->fileid);
                        }
                    }
                }
                if ($type) {
                    set_field('artefact_file_files', 'filetype', $type, 'artefact', $a->artefact);
                }
            }
        }
        delete_records('config', 'field', 'pathtofile');
    }
    if ($oldversion < 2008101701) {
        if ($data = get_config_plugin('blocktype', 'internalmedia', 'enabledtypes')) {
            $olddata = unserialize($data);
            $newdata = array();
            foreach ($olddata as $d) {
                if ($d == 'mov') {
                    $newdata[] = 'quicktime';
                } else {
                    if ($d == 'mp4') {
                        $newdata[] = 'mp4_video';
                    } else {
                        if ($d != 'mpg') {
                            $newdata[] = $d;
                        }
                    }
                }
            }
            set_config_plugin('blocktype', 'internalmedia', 'enabledtypes', serialize($newdata));
        }
    }
    if ($oldversion < 2009021200) {
        $table = new XMLDBTable('artefact_file_mime_types');
        $key = new XMLDBKey('artefilemimetype_des_fk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('description'), 'artefact_file_file_types', array('description'));
        drop_key($table, $key);
        $table = new XMLDBTable('artefact_file_file_types');
        drop_table($table);
        PluginArtefactFile::resync_filetype_list();
    }
    if ($oldversion < 2009021301) {
        // IE has been uploading jpegs with the image/pjpeg mimetype,
        // which is not recognised as an image by the download script.
        // Fix all existing jpegs in the db:
        set_field('artefact_file_files', 'filetype', 'image/jpeg', 'filetype', 'image/pjpeg');
        // This won't happen again because we now read the contents of the
        // uploaded file to detect image artefacts, and overwrite the mime
        // type declared by the browser if we see an image.
    }
    if ($oldversion < 2009033000) {
        if (!get_record('artefact_config', 'plugin', 'file', 'field', 'uploadagreement')) {
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'uploadagreement', 'value' => 1));
            insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'usecustomagreement', 'value' => 1));
        }
    }
    if ($oldversion < 2009091700) {
        execute_sql("DELETE FROM {artefact_file_files} WHERE artefact IN (SELECT id FROM {artefact} WHERE artefacttype = 'folder')");
    }
    if ($oldversion < 2009091701) {
        $table = new XMLDBTable('artefact_file_files');
        $key = new XMLDBKey('artefactpk');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('artefact'));
        add_key($table, $key);
        $table = new XMLDBTable('artefact_file_image');
        $key = new XMLDBKey('artefactpk');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('artefact'));
        add_key($table, $key);
    }
    if ($oldversion < 2009092300) {
        insert_record('artefact_installed_type', (object) array('plugin' => 'file', 'name' => 'archive'));
        // update old files
        if (function_exists('zip_open')) {
            $files = get_records_select_array('artefact_file_files', "filetype IN ('application/zip', 'application/x-zip')");
            if ($files) {
                $checked = array();
                foreach ($files as $file) {
                    $path = get_config('dataroot') . 'artefact/file/originals/' . $file->fileid % 256 . '/' . $file->fileid;
                    $zip = zip_open($path);
                    if (is_resource($zip)) {
                        $checked[] = $file->artefact;
                        zip_close($zip);
                    }
                }
                if (!empty($checked)) {
                    set_field_select('artefact', 'artefacttype', 'archive', "artefacttype = 'file' AND id IN (" . join(',', $checked) . ')', array());
                }
            }
        }
    }
    if ($oldversion < 2010012702) {
        if ($records = get_records_sql_array("SELECT * FROM {artefact_file_files} WHERE filetype='application/octet-stream'", array())) {
            require_once 'file.php';
            foreach ($records as &$r) {
                $path = get_config('dataroot') . 'artefact/file/originals/' . $r->fileid % 256 . '/' . $r->fileid;
                set_field('artefact_file_files', 'filetype', file_mime_type($path), 'fileid', $r->fileid, 'artefact', $r->artefact);
            }
        }
    }
    return $status;
}