function close() { global $CFG; require_once $CFG->libdir . '/filelib.php'; $dir = 'ods/' . time(); make_temp_directory($dir); make_temp_directory($dir . '/META-INF'); $dir = "{$CFG->tempdir}/{$dir}"; $files = array(); $handle = fopen("{$dir}/mimetype", 'w'); fwrite($handle, get_ods_mimetype()); $files[] = "{$dir}/mimetype"; $handle = fopen("{$dir}/content.xml", 'w'); fwrite($handle, get_ods_content($this->worksheets)); $files[] = "{$dir}/content.xml"; $handle = fopen("{$dir}/meta.xml", 'w'); fwrite($handle, get_ods_meta()); $files[] = "{$dir}/meta.xml"; $handle = fopen("{$dir}/styles.xml", 'w'); fwrite($handle, get_ods_styles()); $files[] = "{$dir}/styles.xml"; $handle = fopen("{$dir}/META-INF/manifest.xml", 'w'); fwrite($handle, get_ods_manifest()); $files[] = "{$dir}/META-INF"; $filename = "{$dir}/result.ods"; zip_files($files, $filename); $handle = fopen($filename, 'rb'); $contents = fread($handle, filesize($filename)); fclose($handle); remove_dir($dir); // cleanup the temp directory send_file($contents, $this->filename, 0, 0, true, true, 'application/vnd.oasis.opendocument.spreadsheet'); }
/** * Return t3lib helper class * @return t3lib_cs */ protected static function typo3() { static $typo3cs = null; if (isset($typo3cs)) { return $typo3cs; } global $CFG; // Required files require_once $CFG->libdir . '/typo3/class.t3lib_cs.php'; require_once $CFG->libdir . '/typo3/class.t3lib_div.php'; // do not use mbstring or recode because it may return invalid results in some corner cases $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv'; $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'iconv'; // Tell Typo3 we are curl enabled always (mandatory since 2.0) $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1'; // And this directory must exist to allow Typo to cache conversion // tables when using internal functions make_temp_directory('typo3temp/cs'); // Make sure typo is using our dir permissions $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions); // Default mask for Typo $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions; // This full path constants must be defined too, transforming backslashes // to forward slashed because Typo3 requires it. define('PATH_t3lib', str_replace('\\', '/', $CFG->libdir . '/typo3/')); define('PATH_typo3', str_replace('\\', '/', $CFG->libdir . '/typo3/')); define('PATH_site', str_replace('\\', '/', $CFG->tempdir . '/')); define('TYPO3_OS', stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin') ? 'WIN' : ''); $typo3cs = new t3lib_cs(); return $typo3cs; }
/** * Constructor - create temporary directories and build paths to * external 'helper' binaries. * Other platforms could/should be added */ function latex() { global $CFG; // construct directory structure $this->temp_dir = $CFG->tempdir . "/latex"; make_temp_directory('latex'); }
public function get_plugintype_location($plugintype) { $testableroot = make_temp_directory('testable_core_update_validator/plugintypes'); if (!file_exists($testableroot . '/' . $plugintype)) { make_temp_directory('testable_core_update_validator/plugintypes/' . $plugintype); } return $testableroot . '/' . $plugintype; }
public function setUp() { parent::setUp(); $this->resetAfterTest(true); if (!($this->tempdir = make_temp_directory('assignfeedback_pdf'))) { throw new coding_exception("Unable to create temporary directory"); } }
/** * Constructor. */ public function __construct() { make_temp_directory(''); make_upload_directory('lang'); $this->info = array(); $this->errors = array(); $this->installer = new \lang_installer(); $this->availablelangs = $this->installer->get_remote_list_of_languages(); }
/** * Set the file path to the temporary file. */ protected function set_temp_file_path() { global $USER, $CFG; make_temp_directory('ratingallocate/' . $USER->id); $path = $CFG->tempdir . '/ratingallocate/' . $USER->id . '/' . $this->filename; // Check to see if the file exists, if so delete it. if (file_exists($path)) { unlink($path); } $this->path = $path; }
/** * Wrapper to get a Google Client object. * * This automatically sets the config to Moodle's defaults. * * @return Google_Client */ function get_google_client() { global $CFG, $SITE; make_temp_directory('googleapi'); $tempdir = $CFG->tempdir . '/googleapi'; $config = new Google_Config(); $config->setApplicationName('Moodle ' . $CFG->release); $config->setIoClass('moodle_google_curlio'); $config->setClassConfig('Google_Cache_File', 'directory', $tempdir); $config->setClassConfig('Google_Auth_OAuth2', 'access_type', 'online'); $config->setClassConfig('Google_Auth_OAuth2', 'approval_prompt', 'auto'); return new Google_Client($config); }
/** * Constructs one Moodle Workbook. * * @global object * @param string $filename The name of the file */ function MoodleExcelWorkbook($filename) { global $CFG; /// Internally, create one PEAR Spreadsheet_Excel_Writer_Workbook class $this->pear_excel_workbook = new Spreadsheet_Excel_Writer($filename); /// Prepare it to accept UTF-16LE data and to encode it properly if (empty($CFG->latinexcelexport)) { /// Only if don't want to use latin (win1252) stronger output $this->pear_excel_workbook->setVersion(8); $this->latin_output = false; } else { /// We want latin (win1252) output $this->latin_output = true; } /// Choose our temporary directory - see MDL-7176, found by paulo.matos make_temp_directory('excel'); $this->pear_excel_workbook->setTempDir($CFG->tempdir . '/excel'); }
/** * Download the community course backup and save it in file API * @param integer $courseid * @param string $huburl * @return array 'privatefile' the file name saved in private area * 'tmpfile' the file name saved in the moodledata temp dir (for restore) */ public function block_community_download_course_backup($course) { global $CFG, $USER; require_once $CFG->libdir . "/filelib.php"; require_once $CFG->dirroot . "/course/publish/lib.php"; $params['courseid'] = $course->id; $params['filetype'] = HUB_BACKUP_FILE_TYPE; make_temp_directory('backup'); $filename = md5(time() . '-' . $course->id . '-' . $USER->id . '-' . random_string(20)); $url = new moodle_url($course->huburl . '/local/hub/webservice/download.php', $params); $path = $CFG->tempdir . '/backup/' . $filename . ".mbz"; $fp = fopen($path, 'w'); $curlurl = $course->huburl . '/local/hub/webservice/download.php?filetype=' . HUB_BACKUP_FILE_TYPE . '&courseid=' . $course->id; //send an identification token if the site is registered on the hub require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php'; $registrationmanager = new registration_manager(); $registeredhub = $registrationmanager->get_registeredhub($course->huburl); if (!empty($registeredhub)) { $token = $registeredhub->token; $curlurl .= '&token=' . $token; } $ch = curl_init($curlurl); curl_setopt($ch, CURLOPT_FILE, $fp); $data = curl_exec($ch); curl_close($ch); fclose($fp); $fs = get_file_storage(); $record = new stdClass(); $record->contextid = context_user::instance($USER->id)->id; $record->component = 'user'; $record->filearea = 'private'; $record->itemid = 0; $record->filename = urlencode($course->fullname) . "_" . time() . ".mbz"; $record->filepath = '/downloaded_backup/'; if (!$fs->file_exists($record->contextid, $record->component, $record->filearea, 0, $record->filepath, $record->filename)) { $fs->create_file_from_pathname($record, $CFG->tempdir . '/backup/' . $filename . ".mbz"); } $filenames = array(); $filenames['privatefile'] = $record->filename; $filenames['tmpfile'] = $filename; return $filenames; }
/** * Instantiate the class instance * * @param string $dirroot full path to the moodle app directory root * @param string $temproot full path to our temp directory */ public function __construct($dirroot = null, $temproot = null) { global $CFG; if (empty($dirroot)) { $dirroot = $CFG->dirroot; } if (empty($temproot)) { // Note we are using core_plugin here as that is the valid core // subsystem we are part of. The namespace of this class (core\update) // does not match it for legacy reasons. The data stored in the // temp directory are expected to survive multiple requests and // purging caches during the upgrade, so we make use of // make_temp_directory(). The contents of it can be removed if needed, // given the site is in the maintenance mode (so that cron is not // executed) and the site is not being upgraded. $temproot = make_temp_directory('core_plugin/code_manager'); } $this->dirroot = $dirroot; $this->temproot = $temproot; $this->init_temp_directories(); }
/** * On the attempt page, simulate clicking the download link to get the responses. * @When /^I follow the emergency download link$/ */ public function i_follow_the_emergency_download_link() { $session = $this->getSession(); $session->evaluateScript(' window.behat_quizaccess_offlinemode_click_handler = function(e) { e.preventDefault(); }; document.body.addEventListener("click", window.behat_quizaccess_offlinemode_click_handler);'); $linknode = $this->find_link(get_string('savetheresponses', 'quizaccess_offlinemode')); $this->ensure_node_is_visible($linknode); $linknode->click(); $session->evaluateScript(' document.body.removeEventListener("click", window.behat_quizaccess_offlinemode_click_handler);'); // Get the link again, or we won't seen the new URL. $linknode = $this->find_link(get_string('savetheresponses', 'quizaccess_offlinemode')); $url = $linknode->getAttribute('href'); if (substr($url, 0, 30) !== 'data:application/octet-stream,') { throw new ExpectationException('Expected the URL to look like a data URL, but it didn\'t.', $session); } $tempdir = make_temp_directory('behat_quizaccess_offlinemode'); $this->downloadedfile = tempnam($tempdir, 'download'); file_put_contents($this->downloadedfile, substr($url, 30)); }
/** * writes log output to a temp log file * * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename * @param string $text - text to be written to file. * @param integer $scoid - scoid of object this log entry is for. */ function scorm_debug_log_write($type, $text, $scoid) { global $CFG; $debugenablelog = get_config('scorm', 'allowapidebug'); if (!$debugenablelog || empty($text)) { return; } if (make_temp_directory('scormlogs/')) { $logfile = scorm_debug_log_filename($type, $scoid); @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND); @chmod($logfile, $CFG->filepermissions); } }
/** * This function takes the combined pdf and embeds all the comments and annotations. * @param int|\assign $assignment * @param int $userid * @param int $attemptnumber (-1 means latest attempt) * @return stored_file */ public static function generate_feedback_document($assignment, $userid, $attemptnumber) { $assignment = self::get_assignment_from_param($assignment); if (!$assignment->can_view_submission($userid)) { \print_error('nopermission'); } if (!$assignment->can_grade()) { \print_error('nopermission'); } // Need to generate the page images - first get a combined pdf. $file = self::get_combined_pdf_for_attempt($assignment, $userid, $attemptnumber); if (!$file) { throw new \moodle_exception('Could not generate combined pdf.'); } $tmpdir = \make_temp_directory('assignfeedback_editpdf/final/' . self::hash($assignment, $userid, $attemptnumber)); $combined = $tmpdir . '/' . self::COMBINED_PDF_FILENAME; $file->copy_content_to($combined); // Copy the file. $pdf = new pdf(); $fs = \get_file_storage(); $stamptmpdir = \make_temp_directory('assignfeedback_editpdf/stamps/' . self::hash($assignment, $userid, $attemptnumber)); $grade = $assignment->get_user_grade($userid, true, $attemptnumber); // Copy any new stamps to this instance. if ($files = $fs->get_area_files($assignment->get_context()->id, 'assignfeedback_editpdf', 'stamps', $grade->id, "filename", false)) { foreach ($files as $file) { $filename = $stamptmpdir . '/' . $file->get_filename(); $file->copy_content_to($filename); // Copy the file. } } $pagecount = $pdf->set_pdf($combined); $grade = $assignment->get_user_grade($userid, true, $attemptnumber); page_editor::release_drafts($grade->id); for ($i = 0; $i < $pagecount; $i++) { $pdf->copy_page(); $comments = page_editor::get_comments($grade->id, $i, false); $annotations = page_editor::get_annotations($grade->id, $i, false); foreach ($comments as $comment) { $pdf->add_comment($comment->rawtext, $comment->x, $comment->y, $comment->width, $comment->colour); } foreach ($annotations as $annotation) { $pdf->add_annotation($annotation->x, $annotation->y, $annotation->endx, $annotation->endy, $annotation->colour, $annotation->type, $annotation->path, $stamptmpdir); } } fulldelete($stamptmpdir); $filename = self::get_downloadable_feedback_filename($assignment, $userid, $attemptnumber); $filename = clean_param($filename, PARAM_FILE); $generatedpdf = $tmpdir . '/' . $filename; $pdf->save_pdf($generatedpdf); $record = new \stdClass(); $record->contextid = $assignment->get_context()->id; $record->component = 'assignfeedback_editpdf'; $record->filearea = self::FINAL_PDF_FILEAREA; $record->itemid = $grade->id; $record->filepath = '/'; $record->filename = $filename; // Only keep one current version of the generated pdf. $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid); $file = $fs->create_file_from_pathname($record, $generatedpdf); // Cleanup. @unlink($generatedpdf); @unlink($combined); @rmdir($tmpdir); return $file; }
/** * Install core moodle tables and initialize * @param float $version target version * @param bool $verbose * @return void, may throw exception */ function install_core($version, $verbose) { global $CFG, $DB; // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty. remove_dir($CFG->cachedir.'', true); make_cache_directory('', true); remove_dir($CFG->localcachedir.'', true); make_localcache_directory('', true); remove_dir($CFG->tempdir.'', true); make_temp_directory('', true); remove_dir($CFG->dataroot.'/muc', true); make_writable_directory($CFG->dataroot.'/muc', true); try { core_php_time_limit::raise(600); print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml"); upgrade_started(); // we want the flag to be stored in config table ;-) // set all core default records and default settings require_once("$CFG->libdir/db/install.php"); xmldb_main_install(); // installs the capabilities too // store version upgrade_main_savepoint(true, $version, false); // Continue with the installation log_update_descriptions('moodle'); external_update_descriptions('moodle'); events_update_definition('moodle'); \core\task\manager::reset_scheduled_tasks_for_component('moodle'); message_update_providers('moodle'); \core\message\inbound\manager::update_handlers_for_component('moodle'); // Write default settings unconditionally admin_apply_default_settings(NULL, true); print_upgrade_part_end(null, true, $verbose); // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something // during installation didn't use APIs. cache_helper::purge_all(); } catch (exception $ex) { upgrade_handle_exception($ex); } }
function data_presets_export($course, $cm, $data, $tostorage = false) { global $CFG, $DB; $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi"); $exportsubdir = "mod_data/presetexport/{$presetname}"; make_temp_directory($exportsubdir); $exportdir = "{$CFG->tempdir}/{$exportsubdir}"; // Assemble "preset.xml": $presetxmldata = data_presets_generate_xml($course, $cm, $data); // After opening a file in write mode, close it asap $presetxmlfile = fopen($exportdir . '/preset.xml', 'w'); fwrite($presetxmlfile, $presetxmldata); fclose($presetxmlfile); // Now write the template files $singletemplate = fopen($exportdir . '/singletemplate.html', 'w'); fwrite($singletemplate, $data->singletemplate); fclose($singletemplate); $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w'); fwrite($listtemplateheader, $data->listtemplateheader); fclose($listtemplateheader); $listtemplate = fopen($exportdir . '/listtemplate.html', 'w'); fwrite($listtemplate, $data->listtemplate); fclose($listtemplate); $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w'); fwrite($listtemplatefooter, $data->listtemplatefooter); fclose($listtemplatefooter); $addtemplate = fopen($exportdir . '/addtemplate.html', 'w'); fwrite($addtemplate, $data->addtemplate); fclose($addtemplate); $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w'); fwrite($rsstemplate, $data->rsstemplate); fclose($rsstemplate); $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w'); fwrite($rsstitletemplate, $data->rsstitletemplate); fclose($rsstitletemplate); $csstemplate = fopen($exportdir . '/csstemplate.css', 'w'); fwrite($csstemplate, $data->csstemplate); fclose($csstemplate); $jstemplate = fopen($exportdir . '/jstemplate.js', 'w'); fwrite($jstemplate, $data->jstemplate); fclose($jstemplate); $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w'); fwrite($asearchtemplate, $data->asearchtemplate); fclose($asearchtemplate); // Check if all files have been generated if (!is_directory_a_preset($exportdir)) { print_error('generateerror', 'data'); } $filenames = array('preset.xml', 'singletemplate.html', 'listtemplateheader.html', 'listtemplate.html', 'listtemplatefooter.html', 'addtemplate.html', 'rsstemplate.html', 'rsstitletemplate.html', 'csstemplate.css', 'jstemplate.js', 'asearchtemplate.html'); $filelist = array(); foreach ($filenames as $filename) { $filelist[$filename] = $exportdir . '/' . $filename; } $exportfile = $exportdir . '.zip'; file_exists($exportfile) && unlink($exportfile); $fp = get_file_packer('application/zip'); $fp->archive_to_pathname($filelist, $exportfile); foreach ($filelist as $file) { unlink($file); } rmdir($exportdir); // Return the full path to the exported preset file: return $exportfile; }
/** * Decide where to save the file, can be overwriten by subclass * * @param string $filename file name * @return file path */ public function prepare_file($filename) { global $CFG; $dir = make_temp_directory('download/'.get_class($this).'/'); while (empty($filename) || file_exists($dir.$filename)) { $filename = uniqid('', true).'_'.time().'.tmp'; } return $dir.$filename; }
/** * Returns a temporary file, do not forget to delete after not needed any more. * * @param string $elname name of the elmenet * @return string|bool either string or false */ function save_temp_file($elname) { if (!$this->get_new_filename($elname)) { return false; } if (!($dir = make_temp_directory('forms'))) { return false; } if (!($tempfile = tempnam($dir, 'tempup_'))) { return false; } if (!$this->save_file($elname, $tempfile, true)) { // something went wrong @unlink($tempfile); return false; } return $tempfile; }
/** * Return content of all files containing questions, * as an array one element for each file found, * For each file, the corresponding element is an array of lines. * @param string filename name of file * @return mixed contents array or false on failure */ public function readdata($filename) { // Find if we are importing a .txt file. if (strtolower(pathinfo($filename, PATHINFO_EXTENSION)) == 'txt') { if (!is_readable($filename)) { $this->error(get_string('filenotreadable', 'error')); return false; } return file($filename); } // We are importing a zip file. // Create name for temporary directory. $uniquecode = time(); $this->tempdir = make_temp_directory('webct_import/' . $uniquecode); if (is_readable($filename)) { if (!copy($filename, $this->tempdir . '/webct.zip')) { $this->error(get_string('cannotcopybackup', 'question')); fulldelete($this->tempdir); return false; } if (unzip_file($this->tempdir . '/webct.zip', '', false)) { $dir = $this->tempdir; if (($handle = opendir($dir)) == false) { // The directory could not be opened. fulldelete($this->tempdir); return false; } // Create arrays to store files and directories. $dirfiles = array(); $dirsubdirs = array(); $slash = '/'; // Loop through all directory entries, and construct two temporary arrays containing files and sub directories. while (false !== ($entry = readdir($handle))) { if (is_dir($dir . $slash . $entry) && $entry != '..' && $entry != '.') { $dirsubdirs[] = $dir . $slash . $entry; } else { if ($entry != '..' && $entry != '.') { $dirfiles[] = $dir . $slash . $entry; } } } if (($handle = opendir($dirsubdirs[0])) == false) { // The directory could not be opened. fulldelete($this->tempdir); return false; } while (false !== ($entry = readdir($handle))) { if (is_dir($dirsubdirs[0] . $slash . $entry) && $entry != '..' && $entry != '.') { $dirsubdirs[] = $dirsubdirs[0] . $slash . $entry; } else { if ($entry != '..' && $entry != '.') { $dirfiles[] = $dirsubdirs[0] . $slash . $entry; } } } return file($dirfiles[1]); } else { $this->error(get_string('cannotunzip', 'question')); fulldelete($this->temp_dir); } } else { $this->error(get_string('cannotreaduploadfile', 'error')); fulldelete($this->tempdir); } return false; }
/** * Create new import id * * @global object * @param string who imports? * @return int iid */ static function get_new_iid($type) { global $USER; $filename = make_temp_directory('csvimport/' . $type . '/' . $USER->id); // use current (non-conflicting) time stamp $iiid = time(); while (file_exists($filename . '/' . $iiid)) { $iiid--; } return $iiid; }
/** * Creates a temp file for submission to Turnitin uses a random number * suffixed with the stored filename * * @param string $suffix The file extension for the upload * @return string $file The filepath of the temp file */ function turnitintool_tempfile($suffix) { global $CFG; $fp = false; if (function_exists('make_temp_directory')) { $temp_dir = make_temp_directory('turnitintool'); } else { $temp_dir = $CFG->dataroot . '/temp/turnitintool'; if (!file_exists($temp_dir)) { mkdir($tempdir, $CFG->directorypermissions, true); } } while (!$fp) { $file = $temp_dir . DIRECTORY_SEPARATOR . mt_rand() . '.' . $suffix; $fp = @fopen($file, 'w'); } fclose($fp); return $file; }
/** * Sends the student their issued certificate from moddata as an email * attachment. * * @param stdClass $course * @param stdClass $certificate * @param stdClass $certrecord * @param stdClass $context * @param string $filecontents the PDF file contents * @param string $filename * @return bool Returns true if mail was sent OK and false if there was an error. */ function certificate_email_student($course, $certificate, $certrecord, $context, $filecontents, $filename) { global $USER; // Get teachers if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC', '', '', '', '', false, true)) { $users = sort_by_roleassignment_authority($users, $context); $teacher = array_shift($users); } // If we haven't found a teacher yet, look for a non-editing teacher in this course. if (empty($teacher) && ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC', '', '', '', '', false, true))) { $users = sort_by_roleassignment_authority($users, $context); $teacher = array_shift($users); } // Ok, no teachers, use administrator name if (empty($teacher)) { $teacher = fullname(get_admin()); } $info = new stdClass(); $info->username = fullname($USER); $info->certificate = format_string($certificate->name, true); $info->course = format_string($course->fullname, true); $from = fullname($teacher); $subject = $info->course . ': ' . $info->certificate; $message = get_string('emailstudenttext', 'certificate', $info) . "\n"; // Make the HTML version more XHTML happy (&) $messagehtml = text_to_html(get_string('emailstudenttext', 'certificate', $info)); $tempdir = make_temp_directory('certificate/attachment'); if (!$tempdir) { return false; } $tempfile = $tempdir . '/' . md5(sesskey() . microtime() . $USER->id . '.pdf'); $fp = fopen($tempfile, 'w+'); fputs($fp, $filecontents); fclose($fp); $prevabort = ignore_user_abort(true); $result = email_to_user($USER, $from, $subject, $message, $messagehtml, $tempfile, $filename); @unlink($tempfile); ignore_user_abort($prevabort); return $result; }
/** * Purge dataroot directory * @static * @return void */ public static function reset_dataroot() { global $CFG; $childclassname = self::get_framework() . '_util'; $handle = opendir($CFG->dataroot); while (false !== ($item = readdir($handle))) { if (in_array($item, $childclassname::$datarootskiponreset)) { continue; } if (is_dir("$CFG->dataroot/$item")) { remove_dir("$CFG->dataroot/$item", false); } else { unlink("$CFG->dataroot/$item"); } } closedir($handle); make_temp_directory(''); make_cache_directory(''); make_cache_directory('htmlpurifier'); // Reset the cache API so that it recreates it's required directories as well. cache_factory::reset(); // Purge all data from the caches. This is required for consistency. // Any file caches that happened to be within the data root will have already been clearer (because we just deleted cache) // and now we will purge any other caches as well. cache_helper::purge_all(); }
public function get_plugintype_location($plugintype) { $testableroot = make_temp_directory('testable_tool_installaddon_validator/plugintypes'); if (!is_dir($testableroot . '/' . $plugintype)) { make_temp_directory('testable_tool_installaddon_validator/plugintypes/' . $plugintype); } if ($plugintype === 'local') { // We need the following for the test_validate_target_location() method make_temp_directory('testable_tool_installaddon_validator/plugintypes/local/greenbar'); } return $testableroot . '/' . $plugintype; }
/** * Profiling tool import utility. * * @package tool_profiling * @copyright 2013 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once __DIR__ . '/../../../config.php'; require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/xhprof/xhprof_moodle.php'; require_once __DIR__ . '/import_form.php'; admin_externalpage_setup('toolprofiling'); $PAGE->navbar->add(get_string('import', 'tool_profiling')); // Calculate export variables. $tempdir = 'profiling'; make_temp_directory($tempdir); // URL where we'll end, both on success and failure. $url = new moodle_url('/admin/tool/profiling/index.php'); // Instantiate the upload profiling runs form. $mform = new profiling_import_form(); // If there is any file to import. if ($data = $mform->get_data()) { $filename = $mform->get_new_filename('mprfile'); $file = $CFG->tempdir . '/' . $tempdir . '/' . $filename; $status = $mform->save_file('mprfile', $file); if ($status) { // File saved properly, let's import it. $status = profiling_import_runs($file, $data->importprefix); } // Delete the temp file, not needed anymore. if (file_exists($file)) {
} //========== // PAGE HEADER //========== $PAGE->set_title($txt->importquestions); $PAGE->set_heading($COURSE->fullname); echo $OUTPUT->header(); // file upload form sumitted if ($form = $import_form->get_data()) { // file checks out ok $fileisgood = false; // work out if this is an uploaded file // or one from the filesarea. $realfilename = $import_form->get_new_filename('newfile'); $importfile = "{$CFG->tempdir}/questionimport/{$realfilename}"; make_temp_directory('questionimport'); if (!($result = $import_form->save_file('newfile', $importfile, true))) { throw new moodle_exception('uploadproblem'); } $formatfile = 'format/' . $form->format . '/format.php'; if (!is_readable($formatfile)) { throw new moodle_exception('formatnotfound', 'question', '', $form->format); } require_once $formatfile; $classname = 'qformat_' . $form->format; $qformat = new $classname(); // load data into class $qformat->setCategory($category); $qformat->setContexts($contexts->having_one_edit_tab_cap('import')); $qformat->setCourse($COURSE); $qformat->setFilename($importfile);
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Basic configuration overwrite for Google API. * * @package core * @copyright Frédéric Massart <*****@*****.**> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; global $CFG, $SITE; require_once $CFG->libdir . '/weblib.php'; require_once $CFG->dirroot . '/repository/m27tube/google/curlio.php'; make_temp_directory('googleapi'); $GoogleConfigTempDir = $CFG->tempdir . '/googleapi'; global $apiConfig; $apiConfig = array('application_name' => 'Moodle ' . $CFG->release, 'site_name' => $SITE->fullname, 'ioClass' => 'moodle_google_curlio', 'ioFileCache_directory' => $GoogleConfigTempDir, 'oauth2_access_type' => 'online', 'oauth2_approval_prompt' => 'auto');
/** * Perform a file format conversion on the specified document. * * @param stored_file $file the file we want to preview * @param string $format The desired format - e.g. 'pdf'. Formats are specified by file extension. * @return stored_file|bool false if unable to create the conversion, stored file otherwise */ protected function create_converted_document(stored_file $file, $format) { global $CFG; if (empty($CFG->pathtounoconv) || !file_is_executable(trim($CFG->pathtounoconv))) { // No conversions are possible, sorry. return false; } $fileextension = core_text::strtolower(pathinfo($file->get_filename(), PATHINFO_EXTENSION)); if (!self::is_format_supported_by_unoconv($fileextension)) { return false; } if (!self::is_format_supported_by_unoconv($format)) { return false; } // Copy the file to the tmp dir. $uniqdir = "core_file/conversions/" . uniqid($file->get_id() . "-", true); $tmp = make_temp_directory($uniqdir); $localfilename = $file->get_filename(); // Safety. $localfilename = clean_param($localfilename, PARAM_FILE); $filename = $tmp . '/' . $localfilename; try { // This function can either return false, or throw an exception so we need to handle both. if ($file->copy_content_to($filename) === false) { throw new file_exception('storedfileproblem', 'Could not copy file contents to temp file.'); } } catch (file_exception $fe) { remove_dir($uniqdir); throw $fe; } $newtmpfile = pathinfo($filename, PATHINFO_FILENAME) . '.' . $format; // Safety. $newtmpfile = $tmp . '/' . clean_param($newtmpfile, PARAM_FILE); $cmd = escapeshellcmd(trim($CFG->pathtounoconv)) . ' ' . escapeshellarg('-f') . ' ' . escapeshellarg($format) . ' ' . escapeshellarg('-o') . ' ' . escapeshellarg($newtmpfile) . ' ' . escapeshellarg($filename); $output = null; $currentdir = getcwd(); chdir($tmp); $result = exec($cmd, $output); chdir($currentdir); if (!file_exists($newtmpfile)) { remove_dir($uniqdir); // Cleanup. return false; } $context = context_system::instance(); $record = array('contextid' => $context->id, 'component' => 'core', 'filearea' => 'documentconversion', 'itemid' => 0, 'filepath' => '/' . $format . '/', 'filename' => $file->get_contenthash()); $convertedfile = $this->create_file_from_pathname($record, $newtmpfile); // Cleanup. remove_dir($uniqdir); return $convertedfile; }
admin_externalpage_setup('outcomes'); $context = context_system::instance(); } require_capability('moodle/grade:manageoutcomes', $context); $navigation = grade_build_nav(__FILE__, get_string('outcomes', 'grades'), $courseid); $upload_form = new import_outcomes_form(); // display import form if (!$upload_form->get_data()) { print_grade_page_head($courseid, 'outcome', 'import', get_string('importoutcomes', 'grades')); $upload_form->display(); echo $OUTPUT->footer(); die; } print_grade_page_head($courseid, 'outcome', 'import', get_string('importoutcomes', 'grades')); $imported_file = $CFG->tempdir . '/outcomeimport/importedfile_' . time() . '.csv'; make_temp_directory('outcomeimport'); // copying imported file if (!$upload_form->save_file('userfile', $imported_file, true)) { redirect('import.php' . ($courseid ? "?courseid={$courseid}" : ''), get_string('importfilemissing', 'grades')); } /// which scope are we importing the outcomes in? if (isset($courseid) && $scope == 'custom') { // custom scale $local_scope = true; } elseif ($scope == 'global' && has_capability('moodle/grade:manage', context_system::instance())) { // global scale $local_scope = false; } else { // shouldn't happen .. user might be trying to access this script without the right permissions. redirect('index.php', get_string('importerror', 'grades')); }
/** * Open or create archive (depending on $mode). * * @todo MDL-31048 return error message * @param string $archivepathname * @param int $mode OPEN, CREATE or OVERWRITE constant * @param string $encoding archive local paths encoding, empty means autodetect * @return bool success */ public function open($archivepathname, $mode = file_archive::CREATE, $encoding = null) { $this->close(); $this->usedmem = 0; $this->pos = 0; $this->encoding = $encoding; $this->mode = $mode; $this->za = new ZipArchive(); switch ($mode) { case file_archive::OPEN: $flags = 0; break; case file_archive::OVERWRITE: $flags = ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE; break; //changed in PHP 5.2.8 //changed in PHP 5.2.8 case file_archive::CREATE: default: $flags = ZIPARCHIVE::CREATE; break; } $result = $this->za->open($archivepathname, $flags); if ($flags == 0 and $result === ZIPARCHIVE::ER_NOZIP and filesize($archivepathname) === 22) { // Legacy PHP versions < 5.3.10 can not deal with empty zip archives. if (file_get_contents($archivepathname) === base64_decode(self::$emptyzipcontent)) { if ($temp = make_temp_directory('zip')) { $this->emptyziphack = tempnam($temp, 'zip'); $this->za = new ZipArchive(); $result = $this->za->open($this->emptyziphack, ZIPARCHIVE::CREATE); } } } if ($result === true) { if (file_exists($archivepathname)) { $this->archivepathname = realpath($archivepathname); } else { $this->archivepathname = $archivepathname; } return true; } else { $message = 'Unknown error.'; switch ($result) { case ZIPARCHIVE::ER_EXISTS: $message = 'File already exists.'; break; case ZIPARCHIVE::ER_INCONS: $message = 'Zip archive inconsistent.'; break; case ZIPARCHIVE::ER_INVAL: $message = 'Invalid argument.'; break; case ZIPARCHIVE::ER_MEMORY: $message = 'Malloc failure.'; break; case ZIPARCHIVE::ER_NOENT: $message = 'No such file.'; break; case ZIPARCHIVE::ER_NOZIP: $message = 'Not a zip archive.'; break; case ZIPARCHIVE::ER_OPEN: $message = 'Can\'t open file.'; break; case ZIPARCHIVE::ER_READ: $message = 'Read error.'; break; case ZIPARCHIVE::ER_SEEK: $message = 'Seek error.'; break; } debugging($message . ': ' . $archivepathname, DEBUG_DEVELOPER); $this->za = null; $this->archivepathname = null; return false; } }