/** * Helper function for sending notification mails * * @param string $message The message * @param int $level Notification level * @return */ function local_sandbox_inform_admin($message, $level = SANDBOX_LEVEL_NOTICE) { // Get recipients $recipients = get_users_from_config(get_config('local_sandbox', 'notifyonerrors'), 'moodle/site:config'); // If there are no recipients, don't execute. if (!is_array($recipients) || count($recipients) <= 0) { return false; } // If message level is below configured notice level, don't execute if ($level < get_config('local_sandbox', 'notifylevel')) { return false; } // Get subject if ($level > SANDBOX_LEVEL_WARNING) { $subject = get_string('emailsubjecterror', 'local_sandbox'); } else { if ($level > SANDBOX_LEVEL_NOTICE) { $subject = get_string('emailsubjectwarning', 'local_sandbox'); } else { $subject = get_string('emailsubjectnotice', 'local_sandbox'); } } // Send mail foreach ($recipients as $r) { // Email the admin directly rather than putting these through the messaging system email_to_user($r, core_user::get_support_user(), $subject, $message); } }
public function test_get_user() { global $CFG; $this->resetAfterTest(true); // Create user and try fetach it with api. $user = $this->getDataGenerator()->create_user(); $this->assertEquals($user, core_user::get_user($user->id, '*', MUST_EXIST)); // Test noreply user. $CFG->noreplyuserid = null; $noreplyuser = core_user::get_noreply_user(); $this->assertEquals(1, $noreplyuser->emailstop); $this->assertFalse(core_user::is_real_user($noreplyuser->id)); $this->assertEquals($CFG->noreplyaddress, $noreplyuser->email); $this->assertEquals(get_string('noreplyname'), $noreplyuser->firstname); // Set user as noreply user and make sure noreply propery is set. core_user::reset_internal_users(); $CFG->noreplyuserid = $user->id; $noreplyuser = core_user::get_noreply_user(); $this->assertEquals(1, $noreplyuser->emailstop); $this->assertTrue(core_user::is_real_user($noreplyuser->id)); // Test support user. core_user::reset_internal_users(); $CFG->supportemail = null; $CFG->noreplyuserid = null; $supportuser = core_user::get_support_user(); $adminuser = get_admin(); $this->assertEquals($adminuser, $supportuser); $this->assertTrue(core_user::is_real_user($supportuser->id)); // When supportemail is set. core_user::reset_internal_users(); $CFG->supportemail = '*****@*****.**'; $supportuser = core_user::get_support_user(); $this->assertEquals(core_user::SUPPORT_USER, $supportuser->id); $this->assertFalse(core_user::is_real_user($supportuser->id)); // Set user as support user and make sure noreply propery is set. core_user::reset_internal_users(); $CFG->supportuserid = $user->id; $supportuser = core_user::get_support_user(); $this->assertEquals($user, $supportuser); $this->assertTrue(core_user::is_real_user($supportuser->id)); }
function activenotification($id){ global $DB, $USER, $CFG,$COURSE,$PAGE,$OUTPUT; //Batch Name $batchname=$DB->get_field('facetoface','name',array('id'=>$id)); //getting batch users $batch_users=$DB->get_records_sql("select * from {local_batch_users} where f2fid=$id"); //getting session details $session_details=$DB->get_records_sql("select * from {facetoface_sessions} where facetoface=$id"); $sessionsingle="<table border='1' style='text-align:center;'><tr><th>Serial</th><th>Startdate</th><th>Enddate</th><th>Classroom</th></tr>"; $n=1; foreach($session_details as $session_detail){ //session dates $startdateunix=$DB->get_field('facetoface_sessions_dates','timestart',array('sessionid'=>$session_detail->id)); $enddateuinx=$DB->get_field('facetoface_sessions_dates','timefinish',array('sessionid'=>$session_detail->id)); //converting dates $statrtdate=date('d M Y H:i:s',$startdateunix); $enddate=date('d M Y H:i:s',$enddateuinx); //session room $sessionroom=$DB->get_field('facetoface_room','name',array('id'=>$session_detail->roomid)); $sessionsingle .="<tr><td>$n</td><td>$statrtdate</td><td>$enddate</td><td>$sessionroom</td></tr>"; $n++; } // sending email to each users foreach($batch_users as $batch_user){ $user_active_details=$DB->get_record_sql("select * from {user} where id=$batch_user->userid"); // Course Name $coursename=$DB->get_field('course','fullname',array('id'=>$batch_user->courseid)); $from = core_user::get_support_user(); $subject =get_string('activenotification', 'facetoface'); $usermail=new stdClass(); $usermail->fullname=fullname($batch_user->userid); $usermail->batchname=$batchname; $usermail->coursename=$coursename; $usermail->session=$sessionsingle; $messagetext=get_string('activenotificationmsg', 'facetoface',$usermail); $email=email_to_user($user_active_details,$from,$subject,$messagetext); //print_object(email_to_user($user_active_details,$from,$subject,$messagetext)); } }
/** * Test message_get_contacts. */ public function test_message_get_contacts() { global $USER, $CFG; // Set this user as the admin. $this->setAdminUser(); $noreplyuser = core_user::get_noreply_user(); $supportuser = core_user::get_support_user(); // Create a user to add to the admin's contact list. $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $user3 = $this->getDataGenerator()->create_user(); // Stranger. // Add users to the admin's contact list. message_add_contact($user1->id); message_add_contact($user2->id); // Send some messages. $this->send_fake_message($user1, $USER); $this->send_fake_message($user2, $USER); $this->send_fake_message($user3, $USER); list($onlinecontacts, $offlinecontacts, $strangers) = message_get_contacts(); $this->assertCount(0, $onlinecontacts); $this->assertCount(2, $offlinecontacts); $this->assertCount(1, $strangers); // Send message from noreply and support users. $this->send_fake_message($noreplyuser, $USER); $this->send_fake_message($supportuser, $USER); list($onlinecontacts, $offlinecontacts, $strangers) = message_get_contacts(); $this->assertCount(0, $onlinecontacts); $this->assertCount(2, $offlinecontacts); $this->assertCount(3, $strangers); // Block 1 user. message_block_contact($user2->id); list($onlinecontacts, $offlinecontacts, $strangers) = message_get_contacts(); $this->assertCount(0, $onlinecontacts); $this->assertCount(1, $offlinecontacts); $this->assertCount(3, $strangers); // Noreply user being valid user. core_user::reset_internal_users(); $CFG->noreplyuserid = $user3->id; $noreplyuser = core_user::get_noreply_user(); list($onlinecontacts, $offlinecontacts, $strangers) = message_get_contacts(); $this->assertCount(0, $onlinecontacts); $this->assertCount(1, $offlinecontacts); $this->assertCount(2, $strangers); }
/** * Lockout user and send notification email. * * @param stdClass $user */ function login_lock_account($user) { global $CFG, $SESSION; if ($user->mnethostid != $CFG->mnet_localhost_id) { return; } if (isguestuser($user)) { return; } if (get_user_preferences('login_lockout_ignored', 0, $user)) { // This user can not be locked out. return; } $alreadylockedout = get_user_preferences('login_lockout', 0, $user); set_user_preference('login_lockout', time(), $user); if ($alreadylockedout == 0) { $secret = random_string(15); set_user_preference('login_lockout_secret', $secret, $user); // Some nasty hackery to get strings and dates localised for target user. $sessionlang = isset($SESSION->lang) ? $SESSION->lang : null; if (get_string_manager()->translation_exists($user->lang, false)) { $SESSION->lang = $user->lang; moodle_setlocale(); } $site = get_site(); $supportuser = core_user::get_support_user(); $data = new stdClass(); $data->firstname = $user->firstname; $data->lastname = $user->lastname; $data->username = $user->username; $data->sitename = format_string($site->fullname); $data->link = $CFG->wwwroot . '/login/unlock_account.php?u=' . $user->id . '&s=' . $secret; $data->admin = generate_email_signoff(); $message = get_string('lockoutemailbody', 'admin', $data); $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname)); if ($message) { // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber. email_to_user($user, $supportuser, $subject, $message); } if ($SESSION->lang !== $sessionlang) { $SESSION->lang = $sessionlang; moodle_setlocale(); } } }
// Save custom profile fields data. profile_save_data($usernew); // Trigger event. \core\event\user_updated::create_from_userid($user->id)->trigger(); // If email was changed and confirmation is required, send confirmation email now to the new address. if ($emailchanged && $CFG->emailchangeconfirmation) { $tempuser = $DB->get_record('user', array('id' => $user->id), '*', MUST_EXIST); $tempuser->email = $usernew->preference_newemail; $a = new stdClass(); $a->url = $CFG->wwwroot . '/user/emailupdate.php?key=' . $usernew->preference_newemailkey . '&id=' . $user->id; $a->site = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))); $a->fullname = fullname($tempuser, true); $emailupdatemessage = get_string('emailupdatemessage', 'auth', $a); $emailupdatetitle = get_string('emailupdatetitle', 'auth', $a); // Email confirmation directly rather than using messaging so they will definitely get an email. $supportuser = core_user::get_support_user(); if (!($mailresults = email_to_user($tempuser, $supportuser, $emailupdatetitle, $emailupdatemessage))) { die("could not send email!"); } } // Reload from db, we need new full name on this page if we do not redirect. $user = $DB->get_record('user', array('id' => $user->id), '*', MUST_EXIST); if ($USER->id == $user->id) { // Override old $USER session variable if needed. foreach ((array) $user as $variable => $value) { if ($variable === 'description' or $variable === 'password') { // These are not set for security nad perf reasons. continue; } $USER->{$variable} = $value; }
/** * Notify admin users or admin user of any failed logins (since last notification). * * Note that this function must be only executed from the cron script * It uses the cache_flags system to store temporary records, deleting them * by name before finishing * * @return bool True if executed, false if not */ function notify_login_failures() { global $CFG, $DB, $OUTPUT; if (empty($CFG->notifyloginfailures)) { return false; } $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config'); if (empty($CFG->lastnotifyfailure)) { $CFG->lastnotifyfailure = 0; } // If it has been less than an hour, or if there are no recipients, don't execute. if (time() - HOURSECS < $CFG->lastnotifyfailure || !is_array($recip) || count($recip) <= 0) { return false; } // we need to deal with the threshold stuff first. if (empty($CFG->notifyloginthreshold)) { $CFG->notifyloginthreshold = 10; // default to something sensible. } // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure // and insert them into the cache_flags temp table $sql = "SELECT ip, COUNT(*)\n FROM {log}\n WHERE module = 'login' AND action = 'error'\n AND time > ?\n GROUP BY ip\n HAVING COUNT(*) >= ?"; $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold); $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $iprec) { if (!empty($iprec->ip)) { set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0); } } $rs->close(); // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure // and insert them into the cache_flags temp table $sql = "SELECT info, count(*)\n FROM {log}\n WHERE module = 'login' AND action = 'error'\n AND time > ?\n GROUP BY info\n HAVING count(*) >= ?"; $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold); $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $inforec) { if (!empty($inforec->info)) { set_cache_flag('login_failure_by_info', $inforec->info, '1', 0); } } $rs->close(); // Now, select all the login error logged records belonging to the ips and infos // since lastnotifyfailure, that we have stored in the cache_flags table $sql = "SELECT * FROM (\n SELECT l.*, u.firstname, u.lastname\n FROM {log} l\n JOIN {cache_flags} cf ON l.ip = cf.name\n LEFT JOIN {user} u ON l.userid = u.id\n WHERE l.module = 'login' AND l.action = 'error'\n AND l.time > ?\n AND cf.flagtype = 'login_failure_by_ip'\n UNION ALL\n SELECT l.*, u.firstname, u.lastname\n FROM {log} l\n JOIN {cache_flags} cf ON l.info = cf.name\n LEFT JOIN {user} u ON l.userid = u.id\n WHERE l.module = 'login' AND l.action = 'error'\n AND l.time > ?\n AND cf.flagtype = 'login_failure_by_info') t\n ORDER BY t.time DESC"; $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure); // Init some variables $count = 0; $messages = ''; // Iterate over the logs recordset $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $log) { $log->time = userdate($log->time); $messages .= get_string('notifyloginfailuresmessage', '', $log) . "\n"; $count++; } $rs->close(); // If we have something useful to report. if ($count > 0) { $site = get_site(); $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname)); // Calculate the complete body of notification (start + messages + end) $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) . ($CFG->lastnotifyfailure != 0 ? '(' . userdate($CFG->lastnotifyfailure) . ')' : '') . "\n\n" . $messages . "\n\n" . get_string('notifyloginfailuresmessageend', '', $CFG->wwwroot) . "\n\n"; // For each destination, send mail mtrace('Emailing admins about ' . $count . ' failed login attempts'); foreach ($recip as $admin) { //emailing the admins directly rather than putting these through the messaging system email_to_user($admin, core_user::get_support_user(), $subject, $body); } } // Update lastnotifyfailure with current time set_config('lastnotifyfailure', time()); // Finally, delete all the temp records we have created in cache_flags $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')"); return true; }
/** * Sends an email containinginformation on how to change your password. * * @param stdClass $user A {@link $USER} object * @return bool Returns true if mail was sent OK and false if there was an error. */ function send_password_change_info($user) { global $CFG; $site = get_site(); $supportuser = core_user::get_support_user(); $systemcontext = context_system::instance(); $data = new stdClass(); $data->firstname = $user->firstname; $data->lastname = $user->lastname; $data->sitename = format_string($site->fullname); $data->admin = generate_email_signoff(); $userauth = get_auth_plugin($user->auth); if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') { $message = get_string('emailpasswordchangeinfodisabled', '', $data); $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname)); // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber. return email_to_user($user, $supportuser, $subject, $message); } if ($userauth->can_change_password() and $userauth->change_password_url()) { // We have some external url for password changing. $data->link .= $userauth->change_password_url(); } else { // No way to change password, sorry. $data->link = ''; } if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) { $message = get_string('emailpasswordchangeinfo', '', $data); $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname)); } else { $message = get_string('emailpasswordchangeinfofail', '', $data); $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname)); } // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber. return email_to_user($user, $supportuser, $subject, $message); }
/** * Generate a fake user for emails based on support settings * * @deprecated since Moodle 2.6 * @see core_user::get_support_user() * @return stdClass user info */ function generate_email_supportuser() { debugging('generate_email_supportuser is deprecated, please use core_user::get_support_user'); return core_user::get_support_user(); }
/** * Gets the user company information for the provided user * * Parameters - $user = stdclass(); * **/ private function get_sender($user) { // Get the user's company. if ($usercompany = company::get_company_byuserid($user->id)) { // Is there a default contact userid? if (isset($usercompany->defaultcontactid)) { $returnid = $usercompany->defaultcontactid; } else { // Use the default support email account. $returnid = core_user::get_support_user(); } } else { // No company use default support user. $returnid = core_user::get_support_user(); } return $returnid; }
function sendConfirmMailToManagers($instance,$info,$applydescription){ global $DB; global $CFG; global $USER; $courseid = $instance->courseid; $apply_setting = $DB->get_records_sql("select name,value from ".$CFG->prefix."config_plugins where plugin='enrol_apply'"); $show_standard_user_profile = $show_extra_user_profile = false; if($instance->customint1 != ''){ ($instance->customint1 == 0)?$show_standard_user_profile = true:$show_standard_user_profile = false; }else{ ($apply_setting['show_standard_user_profile']->value == 0)?$show_standard_user_profile = true:$show_standard_user_profile = false; } if($instance->customint2 != ''){ ($instance->customint2 == 0)?$show_extra_user_profile = true:$show_extra_user_profile = false; }else{ ($apply_setting['show_extra_user_profile']->value == 0)?$show_extra_user_profile = true:$show_extra_user_profile = false; } if($apply_setting['sendmailtomanager']->value == 1){ $course = get_course($courseid); $context = context_system::instance(); $managerType = $DB->get_record('role',array("shortname"=>"manager")); $managers = $DB->get_records('role_assignments', array('contextid'=>$context->id,'roleid'=>$managerType->id)); foreach($managers as $manager){ $userWithManagerRole = $DB->get_record('user',array('id'=>$manager->userid)); $body = '<p>'. get_string('coursename', 'enrol_apply') .': '.format_string($course->fullname).'</p>'; $body .= '<p>'. get_string('applyuser', 'enrol_apply') .': '.$USER->firstname.' '.$USER->lastname.'</p>'; $body .= '<p>'. get_string('comment', 'enrol_apply') .': '.$applydescription.'</p>'; if($show_standard_user_profile){ $body .= '<p><strong>'. get_string('user_profile', 'enrol_apply').'</strong></p>'; $body .= '<p>'. get_string('firstname') .': '.$info->firstname.'</p>'; $body .= '<p>'. get_string('lastname') .': '.$info->lastname.'</p>'; $body .= '<p>'. get_string('email') .': '.$info->email.'</p>'; $body .= '<p>'. get_string('city') .': '.$info->city.'</p>'; $body .= '<p>'. get_string('country') .': '.$info->country.'</p>'; $body .= '<p>'. get_string('preferredlanguage') .': '.$info->lang.'</p>'; $body .= '<p>'. get_string('description') .': '.$info->description_editor['text'].'</p>'; $body .= '<p>'. get_string('firstnamephonetic') .': '.$info->firstnamephonetic.'</p>'; $body .= '<p>'. get_string('lastnamephonetic') .': '.$info->lastnamephonetic.'</p>'; $body .= '<p>'. get_string('middlename') .': '.$info->middlename.'</p>'; $body .= '<p>'. get_string('alternatename') .': '.$info->alternatename.'</p>'; $body .= '<p>'. get_string('url') .': '.$info->url.'</p>'; $body .= '<p>'. get_string('icqnumber') .': '.$info->icq.'</p>'; $body .= '<p>'. get_string('skypeid') .': '.$info->skype.'</p>'; $body .= '<p>'. get_string('aimid') .': '.$info->aim.'</p>'; $body .= '<p>'. get_string('yahooid') .': '.$info->yahoo.'</p>'; $body .= '<p>'. get_string('msnid') .': '.$info->msn.'</p>'; $body .= '<p>'. get_string('idnumber') .': '.$info->idnumber.'</p>'; $body .= '<p>'. get_string('institution') .': '.$info->institution.'</p>'; $body .= '<p>'. get_string('department') .': '.$info->department.'</p>'; $body .= '<p>'. get_string('phone') .': '.$info->phone1.'</p>'; $body .= '<p>'. get_string('phone2') .': '.$info->phone2.'</p>'; $body .= '<p>'. get_string('address') .': '.$info->address.'</p>'; } if($show_extra_user_profile){ require_once($CFG->dirroot.'/user/profile/lib.php'); $user = $DB->get_record('user',array('id'=>$USER->id)); profile_load_custom_fields($user); foreach ($user->profile as $key => $value) { $body .= '<p>'. $key .': '.$value.'</p>'; } } $body .= '<p>'. html_writer::link(new moodle_url('/enrol/apply/manage.php'), get_string('applymanage', 'enrol_apply')).'</p>'; $contact = core_user::get_support_user(); $info = $userWithManagerRole; $info->coursename = $course->fullname; email_to_user($info, $contact, get_string('mailtoteacher_suject', 'enrol_apply'), html_to_text($body), $body); } } }
/** * Send confirmation email when the cron has send all the coupons * * @param int $ownerid * @param int $timecreated * @return bool */ public static final function confirm_coupons_sent($ownerid, $timecreated) { global $CFG, $DB; require_once $CFG->libdir . '/phpmailer/moodle_phpmailer.php'; $owner = $DB->get_record('user', array('id' => $ownerid)); $supportuser = \core_user::get_support_user(); $mailcontent = get_string("confirm_coupons_sent_body", 'block_coupon', array('timecreated' => date('Y-m-d', $timecreated))); // Send. $phpmailer = new \moodle_phpmailer(); $phpmailer->Body = $mailcontent; $phpmailer->AltBody = strip_tags($mailcontent); $phpmailer->From = $supportuser->email; $phpmailer->FromName = trim($supportuser->firstname . ' ' . $supportuser->lastname); $phpmailer->IsHTML(true); $phpmailer->Subject = get_string('confirm_coupons_sent_subject', 'block_coupon'); $phpmailer->AddAddress($owner->email); return $phpmailer->Send(); }
/** * Send welcome email to specified user. * * @param stdClass $instance * @param stdClass $user user record * @return void */ public function email_welcome_message($instance, $user) { global $CFG, $DB; $username = isset($instance->newusername) ? $instance->newusername : null; $password = isset($instance->newaccountpassword) ? $instance->newaccountpassword : null; $course = $DB->get_record('course', array('id' => $instance->courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); $a = new stdClass(); $a->coursename = format_string($course->fullname, true, array('context' => $context)); $a->courseurl = "{$CFG->wwwroot}/course/view.php?id={$course->id}"; $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$course->id}"; $a->forgottenpasswordurl = "{$CFG->wwwroot}/login/forgot_password.php"; $a->username = $username ? $username : ''; $a->password = $password ? $password : ''; if (trim($instance->customtext1) !== '') { // If there is a custom welcome message use it $message = $instance->customtext1; $message = str_replace('{$a->coursename}', $a->coursename, $message); $message = str_replace('{$a->courseurl}', $a->courseurl, $message); $message = str_replace('{$a->profileurl}', $a->profileurl, $message); $message = str_replace('{$a->forgottenpasswordurl}', $a->forgottenpasswordurl, $message); if (strpos($message, '<') === false) { // Plain text only. $messagetext = $message; $messagehtml = text_to_html($messagetext, null, false, true); } else { // This is most probably the tag/newline soup known as FORMAT_MOODLE $messagetext = html_to_text($messagehtml); $messagehtml = format_text($message, FORMAT_MOODLE, array('context' => $context, 'para' => false, 'newlines' => true, 'filter' => true)); } } else { // Otherwise use the default defined in the language file $messagetext = get_string('welcometocoursetext', 'enrol_magento', $a); $messagehtml = get_string('welcometocoursetexthtml', 'enrol_magento', $a); } if ($username && $password) { $messagetext .= get_string('newcredentials', 'enrol_magento', $a); $messagehtml .= get_string('newcredentialshtml', 'enrol_magento', $a); } else { $messagetext .= get_string('existinguser', 'enrol_magento', $a); $messagehtml .= get_string('existinguserhtml', 'enrol_magento', $a); } $subject = get_string('welcometocourse', 'enrol_magento', format_string($course->fullname, true, array('context' => $context))); $rusers = array(); if (!empty($CFG->coursecontact)) { $croles = explode(',', $CFG->coursecontact); list($sort, $sortparams) = users_order_by_sql('u'); $rusers = get_role_users($croles, $context, true, '', 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams); } if ($rusers) { $contact = reset($rusers); } else { $contact = core_user::get_support_user(); } email_to_user($user, $contact, $subject, $messagetext, $messagehtml); }
/** * Handle failure of sender verification. * * This will send a notification to the user identified in the Inbound Message address informing them that a message has been * stored. The message includes a verification link and reply-to address which is handled by the * invalid_recipient_handler. * * @param \Horde_Imap_Client_Ids $messageids * @param string $recipient The message recipient * @return bool */ private function handle_verification_failure(\Horde_Imap_Client_Ids $messageids, $recipient) { global $DB, $USER; if (!($messageid = $this->currentmessagedata->messageid)) { mtrace("---> Warning: Unable to determine the Message-ID of the message."); return false; } // Move the message into a new mailbox. $this->client->copy(self::MAILBOX, $this->get_confirmation_folder(), array('create' => true, 'ids' => $messageids, 'move' => true)); // Store the data from the failed message in the associated table. $record = new \stdClass(); $record->messageid = $messageid; $record->userid = $USER->id; $record->address = $recipient; $record->timecreated = time(); $record->id = $DB->insert_record('messageinbound_messagelist', $record); // Setup the Inbound Message generator for the invalid recipient handler. $addressmanager = new \core\message\inbound\address_manager(); $addressmanager->set_handler('\\tool_messageinbound\\message\\inbound\\invalid_recipient_handler'); $addressmanager->set_data($record->id); $eventdata = new \stdClass(); $eventdata->component = 'tool_messageinbound'; $eventdata->name = 'invalidrecipienthandler'; $userfrom = clone $USER; $userfrom->customheaders = array(); // Adding the In-Reply-To header ensures that it is seen as a reply. $userfrom->customheaders[] = 'In-Reply-To: ' . $messageid; // The message will be sent from the intended user. $eventdata->userfrom = \core_user::get_support_user(); $eventdata->userto = $USER; $eventdata->subject = $this->get_reply_subject($this->currentmessagedata->envelope->subject); $eventdata->fullmessage = get_string('invalidrecipientdescription', 'tool_messageinbound', $this->currentmessagedata); $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = get_string('invalidrecipientdescriptionhtml', 'tool_messageinbound', $this->currentmessagedata); $eventdata->smallmessage = $eventdata->fullmessage; $eventdata->notification = 1; $eventdata->replyto = $addressmanager->generate($USER->id); mtrace("--> Sending a message to the user to report an verification failure."); if (!message_send($eventdata)) { mtrace("---> Warning: Message could not be sent."); return false; } return true; }
function user_signup($user, $notify = false) { global $CFG, $DB, $SESSION; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/enrol/token/lib.php'; $lang = empty($user->lang) ? $CFG->lang : $user->lang; $site = get_site(); $supportuser = core_user::get_support_user(); $newpassword = generate_password(); // the token the user entered (which is now validated) $tokenValue = $user->token; $newuser = new stdClass(); $newuser->auth = 'token'; // since technially this auth plugin is a skin $newuser->firstname = $user->firstname; $newuser->lastname = $user->lastname; $newuser->password = hash_internal_user_password($newpassword, false); $newuser->policyagreed = 1; // might need to put this in somewhere $newuser->username = $user->email; $newuser->email = $user->email; $newuser->lastip = getremoteaddr(); $newuser->timecreated = time(); $newuser->timemodified = $newuser->timecreated; $newuser->mnethostid = $CFG->mnet_localhost_id; $newuser = self::truncate_user_obj($newuser); if (($newuser->id = $DB->insert_record('user', $newuser)) === false) { notice(get_string('signupfailure', 'auth_token'), $CFG->wwwroot); return false; } $user = get_complete_user_data('id', $newuser->id); \core\event\user_created::create_from_userid($user->id)->trigger(); // just the query part of post-login redirect $params = empty($SESSION->wantsurl) === true ? '' : parse_url($SESSION->wantsurl, PHP_URL_QUERY); $a = new stdClass(); $a->firstname = $user->firstname; $a->lastname = $user->lastname; $a->username = $user->username; $a->password = $newpassword; $a->sitename = format_string($site->fullname); $a->link = $CFG->wwwroot . '/auth/token/login.php?' . $params; $a->signoff = generate_email_signoff(); $message = (string) new lang_string('signup_userregoemail', 'auth_token', $a, $lang); $subject = format_string($site->fullname) . ': ' . (string) new lang_string('newusernewpasswordsubj', '', $a, $lang); // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber. email_to_user($user, $supportuser, $subject, $message); // log the user in immediately if (($user = authenticate_user_login($user->username, $newpassword)) === false || complete_user_login($user) == null) { notice(get_string('autologinfailure', 'auth_token'), $CFG->wwwroot); return false; } // now, actually DO the enrolment for this course / user $token_plugin = new enrol_token_plugin(); $courseId = 0; $return_to_url = empty($SESSION->wantsurl) === true ? $CFG->wwwroot : $SESSION->wantsurl; $enrolled_ok = $token_plugin->doEnrolment($tokenValue, $courseId, $return_to_url); if ($enrolled_ok == true) { redirect($return_to_url); } return $enrolled_ok == true; }
/** * Sends the student their issued certificate as an email * attachment. * * @param $issuecert The issue certificate object */ protected function send_certificade_email(stdClass $issuecert) { global $DB, $CFG; if (!($user = $DB->get_record('user', array('id' => $issuecert->userid)))) { print_error('nousersfound', 'moodle'); } $info = new stdClass(); $info->username = format_string(fullname($user), true); $info->certificate = format_string($issuecert->certificatename, true); $info->course = format_string($this->get_instance()->coursename, true); $subject = get_string('emailstudentsubject', 'simplecertificate', $info); $message = get_string('emailstudenttext', 'simplecertificate', $info) . "\n"; // Make the HTML version more XHTML happy (&) $messagehtml = text_to_html($message); // Get generated certificate file if ($file = $this->get_issue_file($issuecert)) { //put in a tmp dir, for e-mail attachament $fullfilepath = $this->create_temp_file($file->get_filename()); $file->copy_content_to($fullfilepath); $relativefilepath = str_replace($CFG->dataroot . DIRECTORY_SEPARATOR, "", $fullfilepath); if (strpos($relativefilepath, DIRECTORY_SEPARATOR, 1) === 0) { $relativefilepath = substr($relativefilepath, 1); } if (!empty($this->get_instance()->emailfrom)) { $from = core_user::get_support_user(); $from->email = format_string($this->get_instance()->emailfrom, true); } else { $from = format_string($this->get_instance()->emailfrom, true); } $ret = email_to_user($user, $from, $subject, $message, $messagehtml, $relativefilepath, $file->get_filename()); @unlink($fullfilepath); return $ret; } else { error_log(get_string('filenotfound', 'simplecertificate')); print_error(get_string('filenotfound', 'simplecertificate')); } }
function email_send_start_first_session_batch(){ global $DB,$CFG; $active_batches=$DB->get_records_sql("SELECT * FROM {facetoface} WHERE active=1"); foreach($active_batches as $active_batche){ $sql="SELECT fss.id,fssd.timestart,fssd.timefinish FROM {facetoface_sessions} as fss JOIN {facetoface_sessions_dates} as fssd ON fssd.sessionid=fss.id where fss.facetoface=$active_batche->id ORDER BY fssd.timestart ASC LIMIT 1"; $batch_firstsession_date=$DB->get_record_sql($sql); $now = time(); // or your date as well $diff_fs = userdate("%d/%m/%Y",$batch_firstsession_date->timestart) - $now; //$diff_fs= floor($datediff_fs/(60*60*24)) ; /* This condition checked date difference between // *firstsession start date and present date */ //$session_infos=$DB->get_records_sql("SELECT * FROM `mdl_facetoface_sessions` as fss // JOIN `mdl_facetoface_sessions_dates` as fsd ON fsd.sessionid=fss.id // where fss.facetoface=$active_batche->id"); if(($diff_fs==-1&&!empty($batch_firstsession_date))){ $batch_users=$DB->get_records_sql("SELECT * FROM {local_batch_users} WHERE f2fid=$active_batche->id"); $session_infos=$DB->get_records_sql("SELECT * FROM {facetoface_sessions} as fss JOIN {facetoface_sessions_dates} as fsd ON fsd.sessionid=fss.id where fss.facetoface=$active_batche->id"); $html_m1 = '<h4 style="text-align:center;font-weight:bold;width:100%">'.$active_batche->name.' '.' Batch '.'SESSION DETAILS</h2>'; $html_m1.= '<table style="width: 100%;">'; foreach($session_infos as $session_info){ $html = html_writer::empty_tag('br'); $sessionobj = facetoface_format_session_times($session_info->timestart, $session_info->timefinish, $session_info->sessiontimezone); if ($sessionobj->startdate == $sessionobj->enddate) { $html .= $sessionobj->startdate . ', '; } else { $html .= $sessionobj->startdate . ' - ' . $sessionobj->enddate . ', '; } $html .= $sessionobj->starttime . ' - ' . $sessionobj->endtime . ' ' . $sessionobj->timezone; $duration=$session_info->duration/60; $html_m1.='<tr style="border-top:1px solid #ccc;border-bottom:1px solid #ccc;height: 50px;">'; $html_m1.='<td class="crm_details">Session Timings:</td>'; $html_m1.='<td>'.$html.'</td>'; $html_m1.='</tr>'; } $html_m1.='</table>'; //echo $html_m1; foreach($batch_users as $batch_user){ //echo "dsasdasd"; $user=$DB->get_record('user',array('id'=>$batch_user->userid)); $invitationmail=new stdClass(); $invitationmail->name=fullname($user); $invitationmail->subject=get_string('invationmail', 'facetoface'); //$invitationmail->sessionname=$nominee->name; //$invitationmail->reason=$nominee->reason; $to=$user; $from = core_user::get_support_user(); //$messagetext=get_string('invationmailmsg','facetoface'); //echo $html_m1; email_to_user($to, $from,$invitationmail->subject,$html_m1);//mail for employees } $batch_supervisorids=$DB->get_records_sql("SELECT supervisorid FROM {local_batch_users} WHERE f2fid=$active_batche->id and supervisorid!='' group by supervisorid"); foreach($batch_supervisorids as $batch_supervisorid){ $user=$DB->get_record('user',array('id'=>$batch_supervisorid->supervisorid)); $invitationmail=new stdClass(); $invitationmail->name=fullname($user); $invitationmail->subject=get_string('invationmail', 'facetoface'); //$invitationmail->sessionname=$nominee->name; //$invitationmail->reason=$nominee->reason; $to=$user; $from = core_user::get_support_user(); //$messagetext=get_string('invationmailmsg','facetoface'); email_to_user($to, $from,$invitationmail->subject,$html_m1);//mail for supervisiors } $user=$DB->get_record('user',array('id'=>$active_batche->trainerid)); $invitationmail=new stdClass(); $invitationmail->name=fullname($user); $invitationmail->subject=get_string('invationmail', 'facetoface'); //$invitationmail->sessionname=$nominee->name; //$invitationmail->reason=$nominee->reason; $to=$user; $from = core_user::get_support_user(); //$messagetext=get_string('invationmailmsg','facetoface'); email_to_user($to, $from,$invitationmail->subject,$html_m1);//mail for tariners } } }
} else { $teacher = false; } $mailstudents = $plugin->get_config('mailstudents'); $mailteachers = $plugin->get_config('mailteachers'); $mailadmins = $plugin->get_config('mailadmins'); $shortname = format_string($course->shortname, true, array('context' => $context)); if (!empty($mailstudents)) { $a = new stdClass(); $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext)); $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}"; $eventdata = new stdClass(); $eventdata->modulename = 'moodle'; $eventdata->component = 'enrol_paypal'; $eventdata->name = 'paypal_enrolment'; $eventdata->userfrom = empty($teacher) ? core_user::get_support_user() : $teacher; $eventdata->userto = $user; $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname); $eventdata->fullmessage = get_string('welcometocoursetext', '', $a); $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = ''; $eventdata->smallmessage = ''; message_send($eventdata); } if (!empty($mailteachers) && !empty($teacher)) { $a->course = format_string($course->fullname, true, array('context' => $coursecontext)); $a->user = fullname($user); $eventdata = new stdClass(); $eventdata->modulename = 'moodle'; $eventdata->component = 'enrol_paypal'; $eventdata->name = 'paypal_enrolment';
/** * Retrieve $user1's contacts (online, offline and strangers) * * @param object $user1 the user whose messages are being viewed * @param object $user2 the user $user1 is talking to. If they are a contact * they will have a variable called 'iscontact' added to their user object * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers) */ function message_get_contacts($user1=null, $user2=null) { global $DB, $CFG, $USER; if (empty($user1)) { $user1 = $USER; } if (!empty($user2)) { $user2->iscontact = false; } $timetoshowusers = 300; //Seconds default if (isset($CFG->block_online_users_timetosee)) { $timetoshowusers = $CFG->block_online_users_timetosee * 60; } // time which a user is counting as being active since $timefrom = time()-$timetoshowusers; // people in our contactlist who are online $onlinecontacts = array(); // people in our contactlist who are offline $offlinecontacts = array(); // people who are not in our contactlist but have sent us a message $strangers = array(); $userfields = user_picture::fields('u', array('lastaccess')); // get all in our contactlist who are not blocked in our contact list // and count messages we have waiting from each of them $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount FROM {message_contacts} mc JOIN {user} u ON u.id = mc.contactid LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ? WHERE u.deleted = 0 AND mc.userid = ? AND mc.blocked = 0 GROUP BY $userfields ORDER BY u.firstname ASC"; $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id)); foreach ($rs as $rd) { if ($rd->lastaccess >= $timefrom) { // they have been active recently, so are counted online $onlinecontacts[] = $rd; } else { $offlinecontacts[] = $rd; } if (!empty($user2) && $user2->id == $rd->id) { $user2->iscontact = true; } } $rs->close(); // get messages from anyone who isn't in our contact list and count the number // of messages we have from each of them $strangersql = "SELECT $userfields, count(m.id) as messagecount FROM {message} m JOIN {user} u ON u.id = m.useridfrom LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto WHERE u.deleted = 0 AND mc.id IS NULL AND m.useridto = ? GROUP BY $userfields ORDER BY u.firstname ASC"; $rs = $DB->get_recordset_sql($strangersql, array($USER->id)); // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users). foreach ($rs as $rd) { $strangers[$rd->id] = $rd; } $rs->close(); // Add noreply user and support user to the list, if they don't exist. $supportuser = core_user::get_support_user(); if (!isset($strangers[$supportuser->id])) { $supportuser->messagecount = message_count_unread_messages($USER, $supportuser); if ($supportuser->messagecount > 0) { $strangers[$supportuser->id] = $supportuser; } } $noreplyuser = core_user::get_noreply_user(); if (!isset($strangers[$noreplyuser->id])) { $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser); if ($noreplyuser->messagecount > 0) { $strangers[$noreplyuser->id] = $noreplyuser; } } return array($onlinecontacts, $offlinecontacts, $strangers); }
/** * Emails all users under a company that the ARIS link is now activated for them. * * @param array $userids Contains only the ids of users to be emailed * * @throws Exception * @throws dml_exception * @throws dml_missing_record_exception * @throws dml_multiple_records_exception */ public static function emailer_email_users_Q01PTa($userids) { global $DB; $q01pta = optional_param('profile_field_Q01PTa', '', PARAM_ALPHA); if ($q01pta != 'No') { /* * When a user updates their Q01PTa field the Moodle events 2 system fires after a db update of that field for that user, meaning you'll need to iterate through each user id under a * particular company name in the user_info_data table for a No field and set a flag to indicate that the Q01PTa is in fact being set from no to yes rather than yes to yes. This * is to prevent an email being sent when setting the Q01PTa field from yes to yes. */ $emailflag = false; $Q01PTafield = $DB->get_record('user_info_field', array('shortname' => 'Q01PTa')); foreach ($userids as $useridobj) { $user = $DB->get_record('user', array('id' => $useridobj->id)); // Get the existing value of an existing user of an existing company for the Q01PTa field. $userotherfields = $DB->get_record('user_info_data', array('userid' => $user->id, 'fieldid' => $Q01PTafield->id)); if ($userotherfields->data == 'No') { $emailflag = true; } } if ($emailflag) { $coursename = get_config('block_autoemailer', 'autoemailercoursename'); $fromuser = core_user::get_support_user(); $subject = "The ARIS link is now activated"; $message = "The ARIS link is now activated under the course named {$coursename}"; $emailcompanyflag = true; foreach ($userids as $useridobj) { $user = $DB->get_record('user', array('id' => $useridobj->id)); if ($q01pta === 'Yes') { // Send one email to the company directly if ($emailcompanyflag) { // Get the company custom field. Using custom sql since the functions profile_load_custom_fields() and profile_display_fields() don't work. $companyemail = $DB->get_record_sql("\n SELECT data FROM {user_info_field}\n JOIN {user_info_data}\n ON {user_info_field}.id = {user_info_data}.fieldid WHERE {user_info_field}.shortname = ? AND {user_info_data}.userid = ?", array('companyemail', $user->id)); if ($companyemail) { $emailobj = static::emailer_mock_email_object(); $emailobj->email = $companyemail->data; email_to_user($emailobj, $fromuser, $subject, $message, $message); $emailcompanyflag = false; } } email_to_user($user, $fromuser, $subject, $message, $message); } else { return; } } } } }
/** * Register the site (creation / update) * @param object $siteinfo Array * @param boolean $siteurltoupdate * @return string token */ public function register_site($siteinfo, $siteurltoupdate = '') { global $CFG; //$siteinfo must be an object if (is_array($siteinfo)) { $siteinfo = (object) $siteinfo; } //md5 the secret if (isset($siteinfo->secret) and !empty($siteinfo->secret)) { $siteinfo->secret = md5($siteinfo->secret); } //if we create or update a site, it can not be deleted $siteinfo->deleted = 0; // If update, check if the url changed, if yes it could be a potential hack attempt. // Make the site not visible and alert the hub administrator. if (!empty($siteurltoupdate)) { //retrieve current hub info $currentsiteinfo = $this->get_site_by_url($siteurltoupdate); $siteinfo->id = $currentsiteinfo->id; //needed for hub update $emailinfo = new stdClass(); $emailinfo->name = $siteinfo->name; $emailinfo->oldname = $currentsiteinfo->name; // needed for the email params $emailinfo->url = $siteinfo->url; $emailinfo->oldurl = $currentsiteinfo->url; //needed for url testing $emailinfo->contactname = $siteinfo->contactname; $emailinfo->contactemail = $siteinfo->contactemail; $emailinfo->huburl = $CFG->wwwroot; $emailinfo->managesiteurl = $CFG->wwwroot . '/local/hub/admin/managesites.php'; $languages = get_string_manager()->get_list_of_languages(); $emailinfo->language = $languages[$siteinfo->language]; //check if the url or name changed if ($siteinfo->url != $emailinfo->oldurl or $siteinfo->name != $emailinfo->oldname) { //check if the site url already exist if ($siteinfo->url != $emailinfo->oldurl) { $existingurlsite = $this->get_site_by_url($siteinfo->url); if (!empty($existingurlsite)) { throw new moodle_exception('urlalreadyexist', 'local_hub', $CFG->wwwroot); } } //make the site not visible (hub admin need to reconfirm it) $siteinfo->visible = 0; // Alert the hub administrator. email_to_user(get_admin(), core_user::get_support_user(), get_string('emailtitlesiteurlchanged', 'local_hub', $emailinfo->name), get_string('emailmessagesiteurlchanged', 'local_hub', $emailinfo)); } } else { //if creation mode, check that the secret doesn't exist already $checkedhub = $this->get_site_by_secret($siteinfo->secret); if (!empty($checkedhub)) { // No registration process failed but the secret still exists. throw new moodle_exception('sitesecretalreadyexist', 'local_hub'); } } //check if the language exist //Note: it should have been tested on client side $languages = get_string_manager()->get_list_of_languages(); if (!key_exists($siteinfo->language, $languages)) { throw new moodle_exception('errorlangnotrecognized', 'hub', new moodle_url('/index.php')); } //check if the image (imageurl) has a correct size //Note: it should have been tested on client side if (!empty($siteinfo->imageurl)) { //getimagesize is a GD function list($imagewidth, $imageheight, $imagetype, $imageattr) = getimagesize($siteinfo->imageurl); if ($imagewidth > HUBLOGOIMAGEWIDTH or $imageheight > HUBLOGOIMAGEHEIGHT) { $sizestrings = new stdClass(); $sizestrings->width = HUBLOGOIMAGEWIDTH; $sizestrings->height = HUBLOGOIMAGEHEIGHT; throw new moodle_exception('errorbadimageheightwidth', 'local_hub', new moodle_url('/index.php'), $sizestrings); } //TODO we do not record image yet, it could be a security issue $siteinfo->imageurl = ''; } // Little hack: clean parameter from float to int // TODO: change database to accept FLOAT. $siteinfo->courses = (int) $siteinfo->courses; $siteinfo->users = (int) $siteinfo->users; $siteinfo->enrolments = (int) $siteinfo->enrolments; $siteinfo->posts = (int) $siteinfo->posts; $siteinfo->questions = (int) $siteinfo->questions; $siteinfo->participantnumberaverage = (int) $siteinfo->participantnumberaverage; $siteinfo->modulenumberaverage = (int) $siteinfo->modulenumberaverage; $siteinfo->resources = (int) $siteinfo->resources; //Add or update the site into the site directory (hub) if (!empty($siteurltoupdate)) { $this->update_site($siteinfo); //update the communication url if it changed if (!empty($currentsiteinfo) and $siteinfo->url != $currentsiteinfo->url) { $newcommunication = $this->get_communication(WSSERVER, REGISTEREDSITE, $emailinfo->oldurl); $newcommunication->remoteurl = $siteinfo->url; $this->update_communication($newcommunication); } } else { $site = $this->add_site($siteinfo); } //we save the token into the communication table in order to have a reference to the hidden token $sitetohubcommunication = $this->get_communication(WSSERVER, REGISTEREDSITE, $siteinfo->url); if (empty($sitetohubcommunication)) { //create token for the hub $capabilities = array('local/hub:updateinfo', 'local/hub:registercourse', 'local/hub:view', 'local/hub:unregistercourse', 'local/hub:viewsmallinfo'); $tokenusedbysite = $this->create_hub_token('Registered Hub User', 'Registered site', $siteinfo->url . '_registered_site_user', $capabilities); $sitetohubcommunication = new stdClass(); $sitetohubcommunication->token = $tokenusedbysite->token; $sitetohubcommunication->type = WSSERVER; $sitetohubcommunication->remoteentity = REGISTEREDSITE; $sitetohubcommunication->remotename = $siteinfo->name; $sitetohubcommunication->remoteurl = $siteinfo->url; $sitetohubcommunication->confirmed = 1; $sitetohubcommunication->id = $this->add_communication($sitetohubcommunication); } //log the operation if (!empty($siteurltoupdate)) { //we just log, do not send an email to admin for update //(an email was sent previously if the url or name changed) add_to_log(SITEID, 'local_hub', 'site update', '', $siteinfo->id); } else { // Send email to the hub administrator. if (empty($emailinfo)) { $emailinfo = new stdClass(); $emailinfo->name = $siteinfo->name; $emailinfo->url = $siteinfo->url; $emailinfo->contactname = $siteinfo->contactname; $emailinfo->contactemail = $siteinfo->contactemail; $emailinfo->huburl = $CFG->wwwroot; $emailinfo->managesiteurl = $CFG->wwwroot . '/local/hub/admin/managesites.php'; $languages = get_string_manager()->get_list_of_languages(); $emailinfo->language = $languages[$siteinfo->language]; } email_to_user(get_admin(), core_user::get_support_user(), get_string('emailtitlesiteadded', 'local_hub', $emailinfo->name), get_string('emailmessagesiteadded', 'local_hub', $emailinfo)); add_to_log(SITEID, 'local_hub', 'site registration', '', $site->id); } return $sitetohubcommunication->token; }
<?php require '../config.php'; require_once $CFG->libdir . '/eventslib.php'; // Form submitted, do not check referer (original page unknown). if ($form = data_submitted()) { // Only deal with real users. if (!isloggedin()) { redirect($CFG->wwwroot); } // Send the message and redirect. $eventdata = new stdClass(); $eventdata->component = 'moodle'; $eventdata->name = 'errors'; $eventdata->userfrom = $USER; $eventdata->userto = core_user::get_support_user(); $eventdata->subject = 'Error: ' . $form->referer . ' -> ' . $form->requested; $eventdata->fullmessage = $form->text; $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = ''; $eventdata->smallmessage = ''; message_send($eventdata); redirect($CFG->wwwroot . '/course/', 'Message sent, thanks', 3); exit; } $site = get_site(); $redirecturl = empty($_SERVER['REDIRECT_URL']) ? '' : $_SERVER['REDIRECT_URL']; $httpreferer = get_local_referer(false); $requesturi = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI']; header("HTTP/1.0 404 Not Found"); header("Status: 404 Not Found");
/** * Send welcome email to specified user. * * @param stdClass $instance * @param stdClass $user user record * @return void */ protected function email_welcome_message($instance, $user) { global $CFG, $DB; $course = $DB->get_record('course', array('id' => $instance->courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); $a = new stdClass(); $a->coursename = format_string($course->fullname, true, array('context' => $context)); $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$course->id}"; if (trim($instance->customtext1) !== '') { $message = $instance->customtext1; $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}'); $value = array($a->coursename, $a->profileurl, fullname($user), $user->email); $message = str_replace($key, $value, $message); if (strpos($message, '<') === false) { // Plain text only. $messagetext = $message; $messagehtml = text_to_html($messagetext, null, false, true); } else { // This is most probably the tag/newline soup known as FORMAT_MOODLE. $messagehtml = format_text($message, FORMAT_MOODLE, array('context' => $context, 'para' => false, 'newlines' => true, 'filter' => true)); $messagetext = html_to_text($messagehtml); } } else { $messagetext = get_string('welcometocoursetext', 'enrol_self', $a); $messagehtml = text_to_html($messagetext, null, false, true); } $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context' => $context))); $rusers = array(); if (!empty($CFG->coursecontact)) { $croles = explode(',', $CFG->coursecontact); list($sort, $sortparams) = users_order_by_sql('u'); // We only use the first user. $i = 0; do { $rusers = get_role_users($croles[$i], $context, true, '', 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams); $i++; } while (empty($rusers) && !empty($croles[$i])); } if ($rusers) { $contact = reset($rusers); } else { $contact = core_user::get_support_user(); } // Directly emailing welcome message rather than using messaging. email_to_user($user, $contact, $subject, $messagetext, $messagehtml); }
/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { global $CFG, $DB; if (empty($CFG->notifyloginfailures)) { return; } $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config'); if (empty($CFG->lastnotifyfailure)) { $CFG->lastnotifyfailure = 0; } // If it has been less than an hour, or if there are no recipients, don't execute. if (time() - HOURSECS < $CFG->lastnotifyfailure || !is_array($recip) || count($recip) <= 0) { return; } // We need to deal with the threshold stuff first. if (empty($CFG->notifyloginthreshold)) { $CFG->notifyloginthreshold = 10; // Default to something sensible. } // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure // and insert them into the cache_flags temp table. $logmang = get_log_manager(); $readers = $logmang->get_readers('\\core\\log\\sql_internal_reader'); $reader = reset($readers); $readername = key($readers); if (empty($reader) || empty($readername)) { // No readers, no processing. return true; } $logtable = $reader->get_internal_log_table_name(); $sql = "SELECT ip, COUNT(*)\n FROM {" . $logtable . "}\n WHERE eventname = ?\n AND timecreated > ?\n GROUP BY ip\n HAVING COUNT(*) >= ?"; $params = array('\\core\\event\\user_login_failed', $CFG->lastnotifyfailure, $CFG->notifyloginthreshold); $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $iprec) { if (!empty($iprec->ip)) { set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0); } } $rs->close(); // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure // and insert them into the cache_flags temp table. $sql = "SELECT userid, count(*)\n FROM {" . $logtable . "}\n WHERE eventname = ?\n AND timecreated > ?\n GROUP BY userid\n HAVING count(*) >= ?"; $params = array('\\core\\event\\user_login_failed', $CFG->lastnotifyfailure, $CFG->notifyloginthreshold); $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $inforec) { if (!empty($inforec->info)) { set_cache_flag('login_failure_by_id', $inforec->userid, '1', 0); } } $rs->close(); // Now, select all the login error logged records belonging to the ips and infos // since lastnotifyfailure, that we have stored in the cache_flags table. $sql = "SELECT * FROM (\n SELECT l.*, u.username\n FROM {" . $logtable . "} l\n JOIN {cache_flags} cf ON l.ip = cf.name\n LEFT JOIN {user} u ON l.userid = u.id\n WHERE l.eventname = ?\n AND l.timecreated > ?\n AND cf.flagtype = 'login_failure_by_ip'\n UNION ALL\n SELECT l.*, u.username\n FROM {" . $logtable . "} l\n JOIN {cache_flags} cf ON l.userid = " . $DB->sql_cast_char2int('cf.name') . "\n LEFT JOIN {user} u ON l.userid = u.id\n WHERE l.eventname = ?\n AND l.timecreated > ?\n AND cf.flagtype = 'login_failure_by_info') t\n ORDER BY t.timecreated DESC"; $params = array('\\core\\event\\user_login_failed', $CFG->lastnotifyfailure, '\\core\\event\\user_login_failed', $CFG->lastnotifyfailure); // Init some variables. $count = 0; $messages = ''; // Iterate over the logs recordset. $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $log) { $a = new \stdClass(); $a->time = userdate($log->timecreated); if (empty($log->username)) { // Entries with no valid username. We get attempted username from the event's other field. $other = unserialize($log->other); $a->info = empty($other['username']) ? '' : $other['username']; } else { $a->info = $log->username; } $a->ip = $log->ip; $messages .= get_string('notifyloginfailuresmessage', '', $a) . "\n"; $count++; } $rs->close(); // If we have something useful to report. if ($count > 0) { $site = get_site(); $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname)); // Calculate the complete body of notification (start + messages + end). $params = array('id' => 0, 'modid' => 'site_errors', 'chooselog' => '1', 'logreader' => $readername); $url = new \moodle_url('/report/log/index.php', $params); $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) . ($CFG->lastnotifyfailure != 0 ? '(' . userdate($CFG->lastnotifyfailure) . ')' : '') . "\n\n" . $messages . "\n\n" . get_string('notifyloginfailuresmessageend', '', $url->out(false) . ' ') . "\n\n"; // For each destination, send mail. mtrace('Emailing admins about ' . $count . ' failed login attempts'); foreach ($recip as $admin) { // Emailing the admins directly rather than putting these through the messaging system. email_to_user($admin, \core_user::get_support_user(), $subject, $body); } } // Update lastnotifyfailure with current time. set_config('lastnotifyfailure', time()); // Finally, delete all the temp records we have created in cache_flags. $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')"); }
/** * Lockout user and send notification email. * * @param stdClass $user */ function login_lock_account($user) { global $CFG; if ($user->mnethostid != $CFG->mnet_localhost_id) { return; } if (isguestuser($user)) { return; } if (get_user_preferences('login_lockout_ignored', 0, $user)) { // This user can not be locked out. return; } $alreadylockedout = get_user_preferences('login_lockout', 0, $user); set_user_preference('login_lockout', time(), $user); if ($alreadylockedout == 0) { $secret = random_string(15); set_user_preference('login_lockout_secret', $secret, $user); $oldforcelang = force_current_language($user->lang); $site = get_site(); $supportuser = core_user::get_support_user(); $data = new stdClass(); $data->firstname = $user->firstname; $data->lastname = $user->lastname; $data->username = $user->username; $data->sitename = format_string($site->fullname); $data->link = $CFG->wwwroot . '/login/unlock_account.php?u=' . $user->id . '&s=' . $secret; $data->admin = generate_email_signoff(); $message = get_string('lockoutemailbody', 'admin', $data); $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname)); if ($message) { // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber. email_to_user($user, $supportuser, $subject, $message); } force_current_language($oldforcelang); } }
/** * Returns list of recipient users. * * @param stdClass $data * @return array user objects */ protected function get_recipient_users($data, $context) { $recipients = array(); // Admin. if (!empty($data->recipient['admin'])) { $user = get_admin(); $recipients[$user->id] = $user; } // Support. if (!empty($data->recipient['support'])) { if ($user = \core_user::get_support_user()) { $recipients[$user->id] = $user; } } // Author. if (!empty($data->recipient['author'])) { $recipients[$data->recipient['author']] = \core_user::get_user($data->recipient['author']); } // Username. if (!empty($data->recipient['username'])) { $usernames = explode(',', $data->recipient['username']); foreach ($usernames as $username) { if ($user = \core_user::get_user_by_username($username)) { $recipients[$user->id] = $user; } } } // Notification roles. if (!empty($config->recipient['role'])) { if ($users = get_users_by_capability($context, 'mod/dataform:notification')) { foreach ($users as $userid => $user) { $recipients[$userid] = $user; } } } return $recipients; }