Пример #1
0
 public static function run($accessString)
 {
     if (empty($accessString)) {
         return true;
     }
     if (preg_match_all('/([\\w\\.]+)(?:\\(([\\w\\.]*)(?:\\/(\\w*))?\\))?,?/', $accessString, $roles)) {
         ClassLoader::import('application.model.user.SessionUser');
         $currentUser = SessionUser::getUser();
         $controller = Controller::getCurrentController();
         $rolesParser = $controller->getRoles();
         $currentControllerName = $controller->getRequest()->getControllerName();
         $currentActionName = $controller->getRequest()->getActionName();
         $rolesCount = count($roles[0]);
         for ($i = 0; $i < $rolesCount; $i++) {
             $roleString = $roles[0][$i];
             $roleName = $roles[1][$i];
             $roleControllerName = empty($roles[3][$i]) ? $currentControllerName : $roles[2][$i];
             $roleActionName = empty($roles[3][$i]) ? empty($roles[2][$i]) ? $currentActionName : $roles[2][$i] : $currentActionName;
             if ($roleControllerName == $currentControllerName && $roleActionName == $currentActionName) {
                 $aRoleName = $rolesParser->getRole($roleActionName);
                 if ($currentUser->hasAccess($aRoleName) && $currentUser->hasAccess($roleName)) {
                     return true;
                 }
             }
         }
         return false;
     }
     throw new ApplicationException('Access string ("' . $accessString . '") has illegal format');
 }
Пример #2
0
 public function setUp()
 {
     ActiveRecordModel::getApplication()->clearCachedVars();
     ActiveRecordModel::beginTransaction();
     if (empty($this->autoincrements)) {
         foreach ($this->getUsedSchemas() as $table) {
             $res = $this->db->executeQuery("SHOW TABLE STATUS LIKE '{$table}'");
             $res->next();
             $this->autoincrements[$table] = (int) $res->getInt("Auto_increment");
         }
     }
     if ($this instanceof BackendControllerTestCase) {
         ClassLoader::import('application.model.user.SessionUser');
         ClassLoader::import('application.model.user.UserGroup');
         // set up user
         $group = UserGroup::getNewInstance('Unit tester');
         $group->save();
         $group->setAllRoles();
         $group->save();
         $user = User::getNewInstance('*****@*****.**', null, $group);
         $user->save();
         SessionUser::setUser($user);
     }
     if ($this instanceof ControllerTestCase) {
         $this->request = self::getApplication()->getRequest();
     }
 }
Пример #3
0
 public static function getUserToolbarItems($types = null, $filter = null, $order = 'ASC')
 {
     if ($filter == null) {
         $filter = new ARSelectFilter();
     }
     $filter->mergeCondition(eq(f(__CLASS__ . '.ownerID'), SessionUser::getUser()->getID()));
     $filter->setOrder(f(__CLASS__ . '.position'), $order);
     $m = array(BackendToolbarItem::TYPE_MENU => '', BackendToolbarItem::TYPE_PRODUCT => '', BackendToolbarItem::TYPE_USER => '', BackendToolbarItem::TYPE_ORDER => '');
     if (is_array($types) == false) {
         $types = array($types);
     }
     $conditions = array();
     foreach ($types as $type) {
         switch ($type) {
             case BackendToolbarItem::TYPE_MENU:
                 $conditions[] = isnotnull(f(__CLASS__ . '.menuID'));
                 break;
             case BackendToolbarItem::TYPE_PRODUCT:
                 $conditions[] = new AndChainCondition(array(isnotnull(f(__CLASS__ . '.productID')), isnotnull(f('Product.ID'))));
                 // fake inner join
                 break;
             case BackendToolbarItem::TYPE_USER:
                 $conditions[] = new AndChainCondition(array(isnotnull(f(__CLASS__ . '.userID')), isnotnull(f('User.ID'))));
                 break;
             case BackendToolbarItem::TYPE_ORDER:
                 $conditions[] = new AndChainCondition(array(isnotnull(f(__CLASS__ . '.orderID')), isnotnull(f('CustomerOrder.ID'))));
                 break;
         }
     }
     if (count($conditions)) {
         $filter->mergeCondition(new OrChainCondition($conditions));
     }
     return self::getRecordSetArray(__CLASS__, $filter, true);
 }
Пример #4
0
 public function __construct(LiveCart $application)
 {
     if ($application->getConfig()->get('SSL_BACKEND')) {
         $application->getRouter()->setSslAction('');
     }
     parent::__construct($application);
     if (!isset($_SERVER['HTTP_USER_AGENT'])) {
         $_SERVER['HTTP_USER_AGENT'] = 'Firefox';
     }
     // no IE yet
     if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
         ClassLoader::import('application.controller.backend.UnsupportedBrowserException');
         throw new UnsupportedBrowserException();
     }
     if (!$this->user->hasBackendAccess() && !$this instanceof SessionController) {
         SessionUser::destroy();
         $url = $this->router->createUrl(array('controller' => 'backend.session', 'action' => 'index', 'query' => array('return' => $_SERVER['REQUEST_URI'])));
         if (!$this->isAjax()) {
             header('Location: ' . $url);
         } else {
             header('Content-type: text/javascript');
             echo json_encode(array('__redirect' => $url));
         }
         exit;
     }
 }
