コード例 #1
0
 public function execute()
 {
     //copy newmodule
     $modPath = $this->topDir . '/availability/condition/' . $this->arguments[0];
     if (file_exists($modPath)) {
         cli_problem("Already exists: '{$modPath}'");
         cli_problem("Not creating new availability condition" . $this->arguments[0]);
         exit(1);
     }
     run_external_command("cp -r '{$this->mooshDir}/vendor/danielneis/moodle-availability_newavailability' '{$modPath}'", "Copying from availability condition 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/newavailability/{$this->arguments[0]}/g' -i {} \\;", "sed command failed");
     //rename lang/en/newmodule.php
     run_external_command("mv '{$modPath}/lang/en/availability_newavailability.php' '{$modPath}/lang/en/availability_{$this->arguments[0]}.php'", "Renaming lang file failed");
     //rename yui/build/moodle-availability_newavailability-form/moodle-availability_newavailability-form.js
     run_external_command("mv '{$modPath}/yui/build/moodle-availability_newavailability-form/moodle-availability_newavailability-form.js' '{$modPath}/yui/build/moodle-availability_newavailability-form/moodle-availability_{$this->arguments[0]}-form.js'", "Renaming yui build js");
     //rename yui/build/moodle-availability_newavailability-form/moodle-availability_newavailability-form-debug.js
     run_external_command("mv '{$modPath}/yui/build/moodle-availability_newavailability-form/moodle-availability_newavailability-form-debug.js' '{$modPath}/yui/build/moodle-availability_newavailability-form/moodle-availability_{$this->arguments[0]}-form-debug.js'", "Renaming yui build debug js");
     //rename yui/build/moodle-availability_newavailability-form/moodle-availability_newavailability-form-min.js
     run_external_command("mv '{$modPath}/yui/build/moodle-availability_newavailability-form/moodle-availability_newavailability-form-min.js' '{$modPath}/yui/build/moodle-availability_newavailability-form/moodle-availability_{$this->arguments[0]}-form-min.js'", "Renaming yui build min js");
     //rename dir yui/build/moodle-availability_newavailability-form
     run_external_command("mv '{$modPath}/yui/build/moodle-availability_newavailability-form' '{$modPath}/yui/build/moodle-availability_{$this->arguments[0]}-form'", "Renaming yui build dir");
 }
コード例 #2
0
ファイル: FormAdd.php プロジェクト: dariogs/moosh
 public function execute()
 {
     $loader = new Twig_Loader_Filesystem($this->mooshDir . '/templates');
     $twig = new Twig_Environment($loader, array('debug' => true));
     $twig->addExtension(new Twig_Extension_Debug());
     $template = 'form/form-element-' . $this->arguments[0] . '.twig';
     if (!$loader->exists($template)) {
         cli_problem("Template {$template} does not exist");
         exit(1);
     }
     $content = $twig->render($template, array('id' => $this->arguments[1], 'langCategory' => $this->getLangCategory()));
     //do I know where to add the new code?
     $this->loadSession();
     if (isset($this->session['generator.last-file'][$this->cwd]) && file_exists($this->cwd . '/' . $this->session['generator.last-file'][$this->cwd])) {
         $fileName = $this->cwd . '/' . $this->session['generator.last-file'][$this->cwd];
         $fileContent = file_get_contents($fileName);
         //replace /** MOOSH AUTO-GENERATED */ with new code
         $fileContent = str_replace(MOOSH_CODE_MARKER, $content . "\n" . MOOSH_CODE_MARKER, $fileContent);
         file_put_contents($fileName, $fileContent);
         if ($this->defaults['global']['xdotool']) {
             $browser = $this->defaults['global']['browser_string'];
             $active_window = run_external_command("xdotool getwindowfocus", "Couldn't find active window");
             $browser_window = run_external_command("xdotool search --name '{$browser}'", "Couldn't find {$browser}");
             run_external_command("xdotool windowactivate {$browser_window['0']} ", "Couldn't activate window: {$browser}");
             run_external_command("xdotool key F5", "Couldn't refresh browser");
             run_external_command("xdotool windowactivate {$active_window['0']}", "Couldn't activate window: {$active_window['0']}");
         }
     } else {
         echo $content;
     }
 }
