Example #1
0
 /**
  * Searchs for an user with the given user id of the social media platform.
  * If there is no user, create one and directly log in.
  *
  * @param string $oauth_id the user id of the social media platform
  * @return bool
  * @throws OAuth_Exception
  */
 protected function getContrexxUser($oauth_id)
 {
     global $sessionObj;
     //\DBG::activate();
     $arrSettings = \User_Setting::getSettings();
     $provider = $this::OAUTH_PROVIDER;
     $FWUser = \FWUser::getFWUserObject();
     $objUser = $FWUser->objUser->getByNetwork($provider, $oauth_id);
     if (!$objUser) {
         // check whether the user is already logged in
         // if the user is logged in just add a new network to the user object
         if ($FWUser->objUser->login()) {
             $objUser = $FWUser->objUser;
             $this->addProviderToUserObject($provider, $oauth_id, $objUser);
             $objUser->getNetworks()->save();
             return true;
         }
         // create a new user with the default profile attributes
         $objUser = new \User();
         $objUser->setEmail($this->getEmail());
         $objUser->setAdminStatus(0);
         $objUser->setProfile(array('firstname' => array($this->getFirstname()), 'lastname' => array($this->getLastname())));
         $registrationRedirectNeeded = $arrSettings['sociallogin_show_signup']['status'];
         // if user_account_verification is true (1), then we need to do checkMandatoryCompliance(), because
         // the required fields must be set.
         if ($registrationRedirectNeeded == false && $arrSettings['user_account_verification']['value'] === 1) {
             $registrationRedirectNeeded = !$objUser->checkMandatoryCompliance();
         }
         $objUser->setActiveStatus(!$registrationRedirectNeeded);
         if ($registrationRedirectNeeded) {
             $objUser->setRestoreKey();
             $objUser->setRestoreKeyTime(intval($arrSettings['sociallogin_activation_timeout']['value']) * 60);
         }
         if (!empty($arrSettings['sociallogin_assign_to_groups']['value'])) {
             $groups = $arrSettings['sociallogin_assign_to_groups']['value'];
         } else {
             $groups = $arrSettings['assigne_to_groups']['value'];
         }
         $objUser->setGroups(explode(',', $groups));
         // if we can create the user without sign up page
         if (!$objUser->store()) {
             // if the email address already exists but not with the given oauth-provider
             throw new OAuth_Exception();
         }
         // add the social network to user
         $this->addProviderToUserObject($provider, $oauth_id, $objUser);
         $objUser->getNetworks()->save();
         // check whether there are empty mandatory fields or the setting to show sign up everytime
         if ($registrationRedirectNeeded) {
             // start session if no session is open
             if (!isset($sessionObj) || !is_object($sessionObj)) {
                 $sessionObj = \cmsSession::getInstance();
             }
             // write the user id to session so we can pre-fill the sign up form
             $_SESSION['user_id'] = $objUser->getId();
             // generate url for sign up page and redirect
             $signUpPageUri = \Cx\Core\Routing\Url::fromModuleAndCmd('Access', 'signup');
             \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $signUpPageUri->__toString());
             exit;
         }
     }
     $FWUser->loginUser($objUser);
 }