Пример #5
0
 protected function _init()
 {
     // Make the session user always available in every controller:
     $this->user = SessionUser::user();
     // Might come in handy sometimes: direct access to the DBAL:
     $this->db = $GLOBALS['db'];
     // Initialize Output/Views (used in 90% of controller actions):
     $this->tpl = new Output($this);
     $this->tpl->viewLayout = '_layout';
     $this->tpl->assign('app', $this);
 }
Пример #6
0
 /**
  * Get CustomerOrder instance from session
  *
  * @return CustomerOrder
  */
 public static function getOrder()
 {
     if (self::$instance) {
         return self::$instance;
     }
     $session = new Session();
     $id = $session->get('CustomerOrder');
     if ($id) {
         try {
             $instance = CustomerOrder::getInstanceById($id, true);
             if (!$instance->getOrderedItems()) {
                 $instance->loadItems();
             }
             $instance->isSyncedToSession = true;
         } catch (ARNotFoundException $e) {
             unset($instance);
         }
     }
     if (!isset($instance)) {
         $userId = SessionUser::getUser()->getID();
         // get the last unfinalized order by this user
         if ($userId > 0) {
             $f = new ARSelectFilter(new EqualsCond(new ARFieldHandle('CustomerOrder', 'userID'), $userId));
             $f->mergeCondition(new NotEqualsCond(new ARFieldHandle('CustomerOrder', 'isFinalized'), true));
             $f->setOrder(new ARFieldHandle('CustomerOrder', 'ID'), 'DESC');
             $f->setLimit(1);
             $orders = ActiveRecordModel::getRecordSet('CustomerOrder', $f);
             if ($orders->size()) {
                 $instance = $orders->get(0);
             }
         }
     }
     if (!isset($instance)) {
         $instance = CustomerOrder::getNewInstance(User::getNewInstance(0));
         $instance->user->set(NULL);
     }
     if (!$instance->user->get() && SessionUser::getUser()->getID() > 0) {
         $instance->setUser(SessionUser::getUser());
         $instance->save();
     }
     if ($instance->isFinalized->get()) {
         $session->unsetValue('CustomerOrder');
         return self::getOrder();
     }
     // fixes issue when trying to add OrderedItem to unsaved(without ID) CustomerOrder.
     // ~ but i don't know if returning unsaved CustomerOrder is expected behaviour.
     if ($instance->isExistingRecord() == false) {
         $instance->save(true);
     }
     self::setOrder($instance);
     return $instance;
 }
Пример #7
0
 public static function setUser(User $user)
 {
     self::$currentUser = $user;
     $app = ActiveRecordModel::getApplication();
     $app->processRuntimePlugins('session/before-login');
     $session = new Session();
     $session->set('User', $user->getID());
     $session->set('UserGroup', $user->userGroup->get() ? $user->userGroup->get()->getID() : 0);
     if ($app->getSessionHandler()) {
         $app->getSessionHandler()->setUser($user);
     }
     $app->processRuntimePlugins('session/login');
 }
Пример #8
0
/**
 * Tab
 *
 * @package application.helper.smarty
 * @author Integry Systems
 *
 * @package application.helper.smarty
 */
function smarty_block_tab($params, $content, Smarty_Internal_Template $smarty, &$repeat)
{
    if (!$repeat) {
        ClassLoader::import('application.helper.AccessStringParser');
        if (!empty($params['role']) && !AccessStringParser::run($params['role'])) {
            return false;
        }
        $user = SessionUser::getUser();
        $userPref = $user->getPreference('tab_' . $params['id']);
        $isHidden = is_null($userPref) ? !empty($params['hidden']) : $userPref == 'false';
        $content = '
<li id="' . $params['id'] . '" rel="' . $params['help'] . '" class="tab ui-state-default ui-corner-top inactive' . ($isHidden ? ' hidden' : '') . '">' . $content . '</li>';
        return $content;
    }
}
Пример #9
0
/**
 * Tab
 *
 * @package application.helper.smarty
 * @author Integry Systems
 *
 * @package application.helper.smarty
 */
function smarty_block_tab($params, $content, LiveCartSmarty $smarty, &$repeat)
{
    if (!$repeat) {
        ClassLoader::import('application.helper.AccessStringParser');
        if (!empty($params['role']) && !AccessStringParser::run($params['role'])) {
            return false;
        }
        $user = SessionUser::getUser();
        $userPref = $user->getPreference('tab_' . $params['id']);
        $isHidden = is_null($userPref) ? !empty($params['hidden']) : $userPref == 'false';
        $content = '
<li id="' . $params['id'] . '" class="tab inactive' . ($isHidden ? ' hidden' : '') . '">' . $content . '
	<span> </span>
	<span class="tabHelp">' . $params['help'] . '</span>
</li>';
        return $content;
    }
}
Пример #10
0
/**
 * Language forms
 *
 * @package application.helper.smarty
 * @author Integry Systems
 *
 * @package application.helper.smarty
 */
