Esempio n. 1
0
 private function get_category_tree($id)
 {
     global $DB;
     $category = $DB->get_record('course_categories', array('id' => $id));
     if ($id && !$category) {
         cli_error("Wrong category '{$id}'");
     } elseif (!$id) {
         $category = NULL;
     }
     $parentcategory = \coursecat::get($id);
     if ($parentcategory->has_children()) {
         $parentschildren = $parentcategory->get_children();
         foreach ($parentschildren as $singlecategory) {
             if ($singlecategory->has_children()) {
                 $childcategories = $this->get_category_tree($singlecategory->id);
                 $category->categories[] = $childcategories;
             } else {
                 // coursecat variables are protected, need to get data from db
                 $singlecategory = $DB->get_record('course_categories', array('id' => $singlecategory->id));
                 $category->categories[] = $singlecategory;
             }
         }
     }
     return $category;
 }
Esempio n. 2
0
 public function execute()
 {
     global $DB;
     $options = $this->expandedOptions;
     $from_date = strtotime($options['from']);
     if ($options['to']) {
         $to_date = strtotime($options['to']);
     } else {
         $to_date = time();
     }
     if ($from_date === false) {
         cli_error('invalid from date');
     }
     if ($to_date === false) {
         cli_error('invalid to date');
     }
     if ($to_date < $from_date) {
         cli_error('to date must be higher than from date');
     }
     $period = $period = $options['period'];
     $sql = "SELECT (FROM_UNIXTIME(period * ( {$period}*60 ))) AS time, \n\t\t\t\tonline_users FROM (SELECT ROUND( time / ( {$period}*60 ) ) AS period,\n\t\t\t\tCOUNT( DISTINCT userid ) AS online_users\n\t\t\t\tFROM {log}\n\t\t\t\tWHERE action <> 'error' AND module <> 'library'\n\t\t\t\tAND time >= {$from_date} AND time <= {$to_date}\n\t\t\t\tGROUP BY period\n\t\t\t\t) AS concurrent_users_report";
     $query = $DB->get_records_sql($sql);
     foreach ($query as $k => $v) {
         echo $k . " users online: " . $v->online_users . "\n";
     }
 }
Esempio n. 3
0
 public function execute()
 {
     $setting = trim($this->arguments[2]);
     $value = trim($this->arguments[3]);
     switch ($this->arguments[0]) {
         case 'course':
             if (!self::setCourseSetting($this->arguments[1], $setting, $value)) {
                 // the setting was not applied, exit with a non-zero exit code
                 cli_error('');
             }
             break;
         case 'category':
             //get all courses in category (recursive)
             $courselist = get_courses($this->arguments[1], '', 'c.id');
             $succeeded = 0;
             $failed = 0;
             foreach ($courselist as $course) {
                 if (self::setCourseSetting($course->id, $setting, $value)) {
                     $succeeded++;
                 } else {
                     $failed++;
                 }
             }
             if ($failed == 0) {
                 echo "OK - successfully modified {$succeeded} courses\n";
             } else {
                 echo "WARNING - failed to mofify {$failed} courses (successfully modified {$succeeded})\n";
             }
             break;
     }
 }
Esempio n. 4
0
 public function execute()
 {
     if (strpos($this->arguments[0], '_') !== false) {
         cli_error("Module name can not contain _");
     }
     //copy newmodule
     $modPath = $this->topDir . '/mod/' . $this->arguments[0];
     if (file_exists($modPath)) {
         cli_problem("Already exists: '{$modPath}'");
         cli_problem("Not creating new module " . $this->arguments[0]);
         exit(1);
     }
     run_external_command("cp -r '{$this->mooshDir}/vendor/moodlehq/moodle-mod_newmodule' '{$modPath}'", "Copying from module template failed");
     if (file_exists("{$modPath}/.git")) {
         run_external_command("rm --interactive=never -r '{$modPath}/.git'", "Removing .git failed");
     }
     //replace newmodule with $this->arguments[0]
     run_external_command("find '{$modPath}' -type f -exec sed 's/newmodule/{$this->arguments[0]}/g' -i {} \\;", "sed command failed");
     //rename lang/en/newmodule.php
     run_external_command("mv '{$modPath}/lang/en/newmodule.php' '{$modPath}/lang/en/{$this->arguments[0]}.php'", "Renaming lang file failed");
     //rename backup files
     run_external_command("mv '{$modPath}/backup/moodle2/backup_newmodule_activity_task.class.php' '{$modPath}/backup/moodle2/backup_{$this->arguments[0]}_activity_task.class.php'", "Renaming backup activity task file failed");
     run_external_command("mv '{$modPath}/backup/moodle2/backup_newmodule_stepslib.php' '{$modPath}/backup/moodle2/backup_{$this->arguments[0]}_stepslib.php'", "Renaming backup stepslib file failed");
     //rename restore files
     run_external_command("mv '{$modPath}/backup/moodle2/restore_newmodule_activity_task.class.php' '{$modPath}/backup/moodle2/restore_{$this->arguments[0]}_activity_task.class.php'", "Renaming restore activity task file failed");
     run_external_command("mv '{$modPath}/backup/moodle2/restore_newmodule_stepslib.php' '{$modPath}/backup/moodle2/restore_{$this->arguments[0]}_stepslib.php'", "Renaming restore stepslib file failed");
 }
