/** * Update grades by firing grade_updated event * * @param object $assignment null means all assignments * @param int $userid specific user only, 0 mean all */ function webquestscorm_update_grades($webquestscorm = null, $userid = 0, $nullifnone = true) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once $CFG->libdir . '/gradelib.php'; } if ($webquestscorm != null) { if ($grades = webquestscorm_get_user_grades($webquestscorm, $userid)) { foreach ($grades as $k => $v) { if ($v->rawgrade == -1) { $grades[$k]->rawgrade = null; } } webquestscorm_grade_item_update($webquestscorm, $grades); } else { webquestscorm_grade_item_update($webquestscorm); } } else { $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid\n FROM {$CFG->prefix}webquestscorm a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m\n WHERE m.name='webquestscorm' AND m.id=cm.module AND cm.instance=a.id"; if ($rs = get_recordset_sql($sql)) { while ($webquestscorm = rs_fetch_next_record($rs)) { if ($webquestscorm->grade != 0) { webquestscorm_update_grades($webquestscorm); } else { webquestscorm_grade_item_update($webquestscorm); } } rs_close($rs); } } }
/** * Specifies available report filters * (empty by default but can be implemented by child class) * * @param boolean $init_data If true, signal the report to load the * actual content of the filter objects * * @return array The list of available filters */ function get_filters($init_data = true) { global $CURMAN; //Get allowed curriculum list by capability $cms = array(); $contexts = get_contexts_by_capability_for_user('curriculum', $this->access_capability, $this->userid); $cms_objects = curriculum_get_listing_recordset('name', 'ASC', 0, 0, '', '', $contexts); if (!empty($cms_objects)) { while ($curriculum = rs_fetch_next_record($cms_objects)) { $cms[$curriculum->id] = $curriculum->name; } } $curricula_options = array('choices' => $cms, 'numeric' => false); //Create optional icon checkbox elements // 15 character name max length - with a 2 character field name - this is for any checkboxes filter $option_choices = array('tot_assignments' => get_string('option_tot_assignments', 'rlreport_course_usage_summary'), 'tot_crs_rscs' => get_string('option_tot_crs_rscs', 'rlreport_course_usage_summary'), 'tot_disc_posts' => get_string('option_tot_disc_posts', 'rlreport_course_usage_summary'), 'tot_quizzes' => get_string('option_tot_quizzes', 'rlreport_course_usage_summary'), 'avg_crs_grd' => get_string('option_avg_crs_grd', 'rlreport_course_usage_summary'), 'avg_hours_crs' => get_string('option_avg_hours_crs', 'rlreport_course_usage_summary'), 'avg_pretest' => get_string('option_avg_pretest', 'rlreport_course_usage_summary'), 'avg_posttest' => get_string('option_avg_posttest', 'rlreport_course_usage_summary')); $option_defaults = array('tot_assignments', 'tot_crs_rscs', 'tot_disc_posts', 'tot_quizzes', 'avg_crs_grd', 'avg_hours_crs', 'avg_pretest', 'avg_posttest'); $option_options = array('choices' => $option_choices, 'checked' => $option_defaults, 'heading' => get_string('filter_options_header', 'rlreport_course_usage_summary'), 'footer' => ''); $filter_entries = array(); $filter_entries[] = new generalized_filter_entry('cc', 'cc', 'id', get_string('filter_curricula', 'rlreport_course_usage_summary'), false, 'selectany', $curricula_options); $this->checkboxes_filter = new generalized_filter_entry('oe', 'oe', 'id', '', false, 'config_checkboxes', $option_options); $filter_entries[] = $this->checkboxes_filter; $filter_entries[] = new generalized_filter_entry('enrol', 'enrol', 'enrolmenttime', get_string('filter_course_date', 'rlreport_course_progress_summary'), false, 'date'); $filter_entries[] = new generalized_filter_entry('enrol', 'enrol', 'enrolmenttime', get_string('filter_course_date', 'rlreport_course_progress_summary'), false, 'date'); return $filter_entries; }
function block_openshare_updategroup($courseid, $groupid) { $sql = 'SELECT u.id FROM mdl_user u JOIN mdl_role_assignments ra ON ra.userid = u.id JOIN mdl_role r ON ra.roleid = r.id JOIN mdl_context con ON ra.contextid = con.id JOIN mdl_course c ON c.id = con.instanceid AND con.contextlevel = 50 WHERE (r.shortname = \'student\' OR r.shortname = \'teacher\' OR r.shortname = \'editingteacher\' OR r.shortname = \'coursecreator\') AND c.id = ' . $courseid; $rs = get_recordset_sql($sql); if (!empty($rs)) { while ($rec = rs_fetch_next_record($rs)) { //prep dataobject for door $groupenroll = new object(); $groupenroll->timeadded = time(); $groupenroll->groupid = $groupid; $groupenroll->userid = $rec->id; $ingroup = get_record("groups_members", "groupid", $groupid, "userid", $rec->id); if (empty($ingroup)) { insert_record("groups_members", $groupenroll); print 'updated' . $groupenroll->groupid . $groupenroll->userid . '<br/>'; } } } else { print_error("No users in this course!"); } // Close the recordset to save memory rs_close($rs); }
function print_filter(&$mform, $data) { global $CFG, $db; $columns = $db->MetaColumns($CFG->prefix . 'course'); $filteroptions = array(); $filteroptions[''] = get_string('choose'); $coursecolumns = array(); foreach ($columns as $c) { $coursecolumns[$c->name] = $c->name; } if (!isset($coursecolumns[$data->field])) { print_error('nosuchcolumn'); } $reportclassname = 'report_' . $this->report->type; $reportclass = new $reportclassname($this->report); $components = cr_unserialize($this->report->components); $conditions = $components['conditions']; $courselist = $reportclass->elements_by_conditions($conditions); if (!empty($courselist)) { if ($rs = get_recordset_sql('SELECT DISTINCT(' . $data->field . ') as ufield FROM ' . $CFG->prefix . 'course WHERE ' . $data->field . ' <> "" ORDER BY ufield ASC')) { while ($u = rs_fetch_next_record($rs)) { $filteroptions[base64_encode($u->ufield)] = $u->ufield; } } } $mform->addElement('select', 'filter_fcoursefield_' . $data->field, get_string($data->field), $filteroptions); $mform->setType('filter_courses', PARAM_INT); }
function definition() { global $CFG; $mform =& $this->_form; $report = $this->_customdata['report']; $options = array(); if ($report->type != 'sql') { $components = cr_unserialize($this->_customdata['report']->components); if (is_array($components) && !empty($components['columns']['elements'])) { $columns = $components['columns']['elements']; foreach ($columns as $c) { $options[] = $c['summary']; } } } else { require_once $CFG->dirroot . '/blocks/configurable_reports/report.class.php'; require_once $CFG->dirroot . '/blocks/configurable_reports/reports/' . $report->type . '/report.class.php'; $reportclassname = 'report_' . $report->type; $reportclass = new $reportclassname($report); $components = cr_unserialize($report->components); $config = isset($components['customsql']['config']) ? $components['customsql']['config'] : new stdclass(); if (isset($config->querysql)) { $sql = $config->querysql; $sql = $reportclass->prepare_sql($sql); if ($rs = $reportclass->execute_query($sql)) { $row = rs_fetch_next_record($rs); $i = 0; foreach ($row as $colname => $value) { $options[$i] = str_replace('_', ' ', $colname); $i++; } } } } $optionsenabled = array(0 => get_string('disabled', 'block_configurable_reports'), 1 => get_string('enabled', 'block_configurable_reports')); $mform->addElement('select', 'enabled', get_string('template', 'block_configurable_reports'), $optionsenabled); $mform->setDefault('enabled', 0); $mform->addElement('htmleditor', 'header', get_string('header', 'block_configurable_reports')); $mform->disabledIf('header', 'enabled', 'eq', 0); $mform->setHelpButton('header', array('template_marks', get_string('conditionexpr'), 'block_configurable_reports')); $availablemarksrec = ''; if ($options) { foreach ($options as $o) { $availablemarksrec .= "[[{$o}]] => {$o} <br />"; } } $mform->addElement('static', 'statictext', get_string('availablemarks', 'block_configurable_reports'), $availablemarksrec); $mform->addElement('htmleditor', 'record', get_string('templaterecord', 'block_configurable_reports')); $mform->disabledIf('record', 'enabled', 'eq', 0); $mform->addElement('htmleditor', 'footer', get_string('footer', 'block_configurable_reports')); $mform->disabledIf('footer', 'enabled', 'eq', 0); $mform->setHelpButton('footer', array('template_marks', get_string('conditionexpr'), 'block_configurable_reports')); //$mform->addRule('record', get_string('required'), 'required', null, 'client'); $mform->setType('header', PARAM_RAW); $mform->setType('record', PARAM_RAW); $mform->setType('footer', PARAM_RAW); $this->add_action_buttons(); }
/** * Run scheduled tasks according to a cron spec. */ function elis_cron() { global $CFG; require $CFG->dirroot . '/elis/core/lib/tasklib.php'; $timenow = time(); // get all tasks that are (over-)due $tasks = get_recordset_select('elis_scheduled_tasks', 'nextruntime <= ' . $timenow, 'nextruntime ASC'); if (empty($tasks)) { return; } while ($task = rs_fetch_next_record($tasks)) { $starttime = microtime(); mtrace("Running {$task->callfunction}({$task->taskname}) from {$task->plugin}..."); if ($task->enddate !== null && $task->enddate < $timenow) { mtrace('* Cancelling task: past end date'); delete_records('elis_scheduled_tasks', 'id', $task->id); continue; } // FIXME: check for blocking tasks // FIXME: check if task is locked // See if some other cron has already run the function while we were // doing something else -- if so, skip it. $nextrun = get_field('elis_scheduled_tasks', 'nextruntime', 'id', $task->id); if ($nextrun > $timenow) { mtrace('* Skipped (someone else already ran it)'); continue; } // calculate the next run time $newtask = new stdClass(); $newtask->id = $task->id; $newtask->lastruntime = time(); $newtask->nextruntime = cron_next_run_time($newtask->lastruntime, (array) $task); // see if we have any runs left if ($task->runsremaining !== null) { $newtask->runsremaining = $task->runsremaining - 1; if ($newtask->runsremaining <= 0) { mtrace('* Cancelling task: no runs left'); delete_records('elis_scheduled_tasks', 'id', $task->id); } else { update_record('elis_scheduled_tasks', $newtask); } } else { update_record('elis_scheduled_tasks', $newtask); } // load the file and call the function if ($task->callfile) { $callfile = $CFG->dirroot . $task->callfile; if (!is_readable($callfile)) { mtrace('* Skipped (file not found)'); continue; } require_once $callfile; } call_user_func(unserialize($task->callfunction), $task->taskname); $difftime = microtime_diff($starttime, microtime()); mtrace("* {$difftime} seconds"); } }
function get_all_elements() { $elements = array(); $rs = get_recordset('course_categories', '', '', '', 'id'); while ($course = rs_fetch_next_record($rs)) { $elements[] = $course->id; } return $elements; }
function get_all_elements() { $elements = array(); $rs = get_recordset('user', '', '', '', 'id'); while ($user = rs_fetch_next_record($rs)) { $elements[] = $user->id; } return $elements; }
function xmldb_forum_upgrade($oldversion = 0) { global $CFG, $THEME, $db; $result = true; /// And upgrade begins here. For each one, you'll need one /// block of code similar to the next one. Please, delete /// this comment lines once this file start handling proper /// upgrade code. /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php /// $result = result of "/lib/ddllib.php" function calls /// } if ($result && $oldversion < 2007101000) { /// Define field timemodified to be added to forum_queue $table = new XMLDBTable('forum_queue'); $field = new XMLDBField('timemodified'); $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'postid'); /// Launch add field timemodified $result = $result && add_field($table, $field); } //===== 1.9.0 upgrade line ======// if ($result and $oldversion < 2007101511) { notify('Processing forum grades, this may take a while if there are many forums...', 'notifysuccess'); //MDL-13866 - send forum ratins to gradebook again require_once $CFG->dirroot . '/mod/forum/lib.php'; // too much debug output $db->debug = false; forum_update_grades(); $db->debug = true; } if ($result && $oldversion < 2007101512) { /// Cleanup the forum subscriptions notify('Removing stale forum subscriptions', 'notifysuccess'); $roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW); $roles = array_keys($roles); $roles = implode(',', $roles); $sql = "SELECT fs.userid, f.id AS forumid\n FROM {$CFG->prefix}forum f\n JOIN {$CFG->prefix}course c ON c.id = f.course\n JOIN {$CFG->prefix}context ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = " . CONTEXT_COURSE . ")\n JOIN {$CFG->prefix}forum_subscriptions fs ON fs.forum = f.id\n LEFT JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = ctx.id AND ra.userid = fs.userid AND ra.roleid IN ({$roles}))\n WHERE ra.id IS NULL"; if ($rs = get_recordset_sql($sql)) { $db->debug = false; while ($remove = rs_fetch_next_record($rs)) { delete_records('forum_subscriptions', 'userid', $remove->userid, 'forum', $remove->forumid); echo '.'; } $db->debug = true; rs_close($rs); } } if ($result && $oldversion < 2007101513) { delete_records('forum_ratings', 'post', 0); /// Clean existing wrong rates. MDL-18227 } return $result; }
/** * Return a list of groups the user belongs to that apply to this forum (same grouping) * @param int $userid * @param int $forumid * @return an array of group lists or an empty array */ function get_group_list($userid, $forumid) { global $CFG; //$courseid = forum::get_from_id($forumng->id, forum::CLONE_DIRECT)->get_course_id(); $sql_group = "\nSELECT\n g.id AS groupid\nFROM\n {$CFG->prefix}forumng f\n INNER JOIN {$CFG->prefix}course_modules cm on f.id = cm.instance \n INNER JOIN {$CFG->prefix}modules m on cm.module = m.id \n INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid = {$userid} \n INNER JOIN {$CFG->prefix}groups g ON gm.groupid = g.id AND g.courseid = cm.course \n LEFT JOIN {$CFG->prefix}groupings_groups gg ON gg.groupid = g.id AND cm.groupingid = gg.groupingid \nWHERE\n f.id = {$forumid}\n AND m.name = 'forumng'\n AND (cm.groupingid = 0 or gg.id IS NOT NULL)"; $rs = forum_utils::get_recordset_sql($sql_group); $results = array(); while ($rec = rs_fetch_next_record($rs)) { $results[] = $rec->groupid; } rs_close($rs); return $results; }
function display_search_field($value = '') { global $CFG; $varcharlat = sql_compare_text('content'); $varcharlong = sql_compare_text('content1'); $latlongsrs = get_recordset_sql("SELECT DISTINCT {$varcharlat} AS la, {$varcharlong} AS lo\n FROM {$CFG->prefix}data_content\n WHERE fieldid = {$this->field->id}\n ORDER BY {$varcharlat}, {$varcharlong}"); $options = array(); while ($latlong = rs_fetch_next_record($latlongsrs)) { $options[$latlong->la . ',' . $latlong->lo] = $latlong->la . ',' . $latlong->lo; } rs_close($latlongsrs); return choose_from_menu($options, 'f_' . $this->field->id, $value, 'choose', '', 0, true); }
/** * Queries for draft posts, including necessary joins with other fields. * @param string $where Text of WHERE clause e.g. 'fdr.id=14'. May refer * to aliases fdr (drafts), fd (discussions), fp (posts; post being * replied to), fpfirst (first post in discussion), and u (user being * replied to) * @return array Array of forum_draft objects (empty if none) */ static function query_drafts($where) { global $CFG; $result = array(); $rs = get_recordset_sql("\nSELECT\n fdr.*, fd.id AS discussionid, fpfirst.subject AS discussionsubject, \n f.course AS courseid,\n " . forum_utils::select_username_fields('u', false) . "\nFROM\n {$CFG->prefix}forumng_drafts fdr\n LEFT JOIN {$CFG->prefix}forumng_posts fp ON fdr.parentpostid = fp.id\n LEFT JOIN {$CFG->prefix}forumng_discussions fd ON fp.discussionid = fd.id\n LEFT JOIN {$CFG->prefix}forumng_posts fpfirst ON fd.postid = fpfirst.id\n LEFT JOIN {$CFG->prefix}user u ON fp.userid = u.id\n INNER JOIN {$CFG->prefix}forumng f ON fdr.forumid = f.id\nWHERE\n {$where}\nORDER BY\n fdr.saved DESC\n "); if (!$rs) { throw new forum_exception("Failed to query for draft posts"); } while ($rec = rs_fetch_next_record($rs)) { $result[] = new forum_draft($rec); } rs_close($rs); return $result; }
function add_selection_all($ufiltering) { global $SESSION; $guest = get_guest(); $sqlwhere = $ufiltering->get_sql_filter("id<>{$guest->id} AND deleted <> 1"); if ($rs = get_recordset_select('user', $sqlwhere, 'fullname', 'id,' . sql_fullname() . ' AS fullname')) { while ($user = rs_fetch_next_record($rs)) { if (!isset($SESSION->bulk_users[$user->id])) { $SESSION->bulk_users[$user->id] = $user->id; } } rs_close($rs); } }
function create_report() { global $CFG; $components = cr_unserialize($this->config->components); $filters = isset($components['filters']['elements']) ? $components['filters']['elements'] : array(); $calcs = isset($components['calcs']['elements']) ? $components['calcs']['elements'] : array(); $tablehead = array(); $finalcalcs = array(); $finaltable = array(); $tablehead = array(); $components = cr_unserialize($this->config->components); $config = isset($components['customsql']['config']) ? $components['customsql']['config'] : new stdclass(); if (isset($config->querysql)) { // FILTERS $sql = $config->querysql; if (!empty($filters)) { foreach ($filters as $f) { require_once $CFG->dirroot . '/blocks/configurable_reports/components/filters/' . $f['pluginname'] . '/plugin.class.php'; $classname = 'plugin_' . $f['pluginname']; $class = new $classname($this->config); $sql = $class->execute($sql, $f['formdata']); } } $sql = $this->prepare_sql($sql); if ($rs = $this->execute_query($sql)) { while ($row = rs_fetch_next_record($rs)) { if (empty($finaltable)) { foreach ($row as $colname => $value) { $tablehead[] = str_replace('_', ' ', $colname); } } $finaltable[] = array_values((array) $row); } } } // Calcs $finalcalcs = $this->get_calcs($finaltable, $tablehead); $table = new stdclass(); $table->id = 'reporttable'; $table->data = $finaltable; $table->head = $tablehead; $calcs = new stdclass(); $calcs->data = array($finalcalcs); $calcs->head = $tablehead; $this->finalreport->table = $table; $this->finalreport->calcs = $calcs; return true; }
function sermon_alphabetical_get_one_node($letterstartnumber) { global $CFG, $COURSE, $alphabet; if (empty($letterstartnumber)) { return ''; } $extrawhere = array(); for ($x = 0; $x < NUMBER_OF_PARTION_LETTERS; $x++) { $extrawhere[] = "name LIKE '{$alphabet[$letterstartnumber + $x]}%' "; } //get the relavant sermons for this sermon series $sql = "SELECT r.*, rs.datedelivered, rs.seriesname, rs.book, rs.beginchapter, cm.id as `cmid`,\n rs.guestspeaker, rs.guestspeakername, rs.hitcounter, rs.lastaccess \n FROM {$CFG->prefix}resource r \n JOIN {$CFG->prefix}resource_sermon rs ON rs.resourceid = r.id\n JOIN {$CFG->prefix}course_modules cm ON cm.instance = r.id \n WHERE r.type = 'sermon' AND r.course = {$COURSE->id} AND name != '' "; $sql .= !empty($extrawhere) ? ' AND (' . implode(' OR ', $extrawhere) . ')' : ''; $sql .= " ORDER BY r.name ASC"; $sermons = get_recordset_sql($sql); //loop through and make them into an array of objecst compatible for a json_encode $letters = array(); while (($sermon = rs_fetch_next_record($sermons)) !== false) { if (empty($sermon->seriesname)) { $sermon->seriesname = 'no name'; } $sermon->datedelivered = date('m-d-Y', $sermon->datedelivered); $sermonnode = new stdClass(); $sermonnode->attributes = new stdClass(); $sermonnode->attributes->id = $sermon->cmid . '~' . sermon_block_make_name_safe_for_id($sermon->seriesname); $sermonnode->attributes->class = 'leaf sermon'; if (!empty($sermon->reference)) { $sermonnode->attributes->class .= ' mp3 '; } else { if (!empty($sermon->referencesermontext)) { $sermonnode->attributes->class .= ' text '; } else { if (!empty($sermon->referencelesson)) { $sermonnode->attributes->class .= ' lesson '; } } } $sermonnode->attributes->class .= rs_fetch_record($sermons) === false ? ' last ' : ''; $sermonnode->data = get_string('sermonleaf', 'resource', $sermon); $letters[] = $sermonnode; } $letters = array_values($letters); if (empty($letters)) { return ''; } return $letters; }
function add_form_elements(&$mform, $fullform) { global $CFG, $db; $components = cr_unserialize($fullform->_customdata['report']->components); $options = array(); if ($this->config->type != 'sql') { if (!is_array($components) || empty($components['columns']['elements'])) { print_error('nocolumns'); } $columns = $components['columns']['elements']; $calcs = isset($components['calcs']['elements']) ? $components['calcs']['elements'] : array(); $columnsused = array(); if ($calcs) { foreach ($calcs as $c) { $columnsused[] = $c['formdata']->column; } } $i = 0; foreach ($columns as $c) { if (!in_array($i, $columnsused)) { $options[$i] = $c['summary']; } $i++; } } else { require_once $CFG->dirroot . '/blocks/configurable_reports/report.class.php'; require_once $CFG->dirroot . '/blocks/configurable_reports/reports/' . $this->config->type . '/report.class.php'; $reportclassname = 'report_' . $this->config->type; $reportclass = new $reportclassname($this->config); $components = cr_unserialize($this->config->components); $config = isset($components['customsql']['config']) ? $components['customsql']['config'] : new stdclass(); if (isset($config->querysql)) { $sql = $config->querysql; $sql = $reportclass->prepare_sql($sql); if ($rs = $reportclass->execute_query($sql)) { $row = rs_fetch_next_record($rs); $i = 0; foreach ($row as $colname => $value) { $options[$i] = str_replace('_', ' ', $colname); $i++; } } } } $mform->addElement('header', '', get_string('coursefield', 'block_configurable_reports'), ''); $mform->addElement('select', 'column', get_string('column', 'block_configurable_reports'), $options); }
/** * Due to MDL-14750, subquestions of multianswer questions restored from backup will * have the wrong parent, and due to MDL-10899 subquestions of multianswer questions * that have been moved between categories will be in the wrong category, This code fixes these up. */ function question_multianswer_fix_subquestion_parents_and_categories() { global $CFG; $result = true; $rs = get_recordset_sql('SELECT q.id, q.category, qma.sequence FROM ' . $CFG->prefix . 'question q JOIN ' . $CFG->prefix . 'question_multianswer qma ON q.id = qma.question'); if ($rs) { while ($q = rs_fetch_next_record($rs)) { if (!empty($q->sequence)) { $result = $result && execute_sql('UPDATE ' . $CFG->prefix . 'question' . ' SET parent = ' . $q->id . ', category = ' . $q->category . ' WHERE id IN (' . $q->sequence . ') AND parent <> 0'); } } rs_close($rs); } else { $result = false; } return $result; }
function definition() { global $USER, $CFG; $mform =& $this->_form; $options = array(0 => get_string('choose')); $report = $this->_customdata['report']; if ($report->type != 'sql') { $components = cr_unserialize($this->_customdata['report']->components); if (!is_array($components) || empty($components['columns']['elements'])) { print_error('nocolumns'); } $columns = $components['columns']['elements']; foreach ($columns as $c) { $options[] = $c['summary']; } } else { require_once $CFG->dirroot . '/blocks/configurable_reports/report.class.php'; require_once $CFG->dirroot . '/blocks/configurable_reports/reports/' . $report->type . '/report.class.php'; $reportclassname = 'report_' . $report->type; $reportclass = new $reportclassname($report); $components = cr_unserialize($report->components); $config = isset($components['customsql']['config']) ? $components['customsql']['config'] : new stdclass(); if (isset($config->querysql)) { $sql = $config->querysql; $sql = $reportclass->prepare_sql($sql); if ($rs = $reportclass->execute_query($sql)) { $row = rs_fetch_next_record($rs); $i = 0; foreach ($row as $colname => $value) { $options[$i] = str_replace('_', ' ', $colname); $i++; } } } } $mform->addElement('header', '', get_string('linegraph', 'block_configurable_reports'), ''); $mform->addElement('select', 'xaxis', get_string('xaxis', 'block_configurable_reports'), $options); $mform->addRule('xaxis', null, 'required', null, 'client'); $mform->addElement('select', 'serieid', get_string('serieid', 'block_configurable_reports'), $options); $mform->addRule('serieid', null, 'required', null, 'client'); $mform->addElement('select', 'yaxis', get_string('yaxis', 'block_configurable_reports'), $options); $mform->addRule('yaxis', null, 'required', null, 'client'); $mform->addElement('checkbox', 'group', get_string('groupseries', 'block_configurable_reports')); // buttons $this->add_action_buttons(true, get_string('add')); }
function validation($data, $files) { global $CFG, $db, $USER; $errors = parent::validation($data, $files); $sql = stripslashes($data['querysql']); // Simple test to avoid evil stuff in the SQL. if (report_customsql_contains_bad_word($sql)) { $errors['querysql'] = get_string('notallowedwords', 'report_customsql', implode(', ', report_customsql_bad_words_list())); // Do not allow any semicolons. } else { if (strpos($sql, ';') !== false) { $errors['querysql'] = get_string('nosemicolon', 'report_customsql'); // Make sure prefix is prefix_, not explicit. } else { if ($CFG->prefix != '' && preg_match('/\\b' . $CFG->prefix . '\\w+/i', $sql)) { $errors['querysql'] = get_string('noexplicitprefix', 'report_customsql', $CFG->prefix); // Now try running the SQL, and ensure it runs without errors. } else { $report = new stdClass(); $report->querysql = $sql; $report->runable = $data['runable']; $sql = report_customsql_prepare_sql($report, time()); $rs = report_customsql_execute_query($sql, 2); if (!$rs) { $errors['querysql'] = get_string('queryfailed', 'report_customsql', $db->ErrorMsg()); } else { if (!empty($data['singlerow'])) { if (rs_EOF($rs)) { $errors['querysql'] = get_string('norowsreturned', 'report_customsql'); } else { rs_fetch_next_record($rs); if (!rs_EOF($rs)) { $errors['querysql'] = get_string('morethanonerowreturned', 'report_customsql'); } } } } if ($rs) { rs_close($rs); } } } } return $errors; }
function sermon_series_get_one_node($seriesname) { global $CFG, $COURSE; if (empty($seriesname)) { return ''; } //get the relavant sermons for this sermon series $sql = "SELECT r.*, rs.datedelivered, rs.seriesname, rs.book, rs.beginchapter, cm.id as `cmid`,\n rs.guestspeaker, rs.guestspeakername, rs.hitcounter, rs.lastaccess \n FROM {$CFG->prefix}resource r \n JOIN {$CFG->prefix}resource_sermon rs ON rs.resourceid = r.id\n JOIN {$CFG->prefix}course_modules cm ON cm.instance = r.id \n WHERE r.type = 'sermon' AND r.course = {$COURSE->id} AND name != '' AND rs.seriesname = '{$seriesname}'\n ORDER BY rs.seriesname ASC, rs.datedelivered DESC"; $sermons = get_recordset_sql($sql); //loop through and make them into an array of objecst compatible for a json_encode $series = array(); while (($sermon = rs_fetch_next_record($sermons)) !== false) { if (empty($sermon->seriesname)) { $sermon->seriesname = 'no name'; } //clean up some variable // $sermon->seriesname = stripslashes($sermon->seriesname); // $sermon->name = stripslashes($sermon->name); $sermon->datedelivered = date('m-d-Y', $sermon->datedelivered); $sermonnode = new stdClass(); $sermonnode->attributes = new stdClass(); $sermonnode->attributes->id = $sermon->cmid . '~' . sermon_block_make_name_safe_for_id($sermon->seriesname); $sermonnode->attributes->class = 'leaf sermon'; if (!empty($sermon->reference)) { $sermonnode->attributes->class .= ' mp3 '; } else { if (!empty($sermon->referencesermontext)) { $sermonnode->attributes->class .= ' text '; } else { if (!empty($sermon->referencelesson)) { $sermonnode->attributes->class .= ' lesson '; } } } $sermonnode->attributes->class .= rs_fetch_record($sermons) === false ? ' last ' : ''; $sermonnode->data = get_string('sermonleaf', 'resource', $sermon); $series[] = $sermonnode; } $series = array_values($series); if (empty($series)) { return ''; } return $series; }
function summary($data) { global $CFG; if ($this->report->type != 'sql') { $components = cr_unserialize($this->report->components); if (!is_array($components) || empty($components['columns']['elements'])) { print_error('nocolumns'); } $columns = $components['columns']['elements']; $i = 0; foreach ($columns as $c) { if ($i == $data->column) { return $c['summary']; } $i++; } } else { require_once $CFG->dirroot . '/blocks/configurable_reports/report.class.php'; require_once $CFG->dirroot . '/blocks/configurable_reports/reports/' . $this->report->type . '/report.class.php'; $reportclassname = 'report_' . $this->report->type; $reportclass = new $reportclassname($this->report); $components = cr_unserialize($this->report->components); $config = isset($components['customsql']['config']) ? $components['customsql']['config'] : new stdclass(); if (isset($config->querysql)) { $sql = $config->querysql; $sql = $reportclass->prepare_sql($sql); if ($rs = $reportclass->execute_query($sql)) { $row = rs_fetch_next_record($rs); $i = 0; foreach ($row as $colname => $value) { if ($i == $data->column) { return str_replace('_', ' ', $colname); } $i++; } } } } return ''; }
function report_customsql_generate_csv($report, $timenow, $limitnum = REPORT_CUSTOMSQL_MAX_RECORDS) { global $db; $starttime = microtime(true); $sql = report_customsql_prepare_sql($report, $timenow); $rs = report_customsql_execute_query($sql, $limitnum); if (!$rs) { throw new Exception($db->ErrorMsg()); } $cvstimestamp = null; while ($row = rs_fetch_next_record($rs)) { if (!$cvstimestamp) { list($csvfilename, $cvstimestamp) = report_customsql_csv_filename($report, $timenow); if (!file_exists($csvfilename)) { $handle = fopen($csvfilename, 'w'); report_customsql_start_csv($handle, $row, $report->singlerow); } else { $handle = fopen($csvfilename, 'a'); } } $data = get_object_vars($row); if ($report->singlerow) { array_unshift($data, strftime('%Y-%m-%d', $timenow)); } report_customsql_write_csv_row($handle, $data); } rs_close($rs); if (!empty($handle)) { fclose($handle); } // Update the execution time in the DB. $updaterecord = new stdClass(); $updaterecord->id = $report->id; $updaterecord->lastrun = time(); $updaterecord->lastexecutiontime = round((microtime(true) - $starttime) * 1000); update_record('report_customsql_queries', $updaterecord); return $cvstimestamp; }
/** * Notify users about enrolments that are going to expire soon! * This function is run by admin/cron.php * @return void */ function cron() { global $CFG, $USER, $SITE; if (!isset($CFG->lastexpirynotify)) { set_config('lastexpirynotify', 0); } // notify once a day only - TODO: add some tz handling here, maybe use timestamps if ($CFG->lastexpirynotify == date('Ymd')) { return; } if ($rs = get_recordset_select('course', 'enrolperiod > 0 AND expirynotify > 0 AND expirythreshold > 0')) { $cronuser = clone $USER; $admin = get_admin(); while ($course = rs_fetch_next_record($rs)) { $a = new object(); $a->coursename = $course->shortname . '/' . $course->fullname; // must be processed by format_string later $a->threshold = $course->expirythreshold / 86400; $a->extendurl = $CFG->wwwroot . '/user/index.php?id=' . $course->id; $a->current = array(); $a->past = array(); $expiry = time() + $course->expirythreshold; $cname = $course->fullname; /// Get all the manual role assignments for this course that have expired. if (!($context = get_context_instance(CONTEXT_COURSE, $course->id))) { continue; } if ($oldenrolments = get_records_sql("\n SELECT u.*, ra.timeend\n FROM {$CFG->prefix}user u\n JOIN {$CFG->prefix}role_assignments ra ON (ra.userid = u.id)\n WHERE ra.contextid = {$context->id}\n AND ra.timeend > 0 AND ra.timeend <= {$expiry}\n AND ra.enrol = 'manual'")) { // inform user who can assign roles or admin if ($teachers = get_users_by_capability($context, 'moodle/role:assign', '', '', '', '', '', '', false)) { $teachers = sort_by_roleassignment_authority($teachers, $context); $teacher = reset($teachers); } else { $teachers = array($admin); $teacher = $admin; } $a->teacherstr = fullname($teacher, true); foreach ($oldenrolments as $user) { /// Email all users about to expire $a->studentstr = fullname($user, true); if ($user->timeend < $expiry - 86400) { $a->past[] = fullname($user) . " <{$user->email}>"; } else { $a->current[] = fullname($user) . " <{$user->email}>"; if ($course->notifystudents) { // Send this guy notice // setup global $COURSE properly - needed for languages $USER = $user; course_setup($course); $a->coursename = format_string($cname); $a->course = $a->coursename; $strexpirynotifystudentsemail = get_string('expirynotifystudentsemail', '', $a); $strexpirynotify = get_string('expirynotify'); email_to_user($user, $teacher, format_string($SITE->fullname) . ' ' . $strexpirynotify, $strexpirynotifystudentsemail); } } } $a->current = implode("\n", $a->current); $a->past = implode("\n", $a->past); if ($a->current || $a->past) { foreach ($teachers as $teacher) { // setup global $COURSE properly - needed for languages $USER = $teacher; course_setup($course); $a->coursename = format_string($cname); $strexpirynotifyemail = get_string('expirynotifyemail', '', $a); $strexpirynotify = get_string('expirynotify'); email_to_user($teacher, $admin, $a->coursename . ' ' . $strexpirynotify, $strexpirynotifyemail); } } } } $USER = $cronuser; course_setup($SITE); // More environment } set_config('lastexpirynotify', date('Ymd')); }
/** * Factory method - uses the parameters to retrieve all matching instances from the DB. * @static final protected * @return mixed array of object instances or false if not found */ function fetch_all_helper($table, $classname, $params) { $instance = new $classname(); $classvars = (array) $instance; $params = (array) $params; $wheresql = array(); // remove incorrect params foreach ($params as $var => $value) { if (!in_array($var, $instance->required_fields) and !array_key_exists($var, $instance->optional_fields)) { continue; } if (is_null($value)) { $wheresql[] = " {$var} IS NULL "; } else { $value = addslashes($value); $wheresql[] = " {$var} = '{$value}' "; } } if (empty($wheresql)) { $wheresql = ''; } else { $wheresql = implode("AND", $wheresql); } if ($rs = get_recordset_select($table, $wheresql, 'id')) { $result = array(); while ($data = rs_fetch_next_record($rs)) { $instance = new $classname(); grade_object::set_properties($instance, $data); $result[$instance->id] = $instance; } rs_close($rs); return $result; } else { return false; } }
if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = get_recordset_sql("SELECT id, firstname, lastname\n FROM {$CFG->prefix}user\n WHERE confirmed = 0\n AND firstaccess > 0\n AND firstaccess < {$cuttime}"); while ($user = rs_fetch_next_record($rs)) { if (delete_records('user', 'id', $user->id)) { mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } } rs_close($rs); } flush(); /// Delete users who haven't completed profile within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = get_recordset_sql("SELECT id, username\n FROM {$CFG->prefix}user\n WHERE confirmed = 1\n AND lastaccess > 0\n AND lastaccess < {$cuttime}\n AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')"); while ($user = rs_fetch_next_record($rs)) { if (delete_records('user', 'id', $user->id)) { mtrace("Deleted not fully setup user {$user->username} ({$user->id})"); } } rs_close($rs); } flush(); /// Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; if (delete_records_select("log", "time < '{$loglifetime}'")) { mtrace("Deleted old log records"); } }
function survey_print_recent_activity($course, $viewfullnames, $timestart) { global $CFG; $modinfo = get_fast_modinfo($course); $ids = array(); foreach ($modinfo->cms as $cm) { if ($cm->modname != 'survey') { continue; } if (!$cm->uservisible) { continue; } $ids[$cm->instance] = $cm->instance; } if (!$ids) { return false; } $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right? if (!($rs = get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,\n u.firstname, u.lastname, u.email, u.picture\n FROM {$CFG->prefix}survey_answers sa\n JOIN {$CFG->prefix}user u ON u.id = sa.userid\n WHERE sa.survey IN ({$slist}) AND sa.time > {$timestart}\n GROUP BY sa.userid, sa.survey, u.firstname, u.lastname, u.email, u.picture\n ORDER BY time ASC"))) { return false; } $surveys = array(); while ($survey = rs_fetch_next_record($rs)) { $cm = $modinfo->instances['survey'][$survey->survey]; $survey->name = $cm->name; $survey->cmid = $cm->id; $surveys[] = $survey; } rs_close($rs); if (!$surveys) { return false; } print_headline(get_string('newsurveyresponses', 'survey') . ':'); foreach ($surveys as $survey) { $url = $CFG->wwwroot . '/mod/survey/view.php?id=' . $survey->cmid; print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames); } return true; }
/** * Update grades by firing grade_updated event * * @param object $assignment null means all assignments * @param int $userid specific user only, 0 mean all */ function assignment_update_grades($assignment = null, $userid = 0, $nullifnone = true) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once $CFG->libdir . '/gradelib.php'; } if ($assignment != null) { if ($grades = assignment_get_user_grades($assignment, $userid)) { foreach ($grades as $k => $v) { if ($v->rawgrade == -1) { $grades[$k]->rawgrade = null; } } assignment_grade_item_update($assignment); grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades); } } else { $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid\n FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m\n WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id"; if ($rs = get_recordset_sql($sql)) { if ($rs->RecordCount() > 0) { while ($assignment = rs_fetch_next_record($rs)) { assignment_grade_item_update($assignment); if ($assignment->grade != 0) { assignment_update_grades($assignment); } } } rs_close($rs); } } }
/** * Clean up the tag tables, making sure all tagged object still exists. * * This should normally not be necessary, but in case related tags are not deleted * when the tagged record is removed, this should be done once in a while, perhaps on * an occasional cron run. On a site with lots of tags, this could become an expensive * function to call: don't run at peak time. */ function tag_cleanup() { global $CFG; $instances = get_recordset('tag_instance'); // cleanup tag instances while ($instance = rs_fetch_next_record($instances)) { $delete = false; if (!record_exists('tag', 'id', $instance->tagid)) { // if the tag has been removed, instance should be deleted. $delete = true; } else { switch ($instance->itemtype) { case 'user': // users are marked as deleted, but not actually deleted if (record_exists('user', 'id', $instance->itemid, 'deleted', 1)) { $delete = true; } break; default: // anything else, if the instance is not there, delete. if (!record_exists($instance->itemtype, 'id', $instance->itemid)) { $delete = true; } break; } } if ($delete) { tag_delete_instance($instance->itemtype, $instance->itemid, $instance->tagid); //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER); } } rs_close($instances); // TODO: this will only clean tags of type 'default'. This is good as // it won't delete 'official' tags, but the day we get more than two // types, we need to fix this. $unused_tags = get_recordset_sql("SELECT tg.id FROM {$CFG->prefix}tag tg WHERE tg.tagtype = 'default' AND NOT EXISTS (" . "SELECT 'x' FROM {$CFG->prefix}tag_instance ti WHERE ti.tagid = tg.id)"); // cleanup tags while ($unused_tag = rs_fetch_next_record($unused_tags)) { tag_delete($unused_tag->id); //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER); } rs_close($unused_tags); }
function assignment_print_overview($courses, &$htmlarray) { global $USER, $CFG; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($assignments = get_all_instances_in_courses('assignment', $courses))) { return; } $assignmentids = array(); // Do assignment_base::isopen() here without loading the whole thing for speed foreach ($assignments as $key => $assignment) { $time = time(); if ($assignment->timedue) { if ($assignment->preventlate) { $isopen = $assignment->timeavailable <= $time && $time <= $assignment->timedue; } else { $isopen = $assignment->timeavailable <= $time; } } if (empty($isopen) || empty($assignment->timedue)) { unset($assignments[$key]); } else { $assignmentids[] = $assignment->id; } } if (empty($assignmentids)) { // no assigments to look at - we're done return true; } $strduedate = get_string('duedate', 'assignment'); $strduedateno = get_string('duedateno', 'assignment'); $strgraded = get_string('graded', 'assignment'); $strnotgradedyet = get_string('notgradedyet', 'assignment'); $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment'); $strsubmitted = get_string('submitted', 'assignment'); $strassignment = get_string('modulename', 'assignment'); $strreviewed = get_string('reviewed', 'assignment'); // NOTE: we do all possible database work here *outside* of the loop to ensure this scales // build up and array of unmarked submissions indexed by assigment id/ userid // for use where the user has grading rights on assigment $rs = get_recordset_sql("SELECT id, assignment, userid \n FROM {$CFG->prefix}assignment_submissions\n WHERE teacher = 0 AND timemarked = 0\n AND assignment IN (" . implode(',', $assignmentids) . ")"); $unmarkedsubmissions = array(); while ($ra = rs_fetch_next_record($rs)) { $unmarkedsubmissions[$ra->assignment][$ra->userid] = $ra->id; } rs_close($rs); // get all user submissions, indexed by assigment id $mysubmissions = get_records_sql("SELECT assignment, timemarked, teacher, grade\n FROM {$CFG->prefix}assignment_submissions \n WHERE userid = {$USER->id} AND \n assignment IN (" . implode(',', $assignmentids) . ")"); foreach ($assignments as $assignment) { $str = '<div class="assignment overview"><div class="name">' . $strassignment . ': ' . '<a ' . ($assignment->visible ? '' : ' class="dimmed"') . 'title="' . $strassignment . '" href="' . $CFG->wwwroot . '/mod/assignment/view.php?id=' . $assignment->coursemodule . '">' . $assignment->name . '</a></div>'; if ($assignment->timedue) { $str .= '<div class="info">' . $strduedate . ': ' . userdate($assignment->timedue) . '</div>'; } else { $str .= '<div class="info">' . $strduedateno . '</div>'; } $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule); if (has_capability('mod/assignment:grade', $context)) { // count how many people can submit $submissions = 0; // init if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) { foreach ($students as $student) { if (isset($unmarkedsubmissions[$assignment->id][$student->id])) { $submissions++; } } } if ($submissions) { $str .= get_string('submissionsnotgraded', 'assignment', $submissions); } } else { if (isset($mysubmissions[$assignment->id])) { $submission = $mysubmissions[$assignment->id]; if ($submission->teacher == 0 && $submission->timemarked == 0) { $str .= $strsubmitted . ', ' . $strnotgradedyet; } else { if ($submission->grade <= 0) { $str .= $strsubmitted . ', ' . $strreviewed; } else { $str .= $strsubmitted . ', ' . $strgraded; } } } else { $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue); } } $str .= '</div>'; if (empty($htmlarray[$assignment->course]['assignment'])) { $htmlarray[$assignment->course]['assignment'] = $str; } else { $htmlarray[$assignment->course]['assignment'] .= $str; } } }
/** * Daily cron. It executes at settlement time (default is 00:05). * * @access private */ function cron_daily() { global $CFG, $SITE; require_once $CFG->dirroot . '/enrol/authorize/authorizenetlib.php'; $oneday = 86400; $timenow = time(); $onepass = $timenow - $oneday; $settlementtime = authorize_getsettletime($timenow); $timediff30 = $settlementtime - 30 * $oneday; // Delete orders that no transaction was made. $select = "(status='" . AN_STATUS_NONE . "') AND (timecreated<'{$timediff30}')"; delete_records_select('enrol_authorize', $select); // Pending orders are expired with in 30 days. $select = "(status='" . AN_STATUS_AUTH . "') AND (timecreated<'{$timediff30}')"; execute_sql("UPDATE {$CFG->prefix}enrol_authorize SET status='" . AN_STATUS_EXPIRE . "' WHERE {$select}", false); // Delete expired orders 60 days later. $timediff60 = $settlementtime - 60 * $oneday; $select = "(status='" . AN_STATUS_EXPIRE . "') AND (timecreated<'{$timediff60}')"; delete_records_select('enrol_authorize', $select); // XXX TODO SEND EMAIL to 'enrol/authorize:uploadcsv' // get_users_by_capability() does not handling user level resolving // After user resolving, get_admin() to get_users_by_capability() $adminuser = get_admin(); $select = "status IN(" . AN_STATUS_UNDERREVIEW . "," . AN_STATUS_APPROVEDREVIEW . ") AND (timecreated<'{$onepass}') AND (timecreated>'{$timediff60}')"; $count = count_records_select('enrol_authorize', $select); if ($count) { $a = new stdClass(); $a->count = $count; $a->course = $SITE->shortname; $subject = get_string('pendingechecksubject', 'enrol_authorize', $a); $a = new stdClass(); $a->count = $count; $a->url = $CFG->wwwroot . '/enrol/authorize/uploadcsv.php'; $message = get_string('pendingecheckemail', 'enrol_authorize', $a); @email_to_user($adminuser, $adminuser, $subject, $message); } // Daily warning email for pending orders expiring. if (empty($CFG->an_emailexpired)) { return; // not enabled } // Pending orders count will be expired. $timediffem = $settlementtime - (30 - intval($CFG->an_emailexpired)) * $oneday; $select = "(status='" . AN_STATUS_AUTH . "') AND (timecreated<'{$timediffem}') AND (timecreated>'{$timediff30}')"; $count = count_records_select('enrol_authorize', $select); if (!$count) { return; } // Email to admin $a = new stdClass(); $a->pending = $count; $a->days = $CFG->an_emailexpired; $a->course = $SITE->shortname; $subject = get_string('pendingorderssubject', 'enrol_authorize', $a); $a = new stdClass(); $a->pending = $count; $a->days = $CFG->an_emailexpired; $a->course = $SITE->fullname; $a->enrolurl = "{$CFG->wwwroot}/{$CFG->admin}/enrol_config.php?enrol=authorize"; $a->url = $CFG->wwwroot . '/enrol/authorize/index.php?status=' . AN_STATUS_AUTH; $message = get_string('pendingordersemail', 'enrol_authorize', $a); email_to_user($adminuser, $adminuser, $subject, $message); // Email to teachers if (empty($CFG->an_emailexpiredteacher)) { return; // email feature disabled for teachers. } $sorttype = empty($CFG->an_sorttype) ? 'ttl' : $CFG->an_sorttype; $sql = "SELECT e.courseid, e.currency, c.fullname, c.shortname,\n COUNT(e.courseid) AS cnt, SUM(e.amount) as ttl\n FROM {$CFG->prefix}enrol_authorize e\n INNER JOIN {$CFG->prefix}course c ON c.id = e.courseid\n WHERE (e.status = " . AN_STATUS_AUTH . ")\n AND (e.timecreated < {$timediffem})\n AND (e.timecreated > {$timediff30})\n GROUP BY e.courseid\n ORDER BY {$sorttype} DESC"; for ($rs = get_recordset_sql($sql); $courseinfo = rs_fetch_next_record($rs);) { $lastcourse = $courseinfo->courseid; $context = get_context_instance(CONTEXT_COURSE, $lastcourse); if ($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments')) { $a = new stdClass(); $a->course = $courseinfo->shortname; $a->pending = $courseinfo->cnt; $a->days = $CFG->an_emailexpired; $subject = get_string('pendingorderssubject', 'enrol_authorize', $a); $a = new stdClass(); $a->course = $courseinfo->fullname; $a->pending = $courseinfo->cnt; $a->currency = $courseinfo->currency; $a->sumcost = $courseinfo->ttl; $a->days = $CFG->an_emailexpired; $a->url = $CFG->wwwroot . '/enrol/authorize/index.php?course=' . $lastcourse . '&status=' . AN_STATUS_AUTH; $message = get_string('pendingordersemailteacher', 'enrol_authorize', $a); foreach ($paymentmanagers as $paymentmanager) { email_to_user($paymentmanager, $adminuser, $subject, $message); } } } rs_close($rs); }