function smarty_block_language($params, $content, Smarty_Internal_Template $smarty, &$repeat)
{
    //$smarty = $smarty->smarty;
    $app = $smarty->smarty->getApplication();
    if (!$app->getLanguageSetArray()) {
        return false;
    }
    if ($repeat) {
        $app->languageBlock = $app->getLanguageSetArray();
        $smarty->assign('languageBlock', $app->languageBlock);
        $smarty->assign('lang', array_shift($app->languageBlock));
        $app->langHeadDisplayed = false;
        $user = SessionUser::getUser();
        foreach ($app->getLanguageSetArray() as $lang) {
            $userPref = $user->getPreference('tab_lang_' . $lang['ID']);
            $isHidden = is_null($userPref) ? !empty($params['hidden']) : $userPref == 'false';
            $classNames[$lang['ID']] = $isHidden ? 'hidden' : '';
        }
        $app->langClassNames = $classNames;
    } else {
        if (!trim($content)) {
            $repeat = false;
            return false;
        }
        if ($app->languageBlock) {
            $repeat = true;
        }
        $contentLang = $smarty->getTemplateVars('lang');
        $content = '<tab class="lang_' . $contentLang['ID'] . '" heading="' . $contentLang['originalName'] . '">' . $content . '</tab>';
        if (!$app->langHeadDisplayed) {
            $smarty->assign('classNames', $app->langClassNames);
            $content = $smarty->fetch('block/backend/langFormHead.tpl') . $content;
            $app->langHeadDisplayed = true;
        }
        $smarty->assign('lang', array_shift($app->languageBlock));
        // form footer
        if (!$repeat) {
            $content .= $smarty->fetch('block/backend/langFormFoot.tpl');
        }
        return $content;
    }
}
Пример #11
0
/**
 * Language forms
 *
 * @package application.helper.smarty
 * @author Integry Systems
 *
 * @package application.helper.smarty
 */
function smarty_block_language($params, $content, LiveCartSmarty $smarty, &$repeat)
{
    if (!$smarty->getApplication()->getLanguageSetArray()) {
        return false;
    }
    if ($repeat) {
        $smarty->languageBlock = $smarty->getApplication()->getLanguageSetArray();
        $smarty->assign('languageBlock', $smarty->languageBlock);
        $smarty->assign('lang', array_shift($smarty->languageBlock));
        $smarty->langHeadDisplayed = false;
        $user = SessionUser::getUser();
        foreach ($smarty->getApplication()->getLanguageSetArray() as $lang) {
            $userPref = $user->getPreference('tab_lang_' . $lang['ID']);
            $isHidden = is_null($userPref) ? !empty($params['hidden']) : $userPref == 'false';
            $classNames[$lang['ID']] = $isHidden ? 'hidden' : '';
        }
        $smarty->langClassNames = $classNames;
    } else {
        if (!trim($content)) {
            $repeat = false;
            return false;
        }
        if ($smarty->languageBlock) {
            $repeat = true;
        }
        $contentLang = $smarty->get_template_vars('lang');
        $content = '<div class="languageFormContainer languageFormContainer_' . $contentLang['ID'] . ' ' . $smarty->langClassNames[$contentLang['ID']] . '">' . $content . '</div>';
        if (!$smarty->langHeadDisplayed) {
            $smarty->assign('langFormId', 'langForm_' . uniqid());
            $smarty->assign('classNames', $smarty->langClassNames);
            $content = $smarty->fetch('block/backend/langFormHead.tpl') . $content;
            $smarty->langHeadDisplayed = true;
        }
        $smarty->assign('lang', array_shift($smarty->languageBlock));
        // form footer
        if (!$repeat) {
            $content .= $smarty->fetch('block/backend/langFormFoot.tpl');
        }
        return $content;
    }
}
Пример #12
0
 public static function getUserToolbarItems($types = null, $filter = null, $order = 'ASC')
 {
     if ($filter == null) {
         $filter = new ARSelectFilter();
     }
     $filter->mergeCondition(eq(f(__CLASS__ . '.ownerID'), SessionUser::getUser()->getID()));
     $filter->setOrder(f(__CLASS__ . '.position'), $order);
     $m = array(BackendToolbarItem::TYPE_MENU => 'menuID', BackendToolbarItem::TYPE_PRODUCT => 'productID', BackendToolbarItem::TYPE_USER => 'userID', BackendToolbarItem::TYPE_ORDER => 'orderID');
     if (is_array($types) == false) {
         $types = array($types);
     }
     $conditions = array();
     foreach ($types as $type) {
         if (array_key_exists($type, $m)) {
             $conditions[] = isnotnull(f(__CLASS__ . '.' . $m[$type]));
         }
     }
     if (count($conditions)) {
         $filter->mergeCondition(new OrChainCondition($conditions));
     }
     return self::getRecordSetArray(__CLASS__, $filter, true);
 }