Esempio n. 5
0
 public function execute()
 {
     global $CFG;
     $connstr = '';
     switch ($CFG->dbtype) {
         case 'mysqli':
         case 'mariadb':
             $connstr = "mysql -h {$CFG->dbhost} -u {$CFG->dbuser} -p{$CFG->dbpass} {$CFG->dbname}";
             break;
         case 'pgsql':
             $portoption = '';
             if (!empty($CFG->dboptions['dbport'])) {
                 $portoption = '-p ' . $CFG->dboptions['dbport'];
             }
             putenv("PGPASSWORD={$CFG->dbpass}");
             $connstr = "psql -h {$CFG->dbhost} -U {$CFG->dbuser} {$portoption} {$CFG->dbname}";
             break;
         default:
             cli_error("Sorry, database type '{$CFG->dbtype}' is not supported yet.  Feel free to contribute!");
             break;
     }
     if ($this->verbose) {
         echo "Connecting to database using '{$connstr}'";
     }
     $process = proc_open($connstr, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
     $proc_status = proc_get_status($process);
     $exit_code = proc_close($process);
     return $proc_status["running"] ? $exit_code : $proc_status["exitcode"];
 }
Esempio n. 6
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/csvlib.class.php';
     require_once $CFG->libdir . '/moodlelib.php';
     $filename = $this->expandedOptions['path'];
     if ($filename[0] != '/') {
         $filename = $this->cwd . DIRECTORY_SEPARATOR . $filename;
     }
     $categories = $DB->get_records('user_info_category', null, 'sortorder ASC');
     $data = array();
     foreach ($categories as $category) {
         if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
             foreach ($fields as $field) {
                 $field->categoryname = $category->name;
                 $field->categorysortorder = $category->sortorder;
                 $data[] = $field;
             }
         }
     }
     // End of $categories foreach.
     $header = array('id', 'shortname', 'name', 'datatype', 'description', 'descriptionformat', 'categoryid', 'sortorder', 'required', 'locked', 'visible', 'forceunique', 'signup', 'defaultdata', 'defaultdataformat', 'param1', 'param2', 'param3', 'param4', 'param5', 'categoryname', 'categorysortorder');
     $csvexport = new \csv_export_writer();
     $csvexport->add_data($header);
     foreach ($data as $row) {
         $arrayrow = (array) $row;
         $csvexport->add_data($arrayrow);
     }
     try {
         file_put_contents($filename, $csvexport->print_csv_data(true));
         echo "Userfields exported to: " . $filename . "\n";
     } catch (Exception $e) {
         cli_error("Unable to save file. Check if file {$filename} is writable");
     }
 }
Esempio n. 7
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/user/lib.php';
     unset($CFG->passwordpolicy);
     $options = $this->expandedOptions;
     if ($options['all']) {
         //run on the whole mdl_user table
         $sql = "UPDATE {user} SET ";
         $sqlFragment = array();
         $parameters = array();
         //we want to use the options that were actually provided on the commandline
         if ($this->parsedOptions->has('password')) {
             $sqlFragment[] = 'password = ?';
             $parameters['password'] = md5($this->parsedOptions['password']->value);
         }
         if ($this->parsedOptions->has('email')) {
             $sqlFragment[] = 'email = ?';
             $parameters['email'] = $this->parsedOptions['email']->value;
         }
         if ($this->parsedOptions->has('auth')) {
             $sqlFragment[] = 'auth = ?';
             $parameters['auth'] = $this->parsedOptions['auth']->value;
         }
         if (count($sqlFragment) == 0) {
             cli_error('You need to provide at least one option for updating a profile field (password or email)');
         }
         $sql .= implode(' , ', $sqlFragment);
         $DB->execute($sql, $parameters);
         exit(0);
     }
     foreach ($this->arguments as $argument) {
         if ($options['id']) {
             $user = $DB->get_record('user', array('id' => $argument));
         } else {
             $user = $DB->get_record('user', array('username' => $argument));
         }
         if (!$user) {
             cli_problem("User '{$argument}' not found'");
             continue;
         }
         if ($this->parsedOptions->has('password')) {
             $user->password = md5($this->parsedOptions['password']->value);
         }
         if ($this->parsedOptions->has('email')) {
             $user->email = $this->parsedOptions['email']->value;
         }
         if ($this->parsedOptions->has('auth')) {
             $user->auth = $this->parsedOptions['auth']->value;
         }
         echo $DB->update_record('user', $user) . "\n";
     }
 }