コード例 #3
0
ファイル: GenerateForm.php プロジェクト: dariogs/moosh
 public function execute()
 {
     //command may need to store some information in-between runs
     $this->loadSession();
     $loader = new Twig_Loader_Filesystem($this->mooshDir . '/templates');
     $twig = new Twig_Environment($loader);
     $formName = '';
     if ($this->pluginInfo['type'] != 'unknown') {
         $formName = $this->pluginInfo['type'] . '_' . $this->pluginInfo['name'] . '_';
     }
     $formName .= $this->arguments[0];
     $fileName = $this->arguments[0] . '_form.php';
     $filePath = $this->cwd . '/' . $fileName;
     //save the information for the next code generation run
     if (!isset($this->session['generator.last-file'])) {
         $this->session['generator.last-file'] = array();
     }
     $this->session['generator.last-file'][$this->cwd] = $fileName;
     $content = $twig->render('form/form.twig', array('formName' => $formName));
     if (file_exists($filePath)) {
         cli_problem("File {$fileName} exists");
         echo $content;
         echo "\n---------------------\n";
     } else {
         file_put_contents($filePath, $content);
     }
     //also generate a client code
     echo $twig->render('form/form_client.twig', array('formName' => $formName, 'formRelativePath' => $this->relativeDir, 'fileName' => $fileName));
     $this->saveSession();
 }
コード例 #4
0
ファイル: GenerateModule.php プロジェクト: sergiohermes/moosh
 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");
 }
コード例 #5
0
ファイル: GenerateCfg.php プロジェクト: dariogs/moosh
 private function extract_help($key)
 {
     $matches = NULL;
     preg_match("/\\\$string\\['{$key}'\\] =\\s*'(.*)';/sU", $this->langfiles, $matches);
     if (!$matches[1]) {
         cli_problem("Couldn't parse string for {$key}");
     }
     return $matches[1];
 }
コード例 #6
0
ファイル: UserMod.php プロジェクト: dariogs/moosh
 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";
     }
 }
コード例 #7
0
ファイル: EventFire.php プロジェクト: tmuras/moosh
 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();
 }
コード例 #8
0
ファイル: CourseEnrol.php プロジェクト: dariogs/moosh
 public function execute()
 {
     global $CFG, $DB, $PAGE;
     require_once $CFG->dirroot . '/enrol/locallib.php';
     require_once $CFG->dirroot . '/group/lib.php';
     $options = $this->expandedOptions;
     $arguments = $this->arguments;
     //find role id for given role
     $role = $DB->get_record('role', array('shortname' => $options['role']), '*', MUST_EXIST);
     if ($options['shortname']) {
         $course = $DB->get_record('course', array('shortname' => $arguments[0]), '*', MUST_EXIST);
     } else {
         $course = $DB->get_record('course', array('id' => $arguments[0]), '*', MUST_EXIST);
     }
     $context = context_course::instance($course->id);
     $manager = new course_enrolment_manager($PAGE, $course);
     $instances = $manager->get_enrolment_instances();
     //find the manual one
     foreach ($instances as $instance) {
         if ($instance->enrol == 'manual') {
             break;
         }
     }
     if ($instance->enrol != 'manual') {
         die("No manual enrolment instance for the course\n");
     }
     $plugins = $manager->get_enrolment_plugins();
     //only one manual enrolment in a course
     if (!isset($plugins['manual'])) {
         die("No manual enrolment plugin for the course\n");
     }
     $plugin = $plugins['manual'];
     $today = time();
     $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
     array_shift($arguments);
     foreach ($arguments as $argument) {
         if ($options['id']) {
             $user = $DB->get_record('user', array('id' => $argument), '*', MUST_EXIST);
         } else {
             $user = $DB->get_record('user', array('username' => $argument), '*', MUST_EXIST);
         }
         if (!$user) {
             cli_problem("User '{$user}' not found");
             continue;
         }
         $plugin->enrol_user($instance, $user->id, $role->id, $today, 0);
     }
 }
