function test_record_exists_sql() { global $CFG; $this->assertTrue(record_exists_sql("SELECT * FROM {$CFG->prefix}{$this->table} WHERE numberfield = 101 AND id = 1")); $this->assertFalse(record_exists_sql("SELECT * FROM {$CFG->prefix}{$this->table} WHERE numberfield = 102 AND id = 1")); $this->assertTrue(record_exists_sql("SELECT * FROM {$CFG->prefix}{$this->table} WHERE numberfield IS NULL")); }
function forgotpass_validate(Pieform $form, $values) { // See if the user input an email address or a username. We favour email addresses if (!$form->get_error('emailusername')) { // Check if the user who associates to username or email address is using the external authentication if (record_exists_sql('SELECT u.authinstance FROM {usr} u INNER JOIN {auth_instance} ai ON (u.authinstance = ai.id) WHERE (LOWER(u.email) = ? OR LOWER(u.username) = ?) AND ((ai.authname != \'internal\') AND (ai.authname != \'none\'))', array_fill(0, 2, strtolower($values['emailusername'])))) { $form->set_error('emailusername', get_string('forgotpassuserusingexternalauthentication', 'mahara', get_config('wwwroot') . 'contact.php')); } else { if (!($authinstance = get_field_sql('SELECT u.authinstance FROM {usr} u INNER JOIN {auth_instance} ai ON (u.authinstance = ai.id) WHERE (LOWER(u.email) = ? OR LOWER(u.username) = ?) AND ai.authname = \'internal\'', array_fill(0, 2, strtolower($values['emailusername']))))) { $form->set_error('emailusername', get_string('forgotpassnosuchemailaddressorusername')); } } } if ($form->get_error('emailusername')) { return; } $authobj = AuthFactory::create($authinstance); if (!method_exists($authobj, 'change_password')) { die_info(get_string('cantchangepassword')); } }
function isAttemptLeftOpen($cmid, $userid) { $result = false; $cm = get_record('course_modules', 'id', $cmid); $sql = 'select * from mdl_quiz_attempts where userid = ' . $userid . ' and quiz =' . $cm->instance . ' and timefinish = 0'; if (record_exists_sql($sql)) { $result = true; } return $result; }
function artefact_in_view($artefact, $view) { $sql = 'SELECT a.id FROM {view_artefact} a WHERE "view" = ? AND artefact = ? UNION SELECT c.parent FROM {view_artefact} top JOIN {artefact_parent_cache} c ON c.parent = top.artefact WHERE top.view = ? AND c.artefact = ? UNION SELECT s.id FROM {view} v INNER JOIN {skin} s ON v.skin = s.id WHERE v.id = ? AND ? in (s.bodybgimg, s.viewbgimg) '; return record_exists_sql($sql, array($view, $artefact, $view, $artefact, $view, $artefact)); }
/** * Dummy can_do method for viewing a curriculum report (needed for the * cluster tree parameter for reports) */ function can_do_viewreport() { global $CFG, $CURMAN; $id = $this->required_param('id', PARAM_INT); //needed for execution mode constants require_once $CFG->dirroot . '/blocks/php_report/php_report_base.php'; //check if we're scheduling or viewing $execution_mode = $this->optional_param('execution_mode', php_report::EXECUTION_MODE_SCHEDULED, PARAM_INT); //check the correct capability $capability = $execution_mode == php_report::EXECUTION_MODE_SCHEDULED ? 'block/php_report:schedule' : 'block/php_report:view'; if ($this->_has_capability($capability)) { return true; } /* * Start of cluster hierarchy extension */ $viewable_clusters = cluster::get_viewable_clusters($capability); $cluster_context_level = context_level_base::get_custom_context_level('cluster', 'block_curr_admin'); $like = sql_ilike(); $parent_path = sql_concat('parent_context.path', "'/%'"); //if the user has no additional access through parent clusters, then they can't view this cluster if (empty($viewable_clusters)) { return false; } $cluster_filter = implode(',', $viewable_clusters); //determine if this cluster is the parent of some accessible child cluster $sql = "SELECT parent_context.instanceid\n FROM {$CURMAN->db->prefix_table('context')} parent_context\n JOIN {$CURMAN->db->prefix_table('context')} child_context\n ON child_context.path {$like} {$parent_path}\n AND parent_context.contextlevel = {$cluster_context_level}\n AND child_context.contextlevel = {$cluster_context_level}\n AND child_context.instanceid IN ({$cluster_filter})\n AND parent_context.instanceid = {$id}"; return record_exists_sql($sql); /* * End of cluster hierarchy extension */ }
function backup_general_info($bf, $preferences) { global $CFG; fwrite($bf, start_tag("INFO", 1, true)); //The name of the backup fwrite($bf, full_tag("NAME", 2, false, $preferences->backup_name)); //The moodle_version fwrite($bf, full_tag("MOODLE_VERSION", 2, false, $preferences->moodle_version)); fwrite($bf, full_tag("MOODLE_RELEASE", 2, false, $preferences->moodle_release)); //The backup_version fwrite($bf, full_tag("BACKUP_VERSION", 2, false, $preferences->backup_version)); fwrite($bf, full_tag("BACKUP_RELEASE", 2, false, $preferences->backup_release)); //The date fwrite($bf, full_tag("DATE", 2, false, $preferences->backup_unique_code)); //The original site wwwroot fwrite($bf, full_tag("ORIGINAL_WWWROOT", 2, false, $CFG->wwwroot)); //The original site identifier. MD5 hashed for security. fwrite($bf, full_tag("ORIGINAL_SITE_IDENTIFIER_HASH", 2, false, md5(get_site_identifier()))); //The zip method used if (!empty($CFG->zip)) { $zipmethod = 'external'; } else { $zipmethod = 'internal'; } //Indicate if it includes external MNET users $sql = "SELECT b.old_id\n FROM {$CFG->prefix}backup_ids b\n JOIN {$CFG->prefix}user u ON b.old_id=u.id\n WHERE b.backup_code = '{$preferences->backup_unique_code}'\n AND b.table_name = 'user' AND u.mnethostid != '{$CFG->mnet_localhost_id}'"; if (record_exists_sql($sql)) { fwrite($bf, full_tag("MNET_REMOTEUSERS", 2, false, 'true')); } fwrite($bf, full_tag("ZIP_METHOD", 2, false, $zipmethod)); //Te includes tag fwrite($bf, start_tag("DETAILS", 2, true)); //Now, go to mod element of preferences to print its status foreach ($preferences->mods as $element) { //Calculate info $included = "false"; $userinfo = "false"; if ($element->backup) { $included = "true"; if ($element->userinfo) { $userinfo = "true"; } } //Prints the mod start fwrite($bf, start_tag("MOD", 3, true)); fwrite($bf, full_tag("NAME", 4, false, $element->name)); fwrite($bf, full_tag("INCLUDED", 4, false, $included)); fwrite($bf, full_tag("USERINFO", 4, false, $userinfo)); if (isset($preferences->mods[$element->name]->instances) && is_array($preferences->mods[$element->name]->instances) && count($preferences->mods[$element->name]->instances)) { fwrite($bf, start_tag("INSTANCES", 4, true)); foreach ($preferences->mods[$element->name]->instances as $id => $object) { if (!empty($object->backup)) { //Calculate info $included = "false"; $userinfo = "false"; if ($object->backup) { $included = "true"; if ($object->userinfo) { $userinfo = "true"; } } fwrite($bf, start_tag("INSTANCE", 5, true)); fwrite($bf, full_tag("ID", 5, false, $id)); fwrite($bf, full_tag("NAME", 5, false, $object->name)); fwrite($bf, full_tag("INCLUDED", 5, false, $included)); fwrite($bf, full_tag("USERINFO", 5, false, $userinfo)); fwrite($bf, end_tag("INSTANCE", 5, true)); } } fwrite($bf, end_tag("INSTANCES", 4, true)); } //Print the end fwrite($bf, end_tag("MOD", 3, true)); } //The metacourse in backup if ($preferences->backup_metacourse == 1) { fwrite($bf, full_tag("METACOURSE", 3, false, "true")); } else { fwrite($bf, full_tag("METACOURSE", 3, false, "false")); } //The user in backup if ($preferences->backup_users == 1) { fwrite($bf, full_tag("USERS", 3, false, "course")); } else { if ($preferences->backup_users == 0) { fwrite($bf, full_tag("USERS", 3, false, "all")); } else { fwrite($bf, full_tag("USERS", 3, false, "none")); } } //The logs in backup if ($preferences->backup_logs == 1) { fwrite($bf, full_tag("LOGS", 3, false, "true")); } else { fwrite($bf, full_tag("LOGS", 3, false, "false")); } //The user files if ($preferences->backup_user_files == 1) { fwrite($bf, full_tag("USERFILES", 3, false, "true")); } else { fwrite($bf, full_tag("USERFILES", 3, false, "false")); } //The course files if ($preferences->backup_course_files == 1) { fwrite($bf, full_tag("COURSEFILES", 3, false, "true")); } else { fwrite($bf, full_tag("COURSEFILES", 3, false, "false")); } //The site files if ($preferences->backup_site_files == 1) { fwrite($bf, full_tag("SITEFILES", 3, false, "true")); } else { fwrite($bf, full_tag("SITEFILES", 3, false, "false")); } //The gradebook histories if (empty($CFG->disablegradehistory) && $preferences->backup_gradebook_history == 1) { fwrite($bf, full_tag("GRADEBOOKHISTORIES", 3, false, "true")); } else { fwrite($bf, full_tag("GRADEBOOKHISTORIES", 3, false, "false")); } //The messages in backup if ($preferences->backup_messages == 1 && $preferences->backup_course == SITEID) { fwrite($bf, full_tag("MESSAGES", 3, false, "true")); } else { fwrite($bf, full_tag("MESSAGES", 3, false, "false")); } //The blogs in backup if ($preferences->backup_blogs == 1 && $preferences->backup_course == SITEID) { fwrite($bf, full_tag("BLOGS", 3, false, "true")); } else { fwrite($bf, full_tag("BLOGS", 3, false, "false")); } //The mode of writing the block data fwrite($bf, full_tag('BLOCKFORMAT', 3, false, 'instances')); fwrite($bf, end_tag("DETAILS", 2, true)); $status = fwrite($bf, end_tag("INFO", 1, true)); ///Roles stuff goes in here fwrite($bf, start_tag('ROLES', 1, true)); $roles = backup_fetch_roles($preferences); $sitecontext = get_context_instance(CONTEXT_SYSTEM); $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course); foreach ($roles as $role) { fwrite($bf, start_tag('ROLE', 2, true)); fwrite($bf, full_tag('ID', 3, false, $role->id)); fwrite($bf, full_tag('NAME', 3, false, $role->name)); fwrite($bf, full_tag('SHORTNAME', 3, false, $role->shortname)); /// Calculate $role name in course $nameincourse = role_get_name($role, $coursecontext); if ($nameincourse != $role->name) { fwrite($bf, full_tag('NAMEINCOURSE', 3, false, $nameincourse)); } // find and write all default capabilities fwrite($bf, start_tag('CAPABILITIES', 3, true)); // pull out all default (site context) capabilities if ($capabilities = role_context_capabilities($role->id, $sitecontext)) { foreach ($capabilities as $capability => $value) { fwrite($bf, start_tag('CAPABILITY', 4, true)); fwrite($bf, full_tag('NAME', 5, false, $capability)); fwrite($bf, full_tag('PERMISSION', 5, false, $value)); // use this to pull out the other info (timemodified and modifierid) $cap = get_record_sql("SELECT *\n FROM {$CFG->prefix}role_capabilities\n WHERE capability = '{$capability}'\n AND contextid = {$sitecontext->id}\n AND roleid = {$role->id}"); fwrite($bf, full_tag("TIMEMODIFIED", 5, false, $cap->timemodified)); fwrite($bf, full_tag("MODIFIERID", 5, false, $cap->modifierid)); fwrite($bf, end_tag('CAPABILITY', 4, true)); } } fwrite($bf, end_tag('CAPABILITIES', 3, true)); fwrite($bf, end_tag('ROLE', 2, true)); } fwrite($bf, end_tag('ROLES', 1, true)); return $status; }
/** * Send the request to the server - decode and return the response * * @param object $mnet_peer A mnet_peer object with details of the * remote host we're connecting to * @return mixed A PHP variable, as returned by the * remote function */ function send($mnet_peer) { global $CFG, $MNET; $this->uri = $mnet_peer->wwwroot . $mnet_peer->application->xmlrpc_server_url; // Initialize with the target URL $ch = curl_init($this->uri); $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices'); if (in_array($this->method, $system_methods)) { // Executing any system method is permitted. } else { $id_list = $mnet_peer->id; if (!empty($CFG->mnet_all_hosts_id)) { $id_list .= ', ' . $CFG->mnet_all_hosts_id; } // At this point, we don't care if the remote host implements the // method we're trying to call. We just want to know that: // 1. The method belongs to some service, as far as OUR host knows // 2. We are allowed to subscribe to that service on this mnet_peer // Find methods that we subscribe to on this host $sql = "\n SELECT\n r.id\n FROM\n {$CFG->prefix}mnet_rpc r,\n {$CFG->prefix}mnet_service2rpc s2r,\n {$CFG->prefix}mnet_host2service h2s\n WHERE\n r.xmlrpc_path = '{$this->method}' AND\n s2r.rpcid = r.id AND\n s2r.serviceid = h2s.serviceid AND\n h2s.subscribe = '1' AND\n h2s.hostid in ({$id_list})"; if (!record_exists_sql($sql)) { global $USER; $this->error[] = '7:User with ID ' . $USER->id . ' attempted to call unauthorised method ' . $this->method . ' on host ' . $mnet_peer->wwwroot; return false; } } $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8", "escaping" => "markup")); $rq = $this->requesttext; $rq = mnet_sign_message($this->requesttext); $this->signedrequest = $rq; $rq = mnet_encrypt_message($rq, $mnet_peer->public_key); $this->encryptedrequest = $rq; curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Moodle'); curl_setopt($ch, CURLOPT_POSTFIELDS, $rq); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8")); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $timestamp_send = time(); $this->rawresponse = curl_exec($ch); $timestamp_receive = time(); if ($this->rawresponse === false) { $this->error[] = curl_errno($ch) . ':' . curl_error($ch); return false; } $this->rawresponse = trim($this->rawresponse); $mnet_peer->touch(); $crypt_parser = new mnet_encxml_parser(); $crypt_parser->parse($this->rawresponse); if ($crypt_parser->payload_encrypted) { $key = array_pop($crypt_parser->cipher); $data = array_pop($crypt_parser->cipher); $crypt_parser->free_resource(); // Initialize payload var $payload = ''; // &$payload $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $MNET->get_private_key()); if (!$isOpen) { // Decryption failed... let's try our archived keys $openssl_history = get_config('mnet', 'openssl_history'); if (empty($openssl_history)) { $openssl_history = array(); set_config('openssl_history', serialize($openssl_history), 'mnet'); } else { $openssl_history = unserialize($openssl_history); } foreach ($openssl_history as $keyset) { $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']); $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $keyresource); if ($isOpen) { // It's an older code, sir, but it checks out break; } } } if (!$isOpen) { trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}."); $this->error[] = '3:No key match'; return false; } if (strpos(substr($payload, 0, 100), '<signedMessage>')) { $sig_parser = new mnet_encxml_parser(); $sig_parser->parse($payload); } else { $this->error[] = '2:Payload not signed: ' . $payload; return false; } } else { if (!empty($crypt_parser->remoteerror)) { $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror; } else { if (!empty($crypt_parser->error)) { $crypt_parser_error = $crypt_parser->error[0]; $message = '3:XML Parse error in payload: ' . $crypt_parser_error['string'] . "\n"; if (array_key_exists('lineno', $crypt_parser_error)) { $message .= 'At line number: ' . $crypt_parser_error['lineno'] . "\n"; } if (array_key_exists('line', $crypt_parser_error)) { $message .= 'Which reads: ' . $crypt_parser_error['line'] . "\n"; } $this->error[] = $message; } else { $this->error[] = '1:Payload not encrypted '; } } $crypt_parser->free_resource(); return false; } // Margin of error is the time it took the request to complete. $margin_of_error = $timestamp_receive - $timestamp_send; // Guess the time gap between sending the request and the remote machine // executing the time() function. Marginally better than nothing. $hysteresis = $margin_of_error / 2; $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis; $time_offset = $remote_timestamp - $timestamp_send; if ($time_offset > 0) { $threshold = get_config('mnet', 'drift_threshold'); if (empty($threshold)) { // We decided 15 seconds was a pretty good arbitrary threshold // for time-drift between servers, but you can customize this in // the config_plugins table. It's not advised though. set_config('drift_threshold', 15, 'mnet'); $threshold = 15; } if ($time_offset > $threshold) { $this->error[] = '6:Time gap with ' . $mnet_peer->name . ' (' . $time_offset . ' seconds) is greater than the permitted maximum of ' . $threshold . ' seconds'; return false; } } $this->xmlrpcresponse = base64_decode($sig_parser->data_object); $this->response = xmlrpc_decode($this->xmlrpcresponse); curl_close($ch); // xmlrpc errors are pushed onto the $this->error stack if (is_array($this->response) && array_key_exists('faultCode', $this->response)) { // The faultCode 7025 means we tried to connect with an old SSL key // The faultString is the new key - let's save it and try again // The re_key attribute stops us from getting into a loop if ($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) { $record = new stdClass(); $record->id = $mnet_peer->id; if ($this->response['faultString'] == clean_param($this->response['faultString'], PARAM_PEM)) { $record->public_key = $this->response['faultString']; $details = openssl_x509_parse($record->public_key); if (is_array($details) && isset($details['validTo_time_t'])) { $record->public_key_expires = $details['validTo_time_t']; update_record('mnet_host', $record); $mnet_peer2 = new mnet_peer(); $mnet_peer2->set_id($record->id); $mnet_peer2->re_key = true; $this->send($mnet_peer2); } else { $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } } else { $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } } else { if (!empty($CFG->mnet_rpcdebug)) { $guidance = get_string('error' . $this->response['faultCode'], 'mnet'); } else { $guidance = ''; } $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } } // ok, it's signed, but is it signed with the right certificate ? // do this *after* we check for an out of date key $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key); if ($verified != 1) { $this->error[] = 'Invalid signature'; } return empty($this->error); }
function edituser_site_validate(Pieform $form, $values) { global $USER, $SESSION; if (!($user = get_record('usr', 'id', $values['id']))) { return false; } if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) { $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled'); $maxquota = get_config_plugin('artefact', 'file', 'maxquota'); if ($maxquotaenabled && $values['quota'] > $maxquota) { $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota))); $SESSION->add_error_msg(get_string('maxquotaexceeded', 'artefact.file', display_size($maxquota))); } } $userobj = new User(); $userobj = $userobj->find_by_id($user->id); if (isset($values['username']) && !empty($values['username']) && $values['username'] != $userobj->username) { if (!isset($values['authinstance'])) { $authobj = AuthFactory::create($userobj->authinstance); } else { $authobj = AuthFactory::create($values['authinstance']); } if (method_exists($authobj, 'change_username')) { if (method_exists($authobj, 'is_username_valid_admin')) { if (!$authobj->is_username_valid_admin($values['username'])) { $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal')); } } else { if (method_exists($authobj, 'is_username_valid')) { if (!$authobj->is_username_valid($values['username'])) { $form->set_error('username', get_string('usernameinvalidform', 'auth.internal')); } } } if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($values['username'])))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); } } else { $form->set_error('username', get_string('usernamechangenotallowed', 'admin')); } } // Check that the external username isn't already in use by someone else if (isset($values['authinstance']) && isset($values['remoteusername'])) { // there are 4 cases for changes on the page // 1) ai and remoteuser have changed // 2) just ai has changed // 3) just remoteuser has changed // 4) the ai changes and the remoteuser is wiped - this is a delete of the old ai-remoteuser // determine the current remoteuser $current_remotename = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id); if (!$current_remotename) { $current_remotename = $user->username; } // what should the new remoteuser be $new_remoteuser = get_field('auth_remote_user', 'remoteusername', 'authinstance', $values['authinstance'], 'localusr', $user->id); if (!$new_remoteuser) { $new_remoteuser = $user->username; } if (strlen(trim($values['remoteusername'])) > 0) { // value changed on page - use it if ($values['remoteusername'] != $current_remotename) { $new_remoteuser = $values['remoteusername']; } } // what really counts is who owns the target remoteuser slot $target_owner = get_field('auth_remote_user', 'localusr', 'authinstance', $values['authinstance'], 'remoteusername', $new_remoteuser); // target remoteuser is owned by someone else if ($target_owner && $target_owner != $user->id) { $usedbyuser = get_field('usr', 'username', 'id', $target_owner); $SESSION->add_error_msg(get_string('duplicateremoteusername', 'auth', $usedbyuser)); $form->set_error('remoteusername', get_string('duplicateremoteusernameformerror', 'auth')); } } // Check if the new primary email address is valid if (isset($values['email']) && $values['email'] !== $user->email) { $email = sanitize_email($values['email']); if (!$form->get_error('email')) { if (!$form->get_error('email') && empty($email)) { $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal')); } if (record_exists_sql(' SELECT id FROM {usr} WHERE deleted != 1 AND email = ? AND id != ?', array($email, $user->id)) || record_exists_sql(' SELECT owner FROM {artefact_internal_profile_email} WHERE email = ? AND owner != ?', array($email, $user->id))) { $form->set_error('email', get_string('emailalreadytakenbyothers', 'auth.internal')); } } } }
/** * Test whether a record exists in a table where all the given fields match the given values. * * The record to test is specified by giving up to three fields that must * equal the corresponding values. * * @uses $CFG * @param string $table The table to check. * @param string $field1 the first field to check (optional). * @param string $value1 the value field1 must have (requred if field1 is given, else optional). * @param string $field2 the second field to check (optional). * @param string $value2 the value field2 must have (requred if field2 is given, else optional). * @param string $field3 the third field to check (optional). * @param string $value3 the value field3 must have (requred if field3 is given, else optional). * @return bool true if a matching record exists, else false. */ function record_exists($table, $field1 = null, $value1 = null, $field2 = null, $value2 = null, $field3 = null, $value3 = null) { global $CFG; $select = where_clause_prepared($field1, $field2, $field3); $values = where_values_prepared($value1, $value2, $value3); return record_exists_sql('SELECT * FROM ' . $CFG->prefix . $table . ' ' . $select . ' LIMIT 1', $values); }
function online_assignment_cleanup($output = false) { global $CFG; if ($output) { print_heading('Online Assignment Cleanup'); echo '<center>'; } /// We don't want to run this code if we are doing an upgrade from an assignment /// version earlier than 2005041400 /// because the assignment type field will not exist $amv = get_field('modules', 'version', 'name', 'assignment'); if ((int) $amv < 2005041400) { if ($output) { echo '</center>'; } return; } /// get the module id for assignments from db $arecord = get_record('modules', 'name', 'assignment'); $aid = $arecord->id; /// get a list of all courses on this site $courses = get_records('course'); /// cycle through each course foreach ($courses as $course) { $fullname = empty($course->fullname) ? 'Course: ' . $course->id : $course->fullname; if ($output) { print_heading($fullname); } /// retrieve a list of sections beyond what is currently being shown $sql = 'SELECT * FROM ' . $CFG->prefix . 'course_sections WHERE course=' . $course->id . ' AND section>' . $course->numsections . ' ORDER BY section ASC'; if (!($xsections = get_records_sql($sql))) { if ($output) { echo 'No extra sections<br />'; } continue; } /// cycle through each of the xtra sections foreach ($xsections as $xsection) { if ($output) { echo 'Checking Section: ' . $xsection->section . '<br />'; } /// grab any module instances from the sequence field if (!empty($xsection->sequence)) { $instances = explode(',', $xsection->sequence); /// cycle through the instances foreach ($instances as $instance) { /// is this an instance of an online assignment $sql = "SELECT a.id\n FROM {$CFG->prefix}course_modules cm,\n {$CFG->prefix}assignment a\n WHERE cm.id = '{$instance}' AND\n cm.module = '{$aid}' AND\n cm.instance = a.id AND\n a.assignmenttype = 'online'"; /// if record exists then we need to move instance to it's correct section if (record_exists_sql($sql)) { /// check the new section id /// the journal update erroneously stored it in course_sections->section $newsection = $xsection->section; /// double check the new section if ($newsection > $course->numsections) { /// get the record for section 0 for this course if (!($zerosection = get_record('course_sections', 'course', $course->id, 'section', '0'))) { continue; } $newsection = $zerosection->id; } /// grab the section record if (!($section = get_record('course_sections', 'id', $newsection))) { if ($output) { echo 'Serious error: Cannot retrieve section: ' . $newsection . ' for course: ' . format_string($course->fullname) . '<br />'; } continue; } /// explode the sequence if (($sequence = explode(',', $section->sequence)) === false) { $sequence = array(); } /// add instance to correct section array_push($sequence, $instance); /// implode the sequence $section->sequence = implode(',', $sequence); set_field('course_sections', 'sequence', $section->sequence, 'id', $section->id); /// now we need to remove the instance from the old sequence /// grab the old section record if (!($section = get_record('course_sections', 'id', $xsection->id))) { if ($output) { echo 'Serious error: Cannot retrieve old section: ' . $xsection->id . ' for course: ' . $course->fullname . '<br />'; } continue; } /// explode the sequence if (($sequence = explode(',', $section->sequence)) === false) { $sequence = array(); } /// remove the old value from the array $key = array_search($instance, $sequence); unset($sequence[$key]); /// implode the sequence $section->sequence = implode(',', $sequence); set_field('course_sections', 'sequence', $section->sequence, 'id', $section->id); if ($output) { echo 'Online Assignment (instance ' . $instance . ') moved from section ' . $section->id . ': to section ' . $newsection . '<br />'; } } } } /// if the summary and sequence are empty then remove this section if (empty($xsection->summary) and empty($xsection->sequence)) { delete_records('course_sections', 'id', $xsection->id); if ($output) { echo 'Deleting empty section ' . $xsection->section . '<br />'; } } } } echo '</center>'; }
/** * Test whether any records exists in a table which match a particular WHERE clause. * * This function returns true if at least one record is returned * * @param string $table The database table to be checked against. * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call. * @param array $values When using prepared statements, this is the value array (optional). * @return bool true if a matching record exists, else false. * @throws SQLException */ function record_exists_select($table, $select = '', $values = null) { global $CFG; if ($select) { $select = 'WHERE ' . $select; } return record_exists_sql('SELECT * FROM ' . db_table_name($table) . ' ' . $select, $values); }
function get_content() { global $USER, $CFG, $COURSE; if ($this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; if (empty($this->instance)) { return $this->content; } $timetoshowusers = 300; //Seconds default if (isset($CFG->block_online_users_timetosee)) { $timetoshowusers = $CFG->block_online_users_timetosee * 60; } $timefrom = 100 * floor((time() - $timetoshowusers) / 100); // Round to nearest 100 seconds for better query cache // Get context so we can check capabilities. $context = get_context_instance(CONTEXT_COURSE, $COURSE->id); //Calculate if we are in separate groups $isseparategroups = $COURSE->groupmode == SEPARATEGROUPS && $COURSE->groupmodeforce && !has_capability('moodle/site:accessallgroups', $context); //Get the user current group $currentgroup = $isseparategroups ? groups_get_course_group($COURSE) : NULL; $groupmembers = ""; $groupselect = ""; //Add this to the SQL to show only group users if ($currentgroup !== NULL) { $groupmembers = ", {$CFG->prefix}groups_members gm "; $groupselect = " AND u.id = gm.userid AND gm.groupid = '{$currentgroup}'"; } if ($COURSE->id == SITEID) { // Site-level $select = "SELECT u.id, u.username, u.firstname, u.lastname, u.picture, max(u.lastaccess) as lastaccess "; $from = "FROM {$CFG->prefix}user u \n {$groupmembers} "; $where = "WHERE u.lastaccess > {$timefrom}\n {$groupselect} "; $order = "ORDER BY lastaccess DESC "; } else { // Course-level $courseselect = "AND ul.courseid = '" . $COURSE->id . "'"; $select = "SELECT u.id, u.username, u.firstname, u.lastname, u.picture, max(ul.timeaccess) as lastaccess "; $from = "FROM {$CFG->prefix}user_lastaccess ul,\n {$CFG->prefix}user u\n {$groupmembers} "; $where = "WHERE ul.timeaccess > {$timefrom}\n AND u.id = ul.userid\n AND ul.courseid = {$COURSE->id}\n {$groupselect} "; $order = "ORDER BY lastaccess DESC "; } $groupby = "GROUP BY u.id, u.username, u.firstname, u.lastname, u.picture "; $SQL = $select . $from . $where . $groupby . $order; $users = array(); $pcontext = get_related_contexts_string($context); if ($pusers = get_records_sql($SQL, 0, 50)) { // We'll just take the most recent 50 maximum foreach ($pusers as $puser) { // if current user can't view hidden role assignment in this context and // user has a hidden role assigned at this context or any parent contexts, // ignore this user $SQL = "SELECT id FROM {$CFG->prefix}role_assignments\n WHERE userid = {$puser->id}\n AND contextid {$pcontext}\n AND hidden = 1"; if (!has_capability('moodle/role:viewhiddenassigns', $context) && record_exists_sql($SQL)) { // can't see this user as the current user has no capability // and this user has a hidden assignment at this context or higher continue; } $puser->fullname = fullname($puser); $users[$puser->id] = $puser; } } //Calculate minutes $minutes = floor($timetoshowusers / 60); $this->content->text = "<div class=\"info\">(" . get_string("periodnminutes", "block_online_users", $minutes) . ")</div>"; //Now, we have in users, the list of users to show //Because they are online if (!empty($users)) { //Accessibility: Don't want 'Alt' text for the user picture; DO want it for the envelope/message link (existing lang string). //Accessibility: Converted <div> to <ul>, inherit existing classes & styles. $this->content->text .= "<ul class='list'>\n"; foreach ($users as $user) { $this->content->text .= '<li class="listentry">'; $timeago = format_time(time() - $user->lastaccess); //bruno to calculate correctly on frontpage if ($user->username == 'guest') { $this->content->text .= '<div class="user">' . print_user_picture($user->id, $COURSE->id, $user->picture, 16, true, false, '', false); $this->content->text .= get_string('guestuser') . '</div>'; } else { $this->content->text .= '<div class="user"><a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&course=' . $COURSE->id . '" title="' . $timeago . '">'; $this->content->text .= print_user_picture($user->id, $COURSE->id, $user->picture, 16, true, false, '', false); $this->content->text .= $user->fullname . '</a></div>'; } if (!empty($USER->id) and $USER->id != $user->id and !empty($CFG->messaging) and !isguest() and $user->username != 'guest') { // Only when logged in and messaging active etc $this->content->text .= '<div class="message"><a title="' . get_string('messageselectadd') . '" href="' . $CFG->wwwroot . '/message/discussion.php?id=' . $user->id . '" onclick="this.target=\'message_' . $user->id . '\';return openpopup(\'/message/discussion.php?id=' . $user->id . '\', \'message_' . $user->id . '\', \'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500\', 0);">' . '<img class="iconsmall" src="' . $CFG->pixpath . '/t/message.gif" alt="' . get_string('messageselectadd') . '" /></a></div>'; } $this->content->text .= "</li>\n"; } $this->content->text .= '</ul><div class="clearer"><!-- --></div>'; } else { $this->content->text .= "<div class=\"info\">" . get_string("none") . "</div>"; } return $this->content; }
/** * Returns true if user created new discussion already * @param int $forumid * @param int $userid * @return bool */ function forum_user_has_posted_discussion($forumid, $userid) { global $CFG; $sql = "SELECT 'x'\n FROM {$CFG->prefix}forum_discussions d, {$CFG->prefix}forum_posts p\n WHERE d.forum = {$forumid} AND p.discussion = d.id AND p.parent = 0"; return record_exists_sql($sql); }
function data_preprocessing(&$default_values) { global $CFG; if (array_key_exists('update', $default_values)) { $sql = "SELECT id FROM {$CFG->prefix}adobeconnect_meeting_groups WHERE " . "instanceid = " . $default_values['id']; if (record_exists_sql($sql)) { $default_values['tempenable'] = 0; } } }
} elseif (intval($days2expire) < 0) { print_header("{$site->fullname}: {$loginsite}", "{$site->fullname}", $navigation, '', '', true, "<div class=\"langmenu\">{$langmenu}</div>"); notice_yesno(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo); print_footer(); exit; } } reset_login_count(); redirect($urltogo); exit; } else { if (empty($errormsg)) { $errormsg = get_string("invalidlogin"); $errorcode = 3; } if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode === 'strict' && is_enabled_auth('mnet') && record_exists_sql("SELECT h.id FROM {$CFG->prefix}mnet_host h\n INNER JOIN {$CFG->prefix}mnet_host2service m ON h.id=m.hostid\n INNER JOIN {$CFG->prefix}mnet_service s ON s.id=m.serviceid\n WHERE s.name='sso_sp' AND h.deleted=0 AND m.publish = 1") && record_exists_select('user', "username = '******' AND mnethostid != {$CFG->mnet_localhost_id}")) { $errormsg .= get_string('loginlinkmnetuser', 'mnet', "mnet_email.php?u={$frm->username}"); } } } } /// Detect problems with timedout sessions if ($session_has_timed_out and !data_submitted()) { $errormsg = get_string('sessionerroruser', 'error'); $errorcode = 4; } /// First, let's remember where the user was trying to get to before they got here if (empty($SESSION->wantsurl)) { $SESSION->wantsurl = array_key_exists('HTTP_REFERER', $_SERVER) && $_SERVER["HTTP_REFERER"] != $CFG->wwwroot && $_SERVER["HTTP_REFERER"] != $CFG->wwwroot . '/' && $_SERVER["HTTP_REFERER"] != $CFG->httpswwwroot . '/login/' && $_SERVER["HTTP_REFERER"] != $CFG->httpswwwroot . '/login/index.php' ? $_SERVER["HTTP_REFERER"] : NULL; } /// Redirect to alternative login URL if needed
/** * Update or create a favourites list for a user * * @param $owner integer owner of the favorites list * @param $shortname string name for the favorites list * @param $institution string institution with permission to update the favorites list * @param $userlist array array of userids to add to the list */ function update_favorites($owner, $shortname, $institution, $userlist) { global $USER; if (empty($institution)) { // User-editable favorites lists are not implemented yet. return; } if (!$USER->can_edit_institution($institution)) { throw new AccessDeniedException("update_favorites: access denied"); } $owner = (int) $owner; if ($institution == 'mahara') { if (!record_exists('usr', 'id', $owner, 'deleted', 0)) { throw new NotFoundException("update_favorites: user {$owner} not found"); } } else { $sql = ' SELECT u.id FROM {usr} u JOIN {usr_institution} ui ON u.id = ui.usr AND ui.institution = ? WHERE u.id = ? AND u.deleted = 0'; if (!record_exists_sql($sql, array($institution, $owner))) { throw new NotFoundException("update_favorites: user {$owner} not found in institution {$institution}"); } } $listdata = get_record('favorite', 'owner', $owner, 'shortname', $shortname); if ($listdata && $listdata->institution != $institution) { throw new AccessDeniedException("update_favorites: user {$owner} already has a favorites list called {$shortname} which is updated by another institution"); } if (!is_array($userlist)) { throw new SystemException("update_favorites: userlist is not an array"); } if (!empty($userlist)) { $userids = get_column_sql(' SELECT id FROM {usr} WHERE id IN (' . join(',', array_fill(0, count($userlist), '?')) . ') AND deleted = 0', array_map('intval', $userlist)); } if (empty($userids)) { $userids = array(); } db_begin(); $now = db_format_timestamp(time()); if ($listdata) { delete_records('favorite_usr', 'favorite', $listdata->id); $listdata->mtime = $now; update_record('favorite', $listdata, 'id'); } else { $listdata = (object) array('owner' => $owner, 'shortname' => $shortname, 'institution' => $institution, 'ctime' => $now, 'mtime' => $now); $listdata->id = insert_record('favorite', $listdata, 'id', true); } foreach ($userids as $userid) { insert_record('favorite_usr', (object) array('favorite' => $listdata->id, 'usr' => $userid)); } db_commit(); }
/** * Checks if artefact or at least one of its ancestors is in view * * @param int|object $artefact ID of an artefact or object itself. * Will load object if ID is supplied. * @param int $view ID of a page that contains artefact. * * @return boolean True if artefact is in view, False otherwise. */ function artefact_in_view($artefact, $view) { if (!is_object($artefact)) { $artefact = artefact_instance_from_id($artefact); } $ancestors = $artefact->get_item_ancestors(); $params = array($view, $artefact->get('id'), $artefact->get('id')); $extrasql = ''; if ($ancestors) { $extrasql = "SELECT a.parent\n FROM {view_artefact} top JOIN {artefact} a\n ON a.parent = top.artefact\n WHERE top.view = ? AND top.artefact IN (" . implode(',', $ancestors) . ")\n UNION"; $params[] = $view; } $sql = "SELECT a.id\n FROM {view_artefact} a WHERE \"view\" = ? AND artefact = ?\n UNION\n SELECT aa.artefact\n FROM {artefact} a INNER JOIN {artefact_attachment} aa\n ON a.id = aa.artefact\n WHERE aa.attachment = ?\n UNION\n {$extrasql}\n SELECT s.id\n FROM {view} v INNER JOIN {skin} s\n ON v.skin = s.id\n WHERE v.id = ? AND ? in (s.bodybgimg, s.viewbgimg)\n "; $params = array_merge($params, array($view, $artefact->get('id'))); return record_exists_sql($sql, $params); }
/** * Determines if current or specified is member of any active group in activity * @param object $cm coruse module object * @param int $userid id of user, null menas $USER->id * @return booelan true if user member of at least one group used in activity */ function groups_has_membership($cm, $userid = null) { global $CFG, $USER; static $cache = array(); // groupings are ignored when not enabled if (empty($CFG->enablegroupings)) { $cm->groupingid = 0; } if (empty($userid)) { $userid = $USER->id; } $cachekey = $userid . '|' . $cm->course . '|' . $cm->groupingid; if (isset($cache[$cachekey])) { return $cache[$cachekey]; } if ($cm->groupingid) { // find out if member of any group in selected activity grouping $sql = "SELECT 'x'\n FROM {$CFG->prefix}groups_members gm, {$CFG->prefix}groupings_groups gg\n WHERE gm.userid = {$userid} AND gm.groupid = gg.groupid AND gg.groupingid = {$cm->groupingid}"; } else { // no grouping used - check all groups in course $sql = "SELECT 'x'\n FROM {$CFG->prefix}groups_members gm, {$CFG->prefix}groups g\n WHERE gm.userid = {$userid} AND gm.groupid = g.id AND g.courseid = {$cm->course}"; } $cache[$cachekey] = record_exists_sql($sql); return $cache[$cachekey]; }
function exists() { global $CFG; return record_exists_sql("\n SELECT parent_qc.id AS parent, child_qc.id AS child, child_qc.contextid\n FROM {$CFG->prefix}question_categories child_qc\n JOIN {$CFG->prefix}question_categories parent_qc ON child_qc.parent = parent_qc.id\n WHERE child_qc.contextid <> parent_qc.contextid"); }
function data_fieldname_exists($name, $dataid, $fieldid = 0) { global $CFG; $LIKE = sql_ilike(); if ($fieldid) { return record_exists_sql("SELECT * from {$CFG->prefix}data_fields df\n WHERE df.name {$LIKE} '{$name}' AND df.dataid = {$dataid}\n AND ((df.id < {$fieldid}) OR (df.id > {$fieldid}))"); } else { return record_exists_sql("SELECT * from {$CFG->prefix}data_fields df\n WHERE df.name {$LIKE} '{$name}' AND df.dataid = {$dataid}"); } }
/** * Check that a given function (or method) in an include file has been designated * ok for export * * @param string $includefile The path to the include file * @param string $functionname The name of the function (or method) to * execute * @param mixed $class A class name, or false if we're just testing * a function * @return int Zero (RPC_OK) if all ok - appropriate * constant otherwise */ function mnet_permit_rpc_call($includefile, $functionname, $class = false) { global $CFG, $MNET_REMOTE_CLIENT; if (file_exists($CFG->dirroot . $includefile)) { include_once $CFG->dirroot . $includefile; // $callprefix matches the rpc convention // of not having a leading slash $callprefix = preg_replace('!^/!', '', $includefile); } else { return RPC_NOSUCHFILE; } if ($functionname != clean_param($functionname, PARAM_PATH)) { // Under attack? // Todo: Should really return a much more BROKEN! response return RPC_FORBIDDENMETHOD; } $id_list = $MNET_REMOTE_CLIENT->id; if (!empty($CFG->mnet_all_hosts_id)) { $id_list .= ', ' . $CFG->mnet_all_hosts_id; } // TODO: change to left-join so we can disambiguate: // 1. method doesn't exist // 2. method exists but is prohibited $sql = "\n SELECT\n count(r.id)\n FROM\n {$CFG->prefix}mnet_host2service h2s,\n {$CFG->prefix}mnet_service2rpc s2r,\n {$CFG->prefix}mnet_rpc r\n WHERE\n h2s.serviceid = s2r.serviceid AND\n s2r.rpcid = r.id AND\n r.xmlrpc_path = '{$callprefix}/{$functionname}' AND\n h2s.hostid in ({$id_list}) AND\n h2s.publish = '1'"; $permissionobj = record_exists_sql($sql); if ($permissionobj === false && 'dangerous' != $CFG->mnet_dispatcher_mode) { return RPC_FORBIDDENMETHOD; } // WE'RE LOOKING AT A CLASS/METHOD if (false != $class) { if (!class_exists($class)) { // Generate error response - unable to locate class return RPC_NOSUCHCLASS; } $object = new $class(); if (!method_exists($object, $functionname)) { // Generate error response - unable to locate method return RPC_NOSUCHMETHOD; } if (!method_exists($object, 'mnet_publishes')) { // Generate error response - the class doesn't publish // *any* methods, because it doesn't have an mnet_publishes // method return RPC_FORBIDDENMETHOD; } // Get the list of published services - initialise method array $servicelist = $object->mnet_publishes(); $methodapproved = false; // If the method is in the list of approved methods, set the // methodapproved flag to true and break foreach ($servicelist as $service) { if (in_array($functionname, $service['methods'])) { $methodapproved = true; break; } } if (!$methodapproved) { return RPC_FORBIDDENMETHOD; } // Stash the object so we can call the method on it later $MNET_REMOTE_CLIENT->object_to_call($object); // WE'RE LOOKING AT A FUNCTION } else { if (!function_exists($functionname)) { // Generate error response - unable to locate function return RPC_NOSUCHFUNCTION; } } return RPC_OK; }
/** * Uses 1 DB query to answer whether a user is an admin at the sitelevel. * It depends on DB schema >=1.7 but does not depend on the new datastructures * in v1.9 (context.path, or $USER->access) * * Will return true if the userid has any of * - moodle/site:config * - moodle/legacy:admin * - moodle/site:doanything * * @param int $userid * @returns bool $isadmin */ function is_siteadmin($userid) { global $CFG; $sql = "SELECT SUM(rc.permission)\n FROM " . $CFG->prefix . "role_capabilities rc\n JOIN " . $CFG->prefix . "context ctx \n ON ctx.id=rc.contextid\n JOIN " . $CFG->prefix . "role_assignments ra\n ON ra.roleid=rc.roleid AND ra.contextid=ctx.id\n WHERE ctx.contextlevel=10\n AND ra.userid={$userid}\n AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything') \n GROUP BY rc.capability\n HAVING SUM(rc.permission) > 0"; $isadmin = record_exists_sql($sql); return $isadmin; }
/** * Test whether any records exists in a table which match a particular WHERE clause. * * @uses $CFG * @param string $table The database table to be checked against. * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call. * @return bool true if a matching record exists, else false. */ function record_exists_select($table, $select = '') { global $CFG; if ($select) { $select = 'WHERE ' . $select; } return record_exists_sql('SELECT * FROM ' . $CFG->prefix . $table . ' ' . $select); }
/** * Determine whether there arey any questions belonging to this context, that is whether any of its * question categories contain any questions. This will return true even if all the questions are * hidden. * * @param mixed $context either a context object, or a context id. * @return boolean whether any of the question categories beloning to this context have * any questions in them. */ function question_context_has_any_questions($context) { global $CFG; if (is_object($context)) { $contextid = $context->id; } else { if (is_numeric($context)) { $contextid = $context; } else { print_error('invalidcontextinhasanyquestions', 'question'); } } return record_exists_sql('SELECT * FROM ' . $CFG->prefix . 'question q ' . 'JOIN ' . $CFG->prefix . 'question_categories qc ON qc.id = q.category ' . "WHERE qc.contextid = {$contextid} AND q.parent = 0"); }
/** * converts a user object to a string representation of the user suitable for * the current user (or specified user) to see * * Both parameters should be objects containing id, preferredname, firstname, * lastname, admin * * @param object $user the user that you're trying to format to a string * @param object $userto the user that is looking at the string representation (if left * blank, will default to the currently logged in user). * @param boolean $nameonly do not append the user's username even if $userto can see it. * @param boolean $realname show the user's real name even if preferredname exists * @param boolean $username show the user's username even if the viewer is not an admin * * @returns string name to display */ function display_name($user, $userto = null, $nameonly = false, $realname = false, $username = false) { global $USER; static $tutorcache = array(); static $usercache = array(); if ($nameonly) { return display_default_name($user); } if (empty($userto)) { $userto = new StdClass(); $userto->id = $USER->get('id'); $userto->username = $USER->get('username'); $userto->preferredname = $USER->get('preferredname'); $userto->firstname = $USER->get('firstname'); $userto->lastname = $USER->get('lastname'); $userto->admin = $USER->get('admin') || $USER->is_institutional_admin(); $userto->staff = $USER->get('staff') || $USER->is_institutional_staff(); } else { if (is_numeric($userto)) { if (isset($usercache[$userto])) { $userto = $usercache[$userto]; } else { if ($userto == $USER->get('id')) { $userto = new StdClass(); $userto->id = $USER->get('id'); $userto->username = $USER->get('username'); $userto->preferredname = $USER->get('preferredname'); $userto->firstname = $USER->get('firstname'); $userto->lastname = $USER->get('lastname'); $userto->admin = $USER->get('admin') || $USER->is_institutional_admin(); $userto->staff = $USER->get('staff') || $USER->is_institutional_staff(); $usercache[$userto->id] = $userto; } else { $userto = $usercache[$userto] = get_record('usr', 'id', $userto); } } } } if (is_array($user)) { $user = (object) $user; } else { if (is_numeric($user)) { if (isset($usercache[$user])) { $user = $usercache[$user]; } else { if ($user == $USER->get('id')) { $user = new StdClass(); $user->id = $USER->get('id'); $user->username = $USER->get('username'); $user->preferredname = $USER->get('preferredname'); $user->firstname = $USER->get('firstname'); $user->lastname = $USER->get('lastname'); $user->admin = $USER->get('admin') || $USER->is_institutional_admin(); $user->staff = $USER->get('staff') || $USER->is_institutional_staff(); $user->deleted = 0; $usercache[$user->id] = $user; } else { $user = $usercache[$user] = get_record('usr', 'id', $user); } } } } if (!is_object($user)) { throw new InvalidArgumentException("Invalid user passed to display_name"); } if ($user instanceof User) { $userObj = $user; $user = new StdClass(); $user->id = $userObj->get('id'); $user->username = $userObj->get('username'); $user->preferredname = $userObj->get('preferredname'); $user->firstname = $userObj->get('firstname'); $user->lastname = $userObj->get('lastname'); $user->admin = $userObj->get('admin'); $user->staff = $userObj->get('staff'); $user->deleted = $userObj->get('deleted'); } $user->id = isset($user->id) ? $user->id : null; $userto->id = isset($userto->id) ? $userto->id : null; $addusername = $username || !empty($userto->admin) || !empty($userto->staff); // if they don't have a preferred name set, just return here if (empty($user->preferredname)) { $firstlast = full_name($user); if ($addusername) { return $firstlast . ' (' . $user->username . ')'; } return $firstlast; } else { if ($user->id == $userto->id) { // If viewing our own name, show it how we like it return $user->preferredname; } } // Preferred name is set $addrealname = $realname || !empty($userto->admin) || !empty($userto->staff); if (!$addrealname) { // Tutors can always see the user's real name, so we need to check if the // viewer is a tutor of the user whose name is being displayed if (!isset($tutorcache[$user->id][$userto->id])) { $tutorcache[$user->id][$userto->id] = record_exists_sql(' SELECT s.member FROM {group_member} s JOIN {group_member} t ON s.group = t.group JOIN {group} g ON (g.id = s.group AND g.deleted = 0) JOIN {grouptype_roles} gtr ON (g.grouptype = gtr.grouptype AND gtr.role = t.role AND gtr.see_submitted_views = 1) WHERE s.member = ? AND t.member = ?', array($user->id, $userto->id)); } $addrealname = $tutorcache[$user->id][$userto->id]; } if ($addrealname) { $firstlast = full_name($user); if ($addusername) { return $user->preferredname . ' (' . $firstlast . ' - ' . $user->username . ')'; } return $user->preferredname . ' (' . $firstlast . ')'; } if ($addusername) { return $user->preferredname . ' (' . $user->username . ')'; } return $user->preferredname; }
/** * */ function forum_user_has_posted($forumid, $did, $userid) { global $CFG; if (empty($did)) { // posted in any forum discussion? $sql = "SELECT 'x'\n FROM {$CFG->prefix}forum_posts p\n JOIN {$CFG->prefix}forum_discussions d ON d.id = p.discussion\n WHERE p.userid = {$userid} AND d.forum = {$forumid}"; return record_exists_sql($sql); } else { // started discussion? return record_exists('forum_posts', 'discussion', $did, 'userid', $userid); } }
/** * Delete one instance of a tag. If the last instance was deleted, it will * also delete the tag, unless its type is 'official'. * * @param string $record_type the type of the record for which to remove the instance * @param int $record_id the id of the record for which to remove the instance * @param int $tagid the tagid that needs to be removed * @return bool true on success, false otherwise */ function tag_delete_instance($record_type, $record_id, $tagid) { global $CFG; if (delete_records('tag_instance', 'tagid', $tagid, 'itemtype', $record_type, 'itemid', $record_id)) { if (!record_exists_sql("SELECT tg.id " . "FROM {$CFG->prefix}tag tg " . "WHERE tg.id = {$tagid} AND ( tg.tagtype = 'official' OR " . "EXISTS (SELECT 1 \n FROM {$CFG->prefix}tag_instance ti \n WHERE ti.tagid={$tagid}) )")) { return tag_delete($tagid); } } else { return false; } return true; }
function get_content() { // Access to settings needed global $USER, $COURSE, $CFG; $eventArray = array(); include $CFG->dirroot . '/blocks/progress/common.php'; include_once $CFG->dirroot . '/blocks/progress/lib.php'; include_once $CFG->libdir . '/ddllib.php'; // If content has already been generated, don't waste time generating it again if ($this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; // Collect up all the events to track progress $numEvents = 0; $visibleEvents = 0; foreach ($modules as $module => $details) { $table = new XMLDBTable($module); if (table_exists($table)) { $events = get_records($module, 'course', $this->instance->pageid, '', 'id, name' . (array_key_exists('defaultTime', $details) ? ', ' . $details['defaultTime'] . ' as due' : '')); if ($events) { foreach ($events as $event) { $monitored = progress_default_value($this->config->{'monitor_' . $module . $event->id}); if (isset($monitored) && $monitored == 'on') { $numEvents++; $courseModule = get_coursemodule_from_instance($module, $event->id, $COURSE->id); // Check if the user has attempted the module $query = $details['actions'][isset($this->config->{'action_' . $module . $event->id}) ? $this->config->{'action_' . $module . $event->id} : $details['actions']['defaultAction']]; $query = str_replace(array('#COURSEID#', '#USERID#', '#EVENTID#', '#CMID#'), array($this->instance->pageid, $USER->id, $event->id, $courseModule->id), $query); $attempted = record_exists_sql($query) ? true : false; // Check the time the module is due $locked = progress_default_value($this->config->{'locked_' . $module . $event->id}); if (isset($details['defaultTime']) && $event->due != 0 && (!isset($locked) || $locked == 'on')) { $expected = progress_default_value($event->due); } else { $day = $this->config->{'day_' . $module . $event->id}; $month = $this->config->{'month_' . $module . $event->id}; $year = $this->config->{'year_' . $module . $event->id}; $hour = $this->config->{'hour_' . $module . $event->id}; $minute = $this->config->{'minute_' . $module . $event->id}; $expected = mktime($hour, $minute, 0, $month, $day, $year); } // Check if the module is visible, and if so, keep a record for it if ($courseModule->visible == 1) { $visibleEvents++; $eventArray[] = array('expected' => $expected, 'type' => $module, 'id' => $event->id, 'name' => $event->name, 'attempted' => $attempted, 'moduleID' => $courseModule->id, 'visible' => $courseModule->visible); } } } } } } // Check if any events were found if ($numEvents == 0) { $this->content->text = get_string('no_events_message', 'block_progress'); } else { if ($visibleEvents == 0) { $this->content->text = get_string('no_visible_events_message', 'block_progress'); } else { // Set up variables sort($eventArray); // by first value in each element, which is time due $now = time(); $nowPos = 0; // Find where to put now arrow while ($nowPos < $visibleEvents && $now > $eventArray[$nowPos]['expected']) { $nowPos++; } // Output function to display activity/resource info $this->content->text = ' <script> function progress_showInfo (mod, type, id, name, message, dateTime, instanceID, icon) { document.getElementById("progressBarInfo"+instanceID).innerHTML="<a href=\\\'' . $CFG->wwwroot . '/mod/"+mod+"/view.php?id="+id+"\\\'><img src=\\\'' . $CFG->wwwroot . '/mod/"+mod+"/icon.gif\\\' /> "+name+"</a><br />"+type+" "+message+" <img align=\\\'absmiddle\\\' src=\\\'' . $CFG->wwwroot . '/blocks/progress/img/"+icon+".gif\\\' /><br />' . get_string('time_expected', 'block_progress') . ': "+dateTime+"<br />"; } </script>'; // Start table $this->content->text .= '<table class="progressBarProgressTable" cellpadding="0" cellspacing="0">'; // Place now arrow if ($this->config->displayNow == '1') { $this->content->text .= '<tr>'; if ($nowPos < $visibleEvents / 2) { for ($i = 0; $i < $nowPos; $i++) { $this->content->text .= '<td> </td>'; } $this->content->text .= '<td colspan="' . ($visibleEvents - $nowPos) . '" style="text-align:left;" id="progressBarHeader"><img src="' . $CFG->wwwroot . '/blocks/progress/img/left.gif" />' . get_string('now_indicator', 'block_progress') . '</td>'; } else { $this->content->text .= '<td colspan=' . $nowPos . ' style="text-align:right;" id="progressBarHeader">' . get_string('now_indicator', 'block_progress') . '<img src="' . $CFG->wwwroot . '/blocks/progress/img/right.gif" /></td>'; for ($i = $nowPos; $i < $visibleEvents; $i++) { $this->content->text .= '<td> </td>'; } } $this->content->text .= '</tr>'; } // Start progress bar $width = 100 / $visibleEvents; $this->content->text .= '<tr>'; foreach ($eventArray as $event) { $this->content->text .= '<td class="progressBarCell" width="' . $width . '%" onclick="document.location=\'' . $CFG->wwwroot . '/mod/' . $event['type'] . '/view.php?' . 'id=' . $event['moduleID'] . '\';"'; $this->content->text .= ' onmouseover="progress_showInfo(\'' . $event['type'] . '\',\'' . get_string($event['type'], 'block_progress') . '\',\'' . $event['moduleID'] . '\',\'' . addSlashes($event['name']) . '\',\'' . get_string($this->config->{'action_' . $event['type'] . $event['id']}, 'block_progress') . '\',\'' . userdate($event['expected'], get_string('date_format', 'block_progress'), $CFG->timezone) . '\',\'' . $this->instance->id . '\',\'' . ($event['attempted'] ? 'tick' : 'cross') . '\');"'; $this->content->text .= ' bgColor="'; if ($event['attempted']) { $this->content->text .= (isset($CFG->blockProgressBarAttemptedColour) ? $CFG->blockProgressBarAttemptedColour : $defaultColours['attempted']) . '" /><img src="' . $CFG->wwwroot . '/blocks/progress/img/' . (isset($this->config->progressBarIcons) && $this->config->progressBarIcons == '1' ? 'tick.gif' : 'blank.gif') . '" />'; } else { if ($event['expected'] < $now) { $this->content->text .= (isset($CFG->blockProgressBarNotAttemptedColour) ? $CFG->blockProgressBarNotAttemptedColour : $defaultColours['notAttempted']) . '" /><img src="' . $CFG->wwwroot . '/blocks/progress/img/' . (isset($this->config->progressBarIcons) && $this->config->progressBarIcons == '1' ? 'cross.gif' : 'blank.gif') . '" />'; } else { $this->content->text .= (isset($CFG->blockProgressBarFutureNotAttemptedColour) ? $CFG->blockProgressBarFutureNotAttemptedColour : $defaultColours['futureNotAttempted']) . '" /><img src="' . $CFG->wwwroot . '/blocks/progress/img/blank.gif" />'; } } $this->content->text .= '</a></td>'; } $this->content->text .= ' </tr> </table> <div class="progressEventInfo" id="progressBarInfo' . $this->instance->id . '">' . get_string('mouse_over_prompt', 'block_progress') . '</div> '; } } return $this->content; }
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; } // 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]); } } $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'); 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', '', '', '', '', 0, '', false)) { foreach ($students as $student) { if (record_exists_sql("SELECT id FROM {$CFG->prefix}assignment_submissions\n WHERE assignment = {$assignment->id} AND\n userid = {$student->id} AND\n teacher = 0 AND\n timemarked = 0")) { $submissions++; } } } if ($submissions) { $str .= get_string('submissionsnotgraded', 'assignment', $submissions); } } else { $sql = "SELECT *\n FROM {$CFG->prefix}assignment_submissions\n WHERE userid = '{$USER->id}'\n AND assignment = '{$assignment->id}'"; if ($submission = get_record_sql($sql)) { 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; } } }
/** * Get the block content * * @return object content items and icons arrays of what is to be displayed in this block */ function get_content() { global $CFG, $COURSE, $USER; if (!isloggedin() || isguestuser()) { //user is not properly logged in return ''; } if ($this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $this->content->footer = ''; $siteContext = get_context_instance(CONTEXT_SYSTEM); if ($COURSE->id == SITEID) { $context = $siteContext; } else { $context = get_context_instance(CONTEXT_COURSE, $COURSE->id); } // make sure the user has the required role if (!empty($this->config->role)) { $sql = "SELECT r.id, r.name\n FROM {$CFG->prefix}role r\n JOIN {$CFG->prefix}role_assignments ra ON ra.roleid = r.id\n JOIN {$CFG->prefix}user u ON u.id = ra.userid\n WHERE ra.contextid = {$context->id}\n AND u.id = {$USER->id}\n AND ra.roleid = {$this->config->role}"; if (!record_exists_sql($sql)) { $this->content->items = array(); $this->content->icons = array(); return $this->content; } } $items = array(); $icons = array(); $categories = array(); if (isset($this->config->reports)) { // Require the php_report class require_once $CFG->dirroot . '/blocks/php_report/php_report_base.php'; $params = array(); // set the parameters that we can get from the environment // (currently only the course ID) if ($this->instance->pagetype == PAGE_COURSE_VIEW) { if ($this->instance->pageid != SITEID) { $params['courseid'] = $this->instance->pageid; } } // TODO: figure out capability for showing scheduling icon $isediting = isediting($this->instance->pageid); // && has_capability('block/php_report:manageactivities', $context); $count = 0; // create links to the reports foreach ($this->config->reports as $report) { if (isset(block_elis_reports::$reports_map[$report->id])) { $report->id = block_elis_reports::$reports_map[$report->id]; } $report_instance = php_report::get_default_instance($report->id); //make sure the report shortname is valid if ($report_instance !== FALSE) { if ($report_instance->is_available() && $report_instance->can_view_report()) { $category = $report_instance->get_category(); if (!isset($categories[$category])) { $categories[$category] = array(); } $name = $report_instance->get_display_name(); $report_link = new moodle_url($CFG->wwwroot . '/blocks/php_report/render_report_page.php', $params + $report->params + array('report' => $report->id)); $categories[$category][$count]['item'] = '<a href="' . $report_link->out() . '">' . $name . '</a>'; //create an instance specifically for testing scheduling permissions $test_scheduling_permissions_instance = php_report::get_default_instance($report->id, NULL, php_report::EXECUTION_MODE_SCHEDULED); //get_default instance will return FALSE if we are not allowed access to scheduling $can_schedule = $test_scheduling_permissions_instance !== FALSE; if ($isediting && $can_schedule) { // TODO: add permissions to this url $link = new moodle_url('/blocks/php_report/schedule.php?report=' . $report->id . '&action=listinstancejobs&createifnone=1'); $image_link = '<a href="#" alt=\'' . get_string('schedule_this_report', 'block_php_report') . '\' title=\'' . get_string('schedule_this_report', 'block_php_report') . '\' onclick="openpopup(\'' . $link->out() . '\', \'php_report_param_popup\', \'menubar=0,location=0,scrollbars,status,resizable,width=1600,height=600\');return false;"> <img src="' . $CFG->wwwroot . '/blocks/php_report/pix/schedule.png"/> </a>'; $categories[$category][$count]['sched_icon'] = $image_link; } $categories[$category][$count]['icon'] = '<img src="' . $CFG->wwwroot . '/blocks/elis_reports/pix/report.png" />'; $count++; } } } // Generates items and icons array $this->generate_content($categories, $this->content->items, $this->content->icons); } return $this->content; }