Регистрация пользователя при оформлении заказа в один шаг

Материал из Umicms
Перейти к:навигация, поиск


Задача: Реализовать возможность регистрации пользователя при оформлении заказа в один шаг.

Реализация:
Для создания формы оформления заказа в один шаг воспользуемся статьей Оформление заказа в один шаг – xslt шаблонизатор.
В шаблоне <xsl:template match="udata[@module='emarket'][@method='fast_purchasing_xslt']"> добавим кнопку-флажок для регистрации пользователя по его желанию.

<xsl:if test="not($user_auth)">
     Зарегистрироваться на сайте <input name="need_reg" type="checkbox"/>
</xsl:if>

В основной файл шаблона нужно добавить переменную user_auth:

<xsl:variable name="user_auth" select="/result/user/@status" />

В файл classes\modules\emarket\__custom.php добавим определения метода регистрации пользователя и генерации случайного пароля:

          protected function registerUser($customer_id){
                 $obj_coll = umiObjectsCollection::getInstance();
                 $customer_obj = $obj_coll->getObject($customer_id);
                 $customer = array ('email' => '', 'fname' => '', 'lname' => '', 'father_name' => '');
                 $oUsersMdl = cmsController::getInstance()->getModule("users");
                 
                 if ($oUsersMdl instanceof def_module)
                    if ($oUsersMdl->is_auth())
                        return false;
                 
                 foreach ($customer as $key=>$value){
                     if ($customer_obj->getValue($key))
                         $customer[$key] = $customer_obj->getValue($key);
                 }
                 if (!$customer['email'])
                     return false;
                 
                 $objectTypes = umiObjectTypesCollection::getInstance();
                 $regedit = regedit::getInstance();
                
                 
                 $objectTypeId = $objectTypes->getBaseType("users", "user");
                 $without_act = (bool) $regedit->getVal("//modules/users/without_act");
                 
                 $customer['email'] = $oUsersMdl->validateEmail($customer['email'], false, !$without_act);
                 
                 
                 $customer['login'] = $customer['email'];
                 $customer['pass'] = self::randomPassword();
                 
                 if (isset($_REQUEST['captcha'])) {
                    $_SESSION['user_captcha'] = md5((int) getRequest('captcha'));
                }

                 if (!umiCaptcha::checkCaptcha()) {
                    $this->errorAddErrors('errors_wrong_captcha');
                 }
                 if (strpos($customer['email'],'@') === false)
                         $this->redirect(getServer('HTTP_REFERER'));
                 
                 $oUsersMdl->errorThrow('public');
                 
                 
                 //Creating user...
                $objectId = $obj_coll->addObject($customer['login'], $objectTypeId);
                $activationCode = md5($customer['login'] . time());

                $object = $obj_coll->getObject($objectId);
                
                $object->setValue("login",  $customer['login']);
                $object->setValue("password", md5($customer['pass']));
                $object->setValue("e-mail",  $customer['email']);
                $object->setValue("fname",  $customer['fname']);
                $object->setValue("lname",  $customer['lname']);
                $object->setValue("father_name",  $customer['fname']);
                
                
                $object->setValue("is_activated", $without_act);
                $object->setValue("activate_code", $activationCode);
                $object->setValue("referer", urldecode(getSession("http_referer")));
                $object->setValue("target", urldecode(getSession("http_target")));
                $object->setValue("register_date", umiDate::getCurrentTimeStamp());
                
                $group_id = regedit::getInstance()->getVal("//modules/users/def_group");
                $object->setValue("groups", Array($group_id));

                $data_module = cmsController::getInstance()->getModule('data');
                $data_module->saveEditedObject($objectId, true);
                
                $object->commit();
                
                $template = 'default';
                list(
				$template_mail, $template_mail_subject, $template_mail_noactivation, $template_mail_subject_noactivation
			) = def_module::loadTemplatesForMail("users/register/".$template,
				"mail_registrated", "mail_registrated_subject", "mail_registrated_noactivation", "mail_registrated_subject_noactivation"
			);

			if ($without_act && $template_mail_noactivation && $template_mail_subject_noactivation) {
				$template_mail = $template_mail_noactivation;
				$template_mail_subject = $template_mail_subject_noactivation;
			}

			$mailData = array(
				'user_id' => $objectId,
				'domain' => $domain = $_SERVER['HTTP_HOST'],
				'activate_link' => "http://" . $domain . $this->pre_lang . "/users/activate/" . $activationCode . "/",
				'login' => $customer['login'],
				'password' => $customer['pass'],
				'lname' => $object->getValue("lname"),
				'fname' => $object->getValue("fname"),
				'father_name' => $object->getValue("father_name"),
			);

			$mailContent = def_module::parseTemplateForMail($template_mail, $mailData, false, $objectId);
			$mailSubject = def_module::parseTemplateForMail($template_mail_subject, $mailData, false, $objectId);

			$fio = $object->getValue("lname") . " " . $object->getValue("fname") . " " . $object->getValue("father_name");

			$email_from = regedit::getInstance()->getVal("//settings/email_from");
			$fio_from = regedit::getInstance()->getVal("//settings/fio_from");


			$registrationMail = new umiMail();
			$registrationMail->addRecipient($customer['email'], $fio);
			$registrationMail->setFrom($email_from, $fio_from);
			$registrationMail->setSubject($mailSubject);
			$registrationMail->setContent($mailContent);
			$registrationMail->commit();
			$registrationMail->send();
                        
                        if (getCookie('customer-id'))
                            setcookie ('customer-id');
                        return $objectId;
                
            }
            
            private function randomPassword(){
                    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
                    $pass = array();
                    $alphaLength = strlen($alphabet) - 1;
                    for ($i = 0; $i < 8; $i++) {
                        $n = rand(0, $alphaLength);
                        $pass[] = $alphabet[$n];
                    }
                    return implode($pass);
            }