Example #2
0
 /**
  * Returns an array with all placeholders and their values to be
  * replaced in any shop mailtemplate for the given order ID.
  *
  * You only have to set the 'substitution' index value of your MailTemplate
  * array to the array returned.
  * Customer data is not included here.  See {@see Customer::getSubstitutionArray()}.
  * Note that this method is now mostly independent of the current session.
  * The language of the mail template is determined by the browser
  * language range stored with the order.
  * @access  private
  * @static
  * @param   integer $order_id     The order ID
  * @param   boolean $create_accounts  If true, creates User accounts
  *                                    and Coupon codes.  Defaults to true
  * @return  array                 The array with placeholders as keys
  *                                and values from the order on success,
  *                                false otherwise
  */
 static function getSubstitutionArray($order_id, $create_accounts = true)
 {
     global $_ARRAYLANG;
     /*
                 $_ARRAYLANG['TXT_SHOP_URI_FOR_DOWNLOAD'].":\r\n".
                 'http://'.$_SERVER['SERVER_NAME'].
                 "/index.php?section=download\r\n";
     */
     $objOrder = Order::getById($order_id);
     if (!$objOrder) {
         // Order not found
         return false;
     }
     $lang_id = $objOrder->lang_id();
     if (!intval($lang_id)) {
         $lang_id = \FWLanguage::getLangIdByIso639_1($lang_id);
     }
     $status = $objOrder->status();
     $customer_id = $objOrder->customer_id();
     $customer = Customer::getById($customer_id);
     $payment_id = $objOrder->payment_id();
     $shipment_id = $objOrder->shipment_id();
     $arrSubstitution = array('CUSTOMER_COUNTRY_ID' => $objOrder->billing_country_id(), 'LANG_ID' => $lang_id, 'NOW' => date(ASCMS_DATE_FORMAT_DATETIME), 'TODAY' => date(ASCMS_DATE_FORMAT_DATE), 'ORDER_ID' => $order_id, 'ORDER_ID_CUSTOM' => ShopLibrary::getCustomOrderId($order_id), 'ORDER_DATE' => date(ASCMS_DATE_FORMAT_DATE, strtotime($objOrder->date_time())), 'ORDER_TIME' => date(ASCMS_DATE_FORMAT_TIME, strtotime($objOrder->date_time())), 'ORDER_STATUS_ID' => $status, 'ORDER_STATUS' => $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $status], 'MODIFIED' => date(ASCMS_DATE_FORMAT_DATETIME, strtotime($objOrder->modified_on())), 'REMARKS' => $objOrder->note(), 'ORDER_SUM' => sprintf('% 9.2f', $objOrder->sum()), 'CURRENCY' => Currency::getCodeById($objOrder->currency_id()));
     $arrSubstitution += $customer->getSubstitutionArray();
     if ($shipment_id) {
         $arrSubstitution += array('SHIPMENT' => array(0 => array('SHIPMENT_NAME' => sprintf('%-40s', Shipment::getShipperName($shipment_id)), 'SHIPMENT_PRICE' => sprintf('% 9.2f', $objOrder->shipment_amount()))), 'SHIPPING_ADDRESS' => array(0 => array('SHIPPING_COMPANY' => $objOrder->company(), 'SHIPPING_TITLE' => $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHIPPING_FIRSTNAME' => $objOrder->firstname(), 'SHIPPING_LASTNAME' => $objOrder->lastname(), 'SHIPPING_ADDRESS' => $objOrder->address(), 'SHIPPING_ZIP' => $objOrder->zip(), 'SHIPPING_CITY' => $objOrder->city(), 'SHIPPING_COUNTRY_ID' => $objOrder->country_id(), 'SHIPPING_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHIPPING_PHONE' => $objOrder->phone())));
     }
     if ($payment_id) {
         $arrSubstitution += array('PAYMENT' => array(0 => array('PAYMENT_NAME' => sprintf('%-40s', Payment::getNameById($payment_id)), 'PAYMENT_PRICE' => sprintf('% 9.2f', $objOrder->payment_amount()))));
     }
     $arrItems = $objOrder->getItems();
     if (!$arrItems) {
         \Message::warning($_ARRAYLANG['TXT_SHOP_ORDER_WARNING_NO_ITEM']);
     }
     // Deduct Coupon discounts, either from each Product price, or
     // from the items total.  Mind that the Coupon has already been
     // stored with the Order, but not redeemed yet.  This is done
     // in this method, but only if $create_accounts is true.
     $coupon_code = NULL;
     $coupon_amount = 0;
     $objCoupon = Coupon::getByOrderId($order_id);
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
     }
     $orderItemCount = 0;
     $total_item_price = 0;
     // Suppress Coupon messages (see Coupon::available())
     \Message::save();
     foreach ($arrItems as $item) {
         $product_id = $item['product_id'];
         $objProduct = Product::getById($product_id);
         if (!$objProduct) {
             //die("Product ID $product_id not found");
             continue;
         }
         //DBG::log("Orders::getSubstitutionArray(): Item: Product ID $product_id");
         $product_name = substr($item['name'], 0, 40);
         $item_price = $item['price'];
         $quantity = $item['quantity'];
         // TODO: Add individual VAT rates for Products
         //            $orderItemVatPercent = $objResultItem->fields['vat_percent'];
         // Decrease the Product stock count,
         // applies to "real", shipped goods only
         $objProduct->decreaseStock($quantity);
         $product_code = $objProduct->code();
         // Pick the order items attributes
         $str_options = '';
         // Any attributes?
         if ($item['attributes']) {
             $str_options = '  ';
             // '[';
             $attribute_name_previous = '';
             foreach ($item['attributes'] as $attribute_name => $arrAttribute) {
                 //DBG::log("Attribute /$attribute_name/ => ".var_export($arrAttribute, true));
                 // NOTE: The option price is optional and may be left out
                 foreach ($arrAttribute as $arrOption) {
                     $option_name = $arrOption['name'];
                     $option_price = $arrOption['price'];
                     $item_price += $option_price;
                     // Recognize the names of uploaded files,
                     // verify their presence and use the original name
                     $option_name_stripped = ShopLibrary::stripUniqidFromFilename($option_name);
                     $path = Order::UPLOAD_FOLDER . $option_name;
                     if ($option_name != $option_name_stripped && \File::exists($path)) {
                         $option_name = $option_name_stripped;
                     }
                     if ($attribute_name != $attribute_name_previous) {
                         if ($attribute_name_previous) {
                             $str_options .= '; ';
                         }
                         $str_options .= $attribute_name . ': ' . $option_name;
                         $attribute_name_previous = $attribute_name;
                     } else {
                         $str_options .= ', ' . $option_name;
                     }
                     // TODO: Add proper formatting with sprintf() and language entries
                     if ($option_price != 0) {
                         $str_options .= ' ' . Currency::formatPrice($option_price) . ' ' . Currency::getActiveCurrencyCode();
                     }
                 }
             }
             //                $str_options .= ']';
         }
         // Product details
         $arrProduct = array('PRODUCT_ID' => $product_id, 'PRODUCT_CODE' => $product_code, 'PRODUCT_QUANTITY' => $quantity, 'PRODUCT_TITLE' => $product_name, 'PRODUCT_OPTIONS' => $str_options, 'PRODUCT_ITEM_PRICE' => sprintf('% 9.2f', $item_price), 'PRODUCT_TOTAL_PRICE' => sprintf('% 9.2f', $item_price * $quantity));
         //DBG::log("Orders::getSubstitutionArray($order_id, $create_accounts): Adding article: ".var_export($arrProduct, true));
         $orderItemCount += $quantity;
         $total_item_price += $item_price * $quantity;
         if ($create_accounts) {
             // Add an account for every single instance of every Product
             for ($instance = 1; $instance <= $quantity; ++$instance) {
                 $validity = 0;
                 // Default to unlimited validity
                 // In case there are protected downloads in the cart,
                 // collect the group IDs
                 $arrUsergroupId = array();
                 if ($objProduct->distribution() == 'download') {
                     $usergroupIds = $objProduct->usergroup_ids();
                     if ($usergroupIds != '') {
                         $arrUsergroupId = explode(',', $usergroupIds);
                         $validity = $objProduct->weight();
                     }
                 }
                 // create an account that belongs to all collected
                 // user groups, if any.
                 if (count($arrUsergroupId) > 0) {
                     // The login names are created separately for
                     // each product instance
                     $username = self::usernamePrefix . "_{$order_id}_{$product_id}_{$instance}";
                     $userEmail = $username . '-' . $arrSubstitution['CUSTOMER_EMAIL'];
                     $userpass = \User::make_password();
                     $objUser = new \User();
                     $objUser->setUsername($username);
                     $objUser->setPassword($userpass);
                     $objUser->setEmail($userEmail);
                     $objUser->setAdminStatus(false);
                     $objUser->setActiveStatus(true);
                     $objUser->setGroups($arrUsergroupId);
                     $objUser->setValidityTimePeriod($validity);
                     $objUser->setFrontendLanguage(FRONTEND_LANG_ID);
                     $objUser->setBackendLanguage(FRONTEND_LANG_ID);
                     $objUser->setProfile(array('firstname' => array(0 => $arrSubstitution['CUSTOMER_FIRSTNAME']), 'lastname' => array(0 => $arrSubstitution['CUSTOMER_LASTNAME']), 'company' => array(0 => $arrSubstitution['CUSTOMER_COMPANY']), 'address' => array(0 => $arrSubstitution['CUSTOMER_ADDRESS']), 'zip' => array(0 => $arrSubstitution['CUSTOMER_ZIP']), 'city' => array(0 => $arrSubstitution['CUSTOMER_CITY']), 'country' => array(0 => $arrSubstitution['CUSTOMER_COUNTRY_ID']), 'phone_office' => array(0 => $arrSubstitution['CUSTOMER_PHONE']), 'phone_fax' => array(0 => $arrSubstitution['CUSTOMER_FAX'])));
                     if (!$objUser->store()) {
                         \Message::error(implode('<br />', $objUser->getErrorMsg()));
                         return false;
                     }
                     if (empty($arrProduct['USER_DATA'])) {
                         $arrProduct['USER_DATA'] = array();
                     }
                     $arrProduct['USER_DATA'][] = array('USER_NAME' => $username, 'USER_PASS' => $userpass);
                 }
                 //echo("Instance $instance");
                 if ($objProduct->distribution() == 'coupon') {
                     if (empty($arrProduct['COUPON_DATA'])) {
                         $arrProduct['COUPON_DATA'] = array();
                     }
                     //DBG::log("Orders::getSubstitutionArray(): Getting code");
                     $code = Coupon::getNewCode();
                     //DBG::log("Orders::getSubstitutionArray(): Got code: $code, calling Coupon::addCode($code, 0, 0, 0, $item_price)");
                     Coupon::storeCode($code, 0, 0, 0, $item_price, 0, 0, 10000000000.0, true);
                     $arrProduct['COUPON_DATA'][] = array('COUPON_CODE' => $code);
                 }
             }
             // Redeem the *product* Coupon, if possible for the Product
             if ($coupon_code) {
                 $objCoupon = Coupon::available($coupon_code, $item_price * $quantity, $customer_id, $product_id, $payment_id);
                 if ($objCoupon) {
                     $coupon_code = NULL;
                     $coupon_amount = $objCoupon->getDiscountAmount($item_price, $customer_id);
                     if ($create_accounts) {
                         $objCoupon->redeem($order_id, $customer_id, $item_price * $quantity);
                     }
                 }
                 //\DBG::log("Orders::getSubstitutionArray(): Got Product Coupon $coupon_code");
             }
         }
         if (empty($arrSubstitution['ORDER_ITEM'])) {
             $arrSubstitution['ORDER_ITEM'] = array();
         }
         $arrSubstitution['ORDER_ITEM'][] = $arrProduct;
     }
     $arrSubstitution['ORDER_ITEM_SUM'] = sprintf('% 9.2f', $total_item_price);
     $arrSubstitution['ORDER_ITEM_COUNT'] = sprintf('% 4u', $orderItemCount);
     // Redeem the *global* Coupon, if possible for the Order
     if ($coupon_code) {
         $objCoupon = Coupon::available($coupon_code, $total_item_price, $customer_id, null, $payment_id);
         if ($objCoupon) {
             $coupon_amount = $objCoupon->getDiscountAmount($total_item_price, $customer_id);
             if ($create_accounts) {
                 $objCoupon->redeem($order_id, $customer_id, $total_item_price);
             }
         }
     }
     \Message::restore();
     // Fill in the Coupon block with proper discount and amount
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
         //\DBG::log("Orders::getSubstitutionArray(): Coupon $coupon_code, amount $coupon_amount");
     }
     if ($coupon_amount) {
         //\DBG::log("Orders::getSubstitutionArray(): Got Order Coupon $coupon_code");
         $arrSubstitution['DISCOUNT_COUPON'][] = array('DISCOUNT_COUPON_CODE' => sprintf('%-40s', $coupon_code), 'DISCOUNT_COUPON_AMOUNT' => sprintf('% 9.2f', -$coupon_amount));
     } else {
         //\DBG::log("Orders::getSubstitutionArray(): No Coupon for Order ID $order_id");
     }
     Products::deactivate_soldout();
     if (Vat::isEnabled()) {
         //DBG::log("Orders::getSubstitutionArray(): VAT amount: ".$objOrder->vat_amount());
         $arrSubstitution['VAT'] = array(0 => array('VAT_TEXT' => sprintf('%-40s', Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL']), 'VAT_PRICE' => $objOrder->vat_amount()));
     }
     return $arrSubstitution;
 }
Example #3
0
 private function signUp()
 {
     global $_ARRAYLANG, $_CORELANG;
     if (!empty($_GET['u']) && !empty($_GET['k'])) {
         $this->_objTpl->hideBlock('access_signup_store_success');
         $this->_objTpl->hideBlock('access_signup_store_error');
         if ($this->confirmSignUp(intval($_GET['u']), contrexx_stripslashes($_GET['k']))) {
             $this->_objTpl->setVariable('ACCESS_SIGNUP_MESSAGE', $_ARRAYLANG['TXT_ACCESS_ACCOUNT_SUCCESSFULLY_ACTIVATED']);
             $this->_objTpl->parse('access_signup_confirm_success');
             $this->_objTpl->hideBlock('access_signup_confirm_error');
         } else {
             $this->_objTpl->setVariable('ACCESS_SIGNUP_MESSAGE', implode('<br />', $this->arrStatusMsg['error']));
             $this->_objTpl->parse('access_signup_confirm_error');
             $this->_objTpl->hideBlock('access_signup_confirm_success');
         }
         return;
     } else {
         $this->_objTpl->hideBlock('access_signup_confirm_success');
         $this->_objTpl->hideBlock('access_signup_confirm_error');
     }
     $arrSettings = \User_Setting::getSettings();
     $objUser = null;
     if (!empty($_SESSION['user_id'])) {
         $objUser = \FWUser::getFWUserObject()->objUser->getUser($_SESSION['user_id']);
         if ($objUser) {
             $objUser->releaseRestoreKey();
             $active = $arrSettings['sociallogin_active_automatically']['status'];
             $objUser->setActiveStatus($active);
             $this->_objTpl->hideBlock('access_logindata');
         }
     }
     if (!$objUser) {
         $objUser = new \User();
     }
     if (isset($_POST['access_signup'])) {
         $objUser->setUsername(isset($_POST['access_user_username']) ? trim(contrexx_stripslashes($_POST['access_user_username'])) : '');
         $objUser->setEmail(isset($_POST['access_user_email']) ? trim(contrexx_stripslashes($_POST['access_user_email'])) : '');
         $objUser->setFrontendLanguage(isset($_POST['access_user_frontend_language']) ? intval($_POST['access_user_frontend_language']) : 0);
         $assignedGroups = $objUser->getAssociatedGroupIds();
         if (empty($assignedGroups)) {
             $objUser->setGroups(explode(',', $arrSettings['assigne_to_groups']['value']));
         }
         $objUser->setSubscribedNewsletterListIDs(isset($_POST['access_user_newsletters']) && is_array($_POST['access_user_newsletters']) ? $_POST['access_user_newsletters'] : array());
         if ((!isset($_POST['access_profile_attribute']) || !is_array($_POST['access_profile_attribute']) || ($arrProfile = $_POST['access_profile_attribute']) && (!isset($_FILES['access_profile_attribute_images']) || !is_array($_FILES['access_profile_attribute_images']) || ($uploadImageError = $this->addUploadedImagesToProfile($objUser, $arrProfile, $_FILES['access_profile_attribute_images'])) === true) && $objUser->setProfile($arrProfile)) && $objUser->setPassword(isset($_POST['access_user_password']) ? trim(contrexx_stripslashes($_POST['access_user_password'])) : '', isset($_POST['access_user_password_confirmed']) ? trim(contrexx_stripslashes($_POST['access_user_password_confirmed'])) : '') && ($arrSettings['user_account_verification']['value'] === 0 || $objUser->checkMandatoryCompliance()) && $this->checkCaptcha() && $this->checkToS() && $objUser->signUp()) {
             if ($this->handleSignUp($objUser)) {
                 if (isset($_SESSION['user_id'])) {
                     unset($_SESSION['user_id']);
                 }
                 $this->_objTpl->setVariable('ACCESS_SIGNUP_MESSAGE', implode('<br />', $this->arrStatusMsg['ok']));
                 $this->_objTpl->parse('access_signup_store_success');
                 $this->_objTpl->hideBlock('access_signup_store_error');
             } else {
                 $this->_objTpl->setVariable('ACCESS_SIGNUP_MESSAGE', implode('<br />', $this->arrStatusMsg['error']));
                 $this->_objTpl->parse('access_signup_store_error');
                 $this->_objTpl->hideBlock('access_signup_store_success');
             }
             $this->_objTpl->hideBlock('access_signup_form');
             return;
         } else {
             if (is_array($uploadImageError)) {
                 $this->arrStatusMsg['error'] = array_merge($this->arrStatusMsg['error'], $uploadImageError);
             }
             $this->arrStatusMsg['error'] = array_merge($this->arrStatusMsg['error'], $objUser->getErrorMsg());
             $this->_objTpl->hideBlock('access_signup_store_success');
             $this->_objTpl->hideBlock('access_signup_store_error');
         }
     } else {
         $this->_objTpl->hideBlock('access_signup_store_success');
         $this->_objTpl->hideBlock('access_signup_store_error');
     }
     $this->parseAccountAttributes($objUser, true);
     while (!$objUser->objAttribute->EOF) {
         $objAttribute = $objUser->objAttribute->getById($objUser->objAttribute->getId());
         if (!$objAttribute->isProtected() || (\Permission::checkAccess($objAttribute->getAccessId(), 'dynamic', true) || $objAttribute->checkModifyPermission())) {
             $this->parseAttribute($objUser, $objAttribute->getId(), 0, true);
         }
         $objUser->objAttribute->next();
     }
     $this->parseNewsletterLists($objUser);
     $this->attachJavaScriptFunction('accessSetWebsite');
     $this->_objTpl->setVariable(array('ACCESS_SIGNUP_BUTTON' => '<input type="submit" name="access_signup" value="' . $_ARRAYLANG['TXT_ACCESS_CREATE_ACCOUNT'] . '" />', 'ACCESS_JAVASCRIPT_FUNCTIONS' => $this->getJavaScriptCode(), 'ACCESS_SIGNUP_MESSAGE' => implode("<br />\n", $this->arrStatusMsg['error'])));
     if (!$arrSettings['use_usernames']['status']) {
         if ($this->_objTpl->blockExists('access_user_username')) {
             $this->_objTpl->hideBlock('access_user_username');
         }
     }
     // set captcha
     if ($this->_objTpl->blockExists('access_captcha')) {
         if ($arrSettings['user_captcha']['status']) {
             $this->_objTpl->setVariable(array('ACCESS_CAPTCHA_CODE' => \Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->getCode(), 'TXT_ACCESS_CAPTCHA' => $_CORELANG['TXT_CORE_CAPTCHA']));
             $this->_objTpl->parse('access_captcha');
         } else {
             $this->_objTpl->hideBlock('access_captcha');
         }
     }
     // set terms and conditions
     if ($this->_objTpl->blockExists('access_tos')) {
         if ($arrSettings['user_accept_tos_on_signup']['status']) {
             $uriTos = CONTREXX_SCRIPT_PATH . '?section=Agb';
             $this->_objTpl->setVariable(array('TXT_ACCESS_TOS' => $_ARRAYLANG['TXT_ACCESS_TOS'], 'ACCESS_TOS' => '<input type="checkbox" name="access_user_tos" id="access_user_tos"' . (!empty($_POST['access_user_tos']) ? ' checked="checked"' : '') . ' /><label for="access_user_tos">' . sprintf($_ARRAYLANG['TXT_ACCESS_ACCEPT_TOS'], $uriTos) . '</label>'));
             $this->_objTpl->parse('access_tos');
         } else {
             $this->_objTpl->hideBlock('access_tos');
         }
     }
     $this->_objTpl->parse('access_signup_form');
 }
 function afterSave(array &$values, User $record)
 {
     if ($this->grid->getCurrentAction() == 'insert' && @$values['_registration_mail']) {
         $record->sendRegistrationEmail();
     }
     $record->setGroups(array_filter((array) @$values['_groups']));
     //        if ($this->grid->hasPermission(null, 'edit'))
     //        {
     //            $this->redirectLocation($this->getView()->userUrl($record->pk()));
     //            exit();
     //        }
 }
 function afterSave(array &$values, User $record)
 {
     $record->setGroups(array_filter((array) @$values['_groups']));
     $event = new Am_Event_UserForm(Am_Event_UserForm::AFTER_SAVE, $this->grid->getForm(), $record, $values);
     $event->run();
     $values = $event->getValues();
     //        if ($this->grid->hasPermission(null, 'edit'))
     //        {
     //            $this->redirectLocation($this->getView()->userUrl($record->pk()));
     //            exit();
     //        }
 }
 /**
  * Return User object of given user_id
  *
  * @param int $user_id
  * @return User
  */
 public function getObjectById($user_id, $cacheMinutes = 0)
 {
     $user_id = intval($user_id);
     $this->query->exec("select * from `" . Tbl::get('TBL_USERS') . "` where `id`='{$user_id}'", $cacheMinutes);
     if ($this->query->countRecords()) {
         $res = $this->query->fetchRecord();
         $user = new User();
         $user->setLogin($res["login"]);
         $user->setId($user_id);
         $user->setCreationDate($res["creation_date"]);
         $user->setStatus($res["enable"]);
         foreach ($res as $key => $val) {
             if ($key != 'id' && $key != 'enable' && $key != 'creation_date' && $key != 'login' && $key != 'password') {
                 $user->{$key} = $val;
             }
         }
         $this->query->exec("select `permission_id` from `" . Tbl::get('TBL_USERS_PERMISSIONS') . "` where `user_id`='{$user_id}'", $cacheMinutes);
         $perms_ids_count = $this->query->countRecords();
         if ($perms_ids_count) {
             $perms_ids = $this->query->fetchFields(0, true);
             $sql_statement = "select `name` from `" . Tbl::get('TBL_PERMISSIONS') . "` where `id` in (";
             $count = $perms_ids_count - 1;
             for ($i = 0; $i < $count; ++$i) {
                 $sql_statement .= $perms_ids[$i] . ", ";
             }
             $sql_statement .= $perms_ids[$count] . ")";
             $this->query->exec($sql_statement, $cacheMinutes);
             $user->setPermissions($this->query->fetchFields(0, true));
         }
         $this->query->exec("select `group_id` from `" . Tbl::get('TBL_USERS_GROUPS') . "` where `user_id`='{$user_id}'", $cacheMinutes);
         $groups_ids_count = $this->query->countRecords();
         if ($groups_ids_count) {
             $groups_ids = $this->query->fetchFields(0, true);
             $sql_statement = "select `name` from `" . Tbl::get('TBL_GROUPS') . "` where `id` in (";
             $count = $groups_ids_count - 1;
             for ($i = 0; $i < $count; ++$i) {
                 $sql_statement .= $groups_ids[$i] . ", ";
             }
             $sql_statement .= $groups_ids[$count] . ")";
             $this->query->exec($sql_statement, $cacheMinutes);
             $groups_names = $this->query->fetchFields(0, true);
             $user->setGroups($groups_names);
             foreach ($groups_names as $group_name) {
                 $user->addPermissions($this->getGroupPermissionsList($group_name, $cacheMinutes));
             }
             $user->setPrimaryGroup($this->getPrimaryGroup($user_id, $cacheMinutes));
         }
         return $user;
     }
     return new User();
 }