コード例 #9
0
ファイル: GenerateGradeExport.php プロジェクト: dariogs/moosh
 public function execute()
 {
     //copy newmodule
     $modPath = $this->topDir . '/grade/export/' . $this->arguments[0];
     if (file_exists($modPath)) {
         cli_problem("Already exists: '{$modPath}'");
         cli_problem("Not creating new grade export " . $this->arguments[0]);
         exit(1);
     }
     run_external_command("cp -r '{$this->mooshDir}/vendor/danielneis/moodle-gradeexport_newgradeexport' '{$modPath}'", "Copying from grade export 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/newgradeexport/{$this->arguments[0]}/g' -i {} \\;", "sed command failed");
     //rename lang/en/newmodule.php
     run_external_command("mv '{$modPath}/lang/en/gradeexport_newgradeexport.php' '{$modPath}/lang/en/gradeexport_{$this->arguments[0]}.php'", "Renaming lang file failed");
 }
コード例 #10
0
ファイル: GenerateQtype.php プロジェクト: dariogs/moosh
 public function execute()
 {
     //copy newmodule
     $modPath = $this->topDir . '/question/type/' . $this->arguments[0];
     if (file_exists($modPath)) {
         cli_problem("Already exists: '{$modPath}'");
         cli_problem("Not creating new question type " . $this->arguments[0]);
         exit(1);
     }
     run_external_command("cp -r '{$this->mooshDir}/vendor/jamiepratt/moodle-qtype_TEMPLATE' '{$modPath}'", "Copying from qtype 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/YOURQTYPENAME/{$this->arguments[0]}/g' -i {} \\;", "sed command failed");
     //rename lang/en/qtype_YOURQTYPENAME.php
     run_external_command("mv '{$modPath}/lang/en/qtype_YOURQTYPENAME.php' '{$modPath}/lang/en/qtype_{$this->arguments[0]}.php'", "Renaming lang file failed");
     //rename edit_YOURQTYPENAME_form.php
     run_external_command("mv '{$modPath}/edit_YOURQTYPENAME_form.php' '{$modPath}/edit_{$this->arguments[0]}_form.php'", "Renaming lang file failed");
 }
コード例 #11
0
ファイル: GenerateMoosh.php プロジェクト: dariogs/moosh
 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);
     }
 }
