本文整理汇总了PHP中file_storage类的典型用法代码示例。如果您正苦于以下问题:PHP file_storage类的具体用法?PHP file_storage怎么用?PHP file_storage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了file_storage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: copy_area_files
/**
* Copy all the files from one file area to another.
*
* @param file_storage $fs - The source context id
* @param int $fromcontextid - The source context id
* @param string $fromcomponent - The source component
* @param string $fromfilearea - The source filearea
* @param int $fromitemid - The source item id
* @param int $tocontextid - The destination context id
* @param string $tocomponent - The destination component
* @param string $tofilearea - The destination filearea
* @param int $toitemid - The destination item id
* @return boolean
*/
private function copy_area_files(file_storage $fs, $fromcontextid, $fromcomponent, $fromfilearea, $fromitemid, $tocontextid, $tocomponent, $tofilearea, $toitemid)
{
$newfilerecord = new stdClass();
$newfilerecord->contextid = $tocontextid;
$newfilerecord->component = $tocomponent;
$newfilerecord->filearea = $tofilearea;
$newfilerecord->itemid = $toitemid;
if ($files = $fs->get_area_files($fromcontextid, $fromcomponent, $fromfilearea, $fromitemid)) {
foreach ($files as $file) {
if ($file->is_directory() and $file->get_filepath() === '/') {
// We need a way to mark the age of each draft area.
// By not copying the root dir we force it to be created
// automatically with current timestamp.
continue;
}
$newfile = $fs->create_file_from_storedfile($newfilerecord, $file);
}
}
return true;
}
示例2: hotpot_pluginfile_dirpath_exists
/**
* Determine if dir path exists or not in repository
*
* @param string $dirpath
* @param stdclass $repository
* @param boolean $encodepath
* @param array $params
* @return boolean true if dir path exists in repository, false otherwise
*/
function hotpot_pluginfile_dirpath_exists($dirpath, $repository, $encodepath, $params)
{
$dirs = explode('/', $dirpath);
foreach ($dirs as $i => $dir) {
$dirpath = implode('/', array_slice($dirs, 0, $i));
if ($encodepath) {
$params['filepath'] = '/' . $dirpath . ($dirpath == '' ? '' : '/');
$params['filename'] = '.';
// "." signifies a directory
$dirpath = file_storage::pack_reference($params);
}
$exists = false;
$listing = $repository->get_listing($dirpath);
foreach ($listing['list'] as $file) {
if (empty($file['source'])) {
if ($file['title'] == $dir) {
$exists = true;
break;
}
}
}
if (!$exists) {
return false;
}
}
// all dirs in path exist - success !!
return true;
}
示例3: define_execution
/**
* What to do when this step is executed.
*/
protected function define_execution()
{
global $DB;
$this->log('processing file aliases queue', backup::LOG_DEBUG);
$fs = get_file_storage();
// Load the queue.
$rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'), '', 'info');
// Iterate over aliases in the queue.
foreach ($rs as $record) {
$info = backup_controller_dbops::decode_backup_temp_info($record->info);
// Try to pick a repository instance that should serve the alias.
$repository = $this->choose_repository($info);
if (is_null($repository)) {
$this->notify_failure($info, 'unable to find a matching repository instance');
continue;
}
if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
// Aliases to Server files and Legacy course files may refer to a file
// contained in the backup file or to some existing file (if we are on the
// same site).
try {
$reference = file_storage::unpack_reference($info->oldfile->reference);
} catch (Exception $e) {
$this->notify_failure($info, 'invalid reference field format');
continue;
}
// Let's see if the referred source file was also included in the backup.
$candidates = $DB->get_recordset('backup_files_temp', array('backupid' => $this->get_restoreid(), 'contextid' => $reference['contextid'], 'component' => $reference['component'], 'filearea' => $reference['filearea'], 'itemid' => $reference['itemid']), '', 'info, newcontextid, newitemid');
$source = null;
foreach ($candidates as $candidate) {
$candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
if ($candidateinfo->filename === $reference['filename'] and $candidateinfo->filepath === $reference['filepath'] and !is_null($candidate->newcontextid) and !is_null($candidate->newitemid)) {
$source = $candidateinfo;
$source->contextid = $candidate->newcontextid;
$source->itemid = $candidate->newitemid;
break;
}
}
$candidates->close();
if ($source) {
// We have an alias that refers to another file also included in
// the backup. Let us change the reference field so that it refers
// to the restored copy of the original file.
$reference = file_storage::pack_reference($source);
// Send the new alias to the filepool.
$fs->create_file_from_reference($info->newfile, $repository->id, $reference);
$this->notify_success($info);
continue;
} else {
// This is a reference to some moodle file that was not contained in the backup
// file. If we are restoring to the same site, keep the reference untouched
// and restore the alias as is if the referenced file exists.
if ($this->task->is_samesite()) {
if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) {
$reference = file_storage::pack_reference($reference);
$fs->create_file_from_reference($info->newfile, $repository->id, $reference);
$this->notify_success($info);
continue;
} else {
$this->notify_failure($info, 'referenced file not found');
continue;
}
// If we are at other site, we can't restore this alias.
} else {
$this->notify_failure($info, 'referenced file not included');
continue;
}
}
} else {
if ($info->oldfile->repositorytype === 'user') {
if ($this->task->is_samesite()) {
// For aliases to user Private files at the same site, we have a chance to check
// if the referenced file still exists.
try {
$reference = file_storage::unpack_reference($info->oldfile->reference);
} catch (Exception $e) {
$this->notify_failure($info, 'invalid reference field format');
continue;
}
if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) {
$reference = file_storage::pack_reference($reference);
$fs->create_file_from_reference($info->newfile, $repository->id, $reference);
$this->notify_success($info);
continue;
} else {
$this->notify_failure($info, 'referenced file not found');
continue;
}
// If we are at other site, we can't restore this alias.
} else {
$this->notify_failure($info, 'restoring at another site');
continue;
}
} else {
// This is a reference to some external file such as in boxnet or dropbox.
// If we are restoring to the same site, keep the reference untouched and
// restore the alias as is.
//.........这里部分代码省略.........
示例4: sync_reference
/**
* Performs synchronisation of an external file if the previous one has expired.
*
* This function must be implemented for external repositories supporting
* FILE_REFERENCE, it is called for existing aliases when their filesize,
* contenthash or timemodified are requested. It is not called for internal
* repositories (see {@link repository::has_moodle_files()}), references to
* internal files are updated immediately when source is modified.
*
* Referenced files may optionally keep their content in Moodle filepool (for
* thumbnail generation or to be able to serve cached copy). In this
* case both contenthash and filesize need to be synchronized. Otherwise repositories
* should use contenthash of empty file and correct filesize in bytes.
*
* Note that this function may be run for EACH file that needs to be synchronised at the
* moment. If anything is being downloaded or requested from external sources there
* should be a small timeout. The synchronisation is performed to update the size of
* the file and/or to update image and re-generated image preview. There is nothing
* fatal if syncronisation fails but it is fatal if syncronisation takes too long
* and hangs the script generating a page.
*
* Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
* $file->get_timemodified() make sure that recursion does not happen.
*
* Called from {@link stored_file::sync_external_file()}
*
* @uses stored_file::set_missingsource()
* @uses stored_file::set_synchronized()
* @param stored_file $file
* @return bool false when file does not need synchronisation, true if it was synchronised
*/
public function sync_reference(stored_file $file) {
if ($file->get_repository_id() != $this->id) {
// This should not really happen because the function can be called from stored_file only.
return false;
}
if ($this->has_moodle_files()) {
// References to local files need to be synchronised only once.
// Later they will be synchronised automatically when the source is changed.
if ($file->get_referencelastsync()) {
return false;
}
$fs = get_file_storage();
$params = file_storage::unpack_reference($file->get_reference(), true);
if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
$params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
$params['filename']))) {
$file->set_missingsource();
} else {
$file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize());
}
return true;
}
// Backward compatibility (Moodle 2.3-2.5) implementation that calls
// methods repository::get_reference_file_lifetime(), repository::sync_individual_file()
// and repository::get_file_by_reference(). These methods are removed from the
// base repository class but may still be implemented by the child classes.
// THIS IS NOT A GOOD EXAMPLE of implementation. For good examples see the overwriting methods.
if (!method_exists($this, 'get_file_by_reference')) {
// Function get_file_by_reference() is not implemented. No synchronisation.
return false;
}
// Check if the previous sync result is still valid.
if (method_exists($this, 'get_reference_file_lifetime')) {
$lifetime = $this->get_reference_file_lifetime($file->get_reference());
} else {
// Default value that was hardcoded in Moodle 2.3 - 2.5.
$lifetime = 60 * 60 * 24;
}
if (($lastsynced = $file->get_referencelastsync()) && $lastsynced + $lifetime >= time()) {
return false;
}
$cache = cache::make('core', 'repositories');
if (($lastsyncresult = $cache->get('sync:'.$file->get_referencefileid())) !== false) {
if ($lastsyncresult === true) {
// We are in the process of synchronizing this reference.
// Avoid recursion when calling $file->get_filesize() and $file->get_contenthash().
return false;
} else {
// We have synchronised the same reference inside this request already.
// It looks like the object $file was created before the synchronisation and contains old data.
if (!empty($lastsyncresult['missing'])) {
$file->set_missingsource();
} else {
$cache->set('sync:'.$file->get_referencefileid(), true);
if ($file->get_contenthash() != $lastsyncresult['contenthash'] ||
$file->get_filesize() != $lastsyncresult['filesize']) {
$file->set_synchronized($lastsyncresult['contenthash'], $lastsyncresult['filesize']);
}
$cache->set('sync:'.$file->get_referencefileid(), $lastsyncresult);
}
return true;
}
}
//.........这里部分代码省略.........
示例5: sql_get_singlevalue
} else {
// make sure the custom ID of the file matches the journal ID
if ($customid != $journalid) {
$_SESSION["error"]["message"][] = "Error: File customid and journal ID do not match";
} else {
// make sure the journal entry belongs to a user
$userid = sql_get_singlevalue("SELECT customid as value FROM journal WHERE journalname='users' AND id='{$journalid}'");
if (!$userid) {
$_SESSION["error"]["message"][] = "Unable to match the provided journal entry to a user journal.";
}
}
}
/*
Produce output - either output request file content,
or take the user to a message page to view errors.
*/
if ($_SESSION["error"]["message"]) {
header("Location: ../index.php?page=message.php");
exit(0);
} else {
// output file data
$file_obj = new file_storage();
$file_obj->id = $fileid;
$file_obj->load_data();
$file_obj->filedata_render();
}
} else {
error_render_noperms();
header("Location: ../index.php?page=message.php");
exit(0);
}
示例6: replace_files_from_to
/**
* Replace the area files in the specified area with those in the source item id.
*
* @param \file_storage $fs The file storage class
* @param int $contextid The ID of the context for the setaskment.
* @param int $sourceitemid The itemid to copy from - typically the source grade id.
* @param int $itemid The itemid to copy to - typically the target grade id.
* @param string $area The file storage area.
* @param bool $includesubdirs Whether to copy the content of sub-directories too.
*/
public static function replace_files_from_to($fs, $contextid, $sourceitemid, $itemid, $area, $includesubdirs = false)
{
$component = 'setaskfeedback_editpdf';
// Remove the existing files within this area.
$fs->delete_area_files($contextid, $component, $area, $itemid);
// Copy the files from the source area.
if ($files = $fs->get_area_files($contextid, $component, $area, $sourceitemid, "filename", $includesubdirs)) {
foreach ($files as $file) {
$newrecord = new \stdClass();
$newrecord->contextid = $contextid;
$newrecord->itemid = $itemid;
$fs->create_file_from_storedfile($newrecord, $file);
}
}
}
示例7: prepare_add_file
function prepare_add_file($fieldname, $file_extension, $file_type, $file_id)
{
log_debug("template_engine", "Executing prepare_add_file({$fieldname}, {$file_extension}, {$file_type}, {$file_id})");
$tmp_filename = file_generate_name("/tmp/{$fieldname}", $file_extension);
// output file data
$file_obj = new file_storage();
$file_obj->data["type"] = $file_type;
$file_obj->data["customid"] = $file_id;
if (!$file_obj->load_data_bytype()) {
log_write("error", "template_engine", "Unable to find company logo image - use the administration config page to upload a company logo");
return 0;
}
$file_obj->filedata_write($tmp_filename);
// work out the filename without path or extension
//
// we have to do this, since latex will not tolerate file extensions in the filename when
// the file is referenced in the tex data.
//
preg_match("/\\S*\\/(\\S*).{$file_extension}\$/", $tmp_filename, $matches);
$tmp_filename_short = $matches[1];
// map fieldname to filename
$this->data_files[$fieldname]["filename"] = $tmp_filename;
$this->data_files[$fieldname]["filename_short"] = $tmp_filename_short;
log_debug("template_engine", "Wrote tempory file {$tmp_filename} with shortname of {$tmp_filename_short}");
return 1;
}
示例8: email_invoice
function email_invoice($email_sender, $email_to, $email_cc, $email_bcc, $email_subject, $email_message)
{
log_debug("invoice", "Executing email_invoice([options])");
// external dependency of Mail_Mime
if (!@(include_once 'Mail.php')) {
log_write("error", "invoice", "Unable to find Mail module required for sending email");
return 0;
}
if (!@(include_once 'Mail/mime.php')) {
log_write("error", "invoice", "Unable to find Mail::Mime module required for sending email");
return 0;
}
// track attachment files to tidy up
$file_attachments = array();
/*
Prepare Email Mime Data & Headers
*/
// fetch sender address
//
// users have the choice of sending as the company or as their own staff email address & name.
//
if ($email_sender == "user") {
// send as the user
$email_sender = "\"" . user_information("realname") . "\" <" . user_information("contact_email") . ">";
} else {
// send as the system
$email_sender = "\"" . sql_get_singlevalue("SELECT value FROM config WHERE name='COMPANY_NAME'") . "\" <" . sql_get_singlevalue("SELECT value FROM config WHERE name='COMPANY_CONTACT_EMAIL'") . ">";
}
// prepare headers
$mail_headers = array('From' => $email_sender, 'Subject' => $email_subject, 'Cc' => $email_cc, 'Bcc' => $email_bcc);
$mail_mime = new Mail_mime("\n");
$mail_mime->setTXTBody($email_message);
/*
Generate a PDF of the invoice and save to tmp file
*/
log_debug("invoice", "Generating invoice PDF for emailing");
// generate PDF
$this->generate_pdf();
if (error_check()) {
return 0;
}
// save to a temporary file
if ($this->type == "ar") {
$tmp_file_invoice = file_generate_name($GLOBALS["config"]["PATH_TMPDIR"] . "/invoice_" . $this->data["code_invoice"] . "", "pdf");
} else {
$tmp_file_invoice = file_generate_name($GLOBALS["config"]["PATH_TMPDIR"] . "/quote_" . $this->data["code_quote"] . "", "pdf");
//$email_template = sql_get_singlevalue("SELECT value FROM config WHERE name IN('TEMPLATE_QUOTE_EMAIL') LIMIT 1");
}
if (!($fhandle = fopen($tmp_file_invoice, "w"))) {
log_write("error", "invoice", "A fatal error occured whilst writing invoice PDF to file {$tmp_file_invoice}, unable to send email");
return 0;
}
fwrite($fhandle, $this->obj_pdf->output);
fclose($fhandle);
// attach
$mail_mime->addAttachment($tmp_file_invoice, 'application/pdf');
$file_attachments[] = $tmp_file_invoice;
/*
Fetch Extra Attachments
Certain billing processes may add file attachments to the journal that should be sent along with the invoice
when an email is generated.
Here we grab those file attachments and send each one.
*/
$obj_sql_journal = new sql_query();
$obj_sql_journal->string = "SELECT id FROM journal WHERE journalname='account_ar' AND customid='" . $this->id . "' AND title LIKE 'SERVICE:%'";
$obj_sql_journal->execute();
if ($obj_sql_journal->num_rows()) {
$obj_sql_journal->fetch_array();
foreach ($obj_sql_journal->data as $data_journal) {
// there are journaled attachments to send
//
// we don't care about any of the journal data, we just need to pull the file attachment from
// storage, write to disk and then attach to the email
//
// fetch file object
$file_obj = new file_storage();
$file_obj->data["type"] = "journal";
$file_obj->data["customid"] = $data_journal["id"];
if (!$file_obj->load_data_bytype()) {
log_write("error", "inc_invoices", "Unable to load file from journal to attach to invoice email - possible file storage issue?");
return 0;
}
$file_extension = format_file_extension($file_obj->data["file_name"]);
$file_name = format_file_noextension($file_obj->data["file_name"]);
$file_ctype = format_file_contenttype($file_extension);
// we have to write the file to disk before attaching it
$tmp_file_attach = file_generate_name($GLOBALS["config"]["PATH_TMPDIR"] . "/" . $file_name, $file_extension);
if (!$file_obj->filedata_write($tmp_file_attach)) {
log_write("error", "inc_invoices", "Unable to write file attachments from journal to tmp space");
return 0;
}
// add to the invoice
$mail_mime->addAttachment($tmp_file_attach, $file_ctype);
$file_attachments[] = $tmp_file_attach;
// cleanup - tmp file will be removed ;ater
unset($file_obj);
}
// end of for each journal item
//.........这里部分代码省略.........
示例9: get_file_reference
/**
* Prepare file reference information
*
* @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
* @return string file reference, ready to be stored
*/
public function get_file_reference($source) {
if ($source && $this->has_moodle_files()) {
$params = @json_decode(base64_decode($source), true);
if (!$params && !in_array($this->get_typename(), array('recent', 'user', 'local', 'coursefiles'))) {
// IMPORTANT! Since default format for moodle files was changed in the minor release as a security fix
// we maintain an old code here in order not to break 3rd party repositories that deal
// with moodle files. Repositories are strongly encouraged to be upgraded, see MDL-45616.
// In Moodle 2.8 this fallback will be removed.
$params = file_storage::unpack_reference($source, true);
return file_storage::pack_reference($params);
}
if (!is_array($params) || empty($params['contextid'])) {
throw new repository_exception('invalidparams', 'repository');
}
$params = array(
'component' => empty($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
'filearea' => empty($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
'itemid' => empty($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
'filename' => empty($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
'filepath' => empty($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
'contextid' => clean_param($params['contextid'], PARAM_INT)
);
// Check if context exists.
if (!context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
throw new repository_exception('invalidparams', 'repository');
}
return file_storage::pack_reference($params);
}
return $source;
}
示例10: xmldb_hvp_upgrade
//.........这里部分代码省略.........
$dbman->add_field($table, $timecreated);
}
// Define field timemodified to be added to hvp.
$timemodified = new xmldb_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated');
// Conditionally launch add field timemodified.
if (!$dbman->field_exists($table, $timemodified)) {
$dbman->add_field($table, $timemodified);
}
// Hvp savepoint reached.
upgrade_mod_savepoint(true, 2016011300, 'hvp');
}
if ($oldversion < 2016042500) {
// Define table hvp_tmpfiles to be created.
$table = new xmldb_table('hvp_tmpfiles');
// Adding fields to table hvp_tmpfiles.
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
// Adding keys to table hvp_tmpfiles.
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
// Conditionally launch create table for hvp_tmpfiles.
if (!$dbman->table_exists($table)) {
$dbman->create_table($table);
}
// Hvp savepoint reached.
upgrade_mod_savepoint(true, 2016042500, 'hvp');
}
if ($oldversion < 2016050600) {
// Define table hvp_events to be created.
$table = new xmldb_table('hvp_events');
// Adding fields to table hvp_events.
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('user_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('created_at', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('type', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null);
$table->add_field('sub_type', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null);
$table->add_field('content_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('content_title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
$table->add_field('library_name', XMLDB_TYPE_CHAR, '127', null, XMLDB_NOTNULL, null, null);
$table->add_field('library_version', XMLDB_TYPE_CHAR, '31', null, XMLDB_NOTNULL, null, null);
// Adding keys to table hvp_events.
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
// Conditionally launch create table for hvp_events.
if (!$dbman->table_exists($table)) {
$dbman->create_table($table);
}
// Define table hvp_counters to be created.
$table = new xmldb_table('hvp_counters');
// Adding fields to table hvp_counters.
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('type', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null);
$table->add_field('library_name', XMLDB_TYPE_CHAR, '127', null, XMLDB_NOTNULL, null, null);
$table->add_field('library_version', XMLDB_TYPE_CHAR, '31', null, XMLDB_NOTNULL, null, null);
$table->add_field('num', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
// Adding keys to table hvp_counters.
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
// Adding indexes to table hvp_counters.
$table->add_index('realkey', XMLDB_INDEX_NOTUNIQUE, array('type', 'library_name', 'library_version'));
// Conditionally launch create table for hvp_counters.
if (!$dbman->table_exists($table)) {
$dbman->create_table($table);
}
// Hvp savepoint reached.
upgrade_mod_savepoint(true, 2016050600, 'hvp');
}
if ($oldversion < 2016051000) {
$table = new xmldb_table('hvp');
// Define field timecreated to be added to hvp.
$intro = new xmldb_field('intro', XMLDB_TYPE_TEXT, null, null, null, null, null, 'name');
// Conditionally launch add field timecreated.
if (!$dbman->field_exists($table, $intro)) {
$dbman->add_field($table, $intro);
}
// Define field timemodified to be added to hvp.
$introformat = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '0', 'intro');
// Conditionally launch add field timemodified.
if (!$dbman->field_exists($table, $introformat)) {
$dbman->add_field($table, $introformat);
}
// Hvp savepoint reached.
upgrade_mod_savepoint(true, 2016051000, 'hvp');
}
if ($oldversion < 2016110100) {
// Change context of activity files from COURSE to MODULE.
$filearea = 'content';
$component = 'mod_hvp';
// Find activity ID and correct context ID
$hvpsresult = $DB->get_records_sql("SELECT f.id AS fileid, f.itemid, c.id, f.filepath, f.filename, f.pathnamehash\n FROM {files} f\n JOIN {course_modules} cm ON f.itemid = cm.instance\n JOIN {modules} md ON md.id = cm.module\n JOIN {context} c ON c.instanceid = cm.id\n WHERE md.name = 'hvp'\n AND f.filearea = 'content'\n AND c.contextlevel = " . CONTEXT_MODULE);
foreach ($hvpsresult as $hvp) {
// Need to re-hash pathname after changing context
$pathnamehash = file_storage::get_pathname_hash($hvp->id, $component, $filearea, $hvp->itemid, $hvp->filepath, $hvp->filename);
// Double check that hash doesn't exist (avoid duplicate entries)
if (!$DB->get_field_sql("SELECT contextid FROM {files} WHERE pathnamehash = '{$pathnamehash}'")) {
// Update context ID and pathname hash for files
$DB->execute("UPDATE {files} SET contextid = {$hvp->id}, pathnamehash = '{$pathnamehash}' WHERE pathnamehash = '{$hvp->pathnamehash}'");
}
}
// Hvp savepoint reached.
upgrade_mod_savepoint(true, 2016110100, 'hvp');
}
return true;
}
示例11: send_file
/**
* Repository method to serve file
*
* @param stored_file $storedfile
* @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
* @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
* @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
* @param array $options additional options affecting the file serving
*/
public function send_file($storedfile, $lifetime = 86400, $filter = 0, $forcedownload = false, array $options = null)
{
$fs = get_file_storage();
$reference = $storedfile->get_reference();
$params = file_storage::unpack_reference($reference);
$filename = is_null($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE);
$filepath = is_null($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH);
$contextid = is_null($params['contextid']) ? null : clean_param($params['contextid'], PARAM_INT);
// hard coded file area and component for security
$srcfile = $fs->get_file($contextid, 'course', 'legacy', 0, $filepath, $filename);
send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
}
示例12: cdr_rate_table
/*
Load Data
*/
$obj_rate_table = new cdr_rate_table();
$obj_rate_table->id = @security_form_input_predefined("int", "id_rate_table", 1, "");
$cdr_import_mode = @security_form_input_predefined("any", "cdr_rate_import_mode", 1, "");
/*
Verify valid rate table
*/
if (!$obj_rate_table->verify_id()) {
log_write("error", "process", "The CDR rate table you have attempted to edit - " . $obj_rate_table->id . " - does not exist in this system.");
}
/*
Verify File Upload
*/
$file_obj = new file_storage();
$file_obj->verify_upload_form("cdr_rate_import_file", array("csv", "zip"));
/*
Handle Errors
*/
if (error_check()) {
header("Location: ../index.php?page=services/cdr-rates-import.php&id=" . $obj_rate_table->id);
exit(0);
} else {
error_clear();
/*
Load the file
*/
$rate_table = array();
switch (format_file_extension($_FILES["cdr_rate_import_file"]["name"])) {
case "zip":
示例13: file_storage
bankstatement-process.php
access: "accounts_import_statement" group members
Validates the uploaded statement file as being a supported format
and reads in the data into session information to pass to the column assignment
and then the record matching pages.
*/
//inclues
require "../../include/config.php";
require "../../include/amberphplib/main.php";
if (user_permissions_get("accounts_import_statement")) {
/*
Process Uploaded File
*/
$file_obj = new file_storage();
$file_obj->verify_upload_form("BANK_STATEMENT", array("csv"));
$dest_account = @security_form_input_predefined("int", "dest_account", 1, "");
$employeeid = @security_form_input_predefined("any", "employeeid", 1, "");
/*
Check for obvious errors
*/
if (error_check()) {
header("Location: ../../index.php?page=accounts/import/bankstatement.php");
exit(0);
}
/*
Import File Contents
*/
// declare array
$transactions = array();
示例14: service_invoices_generate
//.........这里部分代码省略.........
unset($usage_obj);
/*
If enabled, generate the CDR output format for the current service usage and attach
it to the invoice via the invoice journal.
This feature can be enabled/disabled on a per-customer per-service basis.
*/
if ($obj_service->data["billing_cdr_csv_output"]) {
log_write("debug", "inc_service_invoicegen", "Generating CDR export file and attaching to invoice journal");
// generate the CSV formatted export.
$cdr_options = array('id_customer' => $customer_data["id"], 'id_service_customer' => $period_usage_data["id_service_customer"], 'period_start' => $period_usage_data["date_start"], 'period_end' => $period_usage_data["date_end"]);
$csv = new cdr_csv($cdr_options);
if (!($cdr_output = $csv->getCSV())) {
log_write("error", "inc_service_invoicegen", "Unable to generate CSV ouput for the configured range");
return 0;
}
// create journal entry
$journal = new journal_process();
$journal->prepare_set_journalname("account_ar");
$journal->prepare_set_customid($invoiceid);
$journal->prepare_set_type("file");
// we use the prefix "SERVICE:" to find the journal at invoice time
$journal->prepare_set_title("SERVICE: Service CDR Export Attachment");
// details can be anything (just a text block)
$data["content"] = NULL;
$data["content"] .= "Automatically exported CDR for service " . addslashes($obj_service->data["name_service"]) . "\n";
$data["content"] .= "\n";
$journal->prepare_set_content($data["content"]);
$journal->action_update();
// create journal entry
$journal->action_lock();
// lock entry to avoid users deleting it or breaking it
// upload file as an attachment for the journal
$file_obj = new file_storage();
$file_obj->data["type"] = "journal";
$file_obj->data["customid"] = $journal->structure["id"];
$file_obj->data["file_name"] = "invoice_" . $invoicecode . "_service_CDR_export.csv";
if (!$file_obj->action_update_var($cdr_output)) {
log_write("error", "inc_service_invoicegen", "Unable to upload export CDR invoice to journal.");
}
unset($csv);
unset($journal);
unset($file_obj);
unset($cdr_output);
}
break;
case "generic_no_usage":
case "bundle":
// nothing todo for these service types
log_write("debug", "service_invoicegen", "Not processing usage, this is a non-usage service type");
break;
default:
// we should always match all service types, even if we don't need to do anything
// in particular for that type.
die("Unable to process unknown service type: " . $obj_service->data["typeid_string"] . "");
break;
}
// end of processing usage
} else {
log_write("debug", "service_invoicegen", "Not billing for current usage, as this appears to be the first plan period so no usage can exist yet");
}
/*
Set invoice ID for period - this prevents the period from being added to
any other invoices and allows users to see which invoice it was billed under
*/
// set for plan period
示例15: file_prepare_draft_area
/**
* Initialise a draft file area from a real one by copying the files. A draft
* area will be created if one does not already exist. Normally you should
* get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
*
* @category files
* @global stdClass $CFG
* @global stdClass $USER
* @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
* @param int $contextid This parameter and the next two identify the file area to copy files from.
* @param string $component
* @param string $filearea helps indentify the file area.
* @param int $itemid helps identify the file area. Can be null if there are no files yet.
* @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
* @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
* @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
*/
function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options = null, $text = null)
{
global $CFG, $USER, $CFG;
$options = (array) $options;
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
$usercontext = context_user::instance($USER->id);
$fs = get_file_storage();
if (empty($draftitemid)) {
// create a new area and copy existing files into
$draftitemid = file_get_unused_draft_itemid();
$file_record = array('contextid' => $usercontext->id, 'component' => 'user', 'filearea' => 'draft', 'itemid' => $draftitemid);
if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
foreach ($files as $file) {
if ($file->is_directory() and $file->get_filepath() === '/') {
// we need a way to mark the age of each draft area,
// by not copying the root dir we force it to be created automatically with current timestamp
continue;
}
if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
continue;
}
$draftfile = $fs->create_file_from_storedfile($file_record, $file);
// XXX: This is a hack for file manager (MDL-28666)
// File manager needs to know the original file information before copying
// to draft area, so we append these information in mdl_files.source field
// {@link file_storage::search_references()}
// {@link file_storage::search_references_count()}
$sourcefield = $file->get_source();
$newsourcefield = new stdClass();
$newsourcefield->source = $sourcefield;
$original = new stdClass();
$original->contextid = $contextid;
$original->component = $component;
$original->filearea = $filearea;
$original->itemid = $itemid;
$original->filename = $file->get_filename();
$original->filepath = $file->get_filepath();
$newsourcefield->original = file_storage::pack_reference($original);
$draftfile->set_source(serialize($newsourcefield));
// End of file manager hack
}
}
if (!is_null($text)) {
// at this point there should not be any draftfile links yet,
// because this is a new text from database that should still contain the @@pluginfile@@ links
// this happens when developers forget to post process the text
$text = str_replace("\"{$CFG->httpswwwroot}/draftfile.php", "\"{$CFG->httpswwwroot}/brokenfile.php#", $text);
}
} else {
// nothing to do
}
if (is_null($text)) {
return null;
}
// relink embedded files - editor can not handle @@PLUGINFILE@@ !
return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
}