Код метода saveinfo(),который находится в том же файле, должен выглядеть следующим образом:

public function saveinfo() {
                $order = $this->getBasketOrder(false);
                //сохранение регистрационных данных
                $cmsController = cmsController::getInstance();
                $data = $cmsController->getModule('data');
                $data->saveEditedObject(customer::get()->id, false, true);
                
                $need_reg = getRequest('need_reg');
                
                if (isset($need_reg) && $need_reg=='on')
                    $user_id = self::registerUser(customer::get()->id);
                
                //сохранение способа доставки
                $deliveryId = getRequest('delivery-id');
                if ($deliveryId) {
                    $delivery = delivery::get($deliveryId);
                    $deliveryPrice = (float) $delivery->getDeliveryPrice($order);
                    $order->setValue('delivery_id', $deliveryId);
                    $order->setValue('delivery_price', $deliveryPrice);
                }
                //сохранение адреса доставки
                $addressId = getRequest('delivery-address');
                if ($addressId == 'new') {
                    $collection = umiObjectsCollection::getInstance();
                    $types = umiObjectTypesCollection::getInstance();
                    $typeId = $types->getBaseType("emarket", "delivery_address");
                    $customer = customer::get();
                    
                    if ($user_id){
                        $addressId = $collection->addObject("Address for customer #" . $user_id, $typeId);
                        $user = $collection->getObject($user_id);
                        $order->setValue('customer_id',$user_id);
                    }
                    else {
                        $addressId = $collection->addObject("Address for customer #" . $customer->id, $typeId);
                    }
                    $dataModule = $cmsController->getModule("data");
                    if ($dataModule) {
                        $dataModule->saveEditedObject($addressId, true, true);
                    }
                    if (!$user_id)
                        $customer->delivery_addresses = array_merge($customer->delivery_addresses, array($addressId));
                    else
                        $user->delivery_addresses = array_merge($user->delivery_addresses, array($addressId));
                }
                $order->delivery_address = $addressId;

                //сохранение способа оплаты и редирект на итоговую страницу, либо страницу подтверждения оплаты.
                $order->setValue('payment_id', getRequest('payment-id'));
                $order->refresh();

                $paymentId = getRequest('payment-id');
                if (!$paymentId) {
                    $this->errorNewMessage(getLabel('error-emarket-choose-payment'));
                    $this->errorPanic();
                }
                $payment = payment::get($paymentId);
                
                if ($payment instanceof payment) {
                    $paymentName = $payment->getCodeName();
                    
                    $url = "{$this->pre_lang}/" . cmsController::getInstance()->getUrlPrefix() . "emarket/purchase/payment/{$paymentName}/";
                } else {
                    $url = "{$this->pre_lang}/" . cmsController::getInstance()->getUrlPrefix() . "emarket/cart/";
                }
                $this->redirect($url);
            }