Пример #13
0
 protected function processRecord(CustomerOrder $order)
 {
     $order->processMass_history = new OrderHistory($order, SessionUser::getUser());
     switch ($this->getAction()) {
         case 'setNew':
             $status = CustomerOrder::STATUS_NEW;
             break;
         case 'setProcessing':
             $status = CustomerOrder::STATUS_PROCESSING;
             break;
         case 'setAwaitingShipment':
             $status = CustomerOrder::STATUS_AWAITING;
             break;
         case 'setShipped':
             $status = CustomerOrder::STATUS_SHIPPED;
             break;
         case 'setReturned':
             $status = CustomerOrder::STATUS_RETURNED;
             break;
         case 'setUnfinalized':
             $order->isFinalized->set(0);
             break;
         case 'setCancel':
             $order->cancel();
             break;
         case 'setFinalized':
             if (!$order->isFinalized->get() && $order->user->get()) {
                 $order->finalize();
             }
             break;
     }
     if (isset($status) && $status != $order->status->get()) {
         $order->setStatus($status);
         $this->params['controller']->sendStatusNotifyEmail($order);
     }
 }
Пример #14
0
    'WEBMESTRE_COURRIEL'        => WEBMESTRE_COURRIEL,
  );
  // Initialiser la classe
  $auth = new SimpleSAML_Auth_Simple('distant-gepi-saml');
  //on forge une extension SAML pour tramsmettre l'établissement précisé dans SACoche
  $ext = array();
  if($BASE)
  {
    $dom = new DOMDocument();
    $ce = $dom->createElementNS('gepi_name_space', 'gepi_name_space:organization', $BASE);
    $ext[] = new SAML2_XML_Chunk($ce);
  }
  $auth->requireAuth( array('saml:Extensions'=>$ext) );
  // Tester si le user est authentifié, rediriger sinon
  $auth->requireAuth();
  // Récupérer l'identifiant Gepi de l'utilisateur authentifié pour le traiter dans l'application
  $attr = $auth->getAttributes();
  $login_GEPI = $attr['USER_ID_GEPI'][0];
  // Comparer avec les données de la base
  list($auth_resultat,$auth_DB_ROW) = SessionUser::tester_authentification_utilisateur( $BASE , $login_GEPI /*login*/ , FALSE /*password*/ , 'gepi' /*mode_connection*/ );
  if($auth_resultat!='ok')
  {
    exit_error( 'Incident authentification Gepi' /*titre*/ , $auth_resultat /*contenu*/ );
  }
  // Connecter l'utilisateur
  SessionUser::initialiser_utilisateur($BASE,$auth_DB_ROW);
  // Pas de redirection (passage possible d'infos en POST à conserver), on peut laisser le code se poursuivre.
  return; // Ne pas exécuter la suite de ce fichier inclus.
}

?>
Пример #15
0
 public function setAdmin()
 {
     if (!$this->buildAdminValidator()->isValid()) {
         return new ActionRedirectResponse('install', 'admin');
     }
     ClassLoader::import('application.model.user.UserGroup');
     ClassLoader::import('application.model.user.User');
     ClassLoader::import('application.model.user.SessionUser');
     ActiveRecordModel::beginTransaction();
     // create user group for administrators
     $group = UserGroup::getNewInstance('Administrators');
     $group->setAllRoles();
     $group->save();
     // create administrator account
     $user = User::getNewInstance($this->request->get('email'), null, $group);
     $user->loadRequestData($this->request);
     $user->setPassword($this->request->get('password'));
     $user->isEnabled->set(true);
     $user->save();
     ActiveRecordModel::commit();
     // log in
     SessionUser::setUser($user);
     // set store email
     $this->config->set('MAIN_EMAIL', $this->request->get('email'));
     $this->config->set('NOTIFICATION_EMAIL', $this->request->get('email'));
     $this->config->set('NEWSLETTER_EMAIL', $this->request->get('email'));
     $this->config->save();
     return new ActionRedirectResponse('install', 'config');
 }
Пример #16
0
 /**
  * Enregistrer en session les informations authentifiant un partenaire.
  * 
  * @param array   $DB_ROW   ligne issue de la table sacoche_partenaire correspondant à l'utilisateur qui se connecte.
  * @return void
  */
 public static function initialiser_partenaire($DB_ROW)
 {
   // Numéro de la base
   $_SESSION['BASE']                          = 0;
   // Ce n'est pas un utilisateur d'un établissement.
   $_SESSION['USER_ETABLISSEMENT']            = FALSE;
   // Données associées au profil de l'utilisateur.
   $_SESSION['USER_PROFIL_SIGLE']             = 'ENT';
   $_SESSION['USER_PROFIL_TYPE']              = 'partenaire';
   $_SESSION['USER_PROFIL_NOM_COURT']         = 'partenaire';
   $_SESSION['USER_PROFIL_NOM_LONG']          = 'partenariat conventionné (ENT)';
   $_SESSION['USER_MDP_LONGUEUR_MINI']        = 6;
   $_SESSION['USER_DUREE_INACTIVITE']         = 15;
   // Données personnelles de l'utilisateur.
   $_SESSION['USER_ID']                       = (int) $DB_ROW['partenaire_id'];
   $_SESSION['USER_NOM']                      = $DB_ROW['partenaire_nom'];
   $_SESSION['USER_PRENOM']                   = $DB_ROW['partenaire_prenom'];
   $_SESSION['USER_LANGUE']                   = LOCALE_DEFAULT;
   $_SESSION['USER_CONNECTEURS']              = $DB_ROW['partenaire_connecteurs'];
   // Données associées à l'établissement.
   $_SESSION['SESAMATH_ID']                   = 0;
   $_SESSION['ETABLISSEMENT']['DENOMINATION'] = $DB_ROW['partenaire_denomination'];
   $_SESSION['CONNEXION_MODE']                = 'normal';
   // Enregistrer en session le menu personnalisé
   SessionUser::memoriser_menu();
 }
