<?php
  /* This script grabs the user/pass combo directly
   * from the Question2Answer login page.
   * It uses a service account to find
   * the user in the odoo database, via Django
   * When found the user/pass combo is checked against the
   * Odoo authentication source. Following
   * this check, it either creates a SESSION array or
   * a cookie that can be checked by the ldap-login
   * module's check_login function, and bypasses the
   * internal QA auth mechanism by redirecting back to
   * the login page.
  */

  require_once QA_INCLUDE_DIR."qa-base.php";

  require_once QA_INCLUDE_DIR."../qa-plugin/cooperatic-django-odoo-auth/djangoOdooServer.php";

  function django_odoo_process ($user,$pass) {


    // Check ig user or pass is empty
    if ( '' == $user || '' ==  $pass ) {
      return false;
    }

    try {
      return djangoOdooServer::getUserAttributes($user,$pass);
    } catch (Exception $e) {
      // log
    } 

    return false;
  }
  function isEmpty($attr) {
    if($attr == '' || preg_match("/^[[:space:]]+$/", $attr)) {
      return true;
    }
    return false;
  }

  $expire = 14*24*60*60;

  if (!isEmpty($inemailhandle)) {
    if (!isEmpty($inpassword)) {
      $call_result = django_odoo_process($inemailhandle,$inpassword);

      if ($call_result && isset($call_result->credentials)) {
        if (!isset($call_result->credentials->failure)) {
          $source = 'cooperatic_dj_o';
          $identifier = $inemailhandle;

          $fname = $call_result->credentials->firstname;
          $hdle_size = strlen($fname) + strlen($coop_num);
          if ($hdle_size > 20) {
            # remove fname caracters to fit with maximum handle length
            $fname = substr($fname, 0, strlen($fname) - ($hdle_size -20));
          }

          $fields['email'] = $inemailhandle;
          $fields['confirmed'] = true;
          $fields['handle'] = $fname . $call_result->credentials->coop_num;;
          $fields['name'] = $call_result->credentials->firstname . ' ' . $call_result->credentials->lastname;
          qa_log_in_external_user($source, $identifier, $fields, $inremember);
          $topath=qa_get('to');
          if (isset($topath))
            qa_redirect_raw(qa_path_to_root().$topath); // path already provided as URL fragment
          else
            qa_redirect('');
          exit();
        }

      } 
    }
  }