コード例 #12
0
ファイル: install.php プロジェクト: mongo0se/moodle
$installlang = $CFG->lang;
// return back to original dir before executing setup.php which changes the dir again
chdir($olddir);
// We have config.php, it is a real php script from now on :-)
require $configfile;
// use selected language
$CFG->lang = $installlang;
$SESSION->lang = $CFG->lang;
require "{$CFG->dirroot}/version.php";
// Test environment first.
require_once $CFG->libdir . '/environmentlib.php';
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);
}
// Test plugin dependencies.
$failed = array();
if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
    cli_problem(get_string('pluginscheckfailed', 'admin', array('pluginslist' => implode(', ', array_unique($failed)))));
    cli_error(get_string('pluginschecktodo', 'admin'));
}
install_cli_database($options, $interactive);
echo get_string('cliinstallfinished', 'install') . "\n";
exit(0);
// 0 means success
コード例 #13
0
function judge_all_unjudged()
{
    while ($task = get_one_unjudged_task()) {
        verbose(cli_heading('TASK: ' . $task->id, true));
        verbose('Judging...');
        try {
            $task = onlinejudge_judge($task);
            verbose("Successfully judged: {$task->status}");
        } catch (Exception $e) {
            $info = get_exception_info($e);
            $errmsg = "Judged inner level exception handler: " . $info->message . ' Debug: ' . $info->debuginfo . "\n" . format_backtrace($info->backtrace, true);
            cli_problem($errmsg);
            // Continue to get next unjudged task
        }
    }
}
コード例 #14
0
if (!$coursescount) {
    cli_error('No courses found');
}
echo "Checking {$coursescount} courses...\n\n";
require_once $CFG->dirroot . '/course/lib.php';
$problems = array();
$courses = $DB->get_fieldset_sql('SELECT id FROM {course} ' . $where, $params);
foreach ($courses as $courseid) {
    $errors = course_integrity_check($courseid, null, null, true, empty($options['fix']));
    if ($errors) {
        if (!empty($options['fix'])) {
            // Reset the course cache to make sure cache is recalculated next time the course is viewed.
            rebuild_course_cache($courseid, true);
        }
        foreach ($errors as $error) {
            cli_problem($error);
        }
        $problems[] = $courseid;
    } else {
        echo "Course [{$courseid}] is OK\n";
    }
}
if (!count($problems)) {
    echo "\n...All courses are OK\n";
} else {
    if (!empty($options['fix'])) {
        echo "\n...Found and fixed " . count($problems) . " courses with problems" . "\n";
    } else {
        echo "\n...Found " . count($problems) . " courses with problems. To fix run:\n";
        echo "\$sudo -u www-data /usr/bin/php admin/cli/fix_course_sequence.php --courses=" . join(',', $problems) . " --fix" . "\n";
    }
コード例 #15
0
ファイル: install.php プロジェクト: hitphp/moodle
    if (!install_init_dataroot($CFG->dataroot, $CFG->directorypermissions)) {
        $a = (object) array('dataroot' => $CFG->dataroot);
        cli_error(get_string('pathserrcreatedataroot', 'install', $a));
    }
}
//download lang pack with optional notification
if ($CFG->lang != 'en') {
    if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $CFG->lang . '.zip', 'languages.md5', 'lang')) {
        if ($cd->install() == COMPONENT_ERROR) {
            if ($cd->get_error() == 'remotedownloaderror') {
                $a = new stdClass();
                $a->url = 'http://download.moodle.org/langpack/2.0/' . $CFG->lang . '.zip';
                $a->dest = $CFG->dataroot . '/lang';
                cli_problem(get_string($cd->get_error(), 'error', $a));
            } else {
                cli_problem(get_string($cd->get_error(), 'error'));
            }
        } else {
            // install parent lang if defined
            if ($parentlang = get_parent_language()) {
                if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $parentlang . '.zip', 'languages.md5', 'lang')) {
                    $cd->install();
                }
            }
        }
    }
}
// switch the string_manager instance to stop using install/lang/
$CFG->early_install_lang = false;
$CFG->langotherroot = $CFG->dataroot . '/lang';
$CFG->langlocalroot = $CFG->dataroot . '/lang';
コード例 #16
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.");
     }
     $handle = fopen($logfile, "r");
     while (($line = fgets($handle, self::$MAX_LINE_LENGTH)) !== false) {
         if (strpos($line, 'PERF:') === false) {
             continue;
         }
         $row = array();
         //echo $line;
         //time: 2.774779s
         //$row['raw'] = $line;
         $row['time'] = (int) ($this->parse($line, 'time: (\\d+.\\d+)s') * 1000000);
         //[Sun Dec 22 06:29:01 2013]
         //[Sun Dec 22 06:29:01.731010 2013]
         $row['timestamp'] = $this->parse($line, ' (.*?)\\]');
         $row['timestamp'] = preg_replace('/\\.\\d+/', '', $row['timestamp']);
         $tmp = date_parse($row['timestamp']);
         if ($tmp['year'] < 10) {
             $tmp['year'] = '0' . $tmp['year'];
         }
         if ($tmp['month'] < 10) {
             $tmp['month'] = '0' . $tmp['month'];
         }
         if ($tmp['day'] < 10) {
             $tmp['day'] = '0' . $tmp['day'];
         }
         if ($tmp['hour'] < 10) {
             $tmp['hour'] = '0' . $tmp['hour'];
         }
         if ($tmp['minute'] < 10) {
             $tmp['minute'] = '0' . $tmp['minute'];
         }
         if ($tmp['second'] < 10) {
             $tmp['second'] = '0' . $tmp['second'];
         }
         $row['timestamp'] = $tmp['year'] . '-' . $tmp['month'] . '-' . $tmp['day'] . ' ' . $tmp['hour'] . ':' . $tmp['minute'] . ':' . $tmp['second'];
         //PERF: /login/index.php
         $row['url'] = $this->parse($line, 'PERF: (.*?) ');
         //if no URL, we assume it was cron
         if (!$row['url']) {
             $row['url'] = '<cron>';
         }
         //memory_peak: 67556680B (
         $row['memory_peak'] = $this->parse($line, 'memory_peak: (\\d+)B');
         //includecount: 751
         $row['includecount'] = $this->parse($line, 'includecount: (\\d+)');
         //contextswithfilters
         $row['contextswithfilters'] = $this->parse($line, 'contextswithfilters: (\\d+)');
         //filterscreated
         $row['filterscreated'] = $this->parse($line, 'filterscreated: (\\d+)');
         $row['textsfiltered'] = $this->parse($line, 'textsfiltered: (\\d+)');
         $row['stringsfiltered'] = $this->parse($line, 'stringsfiltered: (\\d+)');
         $row['langcountgetstring'] = $this->parse($line, 'langcountgetstring: (\\d+)');
         //db reads/writes: 62/30
         $row['db_reads'] = $this->parse($line, 'db reads\\/writes: (\\d+)');
         $row['db_writes'] = $this->parse($line, 'db reads\\/writes: \\d+\\/(\\d+)');
         //ticks: 278 user: 60 sys: 4 cuser: 0 csys: 0
         $row['ticks'] = $this->parse($line, 'ticks: (\\d+)');
         $row['user'] = $this->parse($line, 'user: (\\d+)');
         $row['sys'] = $this->parse($line, 'sys: (\\d+)');
         $row['cuser'] = $this->parse($line, 'cuser: (\\d+)');
         $row['csys'] = $this->parse($line, 'csys: (\\d+)');
         //serverload: 1.58
         $row['serverload'] = (int) ($this->parse($line, 'serverload: (\\d+.\\d+)') * 100);
         //we assume that the row is unique if timestamp, url and time are unique. Therefore they are required values
         if (!$row['url'] || !$row['timestamp'] || !$row['time']) {
             cli_problem('Invalid row: ' . $row['url']);
             continue;
         }
         // Cache stores
         // cachestore_mongodb(0/1/1)
         // cachestore_static(0/1/1)
         // ** static persist **(6/107/0)
         list($row['cache_mondodb_hits'], $row['cache_mondodb_misses'], $row['cache_mondodb_sets']) = $this->parseCaches($line, 'cachestore_mongodb');
         list($row['cache_static_hits'], $row['cache_static_misses'], $row['cache_static_sets']) = $this->parseCaches($line, 'cachestore_static');
         list($row['cache_staticpersist_hits'], $row['cache_staticpersist_misses'], $row['cache_staticpersist_sets']) = $this->parseCaches($line, '\\*\\* static persist \\*\\*');
         list($row['cache_file_hits'], $row['cache_file_misses'], $row['cache_file_sets']) = $this->parseCaches($line, 'cachestore_file');
         //construct SQL statement
         $columns = array();
         $values = array();
         foreach ($row as $k => $v) {
             if (isset($v)) {
                 $columns[] = $k;
                 $values[] = "'" . @mysql_escape_string($v) . "'";
             }
         }
         $sql = "INSERT IGNORE INTO " . $this->options['table'] . " (" . implode(',', $columns) . ') VALUES (' . implode(',', $values) . ');';
         echo "{$sql}\n";
     }
 }