Esempio n. 8
0
 public function execute()
 {
     global $CFG;
     //some variables you may want to use
     //$this->cwd - the directory where moosh command was executed
     //$this->mooshDir - moosh installation directory
     //$this->expandedOptions - commandline provided options, merged with defaults
     //$this->topDir - top Moodle directory
     //$this->arguments[0] - first argument passed
     //$this->pluginInfo - array with information about the current plugin (based on cwd), keys:'type','name','dir'
     $options = $this->expandedOptions;
     //name of the event
     $name = $this->arguments[0];
     //json serialized data
     $data = $this->arguments[1];
     $data = json_decode($data, true);
     if (!$data) {
         cli_error("Could not decode json data.");
     }
     //load cache file manually as there seems to be no way to get it using Moodle API
     $cachefile = "{$CFG->cachedir}/core_component.php";
     include $cachefile;
     //match the name of the event
     //if was used than assume full namespace was given
     if (strpos($name, '\\') !== false) {
         $fullname = $name;
     } else {
         $matches = array();
         //first look for single match after last \
         foreach ($cache['classmap'] as $k => $class) {
             if (preg_match("/\\\\{$name}\$/", $k)) {
                 $matches[] = $k;
             }
         }
         if (count($matches) > 1) {
             print_r($matches);
             cli_error("More than one matching event");
         }
         $fullname = $matches[0];
     }
     $class = $cache['classmap'][$fullname];
     if (!$class) {
         cli_error("Class '{$fullname}' not found");
     }
     if ($this->verbose) {
         cli_problem("Loading class {$fullname}");
     }
     $event = $fullname::create($data);
     //$event->set_legacy_logdata(array(666, "course", "report log", "report/log/index.php?id=666", 666));
     $event->trigger();
 }
Esempio n. 9
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/course/lib.php';
     $moduleid = intval($this->arguments[0]);
     if ($moduleid <= 0) {
         cli_error("Argument 'moduleid' must be bigger than 0.");
     }
     if (!$DB->get_record('course_modules', array('id' => $this->arguments[0]))) {
         cli_error("There is no such activity to delete.");
     }
     course_delete_module($moduleid);
     echo "Deleted activity {$moduleid}\n";
 }
Esempio n. 10
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/csvlib.class.php';
     require_once $CFG->libdir . '/moodlelib.php';
     $csvfilepath = $this->arguments[0];
     if ($csvfilepath[0] != '/') {
         $csvfilepath = $this->cwd . DIRECTORY_SEPARATOR . $csvfilepath;
     }
     $iid = \csv_import_reader::get_new_iid('userprofile');
     $type = 'userprofile';
     $csvreader = new \csv_import_reader($iid, $type);
     if (false === ($csvfile = file_get_contents($csvfilepath))) {
         cli_error('Unable to load csv file. ' . error_get_last()['message']);
     }
     if (!$csvreader->load_csv_content($csvfile, 'utf-8', 'comma')) {
         cli_error('Unalbe to parse csv file. ' . $csvreader->get_error());
     }
     if (!$csvreader->init()) {
         cli_error('Unable to initialise csv reading');
     }
     $columns = $csvreader->get_columns();
     $columnsids = array_flip($columns);
     while (false !== ($row = $csvreader->next())) {
         $category = $this->get_or_create_category($row[$columnsids['categoryname']], $row[$columnsids['categorysortorder']]);
         $userfield = new \stdClass();
         $userfield->shortname = $row[$columnsids['shortname']];
         $userfield->name = $row[$columnsids['name']];
         $userfield->datatype = $row[$columnsids['datatype']];
         $userfield->description = $row[$columnsids['description']];
         $userfield->descriptionformat = $row[$columnsids['descriptionformat']];
         $userfield->categoryid = $category->id;
         $userfield->sortorder = $row[$columnsids['sortorder']];
         $userfield->required = $row[$columnsids['required']];
         $userfield->locked = $row[$columnsids['locked']];
         $userfield->visible = $row[$columnsids['visible']];
         $userfield->forceunique = $row[$columnsids['forceunique']];
         $userfield->signup = $row[$columnsids['signup']];
         $userfield->defaultdata = $row[$columnsids['defaultdata']];
         $userfield->defaultdataformat = $row[$columnsids['defaultdataformat']];
         $userfield->param1 = $row[$columnsids['param1']];
         $userfield->param2 = $row[$columnsids['param2']];
         $userfield->param3 = $row[$columnsids['param3']];
         $userfield->param4 = $row[$columnsids['param4']];
         $userfield->param5 = $row[$columnsids['param5']];
         $this->get_or_create_userfield($userfield);
     }
 }
