/** * Copy one file from moodle storage to backup storage */ public static function copy_file_moodle2backup($backupid, $filerecorid) { global $DB; // Normalise param if (!is_object($filerecorid)) { $filerecorid = $DB->get_record('files', array('id' => $filerecorid)); } // Directory, nothing to do if ($filerecorid->filename === '.') { return; } $fs = get_file_storage(); $file = $fs->get_file_instance($filerecorid); // If the file is external file, skip copying. if ($file->is_external_file()) { return; } // Calculate source and target paths (use same subdirs strategy for both) $targetfilepath = self::get_backup_storage_base_dir($backupid) . '/' . self::get_backup_content_file_location($filerecorid->contenthash); // Create target dir if necessary if (!file_exists(dirname($targetfilepath))) { if (!check_dir_exists(dirname($targetfilepath), true, true)) { throw new backup_helper_exception('cannot_create_directory', dirname($targetfilepath)); } } // And copy the file (if doesn't exist already) if (!file_exists($targetfilepath)) { $file->copy_content_to($targetfilepath); } }
protected function define_execution() { global $CFG; $basepath = $this->task->get_taskbasepath(); if (!check_dir_exists($basepath, true, true)) { throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath); } }
function xmldb_editor_tinymce_upgrade($oldversion) { global $CFG, $DB; if ($oldversion < 2014062900) { // We only want to delete DragMath from the customtoolbar setting if the directory no longer exists. If // the directory is present then it means it has been restored, so do not remove any settings. if (!check_dir_exists($CFG->libdir . '/editor/tinymce/plugins/dragmath', false)) { // Remove the DragMath plugin from the 'customtoolbar' setting (if it exists) as it has been removed. $currentorder = get_config('editor_tinymce', 'customtoolbar'); $newtoolbarrows = array(); $currenttoolbarrows = explode("\n", $currentorder); foreach ($currenttoolbarrows as $currenttoolbarrow) { $currenttoolbarrow = implode(',', array_diff(str_getcsv($currenttoolbarrow), array('dragmath'))); $newtoolbarrows[] = $currenttoolbarrow; } $neworder = implode("\n", $newtoolbarrows); unset_config('customtoolbar', 'editor_tinymce'); set_config('customtoolbar', $neworder, 'editor_tinymce'); } upgrade_plugin_savepoint(true, 2014062900, 'editor', 'tinymce'); } // Moodle v2.8.0 release upgrade line. // Put any upgrade step following this. // Moodle v2.9.0 release upgrade line. // Put any upgrade step following this. // Moodle v3.0.0 release upgrade line. // Put any upgrade step following this. // Moodle v3.1.0 release upgrade line. // Put any upgrade step following this. return true; }
public function setUp() { global $CFG; $this->tempdir = convert_helper::generate_id('simpletest'); check_dir_exists("$CFG->dataroot/temp/backup/$this->tempdir/course_files/sub1"); check_dir_exists("$CFG->dataroot/temp/backup/$this->tempdir/moddata/unittest/4/7"); copy( "$CFG->dirroot/backup/converter/moodle1/simpletest/files/moodle.xml", "$CFG->dataroot/temp/backup/$this->tempdir/moodle.xml" ); copy( "$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif", "$CFG->dataroot/temp/backup/$this->tempdir/course_files/file1.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif", "$CFG->dataroot/temp/backup/$this->tempdir/course_files/sub1/file2.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif", "$CFG->dataroot/temp/backup/$this->tempdir/moddata/unittest/4/file1.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif", "$CFG->dataroot/temp/backup/$this->tempdir/moddata/unittest/4/icon.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/simpletest/files/icon.gif", "$CFG->dataroot/temp/backup/$this->tempdir/moddata/unittest/4/7/icon.gif" ); }
public function __construct() { global $THEME; // make sure cache/compile paths exist check_dir_exists(get_config('dataroot') . 'dwoo/compile/' . $THEME->basename); check_dir_exists(get_config('dataroot') . 'dwoo/cache/' . $THEME->basename); // set paths $this->template_dir = $THEME->templatedirs; $compileDir = get_config('dataroot') . 'dwoo/compile/' . $THEME->basename; $cacheDir = get_config('dataroot') . 'dwoo/cache/' . $THEME->basename; parent::__construct($compileDir, $cacheDir); // add plugins dir to the loader $this->getLoader()->addDirectory(get_config('libroot') . 'dwoo/mahara/plugins/'); // adds mahara resources and compiler factory $this->setDefaultCompilerFactory('file', array($this, 'compilerFactory')); $this->addResource('artefact', 'Dwoo_Template_Mahara_Artefact', array($this, 'compilerFactory')); $this->addResource('blocktype', 'Dwoo_Template_Mahara_Blocktype', array($this, 'compilerFactory')); $this->addResource('export', 'Dwoo_Template_Mahara_Export', array($this, 'compilerFactory')); $this->addResource('interaction', 'Dwoo_Template_Mahara_Interaction', array($this, 'compilerFactory')); // set base data $theme_list = array(); $themepaths = themepaths(); foreach ($themepaths['mahara'] as $themepath) { $theme_list[$themepath] = $THEME->get_url($themepath); } $this->_data = array('THEME' => $THEME, 'WWWROOT' => get_config('wwwroot'), 'THEMELIST' => json_encode($theme_list), 'HTTPSWWWROOT' => get_config('httpswwwroot')); }
/** * Given one backupid, create all the needed dirs to have one backup temp dir available */ public static function check_and_create_backup_dir($backupid) { global $CFG; if (!check_dir_exists($CFG->tempdir . '/backup/' . $backupid, true, true)) { throw new backup_helper_exception('cannot_create_backup_temp_dir'); } }
/** * Constructor - creates an instance of the SimplePie class * with Moodle defaults. * * @param string $feedurl optional URL of the feed */ function __construct($feedurl = null) { // Use the Moodle class for http requests $this->file_class = 'moodle_simplepie_file'; $cachedir = moodle_simplepie::get_cache_directory(); check_dir_exists($cachedir); parent::__construct(); // Match moodle encoding $this->set_output_encoding('UTF-8'); // default to a short timeout as most operations will be interactive $this->set_timeout(2); // 1 hour default cache $this->set_cache_location($cachedir); $this->set_cache_duration(3600); // init the feed url if passed in constructor if ($feedurl !== null) { $this->set_feed_url($feedurl); $this->init(); } }
protected function setUp() { global $CFG; $this->tempdir = convert_helper::generate_id('unittest'); check_dir_exists("$CFG->tempdir/backup/$this->tempdir/course_files/sub1"); check_dir_exists("$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7"); copy( "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/moodle.xml", "$CFG->tempdir/backup/$this->tempdir/moodle.xml" ); copy( "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif", "$CFG->tempdir/backup/$this->tempdir/course_files/file1.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif", "$CFG->tempdir/backup/$this->tempdir/course_files/sub1/file2.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif", "$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/file1.gif" ); copy( "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif", "$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/icon.gif" ); $this->iconhash = sha1_file($CFG->tempdir.'/backup/'.$this->tempdir.'/moddata/unittest/4/icon.gif'); copy( "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif", "$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7/icon.gif" ); }
/** * constructor. overrides the parent class * to set up smarty and the attachment directory */ public function __construct(User $user, $views, $artefacts, $progresscallback = null) { global $THEME; parent::__construct($user, $views, $artefacts, $progresscallback); $this->rootdir = 'portfolio-for-' . self::text_to_path($user->get('username')); $directory = "{$this->exportdir}/{$this->rootdir}/"; if (!check_dir_exists($directory)) { throw new SystemException("Couldn't create the temporary export directory {$directory}"); } $this->pdffile = 'mahara-export-pdf-user' . $this->get('user')->get('id') . '-' . $this->exporttime . '.pdf'; // Find what base stylesheets need to be included $themedirs = $THEME->get_path('', true); $stylesheets = array('print.css', 'views.css'); foreach ($themedirs as $theme => $themedir) { foreach ($stylesheets as $stylesheet) { if (is_readable($themedir . 'style/' . $stylesheet)) { array_unshift($this->stylesheets[''], $themedir . '/style/' . $stylesheet); } } } // Don't export the dashboard // foreach (array_keys($this->views) as $i) { // if ($this->views[$i]->get('type') == 'dashboard') { // unset($this->views[$i]); // } // } $this->exportingoneview = $this->viewexportmode == PluginExport::EXPORT_LIST_OF_VIEWS && $this->artefactexportmode == PluginExport::EXPORT_ARTEFACTS_FOR_VIEWS && count($this->views) == 1; $this->notify_progress_callback(15, get_string('setupcomplete', 'export')); }
/** * Define a local decimal separator. * * It is not possible to directly change the result of get_string in * a unit test. Instead, we create a language pack for language 'xx' in * dataroot and make langconfig.php with the string we need to change. * The example separator used here is 'X'; on PHP 5.3 and before this * must be a single byte character due to PHP bug/limitation in * number_format, so you can't use UTF-8 characters. */ protected function define_local_decimal_separator() { global $SESSION, $CFG; $SESSION->lang = 'xx'; $langconfig = "<?php\n\$string['decsep'] = 'X';"; $langfolder = $CFG->dataroot . '/lang/xx'; check_dir_exists($langfolder); file_put_contents($langfolder . '/langconfig.php', $langconfig); }
function xmldb_enrol_imsenterprise_upgrade($oldversion) { global $CFG, $DB, $OUTPUT; $dbman = $DB->get_manager(); //NOTE: this file is not executed during upgrade from 1.9.x! if ($oldversion < 2011013000) { // this plugin does not use the new file api - lets undo the migration $fs = get_file_storage(); if ($DB->record_exists('course', array('id' => 1))) { //course 1 is hardcoded here intentionally! if ($context = get_context_instance(CONTEXT_COURSE, 1)) { if ($file = $fs->get_file($context->id, 'course', 'legacy', 0, '/', 'imsenterprise-enrol.xml')) { if (!file_exists("{$CFG->dataroot}/1/imsenterprise-enrol.xml")) { check_dir_exists($CFG->dataroot . '/'); $file->copy_content_to("{$CFG->dataroot}/1/imsenterprise-enrol.xml"); } $file->delete(); } } } if (!empty($CFG->enrol_imsfilelocation)) { if (strpos($CFG->enrol_imsfilelocation, "{$CFG->dataroot}/") === 0) { $location = str_replace("{$CFG->dataroot}/", '', $CFG->enrol_imsfilelocation); $location = str_replace('\\', '/', $location); $parts = explode('/', $location); $courseid = array_shift($parts); if (is_number($courseid) and $DB->record_exists('course', array('id' => $courseid))) { if ($context = get_context_instance(CONTEXT_COURSE, $courseid)) { $file = array_pop($parts); if ($parts) { $dir = '/' . implode('/', $parts) . '/'; } else { $dir = '/'; } if ($file = $fs->get_file($context->id, 'course', 'legacy', 0, $dir, $file)) { if (!file_exists($CFG->enrol_imsfilelocation)) { check_dir_exists($CFG->dataroot . '/' . $courseid . $dir); $file->copy_content_to($CFG->enrol_imsfilelocation); } $file->delete(); } } } } } upgrade_plugin_savepoint(true, 2011013000, 'enrol', 'imsenterprise'); } // Moodle v2.1.0 release upgrade line // Put any upgrade step following this // Moodle v2.2.0 release upgrade line // Put any upgrade step following this return true; }
function referentiel_check_and_create_document_files_dir($referentiel_referentiel_id, $user_creator, $userid) { global $CFG; // Moodle 2.0 // $status = check_dir_exists($CFG->dataroot."/temp/archive/".$referentiel_referentiel_id."/".$user_creator."/document_files/".$userid,true, true); // Moodle 22 $path_temp = cleardoubleslashes(get_string('archivetemp', 'referentiel') . '/' . $referentiel_referentiel_id . '/' . $user_creator); // Moodle 2.2 $temp_dir = make_temp_directory($path_temp); $status = check_dir_exists($temp_dir . "/document_files/" . $userid, true, true); return $status; }
function check_and_create_backup_dir($backup_unique_code) { global $CFG; $status = check_dir_exists($CFG->dataroot . "/temp", true); if ($status) { $status = check_dir_exists($CFG->dataroot . "/temp/backup", true); } if ($status) { $status = check_dir_exists($CFG->dataroot . "/temp/backup/" . $backup_unique_code, true); } return $status; }
public static function get_logger_chain($interactive, $execution, $backupid) { global $CFG; $dfltloglevel = backup::LOG_WARNING; // Default logging level if (debugging('', DEBUG_DEVELOPER)) { // Debug developer raises default logging level $dfltloglevel = backup::LOG_DEBUG; } $enabledloggers = array(); // Array to store all enabled loggers // Create error_log_logger, observing $CFG->backup_error_log_logger_level, // defaulting to $dfltloglevel $elllevel = isset($CFG->backup_error_log_logger_level) ? $CFG->backup_error_log_logger_level : $dfltloglevel; $enabledloggers[] = new error_log_logger($elllevel); // Create output_indented_logger, observing $CFG->backup_output_indented_logger_level and $CFG->debugdisplay, // defaulting to LOG_ERROR. Only if interactive and inmediate if ($CFG->debugdisplay && $interactive == backup::INTERACTIVE_YES && $execution == backup::EXECUTION_INMEDIATE) { $oillevel = isset($CFG->backup_output_indented_logger_level) ? $CFG->backup_output_indented_logger_level : backup::LOG_ERROR; $enabledloggers[] = new output_indented_logger($oillevel, false, false); } // Create file_logger, observing $CFG->backup_file_logger_level // defaulting to $dfltloglevel check_dir_exists($CFG->tempdir . '/backup', true, true); // need to ensure that temp/backup already exists $fllevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : $dfltloglevel; $enabledloggers[] = new file_logger($fllevel, true, true, $CFG->tempdir . '/backup/' . $backupid . '.log'); // Create database_logger, observing $CFG->backup_database_logger_level and defaulting to LOG_WARNING // and pointing to the backup_logs table $dllevel = isset($CFG->backup_database_logger_level) ? $CFG->backup_database_logger_level : backup::LOG_WARNING; $columns = array('backupid' => $backupid); $enabledloggers[] = new database_logger($dllevel, 'timecreated', 'loglevel', 'message', 'backup_logs', $columns); // Create extra file_logger, observing $CFG->backup_file_logger_extra and $CFG->backup_file_logger_extra_level // defaulting to $fllevel (normal file logger) if (isset($CFG->backup_file_logger_extra)) { $flelevel = isset($CFG->backup_file_logger_extra_level) ? $CFG->backup_file_logger_extra_level : $fllevel; $enabledloggers[] = new file_logger($flelevel, true, true, $CFG->backup_file_logger_extra); } // Build the chain $loggers = null; foreach ($enabledloggers as $currentlogger) { if ($loggers == null) { $loggers = $currentlogger; } else { $lastlogger->set_next($currentlogger); } $lastlogger = $currentlogger; } return $loggers; }
function import_submit(Pieform $form, $values) { global $SESSION; $date = time(); $nicedate = date('Y/m/d h:i:s', $date); $uploaddir = get_config('dataroot') . 'import/test-' . $date . '/'; $filename = $uploaddir . $values['file']['name']; check_dir_exists($uploaddir); move_uploaded_file($values['file']['tmp_name'], $filename); if ($values['file']['type'] == 'application/zip') { // Unzip here $command = sprintf('%s %s %s %s', escapeshellcmd(get_config('pathtounzip')), escapeshellarg($filename), get_config('unzipdirarg'), escapeshellarg($uploaddir)); $output = array(); exec($command, $output, $returnvar); if ($returnvar != 0) { $SESSION->add_error_msg('Unable to unzip the file'); redirect('/import/'); } $filename = $uploaddir . 'leap2a.xml'; if (!is_file($filename)) { $SESSION->add_error_msg('No leap2a.xml file detected - please check your export file again'); redirect('/import/'); } } // Create dummy user $user = (object) array('username' => 'import_' . $date, 'password' => 'import1', 'firstname' => 'Imported', 'lastname' => 'User (' . $nicedate . ')', 'email' => '*****@*****.**'); $userid = create_user($user); // And we're good to go echo '<pre>'; $filename = substr($filename, strlen(get_config('dataroot'))); require_once dirname(dirname(__FILE__)) . '/import/lib.php'; safe_require('import', 'leap'); db_begin(); $importer = PluginImport::create_importer(null, (object) array('token' => '', 'usr' => $userid, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'data' => array('filename' => $filename), 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_STDOUT, 'profile' => true)); $importer->process(); // Now done, delete the temporary e-mail address if there's a new one // A bit sucky, presumes only one email in the import $email = artefact_instance_from_id(get_field('artefact', 'id', 'title', '*****@*****.**', 'artefacttype', 'email', 'owner', $userid)); $email->delete(); execute_sql('UPDATE {artefact_internal_profile_email} SET principal = 1 WHERE "owner" = ?', array($userid)); db_commit(); echo "\n\n"; echo 'Done. You can <a href="' . get_config('wwwroot') . '/admin/users/changeuser.php?id=' . $userid . '">change to this user</a> to inspect the result, '; echo 'or <a href="' . get_config('wwwroot') . 'import/">try importing again</a>'; echo '</pre>'; exit; }
function display_sub_dirs($current_dir, $sub_dirs) { $results = explore($current_dir, $sub_dirs, 1); foreach ($results as $r) { echo '<tr id = "row" data-file="' . $r[0] . '" data-type="dir"> <td id = "thumbnail_container" width = "14%"><div id = "thumbs">'; $is_dir = check_dir_exists($current_dir, $r[0]); $margin = 10; $img_id = 1; foreach ($r[1] as $thumbs) { $thumb_exists = false; $thumb_exists = check_thumb_exists($current_dir . $r[0] . '/' . $thumbs); $img_path = \OCP\Util::linkTo('reader', 'ajax/thumbnail.php') . '&filepath=' . urlencode($current_dir . $r[0] . '/' . rtrim($thumbs, 'pdf') . 'png'); $counter = 3; for ($i = 1; $i <= $counter; $i++) { echo '<img id = "' . $current_dir . $r[0] . '/' . $thumbs . '" src = "' . $img_path . '" value = "' . $thumb_exists . '" style = "position:absolute;top:-55px;left:10px;margin-left:' . $margin . 'px; z-index:' . (50 - $margin) . ';"/>'; $margin = $margin + 5; $img_id = $img_id + 1; } } echo '</div></td>'; echo '<td class = "filename svg" width = "86%"> <a class = "dirs" id = "' . $r[0] . '" href = "' . OCP\Util::linkTo('reader', 'index.php') . '&dir=' . $current_dir . $r[0] . '/' . '"> <span class = "nametext">' . htmlspecialchars($r[0]) . '</span> </a> <div id = "more_info" style = "color:#666;margin-left:15px;margin-top:35px; vertical-align:bottom">'; echo "Browse in for"; echo '<br>'; $dir_browse_results = explore($current_dir, array($r[0]), 5); foreach ($dir_browse_results as $browse_result) { foreach ($browse_result[1] as $each) { $each_sub_dir = explode("/", $each); if (count($each_sub_dir) > 1) { foreach ($each_sub_dir as $element) { echo '<span style = "color:#DDD;">>></span>' . $element; } } else { echo '<span style = "color:#DDD;"> >></span>' . $each; } echo '<br>'; } } echo '</div> </td> </tr>'; } }
/** * Make the directory for the file and open the file pointer * * @param string $name The preferred file name (no extension) * @param string $dir The directory to store the file in (temp by default) * @return void */ public function init($name, $dir = NULL) { global $CFG; require_once $CFG->libdir . '/filelib.php'; if (is_null($dir)) { $dir = $CFG->dataroot . '/temp'; } check_dir_exists($dir, true, true); // Generate file path $name = clean_filename($name); $name = trim($name, '_'); $this->file = "{$dir}/{$name}." . $this->get_extension(); // Make sure it doesn't exist $this->cleanup(); // Open for writing $this->fp = fopen($this->file, 'w'); }
function backup_lightboxgallery_files_instance($bf, $preferences, $gallery) { global $CFG; $status = true; if (is_numeric($gallery)) { $gallery = get_record('lightboxgallery', 'id', $gallery); } $tmppath = $CFG->dataroot . '/temp/backup/' . $preferences->backup_unique_code . '/' . $gallery->folder; $status = check_dir_exists($tmppath, true, true); if ($status) { $oldpath = $CFG->dataroot . '/' . $preferences->backup_course . '/' . $gallery->folder; if (is_dir($oldpath)) { $status = backup_copy_file($oldpath, $tmppath); } } return $status; }
function lightboxgallery_restore_files($gallery, $restore) { global $CFG; $status = true; if (is_numeric($gallery)) { $gallery = get_record('lightboxgallery', 'id', $gallery); } $newpath = $CFG->dataroot . '/' . $gallery->course . '/' . $gallery->folder; $status = check_dir_exists($newpath, true, true); if ($status) { $tmppath = $CFG->dataroot . '/temp/backup/' . $restore->backup_unique_code . '/' . $gallery->folder; if (is_dir($tmppath)) { $status = backup_copy_file($tmppath, $newpath); } } return $status; }
function backup_poodllpairwork_files_instance($bf, $preferences, $instanceid) { global $CFG; $status = true; //First we check to moddata exists and create it as necessary //in temp/backup/$backup_code dir $status = check_and_create_moddata_dir($preferences->backup_unique_code); $status = check_dir_exists($CFG->dataroot . "/temp/backup/" . $preferences->backup_unique_code . "/moddata/poodllpairwork/", true); //Now copy the poodllpairwork dir if ($status) { //Only if it exists !! Thanks to Daniel Miksik. if (is_dir($CFG->dataroot . "/" . $preferences->backup_course . "/" . $CFG->moddata . "/poodllpairwork/" . $instanceid)) { $status = backup_copy_file($CFG->dataroot . "/" . $preferences->backup_course . "/" . $CFG->moddata . "/poodllpairwork/" . $instanceid, $CFG->dataroot . "/temp/backup/" . $preferences->backup_unique_code . "/moddata/poodllpairwork/" . $instanceid); } } return $status; }
function xmldb_enrol_imsenterprise_install() { global $CFG, $DB; // NOTE: this file is executed during upgrade from 1.9.x! // this plugin does not use the new file api - lets undo the migration $fs = get_file_storage(); if ($DB->record_exists('course', array('id' => 1))) { //course 1 is hardcoded here intentionally! if ($context = get_context_instance(CONTEXT_COURSE, 1)) { if ($file = $fs->get_file($context->id, 'course', 'legacy', 0, '/', 'imsenterprise-enrol.xml')) { if (!file_exists("{$CFG->dataroot}/1/imsenterprise-enrol.xml")) { check_dir_exists($CFG->dataroot . '/'); $file->copy_content_to("{$CFG->dataroot}/1/imsenterprise-enrol.xml"); } $file->delete(); } } } if (!empty($CFG->enrol_imsfilelocation)) { if (strpos($CFG->enrol_imsfilelocation, "{$CFG->dataroot}/") === 0) { $location = str_replace("{$CFG->dataroot}/", '', $CFG->enrol_imsfilelocation); $location = str_replace('\\', '/', $location); $parts = explode('/', $location); $courseid = array_shift($parts); if (is_number($courseid) and $DB->record_exists('course', array('id' => $courseid))) { if ($context = get_context_instance(CONTEXT_COURSE, $courseid)) { $file = array_pop($parts); if ($parts) { $dir = '/' . implode('/', $parts) . '/'; } else { $dir = '/'; } if ($file = $fs->get_file($context->id, 'course', 'legacy', 0, $dir, $file)) { if (!file_exists($CFG->enrol_imsfilelocation)) { check_dir_exists($CFG->dataroot . '/' . $courseid . $dir); $file->copy_content_to($CFG->enrol_imsfilelocation); } $file->delete(); } } } } } // TODO: migrate old config settings }
/** * Create a zip archive containing the exported data. * * @param array $listing The list of usernames that were exported * @param array $files A list of archive files for each user */ function create_zipfile($listing, $files) { global $USER; if (empty($listing) or empty($files)) { return false; } if (count($listing) != count($files)) { throw new MaharaException("Files and listing don't match."); } // create temporary directories for the export $exportdir = get_config('dataroot') . 'export/' . $USER->get('id') . '/' . time() . '/'; if (!check_dir_exists($exportdir)) { throw new SystemException("Couldn't create the temporary export directory {$exportdir}"); } $usersdir = 'users/'; if (!check_dir_exists($exportdir . $usersdir)) { throw new SystemException("Couldn't create the temporary export directory {$usersdir}"); } // move user zipfiles into the export directory foreach ($files as $filename) { if (copy($filename, $exportdir . $usersdir . basename($filename))) { unlink($filename); } else { throw new SystemException("Couldn't move {$filename} to {$usersdir}"); } } // write username listing to a file $listingfile = 'usernames.csv'; if (!file_put_contents($exportdir . $listingfile, data_to_csv($listing))) { throw new SystemException("Couldn't write usernames to a file"); } // zip everything up $zipfile = $exportdir . 'mahara-bulk-export-' . time() . '.zip'; $cwd = getcwd(); $command = sprintf('%s %s %s %s %s', get_config('pathtozip'), get_config('ziprecursearg'), escapeshellarg($zipfile), escapeshellarg($listingfile), escapeshellarg($usersdir)); $output = array(); chdir($exportdir); exec($command, $output, $returnvar); chdir($cwd); if ($returnvar != 0) { throw new SystemException('Failed to zip the export file: return code ' . $returnvar); } return $zipfile; }
public function test_geoip() { global $CFG; require_once "{$CFG->libdir}/filelib.php"; require_once "{$CFG->dirroot}/iplookup/lib.php"; if (!PHPUNIT_LONGTEST) { // this may take a long time return; } $this->resetAfterTest(); // let's store the file somewhere $gzfile = "{$CFG->dataroot}/phpunit/geoip/GeoLiteCity.dat.gz"; check_dir_exists(dirname($gzfile)); if (file_exists($gzfile) and filemtime($gzfile) < time() - 60 * 60 * 24 * 30) { // delete file if older than 1 month unlink($gzfile); } if (!file_exists($gzfile)) { download_file_content('http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz', null, null, false, 300, 20, false, $gzfile); } $this->assertTrue(file_exists($gzfile)); $zd = gzopen($gzfile, "r"); $contents = gzread($zd, 50000000); gzclose($zd); $geoipfile = "{$CFG->dataroot}/geoip/GeoLiteCity.dat"; check_dir_exists(dirname($geoipfile)); $fp = fopen($geoipfile, 'w'); fwrite($fp, $contents); fclose($fp); $this->assertTrue(file_exists($geoipfile)); $CFG->geoipfile = $geoipfile; $result = iplookup_find_location('147.230.16.1'); $this->assertEquals('array', gettype($result)); $this->assertEquals('Liberec', $result['city']); $this->assertEquals(15.0653, $result['longitude'], '', 0.001); $this->assertEquals(50.7639, $result['latitude'], '', 0.001); $this->assertNull($result['error']); $this->assertEquals('array', gettype($result['title'])); $this->assertEquals('Liberec', $result['title'][0]); $this->assertEquals('Czech Republic', $result['title'][1]); }
public function extract_file() { $filesinfo = $this->get('importertransport')->files_info(); // this contains relativepath and zipfile name $this->relativepath = $filesinfo['relativepath']; $this->zipfile = $filesinfo['zipfile']; $this->tempdir = $filesinfo['tempdir']; if (sha1_file($this->tempdir . $this->zipfile) != $this->zipfilesha1) { throw new ImportException('sha1 of recieved zipfile didn\'t match expected sha1'); } $this->unzipdir = $this->tempdir . 'extract/'; if (!check_dir_exists($this->unzipdir)) { throw new ImportException('Failed to create the temporary directories to work in'); } $command = sprintf('%s %s %s %s', get_config('pathtounzip'), escapeshellarg($this->tempdir . $this->zipfile), get_config('unzipdirarg'), escapeshellarg($this->unzipdir)); $output = array(); exec($command, $output, $returnvar); if ($returnvar != 0) { throw new ImportException('Failed to unzip the file recieved from the transport object'); } }
function &smarty_core() { require_once 'smarty/libs/Smarty.class.php'; $smarty =& new Smarty(); $theme = theme_setup(); $themepaths = themepaths(); $smarty->template_dir = $theme->template_dir; check_dir_exists(get_config('dataroot') . 'smarty/compile/' . $theme->theme); check_dir_exists(get_config('dataroot') . 'smarty/cache/' . $theme->theme); $smarty->compile_dir = get_config('dataroot') . 'smarty/compile/' . $theme->theme; $smarty->cache_dir = get_config('dataroot') . 'smarty/cache/' . $theme->theme; $smarty->plugins_dir[] = get_config('libroot') . 'smarty/mahara/'; $smarty->assign('THEMEURL', get_config('themeurl')); $smarty->assign('WWWROOT', get_config('wwwroot')); $theme_list = array(); foreach ($themepaths['mahara'] as $themepath) { $theme_list[$themepath] = theme_get_url($themepath); } $smarty->assign('THEMELIST', json_encode($theme_list)); return $smarty; }
/** * Create a zip archive containing the exported data. * * @param array $listing The list of usernames that were exported * @param array $files A list of archive files for each user */ function create_zipfile($listing, $files) { global $USER; if (empty($listing) or empty($files)) { return false; } if (count($listing) != count($files)) { throw new MaharaException("Files and listing don't match."); } // create temporary directories for the export $exportdir = get_config('dataroot') . 'export/' . $USER->get('id') . '/' . time() . '/'; if (!check_dir_exists($exportdir)) { throw new SystemException("Couldn't create the temporary export directory {$exportdir}"); } $usersdir = 'users/'; if (!check_dir_exists($exportdir . $usersdir)) { throw new SystemException("Couldn't create the temporary export directory {$usersdir}"); } // move user zipfiles into the export directory foreach ($files as $filename) { if (copy($filename, $exportdir . $usersdir . basename($filename))) { unlink($filename); } else { throw new SystemException("Couldn't move {$filename} to {$usersdir}"); } } // write username listing to a file $listingfile = 'usernames.csv'; if (!file_put_contents($exportdir . $listingfile, data_to_csv($listing))) { throw new SystemException("Couldn't write usernames to a file"); } // zip everything up $filename = 'mahara-bulk-export-' . time() . '.zip'; try { create_zip_archive($exportdir, $filename, array($listingfile, $usersdir)); } catch (SystemException $e) { throw new SystemException('Failed to zip the export file: ' . $e->getMessage()); } return $exportdir . $filename; }
/** * constructor. overrides the parent class * to set up smarty and the attachment directory */ public function __construct(User $user, $views, $artefacts, $progresshandler = null) { parent::__construct($user, $views, $artefacts, $progresshandler); $this->smarty = smarty_core(); if (!check_dir_exists($this->exportdir . '/' . $this->filedir)) { throw new SystemException("Couldn't create the temporary export directory {$this->exportdir}"); } $this->zipfile = 'mahara-export-leap-user' . $this->get('user')->get('id') . '-' . $this->exporttime . '.zip'; // some plugins might want to do their own special thing foreach (plugins_installed('artefact', true) as $plugin) { $plugin = $plugin->name; if (safe_require('export', 'leap/' . $plugin, 'lib.php', 'require_once', true)) { $classname = 'LeapExport' . ucfirst($plugin); if (class_exists($classname) && call_static_method($classname, 'override_entire_export')) { $this->specialcases[$plugin] = array(); } } } $outputfilter = LeapExportOutputFilter::singleton(); $outputfilter->set_artefactids(array_keys($this->artefacts)); $this->notify_progress_callback(5, get_string('setupcomplete', 'export')); }
/** * Stores CSS in a file at the given path. * * This function either succeeds or throws an exception. * * @param theme_config $theme The theme that the CSS belongs to. * @param string $csspath The path to store the CSS at. * @param array $cssfiles The CSS files to store. */ function css_store_css(theme_config $theme, $csspath, array $cssfiles) { global $CFG; if (!empty($CFG->enablecssoptimiser)) { // This is an experimental feature introduced in Moodle 2.3 // The CSS optimiser organises the CSS in order to reduce the overall number // of rules and styles being sent to the client. It does this by collating // the CSS before it is cached removing excess styles and rules and stripping // out any extraneous content such as comments and empty rules. $optimiser = new css_optimiser(); $css = ''; foreach ($cssfiles as $file) { $css .= file_get_contents($file) . "\n"; } $css = $theme->post_process($css); $css = $optimiser->process($css); // If cssoptimisestats is set then stats from the optimisation are collected // and output at the beginning of the CSS if (!empty($CFG->cssoptimiserstats)) { $css = $optimiser->output_stats_css() . $css; } } else { // This is the default behaviour. // The cssoptimise setting was introduced in Moodle 2.3 and will hopefully // in the future be changed from an experimental setting to the default. // The css_minify_css will method will use the Minify library remove // comments, additional whitespace and other minor measures to reduce the // the overall CSS being sent. // However it has the distinct disadvantage of having to minify the CSS // before running the post process functions. Potentially things may break // here if theme designers try to push things with CSS post processing. $css = $theme->post_process(css_minify_css($cssfiles)); } check_dir_exists(dirname($csspath)); $fp = fopen($csspath, 'w'); fwrite($fp, $css); fclose($fp); }
/** * Constructor - creates an instance of the SimplePie class * with Moodle defaults. * * @param string $feedurl optional URL of the feed * @param int $timeout how many seconds requests should wait for server response */ public function __construct($feedurl = null, $timeout = 2) { $cachedir = moodle_simplepie::get_cache_directory(); check_dir_exists($cachedir); parent::__construct(); // Use the Moodle class for http requests $this->set_file_class('moodle_simplepie_file'); // Use html purifier for text cleaning. $this->set_sanitize_class('moodle_simplepie_sanitize'); $this->sanitize = new moodle_simplepie_sanitize(); // Match moodle encoding $this->set_output_encoding('UTF-8'); // default to a short timeout as most operations will be interactive $this->set_timeout($timeout); // 1 hour default cache $this->set_cache_location($cachedir); $this->set_cache_duration(3600); // init the feed url if passed in constructor if ($feedurl !== null) { $this->set_feed_url($feedurl); $this->init(); } }
public function dump_export_data() { foreach ($this->exporter->get('artefacts') as $artefact) { if ($artefact->get('artefacttype') == 'blog') { // Create directory for storing the blog $dirname = PluginExportHtml::text_to_path($artefact->get('title')); if (!check_dir_exists($this->fileroot . $dirname)) { throw new SystemException("Couldn't create blog directory {$this->fileroot}{$dirname}"); } // Render the first page of the blog (the only one if there's // not many posts) $smarty = $this->exporter->get_smarty('../../../', 'blog'); $smarty->assign('page_heading', $artefact->get('title')); $smarty->assign('breadcrumbs', array(array('text' => get_string('blogs', 'artefact.blog')), array('text' => $artefact->get('title'), 'path' => 'index.html'))); $rendered = $artefact->render_self(array('hidetitle' => true)); $outputfilter = new HtmlExportOutputFilter('../../../'); $smarty->assign('rendered_blog', $outputfilter->filter($rendered['html'])); $content = $smarty->fetch('export:html/blog:index.tpl'); if (false === file_put_contents($this->fileroot . $dirname . '/index.html', $content)) { throw new SystemException("Unable to create index.html for blog {$blogid}"); } // If the blog has many posts, we'll need to write out archive pages $postcount = $artefact->count_published_posts(); $perpage = ArtefactTypeBlog::pagination; if ($postcount > $perpage) { for ($i = 2; $i <= ceil($postcount / $perpage); $i++) { $rendered = $artefact->render_self(array('page' => $i)); $smarty->assign('rendered_blog', $outputfilter->filter($rendered['html'])); $content = $smarty->fetch('export:html/blog:index.tpl'); if (false === file_put_contents($this->fileroot . $dirname . "/{$i}.html", $content)) { throw new SystemException("Unable to create {$i}.html for blog {$artefact->get('id')}"); } } } } } }