コード例 #17
0
ファイル: ApacheParsePerfLog.php プロジェクト: janeklb/moosh
 private function analyzeURL($row)
 {
     $script = '';
     $query = NULL;
     $path = NULL;
     $type = 'other';
     if ($row['url'] == '<cron>') {
         // Nothing to analyze here.
         return array($script, $query, $path, 'cli');
     }
     // Split row on first .php
     $exploded = explode('.php', $row['url']);
     if (count($exploded) < 2) {
         $script = rtrim($exploded[0], '?') . 'index.php';
     } else {
         $script = $exploded[0] . '.php';
     }
     // Determine a type of request.
     if ($script == '/pluginfile.php' || $script == '/webservice/pluginfile.php' || $script == '/file.php' || $script == '/draftfile.php') {
         $type = 'download';
     } elseif (preg_match('/download=zip$/', $row['url']) || preg_match('/action=downloadall$/', $row['url'])) {
         $type = 'download';
     } elseif (preg_match('/repository_ajax.php\\?action=upload/', $row['url'])) {
         $type = 'upload';
     } else {
         $type = 'script';
     }
     //echo $script . ' ' . $type . "\n";
     unset($exploded[0]);
     $queryorpath = implode('.php', $exploded);
     if ($queryorpath) {
         if ($queryorpath[0] == '/') {
             $path = $queryorpath;
         } elseif ($queryorpath[0] == '?') {
             $query = ltrim($queryorpath, '?');
         } else {
             cli_problem('Invalid query or path part: ' . $queryorpath);
         }
     }
     return array($script, $query, $path, $type);
 }