Пример #17
0
 /**
  * Magic method for setting properties.
  */
 public function __set($name, $value)
 {
     switch ($name) {
         case 'name':
             $value = trim($value);
             if (strlen($value) < self::MIN_USERNAME_LENGTH) {
                 // Usage of strlen() intentional for unicode characters
                 throw new ErrorException('Username should be at least ' . self::MIN_USERNAME_LENGTH . ' characters.');
             }
             if (mb_strlen($value) > self::MAX_USERNAME_LENGTH) {
                 throw new ErrorException('Username may not exceed ' . self::MAX_USERNAME_LENGTH . ' characters.');
             }
             if (SessionUser::IllegalUsername($value)) {
                 throw new ErrorException('Username is reserved. Please choose another username.');
             }
             try {
                 $class = get_called_class();
                 $user = $class::FindByName($value);
                 throw new ErrorException('Username already exists. Please choose another username.');
             } catch (ActiveRecord_NotFoundException $e) {
                 // "Not Found" is the desired result
             }
             parent::__set($name, $value);
             break;
         case 'password':
             throw new ErrorException('Use <i>SetPassword()</i> to change password.');
         case 'email':
             if (!empty($value)) {
                 $value = filter_var($value, FILTER_VALIDATE_EMAIL);
                 if ($value == false) {
                     throw new ErrorException('Email address is not valid. Please check if you entered it correctly.');
                 }
                 // Check if email host actually exists (parse_url() is faked into thinking email address is URL to get hostname)
                 $parts = parse_url('http://' . $value . '/');
                 if (!isset($parts['host']) || filter_var($parts['host'], FILTER_VALIDATE_IP) == false && gethostbyname($parts['host']) == $parts['host']) {
                     throw new ErrorException('Your email host <i>' . SafeHTML($parts['host']) . '</i> does not appear to exist.');
                 }
                 parent::__set($name, $value);
             }
             break;
         default:
             parent::__set($name, $value);
     }
 }
Пример #18
0
 private function buildValidator()
 {
     // validate contact info
     $validator = $this->getValidator("registrationValidator", $this->request);
     $this->validateAddress($validator, 'billing_');
     $this->validateEmail($validator);
     if ($this->config->get('PASSWORD_GENERATION') == 'PASSWORD_REQUIRE' || $this->request->get('password')) {
         $this->validatePassword($validator);
     }
     if (!$this->config->get('REQUIRE_SAME_ADDRESS') && $this->order->isShippingRequired()) {
         $this->validateAddress($validator, 'shipping_', true);
     }
     SessionUser::getAnonymousUser()->getSpecification()->setValidation($validator);
     return $validator;
 }
Пример #19
0
 *
 *  @author Integry Systems
 */