Esempio n. 11
0
 public function execute()
 {
     //some variables you may want to use
     //$this->cwd - the directory where moosh command was executed
     //$this->mooshDir - moosh installation directory
     //$this->expandedOptions - commandline provided options, merged with defaults
     //$this->topDir - top Moodle directory
     //$this->arguments[0] - first argument passed
     $options = $this->expandedOptions;
     //find main version.php
     $path = $this->topDir . '/' . $this->pluginInfo['dir'] . '/' . $this->pluginInfo['name'] . '/version.php';
     if (!file_exists($path)) {
         cli_error("File does not exist: {$path}");
     }
     if (!is_writeable($path)) {
         cli_error("Can't write to the file: {$path}");
     }
     if ($this->verbose) {
         echo "Updating version.php: {$path}\n";
     }
     //find line like $module->version   = 2010032200
     //YYYYMMDDXX
     $curdate = date('Ymd');
     $content = file($path);
     foreach ($content as $k => $line) {
         if (preg_match('/^\\s*\\$\\w+->version\\s*=\\s*(\\d+)/', $line, $matches)) {
             if (strlen($matches[1]) > 10) {
                 cli_error('Your version is too big, go and bump it yourself');
             }
             if (substr($matches[1], 0, 8) == $curdate) {
                 //bump final XX
                 $xx = substr($matches[1], 8, 2);
                 $xx++;
                 if ($xx < 10) {
                     $xx = '0' . $xx;
                 }
             } else {
                 $xx = '00';
             }
             $version = $curdate . $xx;
             echo "Bumped from " . $matches[1] . " to {$version}\n";
             $content[$k] = preg_replace('/\\d+/', $version, $line, 1);
         }
     }
     file_put_contents($path, $content);
 }
Esempio n. 12
0
 public function execute()
 {
     global $CFG;
     require_once $CFG->dirroot . '/lib/modinfolib.php';
     $options = $this->expandedOptions;
     if (!isset($this->arguments[0]) && !$options['all']) {
         cli_error("Either run with -a for all courses or provide course id as an argument.");
     }
     if (isset($this->arguments[0])) {
         rebuild_course_cache($this->arguments[0]);
         echo "Succesfully rebuilt cache for course " . $this->arguments[0] . "\n";
     }
     if ($options['all']) {
         rebuild_course_cache();
         exit("Succesfully rebuilt all course caches\n");
     }
 }
Esempio n. 13
0
 public function execute()
 {
     global $CFG;
     require_once "{$CFG->libdir}/datalib.php";
     $user = get_admin();
     if (!$user) {
         cli_error("Unable to find admin user in DB.");
     }
     $auth = empty($user->auth) ? 'manual' : $user->auth;
     if ($auth == 'nologin' or !is_enabled_auth($auth)) {
         cli_error(sprintf("User authentication is either 'nologin' or disabled. Check Moodle authentication method for '%s'", $user->username));
     }
     $authplugin = get_auth_plugin($auth);
     $authplugin->sync_roles($user);
     login_attempt_valid($user);
     complete_user_login($user);
     printf("%s:%s\n", session_name(), session_id());
 }
Esempio n. 14
0
 public function execute()
 {
     $filepath = $this->expandedOptions['path'];
     $stat = NULL;
     if (file_exists($filepath)) {
         $stat = stat($filepath);
     }
     if (!$stat || time() - $stat['mtime'] > 60 * 60 * 24 || !$stat['size']) {
         @unlink($filepath);
         file_put_contents($filepath, fopen(self::$APIURL, 'r'));
     }
     $jsonfile = file_get_contents($filepath);
     if ($jsonfile === false) {
         die("Can't read json file");
     }
     $data = json_decode($jsonfile);
     if (!$data) {
         unlink($filepath);
         cli_error("Invalid JSON file, deleted {$filepath}. Run command again.");
     }
     $fulllist = array();
     foreach ($data->plugins as $k => $plugin) {
         if (!$plugin->component) {
             continue;
         }
         $fulllist[$plugin->component] = array('releases' => array());
         foreach ($plugin->versions as $v => $version) {
             if ($this->expandedOptions['versions']) {
                 $fulllist[$plugin->component]['releases'][$version->version] = $version;
             } else {
                 foreach ($version->supportedmoodles as $supportedmoodle) {
                     $fulllist[$plugin->component]['releases'][$supportedmoodle->release] = $version;
                 }
             }
             $fulllist[$plugin->component]['url'] = $version->downloadurl;
         }
     }
     ksort($fulllist);
     foreach ($fulllist as $k => $plugin) {
         $versions = array_keys($plugin['releases']);
         sort($versions);
         echo "{$k}," . implode(",", $versions) . "," . $plugin['url'] . "\n";
     }
 }
Esempio n. 15
0
 public function execute()
 {
     $userprofilename = $this->arguments[0];
     if (!preg_match('/[^a-z_0-9]/i', $userprofilename)) {
         cli_error('Agrument is not valid userprofile name');
     }
     $userprofilepath = $this->topDir . '/user/profile/field/' . $userprofilename;
     if (file_exists($userprofilepath)) {
         cli_error("Already exists: '{$userprofilepath}'");
     }
     run_external_command("cp -r '{$this->mooshDir}/vendor/moodlehq/moodle-user_profile_field' '{$userprofilepath}'", "Copying from module template failed");
     if (file_exists("{$userprofilepath}/.git")) {
         run_external_command("rm --interactive=never -r '{$userprofilepath}/.git'", "Removing .git failed");
     }
     // //replace newblock with $this->arguments[0]
     run_external_command("find '{$userprofilepath}' -type f -exec sed 's/myprofilefield/{$this->arguments[0]}/g' -i {} \\;", "sed command failed");
     //rename lang/en/block_newblock.php
     run_external_command("mv '{$userprofilepath}/lang/en/profilefield_myprofilefield.php' '{$userprofilepath}/lang/en/profilefield_{$this->arguments[0]}.php'", "Renaming lang file failed");
 }
