title: Logging into Moodle via external site
body: <p>I'm setting up a Moodle environment and I need users to be able to login via an external site using their credentials from <em>that</em> site. Ideally they would go to the website, login in, and then click a button that will send them to Moodle along with their account information.</p>
  
  <p>Once they get to Moodle, Moodle will check to see if the account information already exists. If so it will login, otherwise it will create the account and login.</p>
  
  <p>I already have the Moodle environment set up, as well as the login site. The Moodle site is not allowed to access the database on the login site, and the users shouldn't have to enter their information again at any point.</p>
  
  <p>I've already spent several hours attempting to work backwards from a plugin that accomplishes something similar between Moodle and social networking sites (facebook, twitter, google+, etc) but made no progress, as well as from a plugin that linked Moodle with Joomla, and I've searched through here and other forums for anything I could find similar to what I need to accomplish to no avail. Any help would be very appreciated.</p>
  
  <p>Edit: I forgot to mention that the Moodle version is 2.5.4</p>
  
  <p>Edit: The following will create a new user with data posted to the "login/index.php" page. This is currently very incomplete and probably dangerous to implement on a production server. Updated versions will be posted as I continue to work on it, suggestions are more than welcome.</p>
  
  <pre><code>    global $CFG, $DB;
      require_once($CFG-&gt;dirroot.'/user/profile/lib.php');
      require_once($CFG-&gt;libdir.'/authlib.php');
  
      $newuser = $DB-&gt;get_record('user', array('id'=&gt;'1'));
      $newuser-&gt;auth = 'manual';
      $newuser-&gt;username = $frm-&gt;username;
      $newuser-&gt;password = hash_internal_user_password($frm-&gt;password);
  
      $newuser-&gt;username = $DB-&gt;insert_record('user', $newuser);
  
      /// Save any custom profile field information
      profile_save_data($newuser);
  
      $newuser = $DB-&gt;get_record('user', array('id'=&gt;$newuser-&gt;username));
      events_trigger('user_created', $newuser);
  </code></pre>