/** * Updates the provided users profile picture based upon the expected fields * returned from the edit or edit_advanced forms. * * @global moodle_database $DB * @param stdClass $usernew An object that contains some information about the user being updated * @param moodleform $userform The form that was submitted to edit the form * @return bool True if the user was updated, false if it stayed the same. */ function useredit_update_picture(stdClass $usernew, moodleform $userform) { global $CFG, $DB; require_once("$CFG->libdir/gdlib.php"); $context = get_context_instance(CONTEXT_USER, $usernew->id, MUST_EXIST); // This will hold the value to set to the user's picture field at the end of // this function $picturetouse = null; if (!empty($usernew->deletepicture)) { // The user has chosen to delete the selected users picture $fs = get_file_storage(); $fs->delete_area_files($context->id, 'user', 'icon'); // drop all areas $picturetouse = 0; } else if ($iconfile = $userform->save_temp_file('imagefile')) { // There is a new image that has been uploaded // Process the new image and set the user to make use of it. // NOTE: This may be overridden by Gravatar if (process_new_icon($context, 'user', 'icon', 0, $iconfile)) { $picturetouse = 1; } // Delete the file that has now been processed @unlink($iconfile); } // If we have a picture to set we can now do so. Note this will still be NULL // unless the user has changed their picture or caused a change by selecting // to delete their picture or use gravatar if (!is_null($picturetouse)) { $DB->set_field('user', 'picture', $picturetouse, array('id' => $usernew->id)); return true; } return false; }
/** * Suspend the old user, by suspending its account, and updating the profile picture * to a generic one. * @param object $event stdClass with all event data. * @global moodle_database $DB */ function tool_mergeusers_old_user_suspend($event) { global $DB, $CFG; if ($CFG->branch < 26) { $oldid = $event->oldid; } else { $oldid = $event->other['usersinvolved']['fromid']; } // Check configuration to see if the old user gets suspended $enabled = (int) get_config('tool_mergeusers', 'suspenduser'); if ($enabled !== 1) { return true; } // 1. update auth type $olduser = new stdClass(); $olduser->id = $oldid; $olduser->suspended = 1; $olduser->timemodified = time(); $DB->update_record('user', $olduser); // 2. update profile picture // get source, common image $fullpath = dirname(dirname(__DIR__)) . "/pix/suspended.jpg"; if (!file_exists($fullpath)) { return; //do nothing; aborting, given that the image does not exist } // put the common image as the profile picture. $context = context_user::instance($oldid); if ($newrev = process_new_icon($context, 'user', 'icon', 0, $fullpath)) { $DB->set_field('user', 'picture', $newrev, array('id' => $oldid)); } return true; }
/** * Updates the provided users profile picture based upon the expected fields * returned from the edit or edit_advanced forms. * * @global moodle_database $DB * @param stdClass $usernew An object that contains some information about the user being updated * @param moodleform $userform The form that was submitted to edit the form * @return bool True if the user was updated, false if it stayed the same. */ function useredit_update_picture(stdClass $usernew, moodleform $userform) { global $CFG, $DB; require_once "{$CFG->libdir}/gdlib.php"; $context = get_context_instance(CONTEXT_USER, $usernew->id, MUST_EXIST); $user = $DB->get_record('user', array('id' => $usernew->id), 'id, picture', MUST_EXIST); $newpicture = $user->picture; if (!empty($usernew->deletepicture)) { // The user has chosen to delete the selected users picture $fs = get_file_storage(); $fs->delete_area_files($context->id, 'user', 'icon'); // drop all images in area $newpicture = 0; } else { if ($iconfile = $userform->save_temp_file('imagefile')) { // There is a new image that has been uploaded // Process the new image and set the user to make use of it. // NOTE: Uploaded images always take over Gravatar $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile); // Delete the file that has now been processed @unlink($iconfile); } } if ($newpicture != $user->picture) { $DB->set_field('user', 'picture', $newpicture, array('id' => $user->id)); return true; } else { return false; } }
/** * Updates the provided users profile picture based upon the expected fields * returned from the edit or edit_advanced forms. * * @global moodle_database $DB * @param stdClass $usernew An object that contains some information about the user being updated * @param moodleform $userform The form that was submitted to edit the form * @return bool True if the user was updated, false if it stayed the same. */ function useredit_update_picture(stdClass $usernew, moodleform $userform, $filemanageroptions = array()) { global $CFG, $DB; require_once("$CFG->libdir/gdlib.php"); $context = context_user::instance($usernew->id, MUST_EXIST); $user = $DB->get_record('user', array('id'=>$usernew->id), 'id, picture', MUST_EXIST); $newpicture = $user->picture; // Get file_storage to process files. $fs = get_file_storage(); if (!empty($usernew->deletepicture)) { // The user has chosen to delete the selected users picture $fs->delete_area_files($context->id, 'user', 'icon'); // drop all images in area $newpicture = 0; } else { // Save newly uploaded file, this will avoid context mismatch for newly created users. file_save_draft_area_files($usernew->imagefile, $context->id, 'user', 'newicon', 0, $filemanageroptions); if (($iconfiles = $fs->get_area_files($context->id, 'user', 'newicon')) && count($iconfiles) == 2) { // Get file which was uploaded in draft area foreach ($iconfiles as $file) { if (!$file->is_directory()) { break; } } // Copy file to temporary location and the send it for processing icon if ($iconfile = $file->copy_content_to_temp()) { // There is a new image that has been uploaded // Process the new image and set the user to make use of it. // NOTE: Uploaded images always take over Gravatar $newpicture = (int)process_new_icon($context, 'user', 'icon', 0, $iconfile); // Delete temporary file @unlink($iconfile); // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); } else { // Something went wrong while creating temp file. // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); return false; } } } if ($newpicture != $user->picture) { $DB->set_field('user', 'picture', $newpicture, array('id' => $user->id)); return true; } else { return false; } }
function useredit_update_picture(&$usernew, $userform) { global $CFG, $DB; require_once "{$CFG->libdir}/gdlib.php"; $fs = get_file_storage(); $context = get_context_instance(CONTEXT_USER, $usernew->id, MUST_EXIST); if (isset($usernew->deletepicture) and $usernew->deletepicture) { $fs->delete_area_files($context->id, 'user', 'icon'); // drop all areas $DB->set_field('user', 'picture', 0, array('id' => $usernew->id)); } else { if ($iconfile = $userform->save_temp_file('imagefile')) { if (process_new_icon($context, 'user', 'icon', 0, $iconfile)) { $DB->set_field('user', 'picture', 1, array('id' => $usernew->id)); } @unlink($iconfile); } } }
public function updateProfilePicture() { global $CFG; $has_picture = 0; $mhr_user = $this->getUserOnInstitution(); if (!$mhr_user) { return $has_picture; } $picture_id = $mhr_user->getObject()->profileicon; if (!$picture_id || $picture_id == '') { return $has_picture; } $old_picture = $this->app->selectFromMdlTable('gcr_profile_picture', 'user_id', $this->obj->id, true); if (!$old_picture || $old_picture->picture_id != $picture_id) { $iconfile = gcr::moodledataDir . $mhr_user->getApp()->getShortName() . '/artefact/file/profileicons/originals/' . $picture_id % 256 . '/' . $picture_id; require_once "{$CFG->libdir}/gdlib.php"; $context = get_context_instance(CONTEXT_USER, $this->obj->id, MUST_EXIST); if (process_new_icon($context, 'user', 'icon', 0, $iconfile)) { if ($old_picture) { $this->app->updateMdlTable('gcr_profile_picture', array('picture_id' => $picture_id), array('user_id' => $this->obj->id)); } else { $this->app->insertIntoMdlTable('gcr_profile_picture', array('user_id' => $this->obj->id, 'picture_id' => $picture_id)); } $has_picture = 1; } else { $fs = get_file_storage(); $fs->delete_area_files($context->id, 'user', 'icon'); $this->app->deleteFromMdlTable('gcr_profile_picture', 'user_id', $this->obj->id); $has_picture = 0; } } else { $has_picture = 1; } if ($this->obj->picture != $has_picture) { $this->app->updateMdlTable('user', array('picture' => $has_picture), array('id' => $this->obj->id)); } return $has_picture; }
$u->lang = 'en'; $u->description = 'Who\'s your daddy?'; $u->url = 'http://moodle.org'; $u->idnumber = ''; $u->institution = 'Moodle HQ'; $u->department = 'Rock on!'; $u->phone1 = ''; $u->phone2 = ''; $u->address = ''; // Adds an avatar to the user. Will slow down the process. if (MDK_AVATAR) { $params = array('size' => 160, 'force' => 'y', 'default' => 'wavatar'); $url = new moodle_url('http://www.gravatar.com/avatar/' . md5($u->id . ':' . $u->username), $params); // Temporary file name if (empty($CFG->tempdir)) { $tempdir = $CFG->dataroot . "/temp"; } else { $tempdir = $CFG->tempdir; } $picture = $tempdir . '/' . 'mdk_script_users.jpg'; download_file_content($url->out(false), null, null, false, 5, 2, false, $picture); // Ensures retro compatibility if (class_exists('context_user')) { $context = context_user::instance($u->id); } else { $context = get_context_instance(CONTEXT_USER, $u->id, MUST_EXIST); } $u->picture = process_new_icon($context, 'user', 'icon', 0, $picture); } $DB->update_record('user', $u); }
/** * Authentication hook - is called every time user hit the login page * The code is run only if the param code is mentionned. */ public function loginpage_hook() { global $USER, $SESSION, $CFG, $DB; // Check the Google authorization code. $authorizationcode = optional_param('code', '', PARAM_TEXT); if (!empty($authorizationcode)) { $authprovider = required_param('authprovider', PARAM_ALPHANUMEXT); require_once $CFG->dirroot . '/auth/googleoauth2/classes/provider/' . $authprovider . '.php'; $providerclassname = 'provideroauth2' . $authprovider; $provider = new $providerclassname(); // Try to get an access token (using the authorization code grant). $token = $provider->getAccessToken('authorization_code', ['code' => $authorizationcode]); $accesstoken = $token->accessToken; $refreshtoken = $token->refreshToken; $tokenexpires = $token->expires; // With access token request by curl the email address. if (!empty($accesstoken)) { try { // We got an access token, let's now get the user's details. $userdetails = $provider->getUserDetails($token); // Use these details to create a new profile. switch ($authprovider) { case 'battlenet': // Battlenet as no email notion. // TODO: need to check the idp table for matching user and request user to add his email. // TODO: It will be similar logic for twitter. $useremail = $userdetails->id . '@fakebattle.net'; break; case 'github': $useremails = $provider->getUserEmails($token); // Going to try to find someone with a similar email using googleoauth2 auth. $fallbackuseremail = ''; foreach ($useremails as $githubuseremail) { if ($githubuseremail->verified) { if ($DB->record_exists('user', array('auth' => 'googleoauth2', 'email' => $githubuseremail->email))) { $useremail = $githubuseremail->email; } $fallbackuseremail = $githubuseremail->email; } } // If we didn't find anyone then we take a verified email address. if (empty($useremail)) { $useremail = $fallbackuseremail; } break; case 'vk': // VK doesn't return the email address? if ($userdetails->uid) { $useremail = 'id' . $userdetails->uid . '@vkmessenger.com'; } break; default: $useremail = $userdetails->email; break; } $verified = 1; } catch (Exception $e) { // Failed to get user details. throw new moodle_exception('faileduserdetails', 'auth_googleoauth2'); } // Throw an error if the email address is not verified. if (!$verified) { throw new moodle_exception('emailaddressmustbeverified', 'auth_googleoauth2'); } // Prohibit login if email belongs to the prohibited domain. if ($err = email_is_not_allowed($useremail)) { throw new moodle_exception($err, 'auth_googleoauth2'); } // If email not existing in user database then create a new username (userX). if (empty($useremail) or $useremail != clean_param($useremail, PARAM_EMAIL)) { throw new moodle_exception('couldnotgetuseremail', 'auth_googleoauth2'); // TODO: display a link for people to retry. } // Get the user. // Don't bother with auth = googleoauth2 because authenticate_user_login() will fail it if it's not 'googleoauth2'. $user = $DB->get_record('user', array('email' => $useremail, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id)); // Create the user if it doesn't exist. if (empty($user)) { // Deny login if setting "Prevent account creation when authenticating" is on. if ($CFG->authpreventaccountcreation) { throw new moodle_exception("noaccountyet", "auth_googleoauth2"); } // Get following incremented username. $googleuserprefix = core_text::strtolower(get_config('auth/googleoauth2', 'googleuserprefix')); $lastusernumber = get_config('auth/googleoauth2', 'lastusernumber'); $lastusernumber = empty($lastusernumber) ? 1 : $lastusernumber + 1; // Check the user doesn't exist. $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber)); while ($nextuser) { $lastusernumber++; $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber)); } set_config('lastusernumber', $lastusernumber, 'auth/googleoauth2'); $username = $googleuserprefix . $lastusernumber; // Retrieve more information from the provider. $newuser = new stdClass(); $newuser->email = $useremail; switch ($authprovider) { case 'battlenet': // Battlenet as no firstname/lastname notion. $newuser->firstname = $userdetails->display_name; $newuser->lastname = '[' . $userdetails->clan_tag . ']'; break; case 'github': case 'dropbox': // As Github/Dropbox doesn't provide firstname/lastname, we'll split the name at the first whitespace. $githubusername = explode(' ', $userdetails->name, 2); $newuser->firstname = $githubusername[0]; $newuser->lastname = $githubusername[1]; break; default: $newuser->firstname = $userdetails->firstName; $newuser->lastname = $userdetails->lastName; break; } // Some providers allow empty firstname and lastname. if (empty($newuser->firstname)) { $newuser->firstname = get_string('unknownfirstname', 'auth_googleoauth2'); } if (empty($newuser->lastname)) { $newuser->lastname = get_string('unknownlastname', 'auth_googleoauth2'); } // Retrieve country and city if the provider failed to give it. if (!isset($newuser->country) or !isset($newuser->city)) { $googleipinfodbkey = get_config('auth/googleoauth2', 'googleipinfodbkey'); if (!empty($googleipinfodbkey)) { require_once $CFG->libdir . '/filelib.php'; $curl = new curl(); $locationdata = $curl->get('http://api.ipinfodb.com/v3/ip-city/?key=' . $googleipinfodbkey . '&ip=' . getremoteaddr() . '&format=json'); $locationdata = json_decode($locationdata); } if (!empty($locationdata)) { // TODO: check that countryCode does match the Moodle country code. $newuser->country = isset($newuser->country) ? isset($newuser->country) : $locationdata->countryCode; $newuser->city = isset($newuser->city) ? isset($newuser->city) : $locationdata->cityName; } } create_user_record($username, '', 'googleoauth2'); } else { $username = $user->username; } // Authenticate the user. // TODO: delete this log later. require_once $CFG->dirroot . '/auth/googleoauth2/lib.php'; $userid = empty($user) ? 'new user' : $user->id; oauth_add_to_log(SITEID, 'auth_googleoauth2', '', '', $username . '/' . $useremail . '/' . $userid); $user = authenticate_user_login($username, null); if ($user) { // Set a cookie to remember what auth provider was selected. setcookie('MOODLEGOOGLEOAUTH2_' . $CFG->sessioncookie, $authprovider, time() + DAYSECS * 60, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly); // Prefill more user information if new user. if (!empty($newuser)) { $newuser->id = $user->id; $DB->update_record('user', $newuser); $user = (object) array_merge((array) $user, (array) $newuser); } complete_user_login($user); // Let's save/update the access token for this user. $cansaveaccesstoken = get_config('auth/googleoauth2', 'saveaccesstoken'); if (!empty($cansaveaccesstoken)) { $existingaccesstoken = $DB->get_record('auth_googleoauth2_user_idps', array('userid' => $user->id, 'provider' => $authprovider)); if (empty($existingaccesstoken)) { $accesstokenrow = new stdClass(); $accesstokenrow->userid = $user->id; switch ($authprovider) { case 'battlenet': $accesstokenrow->provideruserid = $userdetails->id; break; default: $accesstokenrow->provideruserid = $userdetails->uid; break; } $accesstokenrow->provider = $authprovider; $accesstokenrow->accesstoken = $accesstoken; $accesstokenrow->refreshtoken = $refreshtoken; $accesstokenrow->expires = $tokenexpires; $DB->insert_record('auth_googleoauth2_user_idps', $accesstokenrow); } else { $existingaccesstoken->accesstoken = $accesstoken; $DB->update_record('auth_googleoauth2_user_idps', $existingaccesstoken); } } // Check if the user picture is the default and retrieve the provider picture. if (empty($user->picture)) { switch ($authprovider) { case 'battlenet': require_once $CFG->libdir . '/filelib.php'; require_once $CFG->libdir . '/gdlib.php'; $imagefilename = $CFG->tempdir . '/googleoauth2-portrait-' . $user->id; $imagecontents = download_file_content($userdetails->portrait_url); file_put_contents($imagefilename, $imagecontents); if ($newrev = process_new_icon(context_user::instance($user->id), 'user', 'icon', 0, $imagefilename)) { $DB->set_field('user', 'picture', $newrev, array('id' => $user->id)); } unlink($imagefilename); break; default: // TODO retrieve other provider profile pictures. break; } } // Create event for authenticated user. $event = \auth_googleoauth2\event\user_loggedin::create(array('context' => context_system::instance(), 'objectid' => $user->id, 'relateduserid' => $user->id, 'other' => array('accesstoken' => $accesstoken))); $event->trigger(); // Redirection. if (user_not_fully_set_up($USER)) { $urltogo = $CFG->wwwroot . '/user/edit.php'; // We don't delete $SESSION->wantsurl yet, so we get there later. } else { if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) { $urltogo = $SESSION->wantsurl; // Because it's an address in this site. unset($SESSION->wantsurl); } else { // No wantsurl stored or external - go to homepage. $urltogo = $CFG->wwwroot . '/'; unset($SESSION->wantsurl); } } $loginrecord = array('userid' => $USER->id, 'time' => time(), 'auth' => 'googleoauth2', 'subtype' => $authprovider); $DB->insert_record('auth_googleoauth2_logins', $loginrecord); redirect($urltogo); } else { // Authenticate_user_login() failure, probably email registered by another auth plugin. // Do a check to confirm this hypothesis. $userexist = $DB->get_record('user', array('email' => $useremail)); if (!empty($userexist) and $userexist->auth != 'googleoauth2') { $a = new stdClass(); $a->loginpage = (string) new moodle_url(empty($CFG->alternateloginurl) ? '/login/index.php' : $CFG->alternateloginurl); $a->forgotpass = (string) new moodle_url('/login/forgot_password.php'); throw new moodle_exception('couldnotauthenticateuserlogin', 'auth_googleoauth2', '', $a); } else { throw new moodle_exception('couldnotauthenticate', 'auth_googleoauth2'); } } } else { throw new moodle_exception('couldnotgetgoogleaccesstoken', 'auth_googleoauth2'); } } else { // If you are having issue with the display buttons option, add the button code directly in the theme login page. if (get_config('auth/googleoauth2', 'oauth2displaybuttons') and empty($_POST['username']) and empty($_POST['password'])) { // Display the button on the login page. require_once $CFG->dirroot . '/auth/googleoauth2/lib.php'; // Insert the html code below the login field. // Code/Solution from Elcentra plugin: https://moodle.org/plugins/view/auth_elcentra. global $PAGE, $CFG; $PAGE->requires->jquery(); $content = str_replace(array("\n", "\r"), array("\\\n", "\\\r"), auth_googleoauth2_display_buttons(false)); $PAGE->requires->css('/auth/googleoauth2/style.css'); $PAGE->requires->js_init_code("buttonsCodeOauth2 = '{$content}';"); $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/googleoauth2/script.js")); } } }
/** * Assign photo to Moodle user account. * * @param string|array $params Requested user parameters. * @param string $skiptoken A skiptoken param from a previous get_users query. For pagination. * @return boolean True on photo updated. */ public function assign_photo($muserid, $user) { global $DB, $CFG, $PAGE; require_once "{$CFG->libdir}/gdlib.php"; $record = $DB->get_record('local_o365_appassign', array('muserid' => $muserid)); $photoid = ''; if (!empty($record->photoid)) { $photoid = $record->photoid; } $result = false; $apiclient = $this->construct_outlook_api($muserid, true); $size = $apiclient->get_photo_metadata($user); $muser = $DB->get_record('user', array('id' => $muserid), 'id, picture', MUST_EXIST); // If there is no meta data, there is no photo. if (empty($size)) { // Profile photo has been deleted. if (!empty($muser->picture)) { // User has no photo. Deleting previous profile photo. $fs = \get_file_storage(); $fs->delete_area_files($context->id, 'user', 'icon'); $DB->set_field('user', 'picture', 0, array('id' => $muser->id)); } $result = false; } else { if ($size['@odata.mediaEtag'] !== $photoid) { if (!empty($size['height']) && !empty($size['width'])) { $image = $apiclient->get_photo($user, $size['height'], $size['width']); } else { $image = $apiclient->get_photo($user); } // Check if json error message was returned. if (!preg_match('/^{/', $image)) { // Update profile picture. $tempfile = tempnam($CFG->tempdir . '/', 'profileimage') . '.jpg'; if (!($fp = fopen($tempfile, 'w+b'))) { @unlink($tempfile); return false; } fwrite($fp, $image); fclose($fp); $context = \context_user::instance($muserid, MUST_EXIST); $newpicture = process_new_icon($context, 'user', 'icon', 0, $tempfile); $photoid = $size['@odata.mediaEtag']; if ($newpicture != $muser->picture) { $DB->set_field('user', 'picture', $newpicture, array('id' => $muser->id)); $result = true; } @unlink($tempfile); } } } if (empty($record)) { $record = new \stdClass(); $record->muserid = $muserid; $record->assigned = 0; } $record->photoid = $photoid; $record->photoupdated = time(); if (empty($record->id)) { $DB->insert_record('local_o365_appassign', $record); } else { $DB->update_record('local_o365_appassign', $record); } return $result; }
/** * Try to save the given file (specified by its full path) as the * picture for the user with the given id. * * @param integer $id the internal id of the user to assign the * picture file to. * @param string $originalfile the full path of the picture file. * * @return mixed new unique revision number or false if not saved */ function my_save_profile_image($id, $originalfile) { $context = context_user::instance($id); return process_new_icon($context, 'user', 'icon', 0, $originalfile); }
/** * Update the group icon from form data * * @param stdClass $group group information * @param stdClass $data * @param stdClass $editform */ function groups_update_group_icon($group, $data, $editform) { global $CFG, $DB; require_once "{$CFG->libdir}/gdlib.php"; $fs = get_file_storage(); $context = context_course::instance($group->courseid, MUST_EXIST); //TODO: it would make sense to allow picture deleting too (skodak) if ($iconfile = $editform->save_temp_file('imagefile')) { if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) { $DB->set_field('groups', 'picture', 1, array('id' => $group->id)); $group->picture = 1; } else { $fs->delete_area_files($context->id, 'group', 'icon', $group->id); $DB->set_field('groups', 'picture', 0, array('id' => $group->id)); $group->picture = 0; } @unlink($iconfile); // Invalidate the group data as we've updated the group record. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid)); } }
/** * Creates a new Joomdle user * XXX Also used to update user profile if the user already exists * * @param string $username Joomla username */ function create_joomdle_user($username, $app = '') { global $CFG, $DB; $username = utf8_decode($username); $username = strtolower($username); /* Creamos el nuevo usuario de Moodle si no está creado */ $conditions = array('username' => $username); $user = $DB->get_record('user', $conditions); if (!$user) { $user = $this->create_joomdle_user_record($username, "", "joomdle"); } // Get user info from Joomla $juser_info = $this->call_method("getUserInfo", $username, $app); if (array_key_exists('email', $juser_info)) { $email = $juser_info['email']; } else { $email = ''; } if (array_key_exists('firstname', $juser_info)) { $firstname = $juser_info['firstname']; } else { $firstname = ''; } if (array_key_exists('lastname', $juser_info)) { $lastname = $juser_info['lastname']; } else { $lastname = ''; } if (array_key_exists('city', $juser_info)) { $city = $juser_info['city']; } else { $city = ''; } if (array_key_exists('country', $juser_info)) { $country = $juser_info['country']; } else { $country = ''; } if (array_key_exists('lang', $juser_info)) { $lang = $juser_info['lang']; } else { $lang = ''; } if (array_key_exists('timezone', $juser_info)) { $timezone = $juser_info['timezone']; } else { $timezone = ''; } if (array_key_exists('phone1', $juser_info)) { $phone1 = $juser_info['phone1']; } else { $phone1 = ''; } if (array_key_exists('phone2', $juser_info)) { $phone2 = $juser_info['phone2']; } else { $phone2 = ''; } if (array_key_exists('address', $juser_info)) { $address = $juser_info['address']; } else { $address = ''; } if (array_key_exists('description', $juser_info)) { $description = $juser_info['description']; } else { $description = ''; } if (array_key_exists('institution', $juser_info)) { $institution = $juser_info['institution']; } else { $institution = ''; } if (array_key_exists('url', $juser_info)) { $url = $juser_info['url']; } else { $url = ''; } if (array_key_exists('icq', $juser_info)) { $icq = $juser_info['icq']; } else { $icq = ''; } if (array_key_exists('skype', $juser_info)) { $skype = $juser_info['skype']; } else { $skype = ''; } if (array_key_exists('aim', $juser_info)) { $aim = $juser_info['aim']; } else { $aim = ''; } if (array_key_exists('yahoo', $juser_info)) { $yahoo = $juser_info['yahoo']; } else { $yahoo = ''; } if (array_key_exists('msn', $juser_info)) { $msn = $juser_info['msn']; } else { $msn = ''; } if (array_key_exists('idnumber', $juser_info)) { $idnumber = $juser_info['idnumber']; } else { $idnumber = ''; } if (array_key_exists('department', $juser_info)) { $department = $juser_info['department']; } else { $department = ''; } if (array_key_exists('lastnamephonetic', $juser_info)) { $lastnamephonetic = $juser_info['lastnamephonetic']; } else { $lastnamephonetic = ''; } if (array_key_exists('firstnamephonetic', $juser_info)) { $firstnamephonetic = $juser_info['firstnamephonetic']; } else { $firstnamephonetic = ''; } if (array_key_exists('middlename', $juser_info)) { $middlename = $juser_info['middlename']; } else { $middlename = ''; } if (array_key_exists('alternatename', $juser_info)) { $alternatename = $juser_info['alternatename']; } else { $alternatename = ''; } //XXX Maybe this can be optimized for a single DB call...$bool = update_record('user', addslashes_recursive($localuser)); en ment/aut.php if (!xmlrpc_is_fault($juser_info)) { /* Actualizamos la informacion del usuario recien creado con los datos de Joomla */ $conditions = array('id' => $user->id); if ($firstname) { $DB->set_field('user', 'firstname', $firstname, $conditions); } if ($lastname) { $DB->set_field('user', 'lastname', $lastname, $conditions); } if ($email) { $DB->set_field('user', 'email', $email, $conditions); } /* Set first access as now */ $DB->set_field('user', 'firstaccess', time(), $conditions); /* Optional data in Joomla, only fill if has a value */ if ($city) { $DB->set_field('user', 'city', $city, $conditions); } if ($country) { $DB->set_field('user', 'country', substr($country, 0, 2), $conditions); } // $DB->set_field('user', 'country', $country, $conditions); if ($lang) { $DB->set_field('user', 'lang', $lang, $conditions); } if ($timezone) { $DB->set_field('user', 'timezone', $timezone, $conditions); } if ($phone1) { $DB->set_field('user', 'phone1', $phone1, $conditions); } if ($phone2) { $DB->set_field('user', 'phone2', $phone2, $conditions); } if ($address) { $DB->set_field('user', 'address', $address, $conditions); } if ($description) { $DB->set_field('user', 'description', $description, $conditions); } if ($institution) { $DB->set_field('user', 'institution', $institution, $conditions); } if ($url) { $DB->set_field('user', 'url', $url, $conditions); } if ($icq) { $DB->set_field('user', 'icq', $icq, $conditions); } if ($skype) { $DB->set_field('user', 'skype', $skype, $conditions); } if ($aim) { $DB->set_field('user', 'aim', $aim, $conditions); } if ($yahoo) { $DB->set_field('user', 'yahoo', $yahoo, $conditions); } if ($msn) { $DB->set_field('user', 'msn', $msn, $conditions); } if ($idnumber) { $DB->set_field('user', 'idnumber', $idnumber, $conditions); } if ($department) { $DB->set_field('user', 'department', $department, $conditions); } if ($lastnamephonetic) { $DB->set_field('user', 'lastnamephonetic', $lastnamephonetic, $conditions); } if ($firstnamephonetic) { $DB->set_field('user', 'firstnamephonetic', $firstnamephonetic, $conditions); } if ($middlename) { $DB->set_field('user', 'middlename', $middlename, $conditions); } if ($alternatename) { $DB->set_field('user', 'alternatename', $alternatename, $conditions); } } /* Get user pic */ if (array_key_exists('pic_url', $juser_info) && $juser_info['pic_url']) { if ($juser_info['pic_url'] != 'none') { $joomla_url = get_config('auth/joomdle', 'joomla_url'); if (strncmp($juser_info['pic_url'], 'http', 4) != 0) { $pic_url = $joomla_url . '/' . $juser_info['pic_url']; } else { $pic_url = $juser_info['pic_url']; } $pic = $this->get_file($pic_url); if ($pic) { //$pic = file_get_contents ($pic_url, false, NULL); $pic = $this->get_file_curl($pic_url); $tmp_file = $CFG->dataroot . '/temp/' . 'tmp_pic'; file_put_contents($tmp_file, $pic); $user = get_complete_user_data('username', $username); // We need this to get user id $context = context_user::instance($user->id); process_new_icon($context, 'user', 'icon', 0, $tmp_file); $conditions = array('id' => $user->id); $DB->set_field('user', 'picture', 1, $conditions); } } } /* Custom fields */ if ($fields = $DB->get_records('user_info_field')) { foreach ($fields as $field) { if (array_key_exists('cf_' . $field->id, $juser_info) && $juser_info['cf_' . $field->id]) { $data = new stdClass(); $data->fieldid = $field->id; $data->data = $juser_info['cf_' . $field->id]; $data->userid = $user->id; /* update custom field */ if ($dataid = $DB->get_field('user_info_data', 'id', array('userid' => $user->id, 'fieldid' => $data->fieldid))) { $data->id = $dataid; $DB->update_record('user_info_data', $data); } else { $DB->insert_record('user_info_data', $data); } } } } return 1; }
/** * Process badge image from form data * * @param badge $badge Badge object * @param string $iconfile Original file */ function badges_process_badge_image(badge $badge, $iconfile) { global $CFG, $USER; require_once $CFG->libdir . '/gdlib.php'; if (!empty($CFG->gdversion)) { process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true); @unlink($iconfile); // Clean up file draft area after badge image has been saved. $context = context_user::instance($USER->id, MUST_EXIST); $fs = get_file_storage(); $fs->delete_area_files($context->id, 'user', 'draft'); } }
/** * Update the group icon from form data * * @param stdClass $group group information * @param stdClass $data * @param stdClass $editform */ function groups_update_group_icon($group, $data, $editform) { global $CFG, $DB; require_once "{$CFG->libdir}/gdlib.php"; $fs = get_file_storage(); $context = context_course::instance($group->courseid, MUST_EXIST); $newpicture = $group->picture; if (!empty($data->deletepicture)) { $fs->delete_area_files($context->id, 'group', 'icon', $group->id); $newpicture = 0; } else { if ($iconfile = $editform->save_temp_file('imagefile')) { if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) { $newpicture = $rev; } else { $fs->delete_area_files($context->id, 'group', 'icon', $group->id); $newpicture = 0; } @unlink($iconfile); } } if ($newpicture != $group->picture) { $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id)); $group->picture = $newpicture; // Invalidate the group data as we've updated the group record. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid)); } }
/** * Try to save the given file (specified by its full path) as the * picture for the user with the given id. * * @param integer $id the internal id of the user to assign the * picture file to. * @param string $originalfile the full path of the picture file. * * @return bool */ function my_save_profile_image($id, $originalfile) { $context = get_context_instance(CONTEXT_USER, $id); return process_new_icon($context, 'user', 'icon', 0, $originalfile); }
/** * This function confirms the remote (ID provider) host's mnet session * by communicating the token and UA over the XMLRPC transport layer, and * returns the local user record on success. * * @param string $token The random session token. * @param mnet_peer $remotepeer The ID provider mnet_peer object. * @return array The local user record. */ function confirm_mnet_session($token, $remotepeer) { global $CFG, $DB; require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; require_once $CFG->libdir . '/gdlib.php'; // verify the remote host is configured locally before attempting RPC call if (!($remotehost = $DB->get_record('mnet_host', array('wwwroot' => $remotepeer->wwwroot, 'deleted' => 0)))) { print_error('notpermittedtoland', 'mnet'); } // set up the RPC request $mnetrequest = new mnet_xmlrpc_client(); $mnetrequest->set_method('auth/mnet/auth.php/user_authorise'); // set $token and $useragent parameters $mnetrequest->add_param($token); $mnetrequest->add_param(sha1($_SERVER['HTTP_USER_AGENT'])); // Thunderbirds are go! Do RPC call and store response if ($mnetrequest->send($remotepeer) === true) { $remoteuser = (object) $mnetrequest->response; } else { foreach ($mnetrequest->error as $errormessage) { list($code, $message) = array_map('trim', explode(':', $errormessage, 2)); if ($code == 702) { $site = get_site(); print_error('mnet_session_prohibited', 'mnet', $remotepeer->wwwroot, format_string($site->fullname)); exit; } $message .= "ERROR {$code}:<br/>{$errormessage}<br/>"; } print_error("rpcerror", '', '', $message); } unset($mnetrequest); if (empty($remoteuser) or empty($remoteuser->username)) { print_error('unknownerror', 'mnet'); exit; } if (user_not_fully_set_up($remoteuser)) { print_error('notenoughidpinfo', 'mnet'); exit; } $remoteuser = mnet_strip_user($remoteuser, mnet_fields_to_import($remotepeer)); $remoteuser->auth = 'mnet'; $remoteuser->wwwroot = $remotepeer->wwwroot; // the user may roam from Moodle 1.x where lang has _utf8 suffix // also, make sure that the lang is actually installed, otherwise set site default if (isset($remoteuser->lang)) { $remoteuser->lang = clean_param(str_replace('_utf8', '', $remoteuser->lang), PARAM_LANG); } if (empty($remoteuser->lang)) { if (!empty($CFG->lang)) { $remoteuser->lang = $CFG->lang; } else { $remoteuser->lang = 'en'; } } $firsttime = false; // get the local record for the remote user $localuser = $DB->get_record('user', array('username' => $remoteuser->username, 'mnethostid' => $remotehost->id)); // add the remote user to the database if necessary, and if allowed // TODO: refactor into a separate function if (empty($localuser) || !$localuser->id) { /* if (empty($this->config->auto_add_remote_users)) { print_error('nolocaluser', 'mnet'); } See MDL-21327 for why this is commented out */ $remoteuser->mnethostid = $remotehost->id; $remoteuser->firstaccess = time(); // First time user in this server, grab it here $remoteuser->id = $DB->insert_record('user', $remoteuser); $firsttime = true; $localuser = $remoteuser; } // check sso access control list for permission first if (!$this->can_login_remotely($localuser->username, $remotehost->id)) { print_error('sso_mnet_login_refused', 'mnet', '', array('user' => $localuser->username, 'host' => $remotehost->name)); } $fs = get_file_storage(); // update the local user record with remote user data foreach ((array) $remoteuser as $key => $val) { if ($key == '_mnet_userpicture_timemodified' and empty($CFG->disableuserimages) and isset($remoteuser->picture)) { // update the user picture if there is a newer verion at the identity provider $usercontext = get_context_instance(CONTEXT_USER, $localuser->id, MUST_EXIST); if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.png')) { $localtimemodified = $usericonfile->get_timemodified(); } else { if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.jpg')) { $localtimemodified = $usericonfile->get_timemodified(); } else { $localtimemodified = 0; } } if (!empty($val) and $localtimemodified < $val) { mnet_debug('refetching the user picture from the identity provider host'); $fetchrequest = new mnet_xmlrpc_client(); $fetchrequest->set_method('auth/mnet/auth.php/fetch_user_image'); $fetchrequest->add_param($localuser->username); if ($fetchrequest->send($remotepeer) === true) { if (strlen($fetchrequest->response['f1']) > 0) { $imagefilename = $CFG->dataroot . '/temp/mnet-usericon-' . $localuser->id; $imagecontents = base64_decode($fetchrequest->response['f1']); file_put_contents($imagefilename, $imagecontents); if (process_new_icon($usercontext, 'user', 'icon', 0, $imagefilename)) { $localuser->picture = 1; } unlink($imagefilename); } // note that since Moodle 2.0 we ignore $fetchrequest->response['f2'] // the mimetype information provided is ignored and the type of the file is detected // by process_new_icon() } } } if ($key == 'myhosts') { $localuser->mnet_foreign_host_array = array(); foreach ($val as $rhost) { $name = clean_param($rhost['name'], PARAM_ALPHANUM); $url = clean_param($rhost['url'], PARAM_URL); $count = clean_param($rhost['count'], PARAM_INT); $url_is_local = stristr($url, $CFG->wwwroot); if (!empty($name) && !empty($count) && empty($url_is_local)) { $localuser->mnet_foreign_host_array[] = array('name' => $name, 'url' => $url, 'count' => $count); } } } $localuser->{$key} = $val; } $localuser->mnethostid = $remotepeer->id; if (empty($localuser->firstaccess)) { // Now firstaccess, grab it here $localuser->firstaccess = time(); } $DB->update_record('user', $localuser); if (!$firsttime) { // repeat customer! let the IDP know about enrolments // we have for this user. // set up the RPC request $mnetrequest = new mnet_xmlrpc_client(); $mnetrequest->set_method('auth/mnet/auth.php/update_enrolments'); // pass username and an assoc array of "my courses" // with info so that the IDP can maintain mnetservice_enrol_enrolments $mnetrequest->add_param($remoteuser->username); $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary, startdate, visible'; $courses = enrol_get_users_courses($localuser->id, false, $fields, 'visible DESC,sortorder ASC'); if (is_array($courses) && !empty($courses)) { // Second request to do the JOINs that we'd have done // inside enrol_get_users_courses() if we had been allowed $sql = "SELECT c.id,\n cc.name AS cat_name, cc.description AS cat_description\n FROM {course} c\n JOIN {course_categories} cc ON c.category = cc.id\n WHERE c.id IN (" . join(',', array_keys($courses)) . ')'; $extra = $DB->get_records_sql($sql); $keys = array_keys($courses); $defaultrole = reset(get_archetype_roles('student')); //$defaultrole = get_default_course_role($ccache[$shortname]); //TODO: rewrite this completely, there is no default course role any more!!! foreach ($keys as $id) { if ($courses[$id]->visible == 0) { unset($courses[$id]); continue; } $courses[$id]->cat_id = $courses[$id]->category; $courses[$id]->defaultroleid = $defaultrole->id; unset($courses[$id]->category); unset($courses[$id]->visible); $courses[$id]->cat_name = $extra[$id]->cat_name; $courses[$id]->cat_description = $extra[$id]->cat_description; $courses[$id]->defaultrolename = $defaultrole->name; // coerce to array $courses[$id] = (array) $courses[$id]; } } else { // if the array is empty, send it anyway // we may be clearing out stale entries $courses = array(); } $mnetrequest->add_param($courses); // Call 0800-RPC Now! -- we don't care too much if it fails // as it's just informational. if ($mnetrequest->send($remotepeer) === false) { // error_log(print_r($mnetrequest->error,1)); } } return $localuser; }
function local_ltiprovider_update_user_profile_image($userid, $url) { global $CFG, $DB; require_once "{$CFG->libdir}/filelib.php"; require_once "{$CFG->libdir}/gdlib.php"; $fs = get_file_storage(); try { $context = context_user::instance($userid, MUST_EXIST); $fs->delete_area_files($context->id, 'user', 'newicon'); $filerecord = array('contextid' => $context->id, 'component' => 'user', 'filearea' => 'newicon', 'itemid' => 0, 'filepath' => '/'); if (!($iconfiles = $fs->create_file_from_url($filerecord, $url, array('calctimeout' => false, 'timeout' => 5, 'skipcertverify' => true, 'connecttimeout' => 5)))) { return "Error downloading profile image from {$url}"; } if ($iconfiles = $fs->get_area_files($context->id, 'user', 'newicon')) { // Get file which was uploaded in draft area foreach ($iconfiles as $file) { if (!$file->is_directory()) { break; } } // Copy file to temporary location and the send it for processing icon if ($iconfile = $file->copy_content_to_temp()) { // There is a new image that has been uploaded // Process the new image and set the user to make use of it. $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile); // Delete temporary file @unlink($iconfile); // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); $DB->set_field('user', 'picture', $newpicture, array('id' => $userid)); return true; } else { // Something went wrong while creating temp file. // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); return "Error creating the downloaded profile image from {$url}"; } } else { return "Error converting downloaded profile image from {$url}"; } } catch (Exception $e) { return "Error downloading profile image from {$url}"; } return "Error downloading profile image from {$url}"; }
/** * Update the group icon from form data * * @param stdClass $group group information * @param stdClass $data * @param stdClass $editform */ function groups_update_group_icon($group, $data, $editform) { global $CFG, $DB; require_once "{$CFG->libdir}/gdlib.php"; $fs = get_file_storage(); $context = get_context_instance(CONTEXT_COURSE, $group->courseid, MUST_EXIST); //TODO: it would make sense to allow picture deleting too (skodak) if ($iconfile = $editform->save_temp_file('imagefile')) { if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) { $DB->set_field('groups', 'picture', 1, array('id' => $group->id)); $group->picture = 1; } else { $fs->delete_area_files($context->id, 'group', 'icon', $group->id); $DB->set_field('groups', 'picture', 0, array('id' => $group->id)); $group->picture = 0; } @unlink($iconfile); } }
$file = $fs->create_file_from_pathname($file_record, $_FILES['picture']['tmp_name']); $fs->delete_area_files($usercontext->id, 'user', 'icon'); file_save_draft_area_files($itemid, $usercontext->id, 'user', 'newicon', 0, array()); if (($iconfiles = $fs->get_area_files($usercontext->id, 'user', 'newicon')) && count($iconfiles) == 2) { // Get file which was uploaded in draft area foreach ($iconfiles as $file) { if (!$file->is_directory()) { break; } } // Copy file to temporary location and the send it for processing icon if ($iconfile = $file->copy_content_to_temp()) { // There is a new image that has been uploaded // Process the new image and set the user to make use of it. // NOTE: Uploaded images always take over Gravatar $newpicture = (int) process_new_icon($usercontext, 'user', 'icon', 0, $iconfile); // Delete temporary file @unlink($iconfile); // Remove uploaded file. $fs->delete_area_files($usercontext->id, 'user', 'newicon'); } } $DB->set_field('user', 'picture', $newpicture, array('id' => $USER->id)); $USER->picture = $newpicture; } if (get_user_preferences('bcp_data')) { $DB->delete_records('user_preferences', array('userid' => $USER->id, 'name' => 'bcp_data')); } if (get_user_preferences('auth_forcepasswordchange')) { $DB->delete_records('user_preferences', array('userid' => $USER->id, 'name' => 'auth_forcepasswordchange')); }
/** * @link http://docs.moodle.org/dev/Authentication_plugins#loginpage_hook.28.29 * * Hook for overriding behaviour of login page. * Another auth hook. Process login if $authorizationcode is defined in OAuth url. * Makes cURL POST/GET request to social webservice and fill response data to Moodle user. * We check access tokens in cookies, if the ones exists - get it from $_COOKIE, if no - setcookie * * @uses $SESSION, $CFG, $DB core global objects/variables * @return void or @moodle_exception if OAuth request returns error or fail * * @author Igor Sazonov ( @tigusigalpa ) */ function loginpage_hook() { global $SESSION, $CFG, $DB; $access_token = false; $authorizationcode = optional_param('oauthcode', '', PARAM_TEXT); // get authorization code from url if (!empty($authorizationcode)) { $authprovider = required_param('authprovider', PARAM_TEXT); // get authorization provider (webservice name) $hack_authprovider = $authprovider == 'yahoo1' || $authprovider == 'yahoo2' ? 'yahoo' : $authprovider; $config_field_str = 'auth_lenauth_' . $hack_authprovider . '_social_id_field'; $this->_field_shortname = $this->_oauth_config->{$config_field_str}; $this->_field_id = $this->_lenauth_get_fieldid(); $params = array(); // params to generate data for token request $encode_params = true; $code = true; $redirect_uri = true; $curl_header = false; $curl_options = array(); //if we have access_token in $_COOKIE, so do not need to make request fot the one $this->_send_oauth_request = !isset($_COOKIE[$authprovider]['access_token']) ? true : false; //if service is not enabled, why should we make request? hack protect. maybe $enabled_str = 'auth_lenauth_' . $hack_authprovider . '_enabled'; if (empty($this->_oauth_config->{$enabled_str})) { throw new moodle_exception('Service not enabled in your LenAuth Settings', 'auth_lenauth'); } switch ($authprovider) { case 'facebook': /** * @link https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.0#exchangecode */ $params['client_id'] = $this->_oauth_config->auth_lenauth_facebook_app_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_facebook_app_secret; break; case 'google': /** * @link https://developers.google.com/accounts/docs/OAuth2Login#exchangecode */ $params['client_id'] = $this->_oauth_config->auth_lenauth_google_client_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_google_client_secret; $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; break; case 'yahoo1': if (!isset($_COOKIE[$authprovider]['access_token']) && !isset($_COOKIE[$authprovider]['oauth_verifier'])) { $params = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&'), array('oauth_callback' => $this->_lenauth_redirect_uri($authprovider))); $code = false; $redirect_uri = false; $this->_send_oauth_request = isset($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']) ? false : true; $oauth_verifier = false; // yahoo =)) if (!$this->_send_oauth_request && isset($SESSION->yahoo_expires) && !empty($SESSION->yahoo_expires)) { $access_token = $SESSION->yahoo_access_token = optional_param('oauth_token', '', PARAM_TEXT); setcookie($authprovider . '[access_token]', $access_token, time() + $SESSION->yahoo_expires); $oauth_verifier = $SESSION->yahoo_oauth_verifier = optional_param('oauth_verifier', '', PARAM_TEXT); setcookie($authprovider . '[oauth_verifier]', $oauth_verifier, time() + $SESSION->yahoo_expires); } else { } } else { $this->_send_oauth_request = false; } break; case 'yahoo2': $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; $curl_options = array('USERPWD' => $this->_oauth_config->auth_lenauth_yahoo_consumer_key . ':' . $this->_oauth_config->auth_lenauth_yahoo_consumer_secret); break; case 'twitter': if (!empty($this->_oauth_config->auth_lenauth_twitter_enabled)) { if (!isset($_COOKIE[$authprovider]['access_token'])) { $params = array_merge($this->_lenauth_twitter_request_array($this->_oauth_config->auth_lenauth_twitter_consumer_secret . '&'), array('oauth_callback' => $this->_lenauth_redirect_uri($authprovider))); $code = false; $redirect_uri = false; $this->_send_oauth_request = isset($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']) ? false : true; $oauth_verifier = false; if (!$this->_send_oauth_request && isset($_COOKIE[$authprovider]['oauth_token_secret'])) { $access_token = $SESSION->twitter_access_token = optional_param('oauth_token', '', PARAM_TEXT); setcookie($authprovider . '[access_token]', $access_token, time() + $this->_settings[$authprovider]['expire'], '/'); $oauth_verifier = $SESSION->twitter_oauth_verifier = optional_param('oauth_verifier', '', PARAM_TEXT); setcookie($authprovider . '[oauth_verifier]', $oauth_verifier, time() + $this->_settings[$authprovider]['expire'], '/'); } else { $curl_header = $this->_lenauth_set_twitter_header($params); } //$curl_header = $this->_lenauth_set_twitter_header($params, $access_token/*, $oauth_token_secret = false*/); /*$curl_options = array( 'CURLOPT_RETURNTRANSFER' => true, 'CURLOPT_FOLLOWLOCATION' => true ); if ( !empty( $params['oauth_callback'] ) ) { $curl_options['CURLOPT_POSTFIELDS'] = http_build_query( array() ); }*/ //TWITTER IS GOOD!! $encode_params = false; } else { $this->_send_oauth_request = false; } } break; case 'vk': /** * @link http://vk.com/dev/auth_sites */ $params['client_id'] = $this->_oauth_config->auth_lenauth_vk_app_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_vk_app_secret; break; case 'yandex': $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; $params['client_id'] = $this->_oauth_config->auth_lenauth_yandex_app_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_yandex_app_password; break; case 'mailru': $params['client_id'] = $this->_oauth_config->auth_lenauth_mailru_site_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_mailru_client_secret; $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; break; //odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye! /*case 'ok': $params['client_id'] = $this->_oauth_config->ok_app_id; $params['client_secret'] = $this->_oauth_config->ok_secret_key; break;*/ //odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye! /*case 'ok': $params['client_id'] = $this->_oauth_config->ok_app_id; $params['client_secret'] = $this->_oauth_config->ok_secret_key; break;*/ default: // if authorization provider is wrong throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth'); } // url for catch token value // exception for Yahoo OAuth, because it like.. if ($code) { $params['code'] = $authorizationcode; } if ($redirect_uri) { $params['redirect_uri'] = $this->_lenauth_redirect_uri($authprovider); } //require cURL from Moodle core require_once $CFG->libdir . '/filelib.php'; // requires library with cURL class $curl = new curl(); //hack for twitter and Yahoo if (!empty($curl_options) && is_array($curl_options)) { $curl->setopt($curl_options); } $curl->resetHeader(); // clean cURL header from garbage //Twitter and Yahoo has an own cURL headers, so let them to be! if (!$curl_header) { $curl->setHeader('Content-Type: application/x-www-form-urlencoded'); } else { $curl->setHeader($curl_header); } // cURL REQUEST for tokens if we hasnt it in $_COOKIE if ($this->_send_oauth_request) { if ($this->_curl_type == 'post') { $curl_tokens_values = $curl->post($this->_settings[$authprovider]['request_token_url'], $encode_params ? $this->_generate_query_data($params) : $params); } else { $curl_tokens_values = $curl->get($this->_settings[$authprovider]['request_token_url'] . '?' . ($encode_params ? $this->_generate_query_data($params) : $params)); } } // check for token response if (!empty($curl_tokens_values) || !$this->_send_oauth_request) { $token_values = array(); // parse token values switch ($authprovider) { case 'facebook': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { parse_str($curl_tokens_values, $token_values); $expires = $token_values['expires']; //5183999 = 2 months $access_token = $token_values['access_token']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'google': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //3600 = 1 hour $access_token = $token_values['access_token']; if (!empty($access_token) && !empty($expires)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'yahoo1': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['oauth_token_secret'])) { parse_str($curl_tokens_values, $token_values); $expires = $SESSION->yahoo_expires = $token_values['oauth_expires_in']; //3600 = 1 hour $access_token = $SESSION->yahoo_access_token = $token_values['oauth_token']; setcookie($authprovider . '[oauth_token_secret]', $token_values['oauth_token_secret'], time() + $SESSION->yahoo_expires); $xoauth_request_auth_url = $token_values['xoauth_request_auth_url']; } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['oauth_verifier']) || isset($SESSION->yahoo_access_token, $SESSION->yahoo_oauth_verifier)) { $access_token = isset($_COOKIE[$authprovider]['access_token']) ? $_COOKIE[$authprovider]['access_token'] : $SESSION->yahoo_access_token; $oauth_verifier = isset($_COOKIE[$authprovider]['oauth_verifier']) ? $_COOKIE[$authprovider]['oauth_verifier'] : $SESSION->yahoo_oauth_verifier; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'yahoo2': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //3600 = 1 hour $access_token = $token_values['access_token']; $refresh_token = $token_values['refresh_token']; $user_id = $token_values['xoauth_yahoo_guid']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); if (!empty($user_id)) { setcookie($authprovider . '[user_id]', $user_id, time() + $expires, '/'); } } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['user_id'])) { $access_token = $_COOKIE[$authprovider]['access_token']; $user_id = $_COOKIE[$authprovider]['user_id']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'twitter': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['oauth_token_secret'])) { parse_str($curl_tokens_values, $token_values); $access_token = $SESSION->twitter_access_token = $token_values['oauth_token']; setcookie($authprovider . '[oauth_token_secret]', $token_values['oauth_token_secret'], time() + $this->_settings[$authprovider]['expire'], '/'); } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['oauth_token_secret']) || isset($SESSION->twitter_access_token, $SESSION->twitter_oauth_verifier)) { $access_token = isset($_COOKIE[$authprovider]['access_token']) ? $_COOKIE[$authprovider]['access_token'] : $SESSION->twitter_access_token; $oauth_verifier = isset($_COOKIE[$authprovider]['oauth_verifier']) ? $_COOKIE[$authprovider]['oauth_verifier'] : $SESSION->twitter_oauth_verifier; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'vk': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); if (isset($token_values['error'])) { throw new moodle_exception('Native VK Error ' . $token_values['error'] . (isset($token_values['error_description']) ? ' with description: ' . $token_values['error_description'] : ''), 'auth_lenauth'); } $expires = $token_values['expires_in']; //86400 = 24 hours $access_token = $token_values['access_token']; if (!empty($access_token) && !empty($expires)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } $user_id = $token_values['user_id']; if (!empty($user_id)) { setcookie($authprovider . '[user_id]', $user_id, time() + $expires, '/'); } /** * VK user may do not enter email, soooo =(( */ $user_email = isset($token_values['email']) ? $token_values['email'] : false; // WOW!!! So early???))) Awesome! if (!empty($user_email)) { setcookie($authprovider . '[user_email]', $user_email, time() + $expires, '/'); } } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['user_id'])) { $access_token = $_COOKIE[$authprovider]['access_token']; $user_id = $_COOKIE[$authprovider]['user_id']; if (isset($_COOKIE[$authprovider]['user_email'])) { $user_email = $_COOKIE[$authprovider]['user_email']; } } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'yandex': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //31536000 = 1 year $access_token = $token_values['access_token']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'mailru': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //86400 = 24 hours $access_token = $token_values['access_token']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { //check native errors if exists if (isset($token_values['error'])) { switch ($token_values['error']) { case 'invalid_client': throw new moodle_exception('Mail.RU invalid OAuth settings. Check your Private Key and Secret Key', 'auth_lenauth'); default: throw new moodle_exception('Mail.RU Unknown Error with code: ' . $token_values['error']); } } if (empty($expires) || empty($access_token)) { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; /*case 'ok': $token_values = json_decode( $curl_tokens_values, true ); $access_token = $token_values['access_token']; break;*/ /*case 'ok': $token_values = json_decode( $curl_tokens_values, true ); $access_token = $token_values['access_token']; break;*/ default: throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth'); } } if (!empty($access_token)) { $queryparams = array(); // array to generate data for final request to get user data $request_api_url = $this->_settings[$authprovider]['request_api_url']; //some services check accounts for verifier, so we will check it too. No unverified accounts, only verified! only hardCORE! $is_verified = true; $image_url = ''; switch ($authprovider) { case 'facebook': $queryparams['access_token'] = $access_token; $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['id']; $user_email = $curl_final_data['email']; $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $is_verified = $curl_final_data['verified']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = 'http://graph.facebook.com/' . $social_uid . '/picture'; } break; /** * @link https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation */ /** * @link https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation */ case 'google': $queryparams['access_token'] = $access_token; $queryparams['alt'] = 'json'; $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); if (isset($curl_final_data['error'])) { if (!empty($curl_final_data['error']['errors']) && is_array($curl_final_data['error']['errors'])) { foreach ($curl_final_data['error']['errors'] as $error) { throw new moodle_exception('Native Google error. Message: ' . $error['message'], 'auth_lenauth'); } } else { throw new moodle_exception('Native Google error', 'auth_lenauth'); } } $social_uid = $curl_final_data['id']; $user_email = $curl_final_data['emails'][0]['value']; $first_name = $curl_final_data['name']['givenName']; $last_name = $curl_final_data['name']['familyName']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data['image']['url']) ? $curl_final_data['image']['url'] : ''; } break; case 'yahoo1': if (!$oauth_verifier) { header('Location: ' . $xoauth_request_auth_url); // yahoo =)) die; } $queryparams1 = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $_COOKIE[$authprovider]['oauth_token_secret']), array('oauth_token' => $access_token, 'oauth_verifier' => $oauth_verifier)); $curl_response_pre = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams1)); parse_str($curl_response_pre, $values); $queryparams2 = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $values['oauth_token_secret']), array('oauth_token' => $values['oauth_token'], 'oauth_session_handle' => $values['oauth_session_handle'])); $yet_another = $curl->post($request_api_url . '?' . $this->_generate_query_data($queryparams2)); parse_str($yet_another, $yet_another_values); $params = array('q' => 'SELECT * FROM social.profile where guid="' . $yet_another_values['xoauth_yahoo_guid'] . '"', 'format' => 'json', 'env' => 'http://datatables.org/alltables.env'); $auth_array = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $yet_another_values['oauth_token_secret']), array('realm' => 'yahooapis.com', 'oauth_token' => $yet_another_values['oauth_token'])); $header = ''; foreach ($auth_array as $key => $value) { $header .= ($header === '' ? ' ' : ',') . $this->urlEncodeRfc3986($key) . '="' . $this->urlEncodeRfc3986($value) . '"'; } $curl->setHeader(array('Expect:', 'Accept: application/json', 'Authorization: OAuth ' . $header)); $curl_response = $curl->post($this->_settings[$authprovider]['yql_url'] . '?' . $this->_generate_query_data($params)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['query']['results']['profile']['guid']; $emails = $curl_final_data['query']['results']['profile']['emails']; if (!empty($emails) && is_array($emails)) { foreach ($emails as $email_array) { $user_email = $email_array['handle']; if (isset($email_array['primary'])) { break; } } } $first_name = $curl_final_data['query']['results']['profile']['givenName']; $last_name = $curl_final_data['query']['results']['profile']['familyName']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data['query']['results']['profile']['image']['imageUrl']) ? $curl_final_data['query']['results']['profile']['image']['imageUrl'] : ''; } break; case 'yahoo2': $request_api_url = 'https://social.yahooapis.com/v1/user/' . $user_id . '/profile?format=json'; $queryparams['access_token'] = $access_token; $now_header = array('Authorization: Bearer ' . $access_token, 'Accept: application/json', 'Content-Type: application/json'); $curl->resetHeader(); $curl->setHeader($now_header); $curl_response = $curl->get($request_api_url, $queryparams); $curl->resetHeader(); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['profile']['guid']; $emails = $curl_final_data['profile']['emails']; if (!empty($emails) && is_array($emails)) { foreach ($emails as $email_array) { $user_email = $email_array['handle']; if (isset($email_array['primary'])) { break; } } } $first_name = $curl_final_data['profile']['givenName']; $last_name = $curl_final_data['profile']['familyName']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data['profile']['image']['imageUrl']) ? $curl_final_data['profile']['image']['imageUrl'] : ''; } break; case 'twitter': if (!$oauth_verifier) { header('Location: ' . $this->_settings[$authprovider]['request_api_url'] . '?' . http_build_query(array('oauth_token' => $access_token))); die; } $queryparams = array_merge($this->_lenauth_twitter_request_array(), array('oauth_verifier' => $oauth_verifier, 'oauth_token' => $access_token, 'oauth_token_secret' => $_COOKIE[$authprovider]['oauth_token_secret'])); $curl_header = $this->_lenauth_set_twitter_header($queryparams, $access_token, $_COOKIE[$authprovider]['oauth_token_secret']); $curl->setHeader($curl_header); $curl_final_data_pre = $curl->post($this->_settings[$authprovider]['token_url'], $queryparams); $json_decoded = json_decode($curl_final_data_pre, true); if (isset($json_decoded['error']) && isset($json_decoded['request'])) { throw new moodle_exception('Native Twitter Error: ' . $json_decoded['error'] . '. For request ' . $json_decoded['request'], 'auth_lenauth'); } parse_str($curl_final_data_pre, $curl_final_data); $social_uid = $curl_final_data['user_id']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url_pre = 'https://twitter.com/' . $curl_final_data['screen_name'] . '/profile_image?size=original'; $image_header = get_headers($image_url_pre, 1); $image_url = $image_header['location']; } break; case 'vk': /** * @link http://vk.com/dev/api_requests */ $queryparams['access_token'] = $access_token; $queryparams['user_id'] = !empty($user_id) ? $user_id : false; $queryparams['v'] = self::$vk_api_version; $curl_response = $curl->post($request_api_url, $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); //$social_uid = ( isset( $user_id ) ) ? $user_id : $curl_final_data['response'][0]['id']; //dont forget about this $social_uid = $queryparams['user_id']; /** * If user_email is empty, its not so scare, because its second login and */ $user_email = isset($user_email) ? $user_email : false; //hack, because VK has bugs sometimes $first_name = $curl_final_data['response'][0]['first_name']; $last_name = $curl_final_data['response'][0]['last_name']; /** * @link http://vk.com/dev/users.get */ $fields_array = array('avatar' => 'photo_200'); $additional_fields_pre = $curl->get('http://api.vk.com/method/users.get?user_ids=' . $social_uid . '&fields=' . join(',', $fields_array)); $additional_fields = json_decode($additional_fields_pre, true); if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($additional_fields['response'][0][$fields_array['avatar']]) ? $additional_fields['response'][0][$fields_array['avatar']] : ''; } break; /** * @link http://api.yandex.ru/oauth/doc/dg/reference/accessing-protected-resource.xml * @link http://api.yandex.ru/login/doc/dg/reference/request.xml */ /** * @link http://api.yandex.ru/oauth/doc/dg/reference/accessing-protected-resource.xml * @link http://api.yandex.ru/login/doc/dg/reference/request.xml */ case 'yandex': $queryparams['format'] = $this->_settings[$authprovider]['format']; $queryparams['oauth_token'] = $access_token; $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['id']; /** * fix @since 24.12.2014. Thanks for Yandex Tech team guys!! * @link https://tech.yandex.ru/passport/ */ $user_email = $curl_final_data['default_email']; //was $curl_final_data['emails'][0]; - wrong! $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $nickname = $curl_final_data['display_name']; //for future if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { /** * @link https://tech.yandex.ru/passport/doc/dg/reference/response-docpage/#norights_5 */ $yandex_avatar_size = 'islands-200'; if (isset($curl_final_data['default_avatar_id'])) { $image_url = 'https://avatars.yandex.net/get-yapic/' . $curl_final_data['default_avatar_id'] . '/' . $yandex_avatar_size; } } break; case 'mailru': $queryparams['app_id'] = $params['client_id']; $secret_key = $params['client_secret']; /** * @link http://api.mail.ru/docs/reference/rest/users-getinfo/ */ $queryparams['method'] = 'users.getInfo'; $queryparams['session_key'] = $access_token; $queryparams['secure'] = 1; /** * Additional security from mail.ru * @link http://api.mail.ru/docs/guides/restapi/#sig */ ksort($queryparams); $sig = ''; foreach ($queryparams as $k => $v) { $sig .= "{$k}={$v}"; } $queryparams['sig'] = md5($sig . $secret_key); $curl_response = $curl->post($request_api_url, $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data[0]['uid']; $user_email = $curl_final_data[0]['email']; $first_name = $curl_final_data[0]['first_name']; $last_name = $curl_final_data[0]['last_name']; $is_verified = $curl_final_data[0]['is_verified']; $birthday = $curl_final_data[0]['birthday']; //dd.mm.YYYY if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data[0]['pic_big']) ? $curl_final_data[0]['pic_big'] : ''; } break; /*case 'ok': $queryparams['access_token'] = $access_token; $queryparams['method'] = 'users.getCurrentUser'; $queryparams['sig'] = md5( 'application_key=' . $this->_oauth_config->ok_public_key . 'method=' . $queryparams['method'] . md5( $queryparams['access_token'] . $this->_oauth_config->ok_secret_key ) ); $queryparams['application_key'] = $this->_oauth_config->ok_public_key; $curl_response = $curl->get( $request_api_url . '?' . $this->_generate_query_data( $queryparams ) ); $curl_final_data = json_decode( $curl_response, true ); $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $social_uid = $curl_final_data['uid']; break;*/ /*case 'ok': $queryparams['access_token'] = $access_token; $queryparams['method'] = 'users.getCurrentUser'; $queryparams['sig'] = md5( 'application_key=' . $this->_oauth_config->ok_public_key . 'method=' . $queryparams['method'] . md5( $queryparams['access_token'] . $this->_oauth_config->ok_secret_key ) ); $queryparams['application_key'] = $this->_oauth_config->ok_public_key; $curl_response = $curl->get( $request_api_url . '?' . $this->_generate_query_data( $queryparams ) ); $curl_final_data = json_decode( $curl_response, true ); $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $social_uid = $curl_final_data['uid']; break;*/ default: throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth'); } /** * Check for email returned by webservice. If exist - check for user with this email in Moodle Database */ if (!empty($curl_final_data)) { if (!empty($social_uid)) { if ($is_verified) { if (!empty($user_email)) { if ($err = email_is_not_allowed($user_email)) { throw new moodle_exception($err, 'auth_lenauth'); } $user_lenauth = $DB->get_record('user', array('email' => $user_email, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id)); } else { if (empty($user_lenauth)) { $user_lenauth = $this->_lenauth_get_userdata_by_social_id($social_uid); } /*if ( empty( $user_lenauth ) ) { $user_lenauth = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id)); }*/ } } else { throw new moodle_exception('Your social account is not verified', 'auth_lenauth'); } } else { throw new moodle_exception('Empty Social UID', 'auth_lenauth'); } } else { /** * addon @since 24.12.2014 * I forgot about clear $_COOKIE, thanks again for Yandex Tech Team guys!!! */ @setcookie($authprovider, null, time() - 3600); throw new moodle_exception('Final request returns nothing', 'auth_lenauth'); } $last_user_number = intval($this->_oauth_config->auth_lenauth_last_user_number); $last_user_number = empty($last_user_number) ? 1 : $last_user_number + 1; //$username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; //@todo /** * If user with email from webservice not exists, we will create an account */ if (empty($user_lenauth)) { $username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; //check for username exists in DB $user_lenauth_check = $DB->get_record('user', array('username' => $username)); $i_check = 0; while (!empty($user_lenauth_check)) { $user_lenauth_check = $user_lenauth_check + 1; $username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; $user_lenauth_check = $DB->get_record('user', array('username' => $username)); $i_check++; if ($i_check > 20) { throw new moodle_exception('Something wrong with usernames of LenAuth users. Limit of 20 queries is out. Check last mdl_user table of Moodle', 'auth_lenauth'); } } // create user HERE $user_lenauth = create_user_record($username, '', 'lenauth'); /** * User exists... */ } else { $username = $user_lenauth->username; } set_config('auth_lenauth_last_user_number', $last_user_number, 'auth/lenauth'); if (!empty($social_uid)) { $user_social_uid_custom_field = new stdClass(); $user_social_uid_custom_field->userid = $user_lenauth->id; $user_social_uid_custom_field->fieldid = $this->_field_id; $user_social_uid_custom_field->data = $social_uid; if (!$DB->record_exists('user_info_data', array('userid' => $user_lenauth->id, 'fieldid' => $this->_field_id))) { $DB->insert_record('user_info_data', $user_social_uid_custom_field); } else { $record = $DB->get_record('user_info_data', array('userid' => $user_lenauth->id, 'fieldid' => $this->_field_id)); $user_social_uid_custom_field->id = $record->id; $DB->update_record('user_info_data', $user_social_uid_custom_field); } } //add_to_log( SITEID, 'auth_lenauth', '', '', $username . '/' . $user_email . '/' . $userid ); // complete Authenticate user authenticate_user_login($username, null); // fill $newuser object with response data from webservices $newuser = new stdClass(); if (!empty($user_email)) { $newuser->email = $user_email; } if (!empty($first_name)) { $newuser->firstname = $first_name; } if (!empty($last_name)) { $newuser->lastname = $last_name; } if (!empty($this->_oauth_config->auth_lenauth_default_country)) { $newuser->country = $this->_oauth_config->auth_lenauth_default_country; } if ($user_lenauth) { // update user record if (!empty($newuser)) { $newuser->id = $user_lenauth->id; /*require_once( $CFG->libdir . '/gdlib.php' ); $fs = get_file_storage(); $file_obj = $fs->create_file_from_url( array( 'contextid' => context_user::instance( $newuser->id, MUST_EXIST )->id, 'component' => 'user', 'filearea' => 'icon', 'itemid' => 0, 'filepath' => '/', 'source' => '', 'filename' => 'f' . $newuser->id . '.' . $ext ), $image_url ); //$newuser->picture = $file_obj->get_id();*/ $user_lenauth = (object) array_merge((array) $user_lenauth, (array) $newuser); $DB->update_record('user', $user_lenauth); if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { //processing user avatar from social webservice if (!empty($image_url) && intval($user_lenauth->picture) === 0) { $image_header = get_headers($image_url, 1); if (isset($image_header['Content-Type']) && is_string($image_header['Content-Type']) && in_array($image_header['Content-Type'], array_keys(self::$_allowed_icons_types))) { $mime = $image_header['Content-Type']; } else { if (isset($image_header['Content-Type'][0]) && is_string($image_header['Content-Type'][0]) && in_array($image_header['Content-Type'][0], array_keys(self::$_allowed_icons_types))) { $mime = $image_header['Content-Type'][0]; } } $ext = $this->_lenauth_get_image_extension_from_mime($mime); if ($ext) { //create temp file $tempfilename = substr(microtime(), 0, 10) . '.tmp'; $templfolder = $CFG->tempdir . '/filestorage'; if (!file_exists($templfolder)) { mkdir($templfolder, $CFG->directorypermissions); } @chmod($templfolder, 0777); $tempfile = $templfolder . '/' . $tempfilename; if (copy($image_url, $tempfile)) { require_once $CFG->libdir . '/gdlib.php'; $usericonid = process_new_icon(context_user::instance($newuser->id, MUST_EXIST), 'user', 'icon', 0, $tempfile); if ($usericonid) { $DB->set_field('user', 'picture', $usericonid, array('id' => $newuser->id)); } unset($tempfile); } @chmod($templfolder, $CFG->directorypermissions); } } } } complete_user_login($user_lenauth); // complete user login // Redirection $urltogo = $CFG->wwwroot; if (user_not_fully_set_up($user_lenauth)) { $urltogo = $CFG->wwwroot . '/user/edit.php'; } else { if (isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) { $urltogo = $SESSION->wantsurl; unset($SESSION->wantsurl); } else { unset($SESSION->wantsurl); } } } redirect($urltogo); } else { throw new moodle_exception('Could not get access to access token. Check your App Settings', 'auth_lenauth'); } } }
/** * Updates the users profile image. * * @param int $userid the id of the user * @param string $url the url of the image * @return bool|string true if successful, else a string explaining why it failed */ public static function update_user_profile_image($userid, $url) { global $CFG, $DB; require_once $CFG->libdir . '/filelib.php'; require_once $CFG->libdir . '/gdlib.php'; $fs = get_file_storage(); $context = \context_user::instance($userid, MUST_EXIST); $fs->delete_area_files($context->id, 'user', 'newicon'); $filerecord = array('contextid' => $context->id, 'component' => 'user', 'filearea' => 'newicon', 'itemid' => 0, 'filepath' => '/'); $urlparams = array('calctimeout' => false, 'timeout' => 5, 'skipcertverify' => true, 'connecttimeout' => 5); if (!($iconfiles = $fs->create_file_from_url($filerecord, $url, $urlparams))) { return self::PROFILE_IMAGE_UPDATE_FAILED; } $iconfile = $fs->get_area_files($context->id, 'user', 'newicon', false, 'itemid', false); // There should only be one. $iconfile = reset($iconfile); // Something went wrong while creating temp file - remove the uploaded file. if (!($iconfile = $iconfile->copy_content_to_temp())) { $fs->delete_area_files($context->id, 'user', 'newicon'); return self::PROFILE_IMAGE_UPDATE_FAILED; } // Copy file to temporary location and the send it for processing icon. $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile); // Delete temporary file. @unlink($iconfile); // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); // Set the user's picture. $DB->set_field('user', 'picture', $newpicture, array('id' => $userid)); return self::PROFILE_IMAGE_UPDATE_SUCCESSFUL; }
/** * Retrieve the profile picture and save it in moodle. */ private function set_profile_picture($user, $profilepicurl) { global $CFG, $DB; require_once $CFG->libdir . '/filelib.php'; require_once $CFG->libdir . '/gdlib.php'; $imagefilename = $CFG->tempdir . '/googleoauth2-portrait-' . $user->id; $imagecontents = download_file_content($profilepicurl); file_put_contents($imagefilename, $imagecontents); if ($newrev = process_new_icon(context_user::instance($user->id), 'user', 'icon', 0, $imagefilename)) { $DB->set_field('user', 'picture', $newrev, array('id' => $user->id)); } unlink($imagefilename); }