コード例 #18
0
}
if ($options['adminpass'] === true or $options['adminpass'] === '') {
    cli_error('You have to specify admin password. --help prints out the help');
    // TODO: localize
}
$options['lang'] = clean_param($options['lang'], PARAM_SAFEDIR);
if (!file_exists($CFG->dirroot . '/install/lang/' . $options['lang'])) {
    $options['lang'] = 'en';
}
$CFG->lang = $options['lang'];
// download required lang packs
if ($CFG->lang !== 'en') {
    make_upload_directory('lang');
    $installer = new lang_installer($CFG->lang);
    $results = $installer->run();
    foreach ($results as $langcode => $langstatus) {
        if ($langstatus === lang_installer::RESULT_DOWNLOADERROR) {
            $a = new stdClass();
            $a->url = $installer->lang_pack_url($langcode);
            $a->dest = $CFG->dataroot . '/lang';
            cli_problem(get_string('remotedownloaderror', 'error', $a));
        }
    }
}
// switch the string_manager instance to stop using install/lang/
$CFG->early_install_lang = false;
get_string_manager(true);
install_cli_database($options, true);
echo get_string('cliinstallfinished', 'install') . "\n";
exit(0);
// 0 means success
コード例 #19
0
ファイル: upgrade.php プロジェクト: evltuma/moodle
    $a->oldversion = $oldversion;
    $a->newversion = $newversion;
    echo cli_heading(get_string('databasechecking', '', $a)) . PHP_EOL;
}
// make sure we are upgrading to a stable release or display a warning
if (isset($maturity)) {
    if ($maturity < MATURITY_STABLE and !$options['allow-unstable']) {
        $maturitylevel = get_string('maturity' . $maturity, 'admin');
        if ($interactive) {
            cli_separator();
            cli_heading(get_string('notice'));
            echo get_string('maturitycorewarning', 'admin', $maturitylevel) . PHP_EOL;
            echo get_string('morehelp') . ': ' . get_docs_url('admin/versions') . PHP_EOL;
            cli_separator();
        } else {
            cli_problem(get_string('maturitycorewarning', 'admin', $maturitylevel));
            cli_error(get_string('maturityallowunstable', 'admin'));
        }
    }
}
if ($interactive) {
    echo html_to_text(get_string('upgradesure', 'admin', $newversion)) . "\n";
    $prompt = get_string('cliyesnoprompt', 'admin');
    $input = cli_input($prompt, '', array(get_string('clianswerno', 'admin'), get_string('cliansweryes', 'admin')));
    if ($input == get_string('clianswerno', 'admin')) {
        exit(1);
    }
}
if ($version > $CFG->version) {
    // We purge all of MUC's caches here.
    // Caches are disabled for upgrade by CACHE_DISABLE_ALL so we must set the first arg to true.
コード例 #20
0
ファイル: sync_users.php プロジェクト: evltuma/moodle
 *   - For debugging & better logging, you are encouraged to use in the command line:
 *     -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
 *
 * Performance notes:
 * We have optimized it as best as we could for PostgreSQL and MySQL, with 27K students
 * we have seen this take 10 minutes.
 *
 * @package    auth_cas
 * @copyright  2007 Jerome Gutierrez - based on code by Martin Langhoff
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @deprecated since Moodle 3.0 MDL-51824 - please do not use this CLI script any more, use scheduled task instead.
 * @todo MDL-50264 This will be deleted in Moodle 3.2.
 */
define('CLI_SCRIPT', true);
require __DIR__ . '/../../../config.php';
require_once $CFG->dirroot . '/course/lib.php';
require_once $CFG->libdir . '/clilib.php';
// Ensure errors are well explained
set_debugging(DEBUG_DEVELOPER, true);
if (!is_enabled_auth('cas')) {
    error_log('[AUTH CAS] ' . get_string('pluginnotenabled', 'auth_ldap'));
    die;
}
cli_problem('[AUTH CAS] The sync users cron has been deprecated. Please use the scheduled task instead.');
// Abort execution of the CLI script if the auth_cas\task\sync_task is enabled.
$task = \core\task\manager::get_scheduled_task('auth_cas\\task\\sync_task');
if (!$task->get_disabled()) {
    cli_error('[AUTH CAS] The scheduled task sync_task is enabled, the cron execution has been aborted.');
}
$casauth = get_auth_plugin('cas');
$casauth->sync_users(true);
コード例 #21
0
ファイル: sync_users.php プロジェクト: evltuma/moodle
 *     -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
 *
 * Performance notes:
 * We have optimized it as best as we could for PostgreSQL and MySQL, with 27K students
 * we have seen this take 10 minutes.
 *
 * @package    auth_ldap
 * @copyright  2004 Martin Langhoff
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @deprecated since Moodle 3.0 MDL-51824 - please do not use this CLI script any more, use scheduled task instead.
 * @todo MDL-50264 This will be deleted in Moodle 3.2.
 */
define('CLI_SCRIPT', true);
require __DIR__ . '/../../../config.php';
// global moodle config file.
require_once $CFG->dirroot . '/course/lib.php';
require_once $CFG->libdir . '/clilib.php';
// Ensure errors are well explained
set_debugging(DEBUG_DEVELOPER, true);
if (!is_enabled_auth('ldap')) {
    error_log('[AUTH LDAP] ' . get_string('pluginnotenabled', 'auth_ldap'));
    die;
}
cli_problem('[AUTH LDAP] The users sync cron has been deprecated. Please use the scheduled task instead.');
// Abort execution of the CLI script if the auth_ldap\task\sync_task is enabled.
$taskdisabled = \core\task\manager::get_scheduled_task('auth_ldap\\task\\sync_task');
if (!$taskdisabled->get_disabled()) {
    cli_error('[AUTH LDAP] The scheduled task sync_task is enabled, the cron execution has been aborted.');
}
$ldapauth = get_auth_plugin('ldap');
$ldapauth->sync_users(true);
コード例 #22
0
                }
            } catch (Exception $e) {
                $message = "Caught Exception: " . $e->getMessage();
                echo $message;
                $logger->postmessage($message);
                $logger->setstatus('SUCCESS with some FAILURES');
            }
        } else {
            $message = "Create user: "******"\n";
            echo $message;
        }
    }
} else {
    $message = "Threshold Exceeded:\nDelete: {$stattotaldeletedmoodleusers} \nUpdate: {$stattotalupdatedmoodleusers}";
    $logger->log($message);
    cli_problem($message);
    $logger->setstatus(<<<FAILWHALE
▄██████████████▄▐█▄▄▄▄█▌
██████▌▄▌▄▐▐▌███▌▀▀██▀▀
████▄█▌▄▌▄▐▐▌▀███▄▄█▌
▄▄▄▄▄██████████████▀
FAILWHALE
);
}
/**
 * @param $empid String employee id
 * @return bool
 */
