/**
  * Authentication hook - is called every time user hit the login page
  * The code is run only if the param code is mentioned.
  */
 public function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB;
     $USER->auth = 'apilogin';
     //if the user is already logged into the system, then don't do anything
     if (!$USER->id) {
         $lib = new auth_apilogin_lib();
         $user = $lib->validateToken();
         //if valid, then complete the user login so they can enter directly into the site
         if ($user) {
             complete_user_login($user);
             //redirect to the requested page
             if (!empty($user->redirect)) {
                 redirect($user->redirect);
                 //redirect to the wantsurl if it exists
             } elseif (!empty($SESSION->wantsurl)) {
                 redirect($SESSION->wantsurl);
                 //redirect to the dashboard
             } else {
                 redirect($CFG->wwwroot . '/my/');
             }
             //if not valid, then redirect if the user to the login page set in the plugin config
             //of if not set, then allow moodle to perform the redirect
         } else {
             if ($this->config->loginredirect) {
                 $q = (strpos($this->config->loginredirect, '?') === false ? '?' : '&') . 'invalid=1';
                 redirect($this->config->loginredirect . $q);
             }
         }
     }
 }
require_once $CFG->libdir . '/sessionlib.php';
require_once $CFG->dirroot . '/cache/lib.php';
//------------------------------------------------------------------------
// SETUP
//------------------------------------------------------------------------
//setup the database and connect
setup_DB();
//pull the configuration for the site
initialise_cfg();
//------------------------------------------------------------------------
// ERROR SETTINGS - FOR DEVELOPMENT
//------------------------------------------------------------------------
//*
$CFG->displaydebug = true;
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 0);
//*/
//------------------------------------------------------------------------
// LOAD API CLASS
//------------------------------------------------------------------------
require_once $CFG->dirroot . '/auth/apilogin/lib.php';
$api = new auth_apilogin_lib();
//------------------------------------------------------------------------
// VALIDATE REQUEST
//------------------------------------------------------------------------
$api->validateRequest($_POST);
//------------------------------------------------------------------------
// PROCESS REQUEST
//------------------------------------------------------------------------
call_user_func(array($api, $_POST['method']), $_POST);