// change to application root directory
chdir('..');
// initialize LiveCart
include_once 'application/Initialize.php';
ClassLoader::import('application.LiveCart');
session_start();
$livecart = new LiveCart();
// process update
ClassLoader::import('application.controller.backend.UpdateController');
$user = SessionUser::getUser();
$user->allowBackendAccess();
$user->setID(1);
SessionUser::setUser($user);
$controller = new UpdateController($livecart);
$response = $controller->update();
if ($response instanceof RawResponse) {
    echo $response->getContent() . "\n";
} elseif ($response instanceof ActionResponse) {
    foreach ($response->get('progress') as $key => $value) {
        echo $key . ': OK' . "\n";
    }
    if ($response->get('errors')) {
        echo "\n" . 'Errors:' . "\n\n";
        foreach ($response->get('errors') as $key => $value) {
            echo $key . ': ' . $value . "\n";
        }
        echo "\n" . 'Failed to complete update. If you\'re not able to resolve the problems and complete the update successfuly, please contact the LiveCart support team at http://support.livecart.com';
    } else {
Пример #20
0
 // initialisation
 $auth_resultat = 'Erreur avec les données transmises !';
 // Protection contre les attaques par force brute (laissé même pour cette page requiérant une authentification car la réponse en cas d'erreur de mdp y fait référence)
 if (!isset($_SESSION['FORCEBRUTE'][$PAGE])) {
     exit_json(FALSE, 'Session perdue ou absence de cookie : merci d\'actualiser la page.');
 } else {
     if ($_SERVER['REQUEST_TIME'] - $_SESSION['FORCEBRUTE'][$PAGE]['TIME'] < $_SESSION['FORCEBRUTE'][$PAGE]['DELAI']) {
         $_SESSION['FORCEBRUTE'][$PAGE]['TIME'] = $_SERVER['REQUEST_TIME'];
         exit_json(FALSE, 'Sécurité : patienter ' . $_SESSION['FORCEBRUTE'][$PAGE]['DELAI'] . 's avant une nouvelle tentative.');
     }
 }
 // Pour un utilisateur d'établissement, y compris un administrateur
 if ($login == $_SESSION['USER_LOGIN']) {
     exit_json(FALSE, 'Saisir les identifiants d\'un <span class="u">autre compte</span>, pas celui en cours !');
 }
 list($auth_resultat, $auth_DB_ROW) = SessionUser::tester_authentification_utilisateur($_SESSION['BASE'], $login, $password, 'normal');
 if ($auth_resultat != 'ok') {
     $_SESSION['FORCEBRUTE'][$PAGE]['DELAI']++;
     $_SESSION['FORCEBRUTE'][$PAGE]['TIME'] = $_SERVER['REQUEST_TIME'];
     exit_json(FALSE, $auth_resultat);
 }
 $user_id = $auth_DB_ROW['user_id'];
 // Par sécurité et pour actualiser une éventuelle liaison (dé)faite depuis un autre compte, on ne stocke en session que l'identifiant de la clef des associations
 // La méthode appelée ci-dessous effectue de multiples vérifications complémentaires
 list($_SESSION['USER_SWITCH_ID'], $user_liste) = DB_STRUCTURE_SWITCH::DB_recuperer_et_verifier_listing_comptes_associes($_SESSION['USER_ID'], $_SESSION['USER_SWITCH_ID']);
 // Si le user connecté n'a pas de liaison, il faut aussi vérifier que le user de l'autre compte n'en a pas non plus
 if (!$_SESSION['USER_SWITCH_ID']) {
     list($_SESSION['USER_SWITCH_ID'], $user_liste) = DB_STRUCTURE_SWITCH::DB_recuperer_et_verifier_listing_comptes_associes($user_id, $_SESSION['USER_SWITCH_ID']);
 }
 // Soit c'est la vraiment la 1ère liaison à créer pour les deux
 if (!$_SESSION['USER_SWITCH_ID']) {
Пример #21
0
 public function getBusinessRuleController()
 {
     if (!$this->businessRuleController) {
         $context = new BusinessRuleContext();
         if ($items = SessionOrder::getOrderItems()) {
             $context->setOrder($items);
         }
         if (SessionUser::getUser()) {
             $context->setUser(SessionUser::getUser());
         }
         $this->businessRuleController = new BusinessRuleController($context);
         if ($this->isBackend()) {
             $this->businessRuleController->disableDisplayDiscounts();
         }
     }
     return $this->businessRuleController;
 }
Пример #22
0
 public function testUserCheckoutWithDifferentAddresses()
 {
     $this->order->addProduct($this->products[0], 1);
     $this->order->save();
     $this->assertTrue($this->order->isShippingRequired());
     $this->controller->setOrder($this->reloadOrder($this->order));
     $request = $this->controller->getRequest();
     $request->set('sameAsBilling', '');
     $request->set('email', '*****@*****.**');
     // shipping address not entered at all
     $request->set('billing_firstName', 'First');
     $request->set('billing_lastName', 'Last');
     $request->set('billing_companyName', 'CMP');
     $request->set('billing_address1', 'Address 1');
     $request->set('billing_state_text', 'State');
     $request->set('billing_city', 'Some City');
     $request->set('billing_country', 'LV');
     $request->set('billing_postalCode', 'LV-1234');
     $request->set('billing_phone', '1234');
     $response = $this->controller->processCheckoutRegistration();
     // last name was not entered, so we get back to user/checkout
     // with a bunch of errors for each shipping address field
     $this->assertIsA($response, 'ActionRedirectResponse');
     $this->assertEqual($response->getControllerName(), 'user');
     $this->assertEqual($response->getActionName(), 'checkout');
     $this->assertTrue(1 < count($this->controller->checkout()->get('form')->getValidator()->getErrorList()));
     // let's forget the last name again
     $request->set('shipping_firstName', 'Recipient');
     $request->set('shipping_companyName', 'CMP');
     $request->set('shipping_address1', 'Rec Street');
     $request->set('shipping_city', 'Rec City');
     $request->set('shipping_state_text', 'State');
     $request->set('shipping_country', 'LT');
     $request->set('shipping_postalCode', 'LT-4321');
     $request->set('shipping_phone', '4321');
     $this->assertEqual($response->getControllerName(), 'user');
     $this->assertEqual($response->getActionName(), 'checkout');
     // enter that last name at last
     $request->set('shipping_lastName', 'Last');
     $response = $this->controller->processCheckoutRegistration();
     $this->assertIsA($response, 'ActionRedirectResponse');
     $this->assertEqual($response->getControllerName(), 'checkout');
     $this->assertEqual($response->getActionName(), 'shipping');
     // verify user data
     $user = SessionUser::getUser();
     $user->reload(true);
     $this->assertEquals($user->firstName->get(), 'First');
     $this->assertEquals($user->defaultShippingAddress->get()->userAddress->get()->firstName->get(), 'Recipient');
     $this->assertEquals($user->defaultBillingAddress->get()->userAddress->get()->countryID->get(), 'LV');
     $this->assertEquals($user->defaultShippingAddress->get()->userAddress->get()->countryID->get(), 'LT');
     // order address
     ActiveRecord::clearPool();
     $order = CustomerOrder::getInstanceByID($this->order->getID(), true);
     $order->loadAll();
     $this->assertEquals($order->shippingAddress->get()->countryID->get(), 'LT');
 }
Пример #23
0
 public function getUser()
 {
     if (empty($this->user)) {
         ClassLoader::import('application.model.user.SessionUser');
         $sessionUser = new SessionUser();
         $this->user = $sessionUser->getUser();
     }
     return $this->user;
 }
Пример #24
0
 protected function registerAnonUser()
 {
     if ($this->user->isAnonymous()) {
         $this->order->loadAll();
         ActiveRecord::beginTransaction();
         $this->user->setPassword($this->session->get('password'));
         $this->user->resetModifiedStatus(true);
         $this->user->defaultBillingAddress->resetModifiedStatus();
         $this->user->defaultShippingAddress->resetModifiedStatus();
         if ($this->user->getSpecification()) {
             $this->user->setSpecification(clone $this->user->getSpecification());
         }
         $this->user->save();
         foreach (array('billingAddress' => 'defaultBillingAddress', 'shippingAddress' => 'defaultShippingAddress') as $order => $key) {
             $address = $this->user->{$key}->get();
             if ($address) {
                 $newAddress = clone $address;
                 $newAddress->userAddress->set(clone $newAddress->userAddress->get());
                 $newAddress->user->set($this->user);
                 $this->user->{$key}->set($newAddress);
                 $newAddress->save();
                 $this->order->{$order}->set($newAddress->userAddress->get());
             }
         }
         $this->order->resetArrayData();
         // shipping and billing addresses the same? save only the billing address
         if ($this->order->shippingAddress->get() && $this->order->billingAddress->get()->toString() == $this->order->shippingAddress->get()->toString()) {
             $this->user->defaultShippingAddress->get()->delete();
             $this->user->defaultShippingAddress->setNull();
         }
         $this->user->save();
         $this->order->user->set($this->user);
         $this->order->user->setAsModified();
         SessionUser::setUser($this->user);
         $this->session->set('checkoutUser', null);
         ActiveRecord::commit();
         $this->getUserController()->sendWelcomeEmail($this->user);
     }
 }
Пример #25
0
 public function logout()
 {
     SessionUser::destroy();
     return new ActionRedirectResponse('backend.session', 'index');
 }
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// Mettre à jour la langue par défaut
// ////////////////////////////////////////////////////////////////////////////////////////////////////
if ($etablissement_langue) {
    // Vérifications
    if (!is_dir(LOCALE_DIR . DS . $etablissement_langue)) {
        exit('Erreur : dossier de langue "' . $etablissement_langue . '" non trouvé !');
    }
    // C'est ok...
    $tab_parametres = array();
    $tab_parametres['etablissement_langue'] = $etablissement_langue;
    DB_STRUCTURE_COMMUN::DB_modifier_parametres($tab_parametres);
    // On modifie aussi la session
    $_SESSION['ETABLISSEMENT']['LANGUE'] = $etablissement_langue;
    // sans oublier le menu
    $locale = !empty($_SESSION['USER_LANGUE']) ? $_SESSION['USER_LANGUE'] : $_SESSION['ETABLISSEMENT']['LANGUE'];
    Lang::setlocale(LC_MESSAGES, $locale);
    SessionUser::memoriser_menu();
    // Retour
    exit('ok');
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// Il se peut que rien n'ait été récupéré à cause de l'upload d'un fichier trop lourd
// ////////////////////////////////////////////////////////////////////////////////////////////////////
if (empty($_POST)) {
    exit('Erreur : aucune donnée reçue ! Fichier trop lourd ? ' . InfoServeur::minimum_limitations_upload());
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// On ne devrait pas en arriver là...
// ////////////////////////////////////////////////////////////////////////////////////////////////////
exit('Erreur avec les données transmises !');
Пример #27
0
 private function buildSharingValidator(Product $product)
 {
     ClassLoader::import('application.helper.check.IsUniqueEmailCheck');
     $validator = $this->getValidator('productSharingValidator', $this->getRequest());
     if (!$this->config->get('ENABLE_PRODUCT_SHARING')) {
         $validator->addCheck(md5(time() . mt_rand()), new IsNotEmptyCheck($this->translate('_feature_disabled')));
     }
     $validator->addCheck('friendemail', new IsNotEmptyCheck($this->translate('_err_enter_email')));
     $validator->addCheck('friendemail', new IsValidEmailCheck($this->translate('_err_invalid_email')));
     if (SessionUser::getUser()->isAnonymous()) {
         if (!$this->config->get('ENABLE_ANONYMOUS_PRODUCT_SHARING')) {
             $validator->addCheck(md5(time() . mt_rand()), new IsNotEmptyCheck($this->translate('_feature_disabled_for_anonymous')));
         }
         $validator->addCheck('nickname', new IsNotEmptyCheck($this->translate('_err_enter_nickname')));
     }
     return $validator;
 }
Пример #28
0
        if ($profil == 'webmestre' && $login == 'webmestre' && $password != '') {
            $auth_resultat = SessionUser::tester_authentification_webmestre($password);
            if ($auth_resultat == 'ok') {
                SessionUser::initialiser_webmestre();
            }
        } else {
            if ($profil == 'developpeur' && $login == 'developpeur' && $password != '') {
                $auth_resultat = SessionUser::tester_authentification_developpeur($password);
                if ($auth_resultat == 'ok') {
                    SessionUser::initialiser_developpeur();
                }
            } else {
                if ($profil == 'partenaire' && $partenaire != 0 && $password != '' && IS_HEBERGEMENT_SESAMATH && HEBERGEUR_INSTALLATION == 'multi-structures') {
                    list($auth_resultat, $auth_DB_ROW) = SessionUser::tester_authentification_partenaire($partenaire, $password);
                    if ($auth_resultat == 'ok') {
                        SessionUser::initialiser_partenaire($auth_DB_ROW);
                    }
                }
            }
        }
    }
    // Conclusion & Retour
    if ($auth_resultat == 'ok') {
        exit_json(TRUE, adresse_redirection_apres_authentification());
    } else {
        $_SESSION['FORCEBRUTE'][$PAGE]['DELAI']++;
        $_SESSION['FORCEBRUTE'][$PAGE]['TIME'] = $_SERVER['REQUEST_TIME'];
        exit_json(FALSE, $auth_resultat);
    }
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
Пример #29
0
 * 
 * SACoche est distribué dans l’espoir qu’il vous sera utile, mais SANS AUCUNE GARANTIE :
 * sans même la garantie implicite de COMMERCIALISABILITÉ ni d’ADÉQUATION À UN OBJECTIF PARTICULIER.
 * Consultez la Licence Publique Générale GNU Affero pour plus de détails.
 * 
 * Vous devriez avoir reçu une copie de la Licence Publique Générale GNU Affero avec SACoche ;
 * si ce n’est pas le cas, consultez : <http://www.gnu.org/licenses/>.
 * 
 */
if (!defined('SACoche')) {
    exit('Ce fichier ne peut être appelé directement !');
}
if ($_SESSION['SESAMATH_ID'] == ID_DEMO) {
    exit('Action désactivée pour la démo...');
}
$daltonisme = isset($_POST['daltonisme']) ? Clean::entier($_POST['daltonisme']) : -1;
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// Mettre à jour la session + la base + le css perso
// ////////////////////////////////////////////////////////////////////////////////////////////////////
if (in_array($daltonisme, array(0, 1))) {
    $_SESSION['USER_DALTONISME'] = $daltonisme;
    DB_STRUCTURE_COMMUN::DB_modifier_user_parametre($_SESSION['USER_ID'], 'user_daltonisme', $daltonisme);
    // Enregistrer en session le CSS personnalisé
    SessionUser::adapter_daltonisme();
    SessionUser::actualiser_style();
    exit('ok');
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// On ne devrait pas en arriver là !
// ////////////////////////////////////////////////////////////////////////////////////////////////////
exit('Erreur avec les données transmises !');
Пример #30
0
 public function expressReturn()
 {
     $class = $this->request->get('id');
     $this->order->setPaymentMethod($class);
     $handler = $this->application->getExpressPaymentHandler($class, $this->getTransaction());
     $handler->setOrder($this->order);
     $details = $handler->getTransactionDetails($this->request->toArray());
     $address = UserAddress::getNewInstanceByTransaction($details);
     $address->save();
     $paymentData = array_diff_key($this->request->toArray(), array_flip(array('controller', 'action', 'id', 'route', 'PHPSESSID')));
     // @todo - determine if the order is new or completed earlier, but unpaid
     // for now only new orders can be paid with express checkout methods
     $order = $this->getPaymentOrder();
     $express = ExpressCheckout::getNewInstance($order, $handler);
     $express->address->set($address);
     $express->paymentData->set(serialize($paymentData));
     $express->save();
     // auto-login user if anonymous
     if ($this->user->isAnonymous()) {
         // create new user account if it doesn't exist
         if (!($user = User::getInstanceByEmail($details->email->get()))) {
             $user = User::getNewInstance($details->email->get());
             $user->firstName->set($details->firstName->get());
             $user->lastName->set($details->lastName->get());
             $user->companyName->set($details->companyName->get());
             $user->isEnabled->set(true);
             $user->save();
         }
         SessionUser::setUser($user);
         $order->setUser($user);
     }
     $order->billingAddress->set($address);
     if ($order->isShippingRequired()) {
         $order->shippingAddress->set($address);
     }
     $order->save();
     return new ActionRedirectResponse('checkout', 'shipping');
 }