function is_business_user($empid)
{
    global $busers;
コード例 #23
0
ファイル: CourseRestore.php プロジェクト: tmuras/moosh
 public function execute()
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . "/backup/util/includes/backup_includes.php";
     require_once $CFG->dirroot . "/backup/util/includes/restore_includes.php";
     $arguments = $this->arguments;
     $options = $this->expandedOptions;
     if (empty($CFG->tempdir)) {
         $CFG->tempdir = $CFG->dataroot . DIRECTORY_SEPARATOR . 'temp';
     }
     // Check if category is OK.
     if (!$options['existing']) {
         $category = $DB->get_record('course_categories', array('id' => $this->arguments[1]), '*', MUST_EXIST);
     } else {
         $course = $DB->get_record('course', array('id' => $this->arguments[1]), '*', MUST_EXIST);
         $category = $DB->get_record('course_categories', array('id' => $course->category), '*', MUST_EXIST);
     }
     if (!$options['directory']) {
         if ($arguments[0][0] != '/') {
             $arguments[0] = $this->cwd . DIRECTORY_SEPARATOR . $arguments[0];
         }
         if (!file_exists($arguments[0])) {
             cli_error("Backup file '" . $arguments[0] . "' does not exist.");
         }
         if (!is_readable($arguments[0])) {
             cli_error("Backup file '" . $arguments[0] . "' is not readable.");
         }
     } else {
         $path = $CFG->tempdir . DIRECTORY_SEPARATOR . "backup" . DIRECTORY_SEPARATOR . $arguments[0];
         if (!file_exists($path) || !is_dir($path) || !is_readable($path)) {
             cli_error("Directory '{$path}' does not exist, not a directory or not readable.");
         }
     }
     if (!$options['directory']) {
         //unzip into $CFG->tempdir / "backup" / "auto_restore_" . $split[1];
         $backupdir = "moosh_restore_" . uniqid();
         $path = $CFG->tempdir . DIRECTORY_SEPARATOR . "backup" . DIRECTORY_SEPARATOR . $backupdir;
         if ($this->verbose) {
             echo "Extracting Moode backup file to: '" . $path . "'\n";
         }
         /** @var $fp file_packer */
         $fp = get_file_packer('application/vnd.moodle.backup');
         $fp->extract_to_pathname($arguments[0], $path);
     } else {
         $backupdir = $arguments[0];
     }
     //extract original full & short names
     $xmlfile = $path . DIRECTORY_SEPARATOR . "course" . DIRECTORY_SEPARATOR . "course.xml";
     // Different XML file in Moodle 1.9 backup
     if (!file_exists($xmlfile)) {
         $xmlfile = $path . DIRECTORY_SEPARATOR . "moodle.xml";
     }
     $xml = simplexml_load_file($xmlfile);
     $fullname = $xml->xpath('/course/fullname');
     if (!$fullname) {
         $fullname = $xml->xpath('/MOODLE_BACKUP/COURSE/HEADER/FULLNAME');
     }
     $shortname = $xml->xpath('/course/shortname');
     if (!$shortname) {
         $shortname = $xml->xpath('/MOODLE_BACKUP/COURSE/HEADER/SHORTNAME');
     }
     $fullname = (string) $fullname[0];
     $shortname = (string) $shortname[0];
     if (!$shortname) {
         cli_error('No shortname in the backup file.');
     }
     if (!$fullname) {
         $fullname = $shortname;
     }
     // Get unique shortname if creating new course.
     if (!$options['existing'] && $DB->get_record('course', array('category' => $category->id, 'shortname' => $shortname))) {
         $matches = NULL;
         preg_match('/(.*)_(\\d+)$/', $shortname, $matches);
         if ($matches) {
             $base = $matches[1];
             $number = $matches[2];
         } else {
             $base = $shortname;
             $number = 1;
         }
         $shortname = $base . '_' . $number;
         while ($DB->get_record('course', array('category' => $category->id, 'shortname' => $shortname))) {
             $number++;
             $shortname = $base . '_' . $number;
         }
     }
     if ($options['existing']) {
         $courseid = $arguments[1];
         if ($options['overwrite']) {
             echo "Overwriting current content of existing course -> Course ID: {$courseid}\n";
             $rc = new restore_controller($backupdir, $courseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, 0);
         } else {
             echo "Adding backup to current content of existing course -> Course ID: {$courseid}\n";
             $rc = new restore_controller($backupdir, $courseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, backup::TARGET_CURRENT_ADDING);
         }
     } else {
         echo "Creating new course to restore backup\n";
         $courseid = restore_dbops::create_new_course($fullname, $shortname, $category->id);
         $rc = new restore_controller($backupdir, $courseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, backup::TARGET_NEW_COURSE);
     }
     echo "Restoring (new course id,shortname,destination category): {$courseid},{$shortname}," . $category->id . "\n";
     if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) {
         $rc->convert();
     }
     $plan = $rc->get_plan();
     $tasks = $plan->get_tasks();
     foreach ($tasks as &$task) {
         $setting = $task->get_setting('enrol_migratetomanual');
         $setting->set_value('1');
     }
     if (!$rc->execute_precheck()) {
         $check = $rc->get_precheck_results();
         cli_problem("Restore pre-check failed!");
         var_dump($check);
         die;
     }
     if ($options['existing'] && $options['overwrite']) {
         // If existing course shall be overwritten, delete current content
         $deletingoptions = array();
         $deletingoptions['keep_roles_and_enrolments'] = 0;
         $deletingoptions['keep_groups_and_groupings'] = 0;
         restore_dbops::delete_course_content($courseid, $deletingoptions);
     }
     $rc->execute_plan();
     $rc->destroy();
     echo "New course ID for '{$shortname}': {$courseid} in category {$category->id}\n";
 }