/**
  * Post authentication hook.
  * This method is called from authenticate_user_login() for all enabled auth plugins.
  *
  * @param object $user user object, later used for $USER
  * @param string $username (with system magic quotes)
  * @param string $password plain text password (with system magic quotes)
  */
 function user_authenticated_hook(&$user, $username, $password)
 {
     global $SESSION;
     global $CFG;
     global $DB;
     $record = $DB->get_record('block_gdata_gapps', array('userid' => $user->id));
     if (empty($record) || !empty($record->remove)) {
         return true;
     }
     // Shouldn't need due to Gmail using OAuth
     //
     // TODO: IMPORTANT user_auth hook gets called for all plugins so
     //       setting user to gsaml auth may override all moodle user auth plugins.
     //       auth_gsaml still needs to run the update password code somehow.
     //       if there was another way to test for it.... as compare if password is diff
     //       and then set the google user to the new password. :/
     // Verify that user has a google account. If not create one for them.
     if (!file_exists($CFG->dirroot . '/blocks/gdata/gapps.php')) {
         debugging('gdata block is not installed');
     } else {
         require_once $CFG->dirroot . '/blocks/gdata/gapps.php';
         try {
             $g = new blocks_gdata_gapps();
             try {
                 $g_user = $g->gapps_get_user($username);
                 if (empty($g_user)) {
                     /*
                      * MOODLE must enforce the above minium 6 char passwords!  
                      * http://www.google.com/support/a/bin/answer.py?answer=33386
                      */
                     // Create Moodle User in the Gsync system
                     $g->moodle_create_user($user);
                     // Create google user
                     $m_user = $g->moodle_get_user($user->id);
                     $g->create_user($m_user);
                 }
             } catch (blocks_gdata_exception $e) {
                 // TODO: catch and inform of this common error
                 //if (stripos($e->getMessage(),'Error 1100: UserDeletedRecently') ) {
                 //    notice('Error 1100: UserDeletedRecently.<br/> Google does not allow a user to be created after deletion until at least 5 days have passed.');
                 //}
                 if (method_exists($e, 'getErrors')) {
                     $errors = $e->getErrors();
                     foreach ($errors as $errorcode => $error) {
                         debugging("Error({$errorcode}): {$error}", DEBUG_NORMAL, true);
                     }
                 } else {
                     debugging($e, DEBUG_DEVELOPER);
                 }
             }
         } catch (blocks_gdata_exception $e) {
             //'Authentication with Google Apps failed. Please check your credentials. ->getMessage() ?
             // if Authentication with Google Apps failed. Please check your credentials.
             // print $e->getMessage();
             // TODO: catch and inform of this Error
             debugging($e, DEBUG_DEVELOPER);
         }
     }
     // We are Succesfully logged in and we have a SAML Request
     // So we want to process the rest of the log in and redirect
     // to the Service that the SAML Request is asking for.
     //
     // All this code essentialy makes up for the fact that
     // we have to exit the login page prematurely.
     if (isset($SESSION->samlrequest)) {
         $SESSION->samlrequest = false;
         if (!($user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id)))) {
             // User could not be logged in
             error(get_string('errusernotloggedin', 'auth_gsaml'));
         }
         if (!validate_internal_user_password($user, $password)) {
             // Password not valid
             error(get_string('pwdnotvalid', 'auth_gsaml'));
         }
         // Added to fix navigation
         $navlinks = array(array('name' => 'test', 'link' => null, 'type' => 'misc'));
         $navigation = build_navigation($navlinks);
         update_login_count();
         if ($user) {
             // language setup
             if ($user->username == 'guest') {
                 // no predefined language for guests - use existing session or default site lang
                 unset($user->lang);
             } else {
                 if (!empty($user->lang)) {
                     // unset previous session language - use user preference instead
                     unset($SESSION->lang);
                 }
             }
             if (empty($user->confirmed)) {
                 // This account was never confirmed
                 print_header(get_string("mustconfirm"), get_string("mustconfirm"));
                 print_heading(get_string("mustconfirm"));
                 print_simple_box(get_string("emailconfirmsent", "", $user->email), "center");
                 print_footer();
                 die;
             }
             // TODO : Fix this bug frm isn't on this page here
             if (isset($frm)) {
                 // if isset placed here for now
                 if ($frm->password == 'changeme') {
                     //force the change
                     set_user_preference('auth_forcepasswordchange', true, $user->id);
                 }
             }
             // end of if issuet
             /// Let's get them all set up.
             add_to_log(SITEID, 'user', 'login', "view.php?id={$USER->id}&course=" . SITEID, $user->id, 0, $user->id);
             $USER = complete_user_login($user);
             /// Prepare 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);
                 }
             }
             /// Go to my-moodle page instead of homepage if mymoodleredirect enabled
             if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)) and !empty($CFG->mymoodleredirect) and !isguest()) {
                 if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot . '/' or $urltogo == $CFG->wwwroot . '/index.php') {
                     $urltogo = $CFG->wwwroot . '/my/';
                 }
             }
             /// check if user password has expired
             /// Currently supported only for ldap-authentication module
             $userauth = get_auth_plugin($USER->auth);
             if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
                 if ($userauth->can_change_password()) {
                     $passwordchangeurl = $userauth->change_password_url();
                 } else {
                     $passwordchangeurl = $CFG->httpswwwroot . '/login/change_password.php';
                 }
                 $days2expire = $userauth->password_expire($USER->username);
                 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
                     print_header("{$site->fullname}: {$loginsite}", "{$site->fullname}", $navigation, '', '', true, "<div class=\"langmenu\">{$langmenu}</div>");
                     notice_yesno(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
                     print_footer();
                     exit;
                 } elseif (intval($days2expire) < 0) {
                     print_header("{$site->fullname}: {$loginsite}", "{$site->fullname}", $navigation, '', '', true, "<div class=\"langmenu\">{$langmenu}</div>");
                     notice_yesno(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
                     print_footer();
                     exit;
                 }
             }
             reset_login_count();
             // END of the regular Moodle Login Procedures
             // Process the SAML Request and redirect to the Service
             // it is asking for.
             // This function should never return unless there's an error.
             if (!gsaml_send_auth_response($SESSION->samlrequestdata)) {
                 // SAML code failed turn debugging on
                 error(get_string('samlcodefailed', 'auth_gsaml'));
             }
         } else {
             if (empty($errormsg)) {
                 $errormsg = get_string("invalidlogin");
                 $errorcode = 3;
             }
             // TODO: if the user failed to authenticate, check if the username corresponds to a remote mnet user
             if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode === 'strict' && is_enabled_auth('mnet')) {
                 $errormsg .= get_string('loginlinkmnetuser', 'mnet', "mnet_email.php?u={$frm->username}");
             }
         }
     }
     // else if NO SAML request is made we don't do anything but log in normally
 }
 /**
  * Events API Hook for event 'user_created'
  *
  * The user is created in Google Apps when
  * the admin creates an user in Moodle
  *
  * @param object $user Moodle user record object
  * @return boolean
  **/
 public static function user_created_event($user)
 {
     $file = "/tmp/testerio.txt";
     file_put_contents($file, "Testing");
     echo "TESTING";
     try {
         $gapps = new blocks_gdata_gapps();
         $gapps->create_user($user, $checkexists = true);
         return true;
     } catch (blocks_gdata_exception $e) {
         return false;
     }
 }
 * @author Mark Nielsen
 * @version $Id$
 * @package block_gdata
 **/
// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] == 'POST' || true) {
    $nomoodlecookie = true;
    require '../../config.php';
    require_once $CFG->dirroot . '/blocks/gdata/gapps.php';
    $response = array('counts' => array('errors' => 1), 'message' => '');
    if ($userid = optional_param('userid', 0, PARAM_INT)) {
        try {
            // Want to capture output so we
            // can return it properly
            ob_start();
            $gapps = new blocks_gdata_gapps();
            $moodleuser = $gapps->moodle_get_user($userid);
            $gapps->sync_moodle_user_to_gapps($moodleuser);
            $output = ob_get_contents();
            $output = trim($output);
            ob_end_clean();
            if (!empty($output)) {
                $response['message'] = $output;
            }
            $response['counts'] = $gapps->counts;
        } catch (blocks_gdata_exception $e) {
            $response['message'] = $e->getMessage();
        } catch (Zend_Exception $e) {
            // Catch Zend_Exception just in case it happens
            $response['message'] = $e->getMessage();
        }
 /**
  * Addusers hook - processes the
  * submit from addusers_display()
  *
  * @return void
  **/
 function addusers_process()
 {
     global $CFG;
     global $DB;
     require_once $CFG->dirroot . '/blocks/gdata/gapps.php';
     $userids = optional_param('userids', '', PARAM_RAW);
     $allusers = optional_param('allusers', '', PARAM_RAW);
     $users = optional_param('users', '', PARAM_RAW);
     if ($userids = optional_param('userids', 0, PARAM_INT) or optional_param('allusers', '', PARAM_RAW)) {
         if (!confirm_sesskey()) {
             throw new blocks_gdata_exception('confirmsesskeybad', 'error');
         }
         $gapps = new blocks_gdata_gapps(false);
         if (optional_param('allusers', '', PARAM_RAW)) {
             list($select, $from, $where) = $this->get_sql('addusers');
             // Bulk processing
             if ($rs = $DB->get_recordset_sql("{$select} {$from} {$where}")) {
                 foreach ($rs as $user) {
                     $gapps->moodle_create_user($user);
                 }
                 $rs->close();
             } else {
                 throw new blocks_gdata_exception('invalidparameter');
             }
         } else {
             // Process user IDs
             foreach ($userids as $userid) {
                 if ($user = $DB->get_record('user', array('id' => $userid), 'id, username, password')) {
                     $gapps->moodle_create_user($user);
                 } else {
                     throw new blocks_gdata_exception('invalidparameter');
                 }
             }
         }
         redirect($CFG->wwwroot . '/blocks/gdata/index.php?hook=addusers');
     }
 }
 /**
  * Event handler: processes all events
  *
  * @param string $event Name of the event
  * @param mixed $eventdata Data passed to the event
  * @return boolean
  **/
 private static function event_handler($event, $eventdata)
 {
     // Check first to see if events are allowed
     if (get_config('blocks/gdata', 'allowevents')) {
         switch ($event) {
             case 'user_deleted':
             case 'user_updated':
             case 'password_changed':
                 try {
                     $gapps = new blocks_gdata_gapps();
                     $moodleuser = $gapps->moodle_get_user($eventdata->id);
                     $gappsuser = $gapps->gapps_get_user($moodleuser->oldusername);
                     $gapps->sync_moodle_user_to_gapps($moodleuser, $gappsuser, false);
                 } catch (blocks_gdata_exception $e) {
                     // Do nothing on errors
                 }
                 break;
         }
     }
     return true;
 }