Esempio n. 16
0
 public function execute()
 {
     global $CFG, $DB;
     switch ($CFG->dbtype) {
         case 'mysqli':
             passthru("mysqldump -h {$CFG->dbhost} -u {$CFG->dbuser} --password='******' {$CFG->dbname}");
             break;
         case 'pgsql':
             $portoption = '';
             if (!empty($CFG->dboptions['dbport'])) {
                 $portoption = '-p ' . $CFG->dboptions['dbport'];
             }
             putenv('PGPASSWORD='******'{$CFG->dbtype}' is not supported yet.  Feel free to contribute!");
             break;
     }
 }
Esempio n. 17
0
 public function execute()
 {
     global $DB;
     list($categoryid, $destcategoryid) = $this->arguments;
     if (!($cattomove = $DB->get_record('course_categories', array('id' => $categoryid)))) {
         cli_error("No category with id '{$categoryid}' found");
     }
     if ($cattomove->parent != $destcategoryid) {
         if ($destcategoryid == 0) {
             $newparent = new \stdClass();
             $newparent->id = 0;
             $newparent->visible = 1;
         } else {
             if (!($newparent = $DB->get_record('course_categories', array('id' => $destcategoryid)))) {
                 cli_error("No destination category with id '{$destcategoryid}' found");
             }
         }
         $this->move_category($cattomove, $newparent);
     }
 }
Esempio n. 18
0
 public function execute()
 {
     global $CFG, $DB;
     require_once "{$CFG->libdir}/datalib.php";
     $username = $this->arguments[0];
     $options = $this->expandedOptions;
     if ($options['id']) {
         $user = $DB->get_record('user', array('id' => $username), '*', MUST_EXIST);
     } else {
         $user = $DB->get_record('user', array('username' => $username), '*', MUST_EXIST);
     }
     $auth = empty($user->auth) ? 'manual' : $user->auth;
     if ($auth == 'nologin' or !is_enabled_auth($auth)) {
         cli_error(sprintf("User authentication is either 'nologin' or disabled. Check Moodle authentication method for '%s'", $user->username));
     }
     $authplugin = get_auth_plugin($auth);
     $authplugin->sync_roles($user);
     login_attempt_valid($user);
     complete_user_login($user);
     printf("%s:%s\n", session_name(), session_id());
 }
Esempio n. 19
0
 public function execute()
 {
     cli_error('Not implemented yet');
     global $CFG, $DB;
     require_once $CFG->wwwdir . '/cache/stores/memcache/lib.php';
     //some variables you may want to use
     //$this->cwd - the directory where moosh command was executed
     //$this->mooshDir - moosh installation directory
     //$this->expandedOptions - commandline provided options, merged with defaults
     //$this->topDir - top Moodle directory
     //$this->arguments[0] - first argument passed
     //$this->pluginInfo - array with information about the current plugin (based on cwd), keys:'type','name','dir'
     $options = $this->expandedOptions;
     $contextid = $this->arguments[0];
     //$contextpath = $this->arguments[0];
     $configuration = array();
     $configuration['servers'] = '127.0.0.1';
     $start = microtime(true);
     $memcache = new cachestore_memcache('memcache_test', $configuration);
     $result = sprintf('%01.4f', microtime(true) - $start);
 }
Esempio n. 20
0
 public function execute()
 {
     global $CFG;
     require_once $CFG->dirroot . '/course/lib.php';
     $categoryid = intval($this->arguments[0]);
     $category = get_record('course_categories', 'id', $categoryid);
     if ($categoryid && !$category) {
         cli_error("Wrong category '{$categoryid}'");
     } elseif (!$categoryid) {
         $category = NULL;
     }
     $categories = get_child_categories($categoryid);
     //add top lever category as well
     if ($category) {
         $category->categories = $categories;
         $categories = array($category);
     }
     echo "<categories>\n";
     $this->categories2xml($categories);
     echo "</categories>\n";
 }
 /**
  * Adds a merging action log into tool log.
  * @param int $touserid user.id where all data from $fromuserid will be merged into.
  * @param int $fromuserid user.id moving all data into $touserid.
  * @param bool $success true if merging action was ok; false otherwise.
  * @param array $log list of actions performed for a successful merging;
  * or a problem description if merging failed.
  */
 public function log($touserid, $fromuserid, $success, $log)
 {
     global $DB;
     $record = new stdClass();
     $record->touserid = $touserid;
     $record->fromuserid = $fromuserid;
     $record->timemodified = time();
     $record->success = (int) $success;
     $record->log = json_encode($log);
     //to get it
     try {
         return $DB->insert_record('tool_mergeusers', $record, true);
         //exception is thrown on any error
     } catch (Exception $e) {
         $msg = __METHOD__ . ' : Cannot insert new record on log. Reason: "' . $DB->get_last_error() . '". Message: "' . $e->getMessage() . '". Trace' . $e->getTraceAsString();
         if (CLI_SCRIPT) {
             cli_error($msg);
         } else {
             print_error($msg, null, new moodle_url('/admin/tool/mergeusers/index.php'));
         }
     }
 }
Esempio n. 22
0
 public function execute()
 {
     $arguments = $this->arguments;
     if ($this->expandedOptions['filename']) {
         $filename = $this->expandedOptions['filename'];
     } else {
         $filename = basename($this->arguments[0]);
     }
     if ($this->expandedOptions['filepath']) {
         $savedfilepath = $this->expandedOptions['filepath'];
     } else {
         $savedfilepath = basename($this->arguments[0]);
     }
     if ($arguments[0][0] != '/') {
         $filepath = $this->cwd . DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . $arguments[0];
         $arguments[0] = $this->cwd . DIRECTORY_SEPARATOR . $arguments[0];
     }
     if (!file_exists($arguments[0])) {
         cli_error("File '" . $arguments[0] . "' does not exist.");
     }
     if (!is_readable($arguments[0])) {
         cli_error("File '" . $arguments[0] . "' is not readable.");
     }
     $fp = get_file_storage();
     $filerecord = new \stdClass();
     $filerecord->contextid = $this->expandedOptions['contextid'];
     $filerecord->component = $this->expandedOptions['component'];
     $filerecord->filearea = $this->expandedOptions['filearea'];
     $filerecord->itemid = $this->expandedOptions['itemid'];
     $filerecord->sortorder = $this->expandedOptions['sortorder'];
     $filerecord->filepath = '/' . $savedfilepath . "/";
     $filerecord->filename = $filename;
     try {
         $fp->create_file_from_pathname($filerecord, $filepath);
         echo "File uploaded successfully!\n";
     } catch (Exception $e) {
         echo "File was not uploaded. Error: " . $e . "\n";
     }
 }
Esempio n. 23
0
 public function execute()
 {
     global $DB;
     if (!($this->course = $DB->get_record('course', array('id' => $this->arguments[0])))) {
         print_error("invalidcourseid");
     }
     require_login($this->course);
     $defaults = $this->loadDefaults();
     $defaults->id = $this->course->id;
     $options = $this->expandedOptions;
     if ($options['settings']) {
         $settings = explode(' ', $options['settings']);
         foreach ($settings as $setting) {
             $keyvalue = explode('=', $setting);
             if (count($keyvalue) != 2) {
                 cli_error("Error when parsing setting {$setting}");
             }
             $key = $keyvalue[0];
             $value = $keyvalue[1];
             if (strpos($value, ',') !== FALSE) {
                 $value = explode(',', $value);
                 foreach ($value as $k => $v) {
                     if (!trim($v)) {
                         unset($value[$k]);
                     }
                 }
             }
             $defaults->{$key} = $value;
         }
     }
     if ($options['no-action']) {
         $this->print_settings($defaults);
         exit(0);
     }
     $status = reset_course_userdata($defaults);
     print_r($status);
 }
Esempio n. 24
0
 public function execute()
 {
     $logfile = $this->arguments[0];
     if (!is_file($logfile) || !is_readable($logfile)) {
         cli_error("File '{$logfile}' does not exist or not readable.");
     }
     require_once $this->mooshDir . '/includes/ApacheLogParser/Parser.class.php';
     /*
     LogFormat "H: %v U: %{MOODLEUSER}n T: %Ts / %Dus | %{X-Forwarded-For}i %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" moodle_log
       H: www,example.com U: 10164391 T: 0s / 20500µs | 192.198.151.44 - - [22/Dec/2013:08:20:35 +0000] "GET /login/index.php?testsession=1164 HTTP/1.1"
       303 904 "http://www,example.com/login/index.php" "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
     */
     $elements = array('server_name', array('element' => 'note', 'name' => 'moodle_user'), 'serving_time', 'serving_time_microseconds', array('element' => 'request_header_line', 'name' => 'forwarded_for'), 'remote_logname', 'remote_user', 'time', 'request_first_line', 'status', 'bytes_sent', array('element' => 'request_header_line', 'name' => 'referer'), array('element' => 'request_header_line', 'name' => 'user-agent'));
     $re = 'H: %s U: %s T: %ss \\/ %sµs \\| %s %s %s %s "%s" %s %s "%s" "%s"';
     // $parser = Parser::createFormat(Parser::$FORMAT_COMBINED);
     $parser = new Parser($re, $elements);
     $parser->setFile($logfile);
     while (($line = $parser->next()) != -1) {
         var_dump($line);
         if (!count($line)) {
             die;
         }
     }
 }
Esempio n. 25
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/adminlib.php';
     // various admin-only functions
     require_once $CFG->libdir . '/classes/plugin_manager.php';
     $filtername = $this->arguments[0];
     $newstate = $this->arguments[1];
     if ($newstate != 1 && $newstate != -1 && $newstate != -9999) {
         cli_error("Invalid filter value, use: 1 for on, -1 per course, -9999 for off");
     }
     // Clean up bogus filter states first.
     $plugininfos = core_plugin_manager::instance()->get_plugins_of_type('filter');
     $filters = array();
     $states = filter_get_global_states();
     foreach ($states as $state) {
         if (!isset($plugininfos[$state->filter]) and !get_config('filter_' . $state->filter, 'version')) {
             // Purge messy leftovers after incorrectly uninstalled plugins and unfinished installs.
             $DB->delete_records('filter_active', array('filter' => $state->filter));
             $DB->delete_records('filter_config', array('filter' => $state->filter));
             error_log('Deleted bogus "filter_' . $state->filter . '" states and config data.');
         } else {
             $filters[$state->filter] = $state;
         }
     }
     if (!isset($filters[$filtername])) {
         cli_error("Invalid filter name: '{$filtername}''. Possible values: " . implode(",", array_keys($filters)) . '.');
     }
     filter_set_global_state($filtername, $newstate);
     if ($newstate == TEXTFILTER_DISABLED) {
         filter_set_applies_to_strings($filtername, false);
     }
     reset_text_filters_cache();
     core_plugin_manager::reset_caches();
     echo "Updated {$filtername} to state = {$newstate}\n";
 }
