<?php

function login($conf, $storage) {
    if (!isset($conf['login_url'])) {
        return null;
    }

    $method = HTTP_REQUEST_METHOD_POST;
    $url = $conf['login_url'];
    $username = $storage->getLoginId();
    $password = $storage->getPassword();
    if (PEAR::isError($password)) {
        return $password;
    }
    $post_params = array();
    $login_params = '';
    switch ($conf['input_type']) {
      case 'json':
        $login_params = preg_replace(array('/%u/', '/%p/'), array($username, $password), $conf['login_request']);
        break;
      default:
        $post_params[$conf['login_user']] = $username;
        $post_params[$conf['login_passwd']] = $password;
    }
    if (isset($conf['login_postparams'])) {
        foreach (preg_split('/&/', $conf['login_postparams']) as $elt) {
            if (preg_match('/^([^=]+)=(.*)$/', $elt, $matches)) {
                $post_params[$matches[1]] = $matches[2];
            }
        }
    }
    if (isset($conf['reqparam'])) {
        $post_params[$conf['reqparam']] = $login_params;
        $login_params = '';
    }

    $req =& new HTTP_Request($url);
    $req->setMethod($method);
    foreach ($post_params as $key => $value) {
        $req->addPostData($key, $value);
    }
    if ($login_params) {
        $req->setBody($login_params);
    }
    $res = $req->sendRequest();
    if (PEAR::isError($res)) {
        return $res;
    }

    $session = null;
    $body = $req->getResponseBody();
    if ($body && isset($conf['login_session'])) {
        switch($conf['response_type']) {
          case 'json':
            $data = json_decode($body, true);
            if (!$data || !isset($data[$conf['login_session']])) {
                return PEAR::raiseError($body);
            }
            $session = $data[$conf['login_session']];
            break;
          default:
        }
    }

    if ($session) {
        $storage->set('session', $session);
    }

    return $session;
}

function sendRequest($conf, $session) {
    $body = file_get_contents('php://input');
    if (isset($conf['session_param'])) {
      switch($conf['input_type']) {
        case 'json':
          $input = 'body';
          $json = array();
          if (isset($conf['reqparam'])) {
              if (isset($_GET[$conf['reqparam']])) {
                  $json = json_decode($_GET[$conf['reqparam']], true);
                  $input = 'get';
              } else if (isset($_POST[$conf['reqparam']])) {
                  $json = json_decode($_POST[$conf['reqparam']], true);
                  $input = 'post';
              }
          } else {
              $json = json_decode($body, true);
          }
          $params = array($conf['session_param'] => $session);
          foreach ($json as $key => $value) {
              $params[$key] = $value;
          }

          switch($input) {
            case 'get':
              $_GET[$conf['reqparam']] = json_encode($params);
              break;
            case 'post':
              $_POST[$conf['reqparam']] = json_encode($params);
              break;
            default:
              $body = json_encode($params);
          }
          break;
        case 'get':
          $_GET[$conf['session_param']] = $session;
          break;
        default:
          $_POST[$conf['session_param']] = $session;
      }
    }

    $method = HTTP_REQUEST_METHOD_GET;
    if ($_GET['method'] = 'post') {
        $method = HTTP_REQUEST_METHOD_POST;
    }
    $url = isset($conf['appurl']) ? $conf['appurl'] : (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https': 'http').'://'.$_SERVER['SERVER_NAME'];
    if (isset($_SERVER['PATH_INFO'])) {
        $url .= $_SERVER['PATH_INFO'];
    }
    $qstr = '';
    foreach ($_GET as $key => $value) {
        if ($key != 'action') {
            $qstr .= ($qstr ? '&' : '?')."$key=$value";
        }
    }
    $req =& new HTTP_Request($url.$qstr);
    $req->setMethod($method);
    foreach ($_POST as $key => $value) {
        $req->addPostData($key, $value);
    }
    foreach ($_COOKIE as $key => $value) {
        $req->addCookie($key, $value);
    }
    if ($body) {
        $req->setBody($body);
    }

    $res = $req->sendRequest();
    if (PEAR::isError($res)) {
        return $res;
    }

    $status = $req->getResponseCode();
    $headers = $req->getResponseHeader();
    $body = $req->getResponseBody();

    return array('status' => $status, 'headers' => $headers, 'body' => $body);
}

?>
