<?php

class loginUserAction extends sfAction {

  public function execute($request) {
    if (!$request->isMethod('post')) return "Form";
    $login = $request->getParameter('login', null);

    if (sfConfig::get('app_openid_fake') === true) {

      $user = $this->getUser();
      $user->login($login);
      return $this->redirect('@homepage');
    } else {
      if (!is_null($login)) {
        $identity = sfConfig::get('app_openid_service_uri').$login.'/';
      } else {
        $identity = $request->getParameter('oid', null);
      }

      if (is_null($identity)) return "Form";

      $openid = ThdUtil::getOpenIdObject($identity);
      // Redirect to open id provider
      $redirectUrl = $openid->getRedirectURL(false);
      $nextStep = $openid->getRedirectURL($immediate, $submitLabel);

      if (($nextStep['type'] == 'url') && (!empty($nextStep['content']))) {
        // Using OpenID 1 => redirection using URL
        $result['success'] = true;

        $result['htmlCode'] = "<script type=\"text/javascript\">var transiting = true;document.location.href = \"".$nextStep['content']."\"</script>"; // auto redirect if js on
        $result['htmlCode'] .= "<a href=\"".$nextStep['content']."\" ";
        unset($linkAttrs['href']);
        $linkAttrs['id'] = 'openid_message';

        foreach ($linkAttrs as $name => $attr) {
            $result['htmlCode'] .= sprintf(" %s=\"%s\"", $name, $attr);
        }
        $result['htmlCode'] .= ">$linkLabel</a>";
        $result['htmlCode'] .= "<script type=\"text/javascript\">document.getElementById('".$linkAttrs['id']."').style.display = 'none';</script>"; // Hide the link if js on (=auto redirect)
      }
      else if (($nextStep['type'] == 'form') && (!empty($nextStep['content']))) {
        // Using OpenID 2 => redirection using a form
        $result['success'] = true;

        $result['htmlCode'] = $nextStep['content'];
        $result['htmlCode'] .= "<script type=\"text/javascript\">document.getElementById('openid_message').style.display = 'none';</script>"; // Auto submit if js on
        $result['htmlCode'] .= "<script type=\"text/javascript\">var transiting = true;document.getElementById('openid_message').submit();</script>"; // hide form if js on
      }
      else {
        // Show an error message
        if (empty($nextStep['content']))
          $result['error'] = "Unexpected error.";
        else
          $result['error'] = $nextStep['content'];
      }

      if (!isset($result['success'])) return "Form";

      return $this->renderText($result['htmlCode']);
    }
  }
}