Esempio n. 26
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->libdir . '/csvlib.class.php';
     $username = $this->arguments[0];
     $filename = $this->expandedOptions['name'];
     $user = get_user_by_name($username);
     if (!$user) {
         cli_error("User not found.");
     } else {
         $userid = $user->id;
     }
     $fields = array('id' => 'id', 'username' => 'username', 'email' => 'email', 'firstname' => 'firstname', 'lastname' => 'lastname', 'idnumber' => 'idnumber', 'institution' => 'institution', 'department' => 'department', 'phone1' => 'phone1', 'phone2' => 'phone2', 'city' => 'city', 'url' => 'url', 'icq' => 'icq', 'skype' => 'skype', 'aim' => 'aim', 'yahoo' => 'yahoo', 'msn' => 'msn', 'country' => 'country');
     if ($extrafields = $DB->get_records('user_info_field')) {
         foreach ($extrafields as $n => $v) {
             $fields['profile_field_' . $v->shortname] = 'profile_field_' . $v->shortname;
         }
     }
     $csvexport = new \csv_export_writer();
     $csvexport->set_filename($filename);
     $csvexport->add_data($fields);
     $row = array();
     profile_load_data($user);
     $userprofiledata = array();
     foreach ($fields as $field => $unused) {
         if (is_array($user->{$field})) {
             $userprofiledata[] = reset($user->{$field});
         } else {
             $userprofiledata[] = $user->{$field};
         }
     }
     $csvexport->add_data($userprofiledata);
     file_put_contents($filename, $csvexport->print_csv_data(true));
     echo "User " . $user->username . " successfully downloaded\n";
 }
Esempio n. 27
0
 public function execute()
 {
     $loader = new Twig_Loader_Filesystem($this->mooshDir . '/templates');
     $twig = new Twig_Environment($loader);
     $command = explode('-', $this->arguments[0], 2);
     if (count($command) != 2) {
         cli_error("As argument provide category and command in format: category-command");
     }
     $fileName = ucfirst($command[0]) . ucfirst($command[1]) . '.php';
     $dirPath = $this->cwd . '/Moosh/Command/Moodle23/' . ucfirst($command[0]);
     $filePath = $dirPath . '/' . $fileName;
     $content = $twig->render('moosh/command.twig', array('category' => $command[0], 'command' => $command[1]));
     if (file_exists($filePath)) {
         cli_problem("File {$fileName} exists, dumping output instead of saving as a new file");
         echo $content;
         cli_problem("\n----------------------");
     } elseif (!is_dir($dirPath)) {
         cli_problem("Directory '{$dirPath}' does not exist, dumping output instead of saving as a new file");
         echo $content;
         cli_problem("\n---------------------");
     } else {
         file_put_contents($filePath, $content);
     }
 }
Esempio n. 28
0
/**
 * @package    local-mail
 * @copyright  Albert Gasset <*****@*****.**>
 * @copyright  Marc Català <*****@*****.**>
 * @copyright  Manuel Cagigas <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
define('CLI_SCRIPT', true);
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/config.php';
require_once $CFG->libdir . '/clilib.php';
global $DB;
// Cli options.
list($options, $unrecognized) = cli_get_params(array('help' => false, 'timelimit' => false), array('h' => 'help', 't' => 'timelimit'));
if ($unrecognized) {
    $unrecognized = implode("\n  ", $unrecognized);
    cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
}
if ($options['help']) {
    $help = "Local mail upgrade helper CLI tool.\nWill upgrade all remaining mails if no options are specified.\n\nOptions:\n-t, --timelimit=<n>     Process mails for n number of seconds, then exit. A mail\n                        currently in progress will not be interrupted.\n-h, --help              Print out this help\n\nExample:\n\$sudo -u www-data /usr/bin/php local/mail/cli/cliupgrade.php -t=1000\n";
    echo $help;
    die;
}
// Setup the stop time.
if ($options['timelimit']) {
    $stoptime = time() + $options['timelimit'];
} else {
    $stoptime = false;
}
$countrecords = $DB->count_records('local_mail_messages');
$limitfrom = 0;
$limitnum = 1000;
 * @author    Sun Zhigang
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
define('CLI_SCRIPT', true);
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->libdir . '/clilib.php';
// cli only functions
require_once $CFG->dirroot . '/plagiarism/moss/lib.php';
// now get cli options
$longoptions = array('help' => false, 'nodone' => false);
$shortoptions = array('h' => 'help', 'n' => 'nodone');
list($options, $unrecognized) = cli_get_params($longoptions, $shortoptions);
if ($unrecognized) {
    $cmid = (int) current($unrecognized);
    if ($cmid === 0) {
        $unrecognized = implode("\n  ", $unrecognized);
        cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
    }
}
if ($options['help'] or !isset($cmid)) {
    $help = "Trigger assessable_file_uploaded and assessable_files_done events of specified assignment.\n\ntrigger_assignment_events.php cmid\n\nOptions:\n-h, --help            Print out this help\n-n, --nodone          Do not trigger assessable_files_done event\n\nExample:\n\$sudo -u www-data /usr/bin/php plagiarism/moss/cli/trigger_assignment_events.php 1234\n";
    echo $help;
    die;
}
$count = moss_trigger_assignment_events($cmid, !$options['nodone']);
if ($count === false) {
    cli_error('Failed!');
} else {
    mtrace("{$count} submission(s) are found and events are triggered.");
}
Esempio n. 30
0
/**
 * Install Moodle DB,
 * config.php must exist, there must not be any tables in db yet.
 *
 * @param array $options adminpass is mandatory
 * @param bool $interactive
 * @return void
 */
function install_cli_database(array $options, $interactive)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/environmentlib.php';
    require_once $CFG->libdir . '/upgradelib.php';
    // show as much debug as possible
    @error_reporting(E_ALL | E_STRICT);
    @ini_set('display_errors', '1');
    $CFG->debug = E_ALL | E_STRICT;
    $CFG->debugdisplay = true;
    $CFG->version = '';
    $CFG->release = '';
    $CFG->branch = '';
    $version = null;
    $release = null;
    $branch = null;
    // read $version and $release
    require $CFG->dirroot . '/version.php';
    if ($DB->get_tables()) {
        cli_error(get_string('clitablesexist', 'install'));
    }
    if (empty($options['adminpass'])) {
        cli_error('Missing required admin password');
    }
    // test environment first
    list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
    if (!$envstatus) {
        $errors = environment_get_errors($environment_results);
        cli_heading(get_string('environment', 'admin'));
        foreach ($errors as $error) {
            list($info, $report) = $error;
            echo "!! {$info} !!\n{$report}\n\n";
        }
        exit(1);
    }
    if (!$DB->setup_is_unicodedb()) {
        if (!$DB->change_db_encoding()) {
            // If could not convert successfully, throw error, and prevent installation
            cli_error(get_string('unicoderequired', 'admin'));
        }
    }
    if ($interactive) {
        cli_separator();
        cli_heading(get_string('databasesetup'));
    }
    // install core
    install_core($version, true);
    set_config('release', $release);
    set_config('branch', $branch);
    if (PHPUNIT_TEST) {
        // mark as test database as soon as possible
        set_config('phpunittest', 'na');
    }
    // install all plugins types, local, etc.
    upgrade_noncore(true);
    // set up admin user password
    $DB->set_field('user', 'password', hash_internal_user_password($options['adminpass']), array('username' => 'admin'));
    // rename admin username if needed
    if (isset($options['adminuser']) and $options['adminuser'] !== 'admin' and $options['adminuser'] !== 'guest') {
        $DB->set_field('user', 'username', $options['adminuser'], array('username' => 'admin'));
    }
    // indicate that this site is fully configured
    set_config('rolesactive', 1);
    upgrade_finished();
    // log in as admin - we need do anything when applying defaults
    $admins = get_admins();
    $admin = reset($admins);
    session_set_user($admin);
    // apply all default settings, do it twice to fill all defaults - some settings depend on other setting
    admin_apply_default_settings(NULL, true);
    admin_apply_default_settings(NULL, true);
    set_config('registerauth', '');
    // set the site name
    if (isset($options['shortname']) and $options['shortname'] !== '') {
        $DB->set_field('course', 'shortname', $options['shortname'], array('format' => 'site'));
    }
    if (isset($options['fullname']) and $options['fullname'] !== '') {
        $DB->set_field('course', 'fullname', $options['fullname'], array('format' => 'site'));
    }
}