private static function getInstance()
 {
     if (self::$instance) {
         return self::$instance;
     }
     $loader = new BitrixLoader($_SERVER['DOCUMENT_ROOT']);
     $c = Configuration::getInstance();
     $config = $c->get('maximaster');
     $twigConfig = (array) $config['tools']['twig'];
     $defaultConfig = array('debug' => false, 'charset' => SITE_CHARSET, 'cache' => $_SERVER['DOCUMENT_ROOT'] . '/bitrix/cache/maximaster/tools.twig', 'auto_reload' => isset($_GET['clear_cache']) && strtoupper($_GET['clear_cache']) == 'Y', 'autoescape' => false);
     $twigOptions = array_merge($defaultConfig, $twigConfig);
     $twig = new \Twig_Environment($loader, $twigOptions);
     if ($twig->isDebug()) {
         $twig->addExtension(new \Twig_Extension_Debug());
     }
     $twig->addExtension(new BitrixExtension());
     $twig->addExtension(new CustomFunctionsExtension());
     $event = new Event('', 'onAfterTwigTemplateEngineInited', array($twig));
     $event->send();
     if ($event->getResults()) {
         foreach ($event->getResults() as $evenResult) {
             if ($evenResult->getType() == \Bitrix\Main\EventResult::SUCCESS) {
                 $twig = current($evenResult->getParameters());
             }
         }
     }
     return self::$instance = $twig;
 }
Exemple #2
0
 public static function initClassesList()
 {
     if (static::$classes !== null) {
         return true;
     }
     $classes = array('\\Bitrix\\Sale\\Delivery\\ExtraServices\\Enum' => 'lib/delivery/extra_services/enum.php', '\\Bitrix\\Sale\\Delivery\\ExtraServices\\Store' => 'lib/delivery/extra_services/store.php', '\\Bitrix\\Sale\\Delivery\\ExtraServices\\String' => 'lib/delivery/extra_services/string.php', '\\Bitrix\\Sale\\Delivery\\ExtraServices\\Checkbox' => 'lib/delivery/extra_services/checkbox.php');
     \Bitrix\Main\Loader::registerAutoLoadClasses('sale', $classes);
     unset($classes['\\Bitrix\\Sale\\Delivery\\ExtraServices\\Store']);
     static::$classes = array_keys($classes);
     $event = new Event('sale', 'onSaleDeliveryExtraServicesClassNamesBuildList');
     $event->send();
     $resultList = $event->getResults();
     if (is_array($resultList) && !empty($resultList)) {
         $customClasses = array();
         foreach ($resultList as $eventResult) {
             /** @var  EventResult $eventResult*/
             if ($eventResult->getType() != EventResult::SUCCESS) {
                 throw new SystemException("Can't add custom tracking class successfully");
             }
             $params = $eventResult->getParameters();
             if (!empty($params) && is_array($params)) {
                 $customClasses = array_merge($customClasses, $params);
             }
         }
         if (!empty($customClasses)) {
             \Bitrix\Main\Loader::registerAutoLoadClasses(null, $customClasses);
             $classes = array_merge($customClasses, $classes);
         }
     }
     static::$classes = array_merge(array_keys($classes), static::$classes);
     return static::$classes;
 }
 public function clearCollection()
 {
     /** @var Main\Entity\Event $event */
     $event = new Main\Event('sale', 'OnBeforeCollectionClear', array('COLLECTION' => $this->collection));
     $event->send();
     /** @var CollectableEntity $item */
     foreach ($this->collection as $item) {
         $item->delete();
     }
 }
Exemple #4
0
 /**
  * @return array
  */
 public static function getList()
 {
     $resultList = array();
     $event = new Event('sender', 'OnPresetMailBlockList');
     $event->send();
     foreach ($event->getResults() as $eventResult) {
         if ($eventResult->getType() == EventResult::ERROR) {
             continue;
         }
         $eventResultParameters = $eventResult->getParameters();
         if (!empty($eventResultParameters)) {
             $resultList = array_merge($resultList, $eventResultParameters);
         }
     }
     return $resultList;
 }
Exemple #5
0
 /**
  * Добавляет расширения, в том числе расширение для битрикса,
  * в котором добавляются нужные глобальные переменные и т.п.
  */
 private function addExtensions()
 {
     $this->getEnvironment()->addExtension(new \Twig_Extension_Debug());
     $this->getEnvironment()->addExtension(new BitrixExtension());
     $event = new Event('wlbl.twigrix', 'onAddExtensions');
     $event->send();
     foreach ($event->getResults() as $result) {
         if ($result->getType() == EventResult::SUCCESS) {
             foreach ($result->getParameters() as $extension) {
                 if ($extension instanceof \Twig_Extension) {
                     $this->getEnvironment()->addExtension($extension);
                 }
             }
         }
     }
 }
 public function testUseHandlerClassParams()
 {
     $eventType = EventType::createByParams("ws.tools", "test");
     $this->manager()->subscribe($eventType, $handler = new TestHandler(array('init params')));
     $this->manager()->trigger($eventType, array('process params'));
     $history = $handler->getHistory();
     $this->assertEquals($history[0], array('identity', array('init params'), array('process params')));
     $this->assertEquals($history[1], array('process', array('init params'), array('process params')));
     $this->manager()->trigger($eventType, array('process2 params'));
     $history = $handler->getHistory();
     $this->assertEquals($history[3], array('process', array('init params'), array('process2 params')));
     $e = new Event("ws.tools", "test", array('process3 params'));
     $e->send($this);
     $history = $handler->getHistory();
     $this->assertEquals($history[5], array('process', array('init params'), array('process3 params')));
 }
 protected function __construct()
 {
     $event = new Main\Event("main", "OnApplicationsBuildList");
     $event->send();
     foreach ($event->getResults() as $eventResult) {
         $result = $eventResult->getParameters();
         if (is_array($result)) {
             if (!is_array($result[0])) {
                 $result = array($result);
             }
             foreach ($result as $app) {
                 $this->applications[$app["ID"]] = $app;
             }
         }
     }
     Main\Type\Collection::sortByColumn($this->applications, "SORT");
 }
 /**
  * Создается событие для внесения в Twig изменения из проекта
  */
 private function generateInitEvent()
 {
     $eventName = 'onAfterTwigTemplateEngineInited';
     $event = new Event('', $eventName, array($this->engine));
     $event->send();
     if ($event->getResults()) {
         foreach ($event->getResults() as $evenResult) {
             if ($evenResult->getType() == \Bitrix\Main\EventResult::SUCCESS) {
                 $twig = current($evenResult->getParameters());
                 if (!$twig instanceof \Twig_Environment) {
                     throw new \LogicException("Событие '{$eventName}' должно возвращать экземпляр класса '\\Twig_Environment' при успешной отработке");
                 }
                 $this->engine = $twig;
             }
         }
     }
 }
Exemple #9
0
 /**
  * @return Entity\AddResult|Entity\UpdateResult
  * @throws Main\ArgumentOutOfRangeException
  * @throws Main\ObjectNotFoundException
  * @throws \Exception
  */
 public function save()
 {
     $id = $this->getId();
     $fields = $this->fields->getValues();
     if ($id > 0) {
         $fields = $this->fields->getChangedValues();
         if (!empty($fields) && is_array($fields)) {
             //				$fields['DATE_UPDATE'] = new Main\Type\DateTime();
             $r = Internals\ShipmentTable::update($id, $fields);
             if (!$r->isSuccess()) {
                 return $r;
             }
         }
         $result = new Entity\UpdateResult();
         if (!empty($fields['TRACKING_NUMBER'])) {
             $oldEntityValues = $this->fields->getOriginalValues();
             /** @var Main\Event $event */
             $event = new Main\Event('sale', EventActions::EVENT_ON_SHIPMENT_TRACKING_NUMBER_CHANGE, array('ENTITY' => $this, 'VALUES' => $oldEntityValues));
             $event->send();
         }
     } else {
         $fields['ORDER_ID'] = $this->getParentOrderId();
         $fields['DATE_INSERT'] = new Main\Type\DateTime();
         $fields['SYSTEM'] = $fields['SYSTEM'] ? 'Y' : 'N';
         $r = Internals\ShipmentTable::add($fields);
         if (!$r->isSuccess()) {
             return $r;
         }
         $id = $r->getId();
         $this->setFieldNoDemand('ID', $id);
         $result = new Entity\AddResult();
         /** @var ShipmentItemCollection $shipmentItemCollection */
         if (!($shipmentItemCollection = $this->getShipmentItemCollection())) {
             throw new Main\ObjectNotFoundException('Entity "ShipmentItemCollection" not found');
         }
         /** @var Shipment $shipment */
         if (!($shipment = $shipmentItemCollection->getShipment())) {
             throw new Main\ObjectNotFoundException('Entity "Shipment" not found');
         }
         /** @var ShipmentCollection $shipmentCollection */
         if (!($shipmentCollection = $shipment->getCollection())) {
             throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
         }
         /** @var Order $order */
         if (!($order = $shipmentCollection->getOrder())) {
             throw new Main\ObjectNotFoundException('Entity "Order" not found');
         }
         if ($order->getId() > 0 && !$this->isSystem()) {
             OrderHistory::addAction('SHIPMENT', $order->getId(), 'SHIPMENT_ADDED', $id, $this);
         }
     }
     if ($result->isSuccess() && !$this->isSystem()) {
         $this->saveExtraServices();
         $this->saveStoreId();
     }
     /** @var ShipmentItemCollection $shipmentItemCollection */
     if (!($shipmentItemCollection = $this->getShipmentItemCollection())) {
         throw new Main\ObjectNotFoundException('Entity "ShipmentItemCollection" not found');
     }
     $r = $shipmentItemCollection->save();
     if (!$r->isSuccess()) {
         $result->addErrors($r->getErrors());
     }
     if ($result->isSuccess()) {
         /** @var Shipment $shipment */
         if (!($shipment = $shipmentItemCollection->getShipment())) {
             throw new Main\ObjectNotFoundException('Entity "Shipment" not found');
         }
         /** @var ShipmentCollection $shipmentCollection */
         if (!($shipmentCollection = $shipment->getCollection())) {
             throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
         }
         /** @var Order $order */
         if (!($order = $shipmentCollection->getOrder())) {
             throw new Main\ObjectNotFoundException('Entity "Order" not found');
         }
         if (!$this->isSystem()) {
             OrderHistory::collectEntityFields('SHIPMENT', $order->getId(), $id);
         }
     }
     return $result;
 }
 /**
  * @param $id
  * @param int $timeout
  * @param int $maxMailCount
  * @return bool|string
  * @throws \Bitrix\Main\ArgumentException
  * @throws \Bitrix\Main\DB\Exception
  * @throws \Bitrix\Main\Db\SqlQueryException
  * @throws \Exception
  */
 public static function send($id, $timeout = 0, $maxMailCount = 0)
 {
     $start_time = getmicrotime();
     @set_time_limit(0);
     static::$emailSentPerIteration = 0;
     $postingDb = PostingTable::getList(array('select' => array('ID', 'STATUS', 'MAILING_ID', 'MAILING_CHAIN_ID', 'MAILING_CHAIN_REITERATE' => 'MAILING_CHAIN.REITERATE', 'MAILING_CHAIN_IS_TRIGGER' => 'MAILING_CHAIN.IS_TRIGGER'), 'filter' => array('ID' => $id, 'MAILING.ACTIVE' => 'Y', 'MAILING_CHAIN.STATUS' => MailingChainTable::STATUS_SEND)));
     $postingData = $postingDb->fetch();
     // posting not found
     if (!$postingData) {
         return static::SEND_RESULT_ERROR;
     }
     // if posting in new status, then import recipients from groups and set right status for sending
     $isInitGroupRecipients = false;
     $isChangeStatusToPart = false;
     if ($postingData["STATUS"] == PostingTable::STATUS_NEW) {
         $isInitGroupRecipients = true;
         $isChangeStatusToPart = true;
     }
     if ($postingData["STATUS"] != PostingTable::STATUS_PART && $postingData["MAILING_CHAIN_IS_TRIGGER"] == 'Y') {
         $isInitGroupRecipients = false;
         $isChangeStatusToPart = true;
     }
     if ($isInitGroupRecipients) {
         PostingTable::initGroupRecipients($postingData['ID']);
     }
     if ($isChangeStatusToPart) {
         PostingTable::update(array('ID' => $postingData['ID']), array('STATUS' => PostingTable::STATUS_PART));
         $postingData["STATUS"] = PostingTable::STATUS_PART;
     }
     // posting not in right status
     if ($postingData["STATUS"] != PostingTable::STATUS_PART) {
         return static::SEND_RESULT_ERROR;
     }
     // lock posting for exclude double parallel sending
     if (static::lockPosting($id) === false) {
         throw new \Bitrix\Main\DB\Exception(Loc::getMessage('SENDER_POSTING_MANAGER_ERR_LOCK'));
     }
     // select all recipients of posting, only not processed
     $recipientDataDb = PostingRecipientTable::getList(array('filter' => array('POSTING_ID' => $postingData['ID'], 'STATUS' => PostingRecipientTable::SEND_RESULT_NONE), 'limit' => $maxMailCount));
     while ($recipientData = $recipientDataDb->fetch()) {
         // create name from email
         $recipientEmail = $recipientData["EMAIL"];
         if (empty($recipientData["NAME"])) {
             $recipientEmailParts = explode('@', $recipientEmail);
             $recipientName = $recipientEmailParts[0];
         } else {
             $recipientName = $recipientData["NAME"];
         }
         // prepare params for send
         $sendParams = array('FIELDS' => array('EMAIL_TO' => $recipientEmail, 'NAME' => $recipientName, 'USER_ID' => $recipientData["USER_ID"], 'SENDER_CHAIN_CODE' => 'sender_chain_item_' . $postingData["MAILING_CHAIN_ID"], 'UNSUBSCRIBE_LINK' => Subscription::getLinkUnsub(array('MAILING_ID' => $postingData['MAILING_ID'], 'EMAIL' => $recipientEmail, 'RECIPIENT_ID' => $recipientData["ID"]))), 'TRACK_READ' => array('MODULE_ID' => "sender", 'FIELDS' => array('RECIPIENT_ID' => $recipientData["ID"])), 'TRACK_CLICK' => array('MODULE_ID' => "sender", 'FIELDS' => array('RECIPIENT_ID' => $recipientData["ID"]), 'URL_PARAMS' => array('bx_sender_conversion_id' => $recipientData["ID"])));
         if (is_array($recipientData['FIELDS']) && count($recipientData) > 0) {
             $sendParams['FIELDS'] = $sendParams['FIELDS'] + $recipientData['FIELDS'];
         }
         // set sending result to recipient
         $mailSendResult = static::sendInternal($postingData['MAILING_CHAIN_ID'], $sendParams);
         PostingRecipientTable::update(array('ID' => $recipientData["ID"]), array('STATUS' => $mailSendResult, 'DATE_SENT' => new Type\DateTime()));
         // send event
         $eventData = array('SEND_RESULT' => $mailSendResult == PostingRecipientTable::SEND_RESULT_SUCCESS, 'RECIPIENT' => $recipientData, 'POSTING' => $postingData);
         $event = new Event('sender', 'OnAfterPostingSendRecipient', array($eventData));
         $event->send();
         // limit executing script by time
         if ($timeout > 0 && getmicrotime() - $start_time >= $timeout) {
             break;
         }
         // increment sending statistic
         static::$emailSentPerIteration++;
     }
     //set status and delivered and error emails
     $statusList = PostingTable::getRecipientCountByStatus($id);
     if (!array_key_exists(PostingRecipientTable::SEND_RESULT_NONE, $statusList)) {
         if (array_key_exists(PostingRecipientTable::SEND_RESULT_ERROR, $statusList)) {
             $STATUS = PostingTable::STATUS_SENT_WITH_ERRORS;
         } else {
             $STATUS = PostingTable::STATUS_SENT;
         }
         $DATE = new Type\DateTime();
     } else {
         $STATUS = PostingTable::STATUS_PART;
         $DATE = null;
     }
     // unlock posting for exclude double parallel sending
     static::unlockPosting($id);
     // update status of posting
     PostingTable::update(array('ID' => $id), array('STATUS' => $STATUS, 'DATE_SENT' => $DATE));
     // return status to continue or end of sending
     if ($STATUS == PostingTable::STATUS_PART) {
         return static::SEND_RESULT_CONTINUE;
     } else {
         return static::SEND_RESULT_SENT;
     }
 }
Exemple #11
0
 /**
  * Add new user to b_user table.
  * Returns its identifier or false on failure.
  *
  * @param array $params
  *
  * @return integer|false
  */
 public function addUser($params)
 {
     if (!$this->isEnabled()) {
         $this->errorCollection[] = new Error(Loc::getMessage('B24NET_NETWORK_IN_NOT_ENABLED'), self::ERROR_NETWORK_IN_NOT_ENABLED);
         return false;
     }
     $password = md5($params['XML_ID'] . '|' . $params['CLIENT_DOMAIN'] . '|' . rand(1000, 9999) . '|' . time() . '|' . uniqid());
     $photo = \CFile::MakeFileArray($params['PERSONAL_PHOTO_ORIGINAL']);
     $groups = array();
     if (Loader::includeModule('extranet')) {
         $groups[] = \CExtranet::GetExtranetUserGroupID();
     }
     $addParams = array('LOGIN' => $params['NETWORK_USER_ID'] . '@' . $params['CLIENT_DOMAIN'], 'NAME' => $params['NAME'], 'EMAIL' => $params['EMAIL'], 'LAST_NAME' => $params['LAST_NAME'], 'SECOND_NAME' => $params['SECOND_NAME'], 'PERSONAL_GENDER' => $params['PERSONAL_GENDER'], 'PERSONAL_PHOTO' => $photo, 'WORK_POSITION' => $params['CLIENT_DOMAIN'], 'XML_ID' => $params['XML_ID'], 'EXTERNAL_AUTH_ID' => self::EXTERNAL_AUTH_ID, "ACTIVE" => "Y", "PASSWORD" => $password, "CONFIRM_PASSWORD" => $password, "GROUP_ID" => $groups);
     if (isset($params['EMAIL'])) {
         $addParams['EMAIL'] = $params['EMAIL'];
     }
     $user = new \CUser();
     $userId = $user->Add($addParams);
     if (intval($userId) <= 0) {
         $this->errorCollection[] = new Error($user->LAST_ERROR, self::ERROR_REGISTER_USER);
         return false;
     }
     $event = new Event("socialservices", "OnAfterRegisterUserByNetwork", array($userId, $params['NETWORK_USER_ID'], $params['CLIENT_DOMAIN']));
     $event->send();
     return $userId;
 }
Exemple #12
0
 /**
  * @return Entity\Result|bool
  * @throws \Bitrix\Main\ArgumentException
  * @throws \Bitrix\Main\ArgumentNullException
  */
 public function save()
 {
     $result = new Result();
     /** @var Order $order */
     $order = $this->getOrder();
     $itemsFromDb = array();
     $filter = array();
     if (!$order) {
         /** @var Main\Entity\Event $event */
         $event = new Main\Event('sale', EventActions::EVENT_ON_BASKET_BEFORE_SAVED, array('ENTITY' => $this));
         $event->send();
         if ($event->getResults()) {
             $result = new Result();
             /** @var Main\EventResult $eventResult */
             foreach ($event->getResults() as $eventResult) {
                 if ($eventResult->getType() == Main\EventResult::ERROR) {
                     $errorMsg = new ResultError(Main\Localization\Loc::getMessage('SALE_EVENT_ON_BEFORE_BASKET_SAVED'), 'SALE_EVENT_ON_BEFORE_BASKET_SAVED');
                     if (isset($eventResultData['ERROR']) && $eventResultData['ERROR'] instanceof ResultError) {
                         $errorMsg = $eventResultData['ERROR'];
                     }
                     $result->addError($errorMsg);
                 }
             }
             if (!$result->isSuccess()) {
                 return $result;
             }
         }
     }
     $isNew = $order && $order->isNew() ? true : false;
     if ($order && !$isNew) {
         $filter['ORDER_ID'] = $order->getId();
     } else {
         if ($this->isLoadForFuserId()) {
             $filter = array('FUSER_ID' => $this->getFUserId(), 'ORDER_ID' => null, 'LID' => $this->getSiteId());
         }
         if ($isNew) {
             $fUserId = $this->getFUserId(true);
             if ($fUserId <= 0) {
                 $userId = $order->getUserId();
                 if (intval($userId) > 0) {
                     $fUserId = Fuser::getIdByUserId($userId);
                     if ($fUserId > 0) {
                         $this->setFUserId($fUserId);
                     }
                 }
             }
         }
     }
     if (!empty($filter)) {
         $itemsFromDbList = Internals\BasketTable::getList(array("filter" => $filter, "select" => array("ID", 'TYPE', 'SET_PARENT_ID', 'PRODUCT_ID', 'NAME', 'QUANTITY')));
         while ($itemsFromDbItem = $itemsFromDbList->fetch()) {
             if (intval($itemsFromDbItem['SET_PARENT_ID']) > 0 && intval($itemsFromDbItem['SET_PARENT_ID']) != $itemsFromDbItem['ID']) {
                 continue;
             }
             $itemsFromDb[$itemsFromDbItem["ID"]] = $itemsFromDbItem;
         }
     }
     /** @var BasketItem $basketItem */
     foreach ($this->collection as $index => $basketItem) {
         $r = $basketItem->save();
         if (!$r->isSuccess()) {
             $result->addErrors($r->getErrors());
         }
         if (isset($itemsFromDb[$basketItem->getId()]) && $basketItem->getQuantity() > 0) {
             unset($itemsFromDb[$basketItem->getId()]);
         }
     }
     if (!empty($filter)) {
         foreach ($itemsFromDb as $k => $v) {
             if ($v['TYPE'] == static::TYPE_SET) {
                 Internals\BasketTable::deleteBundle($k);
             } else {
                 Internals\BasketTable::deleteWithItems($k);
             }
             /** @var Order $order */
             if ($order && $order->getId() > 0) {
                 OrderHistory::addAction('BASKET', $order->getId(), 'BASKET_REMOVED', $k, null, array('NAME' => $v['NAME'], 'QUANTITY' => $v['QUANTITY'], 'PRODUCT_ID' => $v['PRODUCT_ID']));
             }
         }
     }
     if ($order && $order->getId() > 0) {
         OrderHistory::collectEntityFields('BASKET', $order->getId());
     }
     if (!$order) {
         /** @var Main\Entity\Event $event */
         $event = new Main\Event('sale', EventActions::EVENT_ON_BASKET_SAVED, array('ENTITY' => $this));
         $event->send();
         if ($event->getResults()) {
             $result = new Result();
             /** @var Main\EventResult $eventResult */
             foreach ($event->getResults() as $eventResult) {
                 if ($eventResult->getType() == Main\EventResult::ERROR) {
                     $errorMsg = new ResultError(Main\Localization\Loc::getMessage('SALE_EVENT_ON_BASKET_SAVED'), 'SALE_EVENT_ON_BASKET_SAVED');
                     if (isset($eventResultData['ERROR']) && $eventResultData['ERROR'] instanceof ResultError) {
                         $errorMsg = $eventResultData['ERROR'];
                     }
                     $result->addError($errorMsg);
                 }
             }
             if (!$result->isSuccess()) {
                 return $result;
             }
         }
     }
     return $result;
 }
 /**
  * Initializes application shell. Called after initializeKernel.
  *
  * @param System\IApplicationStrategy $initStrategy
  */
 protected function initializeShell(\Bitrix\Main\System\IApplicationStrategy $initStrategy = null)
 {
     $this->authenticateUser();
     if ($initStrategy != null) {
         $initStrategy->authenticateUser();
     }
     define("BX_STARTED", true);
     // required for iblock to define site
     //magic parameters: show page creation time
     if ($_GET["show_page_exec_time"] == "Y" || $_GET["show_page_exec_time"] == "N") {
         $_SESSION["SESS_SHOW_TIME_EXEC"] = $_GET["show_page_exec_time"];
     }
     //magic parameters: show included file processing time
     if ($_GET["show_include_exec_time"] == "Y" || $_GET["show_include_exec_time"] == "N") {
         $_SESSION["SESS_SHOW_INCLUDE_TIME_EXEC"] = $_GET["show_include_exec_time"];
     }
     //magic parameters: show include areas
     if (isset($_GET["bitrix_include_areas"]) && $_GET["bitrix_include_areas"] != "") {
         $GLOBALS["APPLICATION"]->setShowIncludeAreas($_GET["bitrix_include_areas"] == "Y");
     }
     //magic sound
     /** @var $context HttpContext */
     $context = $this->context;
     $user = $context->getUser();
     /** @var $request HttpRequest */
     $request = $context->getRequest();
     if ($user->isAuthenticated() && $request->getCookie("SOUND_LOGIN_PLAYED") == null) {
         /** @var $response HttpResponse */
         $response = $context->getResponse();
         $response->addCookie(new \Bitrix\Main\Web\Cookie('SOUND_LOGIN_PLAYED', 'Y', 0));
     }
     $event = new Event("main", "OnBeforeProlog");
     $event->send();
     $this->authorizeUser();
     if ($initStrategy != null) {
         $initStrategy->authorizeUser();
     }
 }
Exemple #14
0
 /**
  * @return Entity\AddResult|Entity\UpdateResult
  * @throws ArgumentException
  * @throws ArgumentNullException
  * @throws \Exception
  */
 public function save()
 {
     $id = $this->getId();
     $changedFields = $this->fields->getChangedValues();
     $isNew = $id <= 0;
     if (!empty($changedFields)) {
         /** @var array $oldEntityValues */
         $oldEntityValues = $this->fields->getOriginalValues();
         /** @var Event $event */
         $event = new Event('sale', EventActions::EVENT_ON_BASKET_ITEM_BEFORE_SAVED, array('ENTITY' => $this, 'IS_NEW' => $isNew, 'VALUES' => $oldEntityValues));
         $event->send();
         if ($event->getResults()) {
             $result = new Result();
             /** @var EventResult $eventResult */
             foreach ($event->getResults() as $eventResult) {
                 if ($eventResult->getType() == EventResult::ERROR) {
                     $errorMsg = new ResultError(Loc::getMessage('SALE_EVENT_ON_BEFORE_BASKET_ITEM_SAVED'), 'SALE_EVENT_ON_BEFORE_BASKET_ITEM_SAVED');
                     if (isset($eventResultData['ERROR']) && $eventResultData['ERROR'] instanceof ResultError) {
                         $errorMsg = $eventResultData['ERROR'];
                     }
                     $result->addError($errorMsg);
                 }
             }
             if (!$result->isSuccess()) {
                 return $result;
             }
         }
     }
     $fields = $this->fields->getValues();
     if ($this->isBundleParent()) {
         $bundleBasketCollection = $this->getBundleCollection();
     }
     if ($id > 0) {
         $fields = $changedFields;
         if (!isset($fields["ORDER_ID"]) || intval($fields["ORDER_ID"]) == 0) {
             $orderId = null;
             if ($this->getParentOrderId() > 0) {
                 $orderId = $this->getParentOrderId();
             }
             if ($this->isBundleChild() && $orderId === null) {
                 /** @var BasketItem $parentBasket */
                 if (!($parentBasket = $this->getParentBasketItem())) {
                     throw new ObjectNotFoundException('Entity parent "BasketItem" not found');
                 }
                 $orderId = $parentBasket->getParentOrderId();
             }
             if (intval($orderId) > 0 && $this->getField('ORDER_ID') != $orderId) {
                 $fields['ORDER_ID'] = $orderId;
             }
         }
         if (!empty($fields) && is_array($fields)) {
             if (isset($fields["QUANTITY"]) && floatval($fields["QUANTITY"]) == 0) {
                 return new Entity\UpdateResult();
             }
             $fields['DATE_UPDATE'] = new DateTime();
             $this->setFieldNoDemand('DATE_UPDATE', $fields['DATE_UPDATE']);
             $r = Internals\BasketTable::update($id, $fields);
             if (!$r->isSuccess()) {
                 return $r;
             }
         }
         $result = new Entity\UpdateResult();
     } else {
         $fields['ORDER_ID'] = $this->getParentOrderId();
         $fields['DATE_INSERT'] = new DateTime();
         $fields['DATE_UPDATE'] = new DateTime();
         $this->setFieldNoDemand('DATE_INSERT', $fields['DATE_INSERT']);
         $this->setFieldNoDemand('DATE_UPDATE', $fields['DATE_UPDATE']);
         if (!$this->isBundleChild() && (!isset($fields["FUSER_ID"]) || intval($fields["FUSER_ID"]) <= 0)) {
             /** @var Basket $basket */
             if (!($basket = $this->getCollection())) {
                 throw new ObjectNotFoundException('Entity "Basket" not found');
             }
             $fields["FUSER_ID"] = intval($basket->getFUserId());
         }
         /** @var Basket $basket */
         if (!($basket = $this->getCollection())) {
             throw new ObjectNotFoundException('Entity "Basket" not found');
         }
         /** @var Order $order */
         if ($order = $basket->getOrder()) {
             if (!isset($fields["LID"]) || strval($fields["LID"]) == '') {
                 $fields['LID'] = $order->getField('LID');
             }
         } else {
             if ($siteId = $basket->getSiteId()) {
                 $fields['LID'] = $siteId;
             }
         }
         if ($this->isBundleChild()) {
             if (!($parentBasketItem = $this->getParentBasketItem())) {
                 throw new ObjectNotFoundException('Entity parent "BasketItem" not found');
             }
             $fields['LID'] = $parentBasketItem->getField('LID');
             if (!isset($fields["FUSER_ID"]) || intval($fields["FUSER_ID"]) <= 0) {
                 $fields['FUSER_ID'] = intval($parentBasketItem->getField('FUSER_ID'));
             }
         }
         if (!isset($fields["LID"]) || strval(trim($fields["LID"])) == '') {
             throw new ArgumentNullException('lid');
         }
         if ($this->isBundleChild() && (!isset($fields["SET_PARENT_ID"]) || intval($fields["QUANTITY"]) <= 0)) {
             $fields["SET_PARENT_ID"] = $this->getParentBasketItemId();
             $this->setFieldNoDemand('SET_PARENT_ID', $fields['SET_PARENT_ID']);
         }
         if (!isset($fields["QUANTITY"]) || floatval($fields["QUANTITY"]) == 0) {
             return new Entity\AddResult();
         }
         if (!isset($fields["CURRENCY"]) || strval(trim($fields["CURRENCY"])) == '') {
             throw new ArgumentNullException('currency');
         }
         $r = Internals\BasketTable::add($fields);
         if (!$r->isSuccess()) {
             return $r;
         }
         $id = $r->getId();
         $this->setFieldNoDemand('ID', $id);
         $this->setFieldNoDemand('LID', $fields['LID']);
         $this->setFieldNoDemand('FUSER_ID', $fields['FUSER_ID']);
         if ($basket->getOrder() && $basket->getOrderId() > 0) {
             OrderHistory::addAction('BASKET', $order->getId(), 'BASKET_ADDED', $id, $this);
         }
         $result = new Entity\AddResult();
     }
     if ($isNew || !empty($changedFields)) {
         /** @var array $oldEntityValues */
         $oldEntityValues = $this->fields->getOriginalValues();
         /** @var Event $event */
         $event = new Event('sale', EventActions::EVENT_ON_BASKET_ITEM_SAVED, array('ENTITY' => $this, 'IS_NEW' => $isNew, 'VALUES' => $oldEntityValues));
         $event->send();
         if ($event->getResults()) {
             $result = new Result();
             /** @var EventResult $eventResult */
             foreach ($event->getResults() as $eventResult) {
                 if ($eventResult->getType() == EventResult::ERROR) {
                     $errorMsg = new ResultError(Loc::getMessage('SALE_EVENT_ON_BEFORE_BASKET_ITEM_SAVED'), 'SALE_EVENT_ON_BEFORE_BASKET_ITEM_SAVED');
                     if (isset($eventResultData['ERROR']) && $eventResultData['ERROR'] instanceof ResultError) {
                         $errorMsg = $eventResultData['ERROR'];
                     }
                     $result->addError($errorMsg);
                 }
             }
             if (!$result->isSuccess()) {
                 return $result;
             }
         }
     }
     if ($eventName = static::getEntityEventName()) {
         /** @var array $oldEntityValues */
         $oldEntityValues = $this->fields->getOriginalValues();
         if (!empty($oldEntityValues)) {
             /** @var Event $event */
             $event = new Event('sale', 'On' . $eventName . 'EntitySaved', array('ENTITY' => $this, 'VALUES' => $oldEntityValues));
             $event->send();
         }
     }
     $this->fields->clearChanged();
     // bundle
     if ($this->isBundleParent()) {
         if (!empty($bundleBasketCollection)) {
             if (!($order = $bundleBasketCollection->getOrder())) {
                 /** @var Basket $basketCollection */
                 $basketCollection = $this->getCollection();
                 if ($order = $basketCollection->getOrder()) {
                     $bundleBasketCollection->setOrder($order);
                 }
             }
             $itemsFromDb = array();
             if (!$isNew) {
                 $itemsFromDbList = Internals\BasketTable::getList(array("filter" => array("SET_PARENT_ID" => $id), "select" => array("ID")));
                 while ($itemsFromDbItem = $itemsFromDbList->fetch()) {
                     if ($itemsFromDbItem["ID"] == $id) {
                         continue;
                     }
                     $itemsFromDb[$itemsFromDbItem["ID"]] = true;
                 }
             }
             /** @var BasketItem $bundleBasketItem */
             foreach ($bundleBasketCollection as $bundleBasketItem) {
                 $r = $bundleBasketItem->save();
                 if (!$r->isSuccess()) {
                     $result->addErrors($r->getErrors());
                 }
                 if (isset($itemsFromDb[$bundleBasketItem->getId()])) {
                     unset($itemsFromDb[$bundleBasketItem->getId()]);
                 }
             }
             foreach ($itemsFromDb as $k => $v) {
                 Internals\BasketTable::delete($k);
             }
         }
     }
     /** @var BasketPropertiesCollection $basketPropertyCollection */
     $basketPropertyCollection = $this->getPropertyCollection();
     $r = $basketPropertyCollection->save();
     if (!$r->isSuccess()) {
         $result->addErrors($r->getErrors());
     }
     return $result;
 }
Exemple #15
0
 /**
  *
  * @param array $values
  * @return Result
  * @throws Main\ArgumentOutOfRangeException
  * @throws Main\NotSupportedException
  * @throws \Exception
  */
 public function setFields(array $values)
 {
     $resultData = array();
     $result = new Result();
     $oldValues = null;
     foreach ($values as $key => $value) {
         $oldValues[$key] = $this->fields->get($key);
     }
     if ($eventName = static::getEntityEventName()) {
         $event = new Main\Event('sale', 'OnBefore' . $eventName . 'SetFields', array('ENTITY' => $this, 'VALUES' => $values, 'OLD_VALUES' => $oldValues));
         $event->send();
         if ($event->getResults()) {
             /** @var Main\EventResult $eventResult */
             foreach ($event->getResults() as $eventResult) {
                 if ($eventResult->getType() == Main\EventResult::SUCCESS) {
                     if ($eventResultData = $eventResult->getParameters()) {
                         if (isset($eventResultData['VALUES'])) {
                             $values = $eventResultData['VALUES'];
                         }
                     }
                 } elseif ($eventResult->getType() == Main\EventResult::ERROR) {
                     $errorMsg = new ResultError(Main\Localization\Loc::getMessage('SALE_EVENT_ON_BEFORE_' . strtoupper($eventName) . '_SET_FIELDS_ERROR'), 'SALE_EVENT_ON_BEFORE_' . strtoupper($eventName) . '_SET_FIELDS_ERROR');
                     if ($eventResultData = $eventResult->getParameters()) {
                         if (isset($eventResultData['ERROR']) && $eventResultData['ERROR'] instanceof ResultError) {
                             $errorMsg = $eventResultData['ERROR'];
                         }
                     }
                     $result->addError($errorMsg);
                 }
             }
         }
     }
     if (!$result->isSuccess()) {
         return $result;
     }
     $isStartField = $this->isStartField();
     foreach ($values as $key => $value) {
         $r = $this->setField($key, $value);
         if (!$r->isSuccess()) {
             $data = $r->getData();
             if (!empty($data) && is_array($data)) {
                 $resultData = array_merge($resultData, $data);
             }
             $result->addErrors($r->getErrors());
         }
     }
     if (!empty($resultData)) {
         $result->setData($resultData);
     }
     if ($isStartField) {
         $hasMeaningfulFields = $this->hasMeaningfulField();
         /** @var Result $r */
         $r = $this->doFinalAction($hasMeaningfulFields);
         if (!$r->isSuccess()) {
             $result->addErrors($r->getErrors());
         } else {
             if (($data = $r->getData()) && !empty($data) && is_array($data)) {
                 $result->setData($result->getData() + $data);
             }
         }
     }
     return $result;
 }
Exemple #16
0
 /**
  * @param array $arData
  * @return bool
  */
 public static function read(array $arData)
 {
     if (array_key_exists('MODULE_ID', $arData)) {
         $filter = array($arData['MODULE_ID']);
     } else {
         $filter = null;
     }
     $event = new \Bitrix\Main\Event("main", "OnMailEventMailRead", array($arData['FIELDS']), $filter);
     $event->send();
     foreach ($event->getResults() as $eventResult) {
         if ($eventResult->getType() == \Bitrix\Main\EventResult::ERROR) {
             return false;
         }
     }
     return true;
 }
Exemple #17
0
 /**
  * @param $arData
  * @return bool
  */
 public static function unsubscribe($arData)
 {
     if (!is_array($arData['FIELDS'])) {
         return false;
     }
     $event = new Event("main", "OnMailEventSubscriptionDisable", array($arData['FIELDS']), array($arData['MODULE_ID']));
     $event->send();
     foreach ($event->getResults() as $eventResult) {
         if ($eventResult->getType() == EventResult::ERROR) {
             return false;
         }
     }
     return true;
 }
Exemple #18
0
 /**
  * @return Entity\AddResult|Entity\UpdateResult
  * @throws Main\ArgumentOutOfRangeException
  * @throws Main\ObjectNotFoundException
  * @throws \Exception
  */
 public function save()
 {
     $id = $this->getId();
     $fields = $this->fields->getValues();
     /** @var ShipmentItemCollection $shipmentItemCollection */
     if (!($shipmentItemCollection = $this->getCollection())) {
         throw new Main\ObjectNotFoundException('Entity "ShipmentItemCollection" not found');
     }
     /** @var Shipment $shipment */
     if (!($shipment = $shipmentItemCollection->getShipment())) {
         throw new Main\ObjectNotFoundException('Entity "Shipment" not found');
     }
     /** @var ShipmentCollection $shipmentCollection */
     if (!($shipmentCollection = $shipment->getCollection())) {
         throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
     }
     /** @var Order $order */
     if (!($order = $shipmentCollection->getOrder())) {
         throw new Main\ObjectNotFoundException('Entity "Order" not found');
     }
     if ($id > 0) {
         $fields = $this->fields->getChangedValues();
         if (!empty($fields) && is_array($fields)) {
             /** @var ShipmentItemCollection $shipmentItemCollection */
             if (!($shipmentItemCollection = $this->getCollection())) {
                 throw new Main\ObjectNotFoundException('Entity "ShipmentItemCollection" not found');
             }
             /** @var Shipment $shipment */
             if (!($shipment = $shipmentItemCollection->getShipment())) {
                 throw new Main\ObjectNotFoundException('Entity "Shipment" not found');
             }
             if (!$shipment->isSystem()) {
                 if (isset($fields["QUANTITY"]) && floatval($fields["QUANTITY"]) == 0) {
                     return new Entity\UpdateResult();
                 }
             }
             //$fields['DATE_UPDATE'] = new Main\Type\DateTime();
             $r = Internals\ShipmentItemTable::update($id, $fields);
             if (!$r->isSuccess()) {
                 return $r;
             }
         }
         $result = new Entity\UpdateResult();
         if ($order && $order->getId() > 0) {
             OrderHistory::collectEntityFields('SHIPMENT_ITEM_STORE', $order->getId(), $id);
         }
     } else {
         $fields['ORDER_DELIVERY_ID'] = $this->getParentShipmentId();
         $fields['DATE_INSERT'] = new Main\Type\DateTime();
         $fields["BASKET_ID"] = $this->basketItem->getId();
         if (!isset($fields["QUANTITY"]) || floatval($fields["QUANTITY"]) == 0) {
             return new Entity\UpdateResult();
         }
         if (!isset($fields['RESERVED_QUANTITY'])) {
             $fields['RESERVED_QUANTITY'] = $this->getReservedQuantity() === null ? 0 : $this->getReservedQuantity();
         }
         $r = Internals\ShipmentItemTable::add($fields);
         if (!$r->isSuccess()) {
             return $r;
         }
         $id = $r->getId();
         $this->setFieldNoDemand('ID', $id);
         $result = new Entity\AddResult();
         if (!$shipment->isSystem()) {
             OrderHistory::addAction('SHIPMENT', $order->getId(), 'SHIPMENT_ITEM_BASKET_ADDED', $shipment->getId(), $this->basketItem, array('QUANTITY' => $this->getQuantity()));
         }
     }
     if ($eventName = static::getEntityEventName()) {
         $oldEntityValues = $this->fields->getOriginalValues();
         if (!empty($oldEntityValues)) {
             /** @var Main\Event $event */
             $event = new Main\Event('sale', 'On' . $eventName . 'EntitySaved', array('ENTITY' => $this, 'VALUES' => $oldEntityValues));
             $event->send();
         }
     }
     $shipmentItemStoreCollection = $this->getShipmentItemStoreCollection();
     $r = $shipmentItemStoreCollection->save();
     if (!$r->isSuccess()) {
         $result->addErrors($r->getErrors());
     }
     if ($result->isSuccess()) {
         OrderHistory::collectEntityFields('SHIPMENT_ITEM', $order->getId(), $id);
     }
     $this->fields->clearChanged();
     return $result;
 }
Exemple #19
0
 /**
  * Вызов события с помощью объекта события
  * @param \Bitrix\Main\Event $eventObject
  * @param object $sender объект который отправил события
  * @return \Bitrix\Main\Event объект события
  */
 public static function triggerObject(\Bitrix\Main\Event $eventObject, $sender = null)
 {
     $eventObject->send($sender);
     return $eventObject;
 }
Exemple #20
0
 /**
  * Initialization coupons providers.
  *
  * @return void
  */
 protected static function initUseDiscount()
 {
     if (self::$onlySaleDiscount === null) {
         self::$onlySaleDiscount = (string) Option::get('sale', 'use_sale_discount_only') == 'Y';
         self::$couponProviders = array();
         if (!self::$onlySaleDiscount) {
             $eventData = array('COUPON_UNKNOWN' => Internals\DiscountCouponTable::TYPE_UNKNOWN, 'COUPON_TYPES' => array(Internals\DiscountCouponTable::TYPE_BASKET_ROW, Internals\DiscountCouponTable::TYPE_ONE_ORDER, Internals\DiscountCouponTable::TYPE_MULTI_ORDER));
             $event = new Main\Event('sale', self::EVENT_ON_BUILD_COUPON_PROVIDES, $eventData);
             $event->send();
             $resultList = $event->getResults();
             if (empty($resultList) || !is_array($resultList)) {
                 return;
             }
             foreach ($resultList as &$eventResult) {
                 if ($eventResult->getType() != Main\EventResult::SUCCESS) {
                     continue;
                 }
                 $module = (string) $eventResult->getModuleId();
                 $provider = $eventResult->getParameters();
                 if (empty($provider) || !is_array($provider)) {
                     continue;
                 }
                 if (empty($provider['getData']) || empty($provider['isExist']) || empty($provider['saveApplied'])) {
                     continue;
                 }
                 self::$couponProviders[] = array('module' => $module, 'getData' => $provider['getData'], 'isExist' => $provider['isExist'], 'saveApplied' => $provider['saveApplied'], 'mode' => isset($provider['mode']) && $provider['mode'] == self::COUPON_MODE_FULL ? self::COUPON_MODE_FULL : self::COUPON_MODE_SIMPLE);
             }
             unset($eventResult);
         }
     }
 }
Exemple #21
0
 protected function deleteNonRecursive($deletedBy)
 {
     foreach ($this->getSharingsAsReal() as $sharing) {
         $sharing->delete($deletedBy);
     }
     //with status unreplied, declined (not approved)
     $success = SharingTable::deleteByFilter(array('REAL_OBJECT_ID' => $this->id));
     if (!$success) {
         return false;
     }
     SimpleRightTable::deleteBatch(array('OBJECT_ID' => $this->id));
     $success = RightTable::deleteByFilter(array('OBJECT_ID' => $this->id));
     if (!$success) {
         return false;
     }
     DeletedLog::addFolder($this, $deletedBy, $this->errorCollection);
     $resultDelete = FolderTable::delete($this->id);
     if (!$resultDelete->isSuccess()) {
         return false;
     }
     if (!$this->isLink()) {
         //todo potential - very hard operation.
         foreach (Folder::getModelList(array('filter' => array('REAL_OBJECT_ID' => $this->id, '!=REAL_OBJECT_ID' => $this->id))) as $link) {
             $link->deleteTree($deletedBy);
         }
         unset($link);
     }
     $event = new Event(Driver::INTERNAL_MODULE_ID, "onAfterDeleteFolder", array($this->getId(), $deletedBy));
     $event->send();
     return true;
 }
Exemple #22
0
 public function moderate($show)
 {
     if ($this->message === null) {
         $this->errorCollection->addOne(new Error(Loc::getMessage("FORUM_CM_ERR_COMMENT_IS_LOST3"), self::ERROR_MESSAGE_IS_NULL));
     } else {
         $fields = array("APPROVED" => $show ? "Y" : "N");
         if ($this->message["ID"] == $fields["APPROVED"] || ($mid = \CForumMessage::Update($this->message["ID"], $fields)) > 0) {
             $this->setComment($this->message["ID"]);
             /***************** Events ******************************************/
             /***************** Event onMessageModerate *************************/
             $event = new Event("forum", "onMessageModerate", array($this->message["ID"], $show ? "SHOW" : "HIDE", $this->message, $this->topic));
             $event->send();
             /***************** Events OnAfterCommentUpdate *********************/
             $fields = array($this->entity->getType(), $this->entity->getId(), array("TOPIC_ID" => $this->topic["ID"], "MESSAGE_ID" => $this->message["ID"], "MESSAGE" => $this->getComment(), "ACTION" => $show ? "SHOW" : "HIDE", "PARAMS" => $fields));
             $event = new Event("forum", "OnAfterCommentUpdate", $fields);
             $event->send();
             /***************** Events OnCommentModerate ************************/
             $event = new Event("forum", "OnCommentModerate", $fields);
             $event->send();
             /***************** /Events *****************************************/
             $res = serialize(array("ID" => $this->message["ID"], "AUTHOR_NAME" => $this->message["AUTHOR_NAME"], "POST_MESSAGE" => $this->message["POST_MESSAGE"], "TITLE" => $this->topic["TITLE"], "TOPIC_ID" => $this->topic["ID"], "FORUM_ID" => $this->topic["FORUM_ID"]));
             \CForumMessage::SendMailMessage($this->message["ID"], array(), false, $show ? "NEW_FORUM_MESSAGE" : "EDIT_FORUM_MESSAGE");
             \CForumEventLog::Log("message", $show ? "approve" : "unapprove", $this->message["ID"], $res);
             return $this->getComment();
         } else {
             $text = Loc::getMessage("FORUM_CM_ERR_MODERATE");
             if (($ex = $this->getApplication()->getException()) && $ex) {
                 $text = $ex->getString();
             }
             $this->errorCollection->addOne(new Error($text, self::ERROR_PARAMS_MESSAGE));
         }
     }
     return false;
 }
Exemple #23
0
            $bCanEdit = false;
        }
        //need fm_lpa for every .php file, even with no php code inside
        if ($bCanEdit && !$USER->CanDoOperation('edit_php') && in_array(GetFileExtension($currentFilePath), GetScriptFileExt()) && !$USER->CanDoFileOperation('fm_lpa', array(SITE_ID, $currentFilePath))) {
            $bCanEdit = false;
        }
        if ($bCanEdit && IsModuleInstalled("fileman") && !($USER->CanDoOperation("fileman_admin_files") && $USER->CanDoOperation("fileman_edit_existent_files"))) {
            $bCanEdit = false;
        }
        if ($bCanEdit) {
            echo $APPLICATION->IncludeStringBefore();
            $BX_GLOBAL_AREA_EDIT_ICON = true;
        }
    }
}
define("START_EXEC_PROLOG_AFTER_2", microtime());
$GLOBALS["BX_STATE"] = "WA";
$APPLICATION->RestartWorkarea(true);
//magically replacing the current file with another one
$event = new Main\Event("main", "OnFileRewrite", array("path" => Main\Context::getCurrent()->getRequest()->getScriptFile()));
$event->send();
foreach ($event->getResults() as $evenResult) {
    if (($result = $evenResult->getParameters()) != '') {
        $file = new Main\IO\File($_SERVER["DOCUMENT_ROOT"] . $result);
        if ($file->isExists()) {
            //only the first result matters
            include $file->getPhysicalPath();
            die;
        }
    }
}
Exemple #24
0
 /**
  * Calculates delivery price
  * @param \Bitrix\Sale\Shipment $shipment.
  * @return \Bitrix\Sale\Delivery\CalculationResult
  */
 public function calculate(\Bitrix\Sale\Shipment $shipment = null)
 {
     if ($shipment && !$shipment->getCollection()) {
         return false;
     }
     $result = $this->calculateConcrete($shipment);
     if ($shipment) {
         $this->extraServices->setValues($shipment->getExtraServices());
         $extraServicePrice = $this->extraServices->getTotalCost();
         if (floatval($extraServicePrice) > 0) {
             $result->setExtraServicesPrice($extraServicePrice);
         }
     }
     $eventParams = array("RESULT" => $result, "SHIPMENT" => $shipment);
     $event = new Event('sale', self::EVENT_ON_CALCULATE, $eventParams);
     $event->send();
     $resultList = $event->getResults();
     if (is_array($resultList) && !empty($resultList)) {
         foreach ($resultList as &$eventResult) {
             if ($eventResult->getType() != EventResult::SUCCESS) {
                 continue;
             }
             $params = $eventResult->getParameters();
             if (isset($params["RESULT"])) {
                 $result = $params["RESULT"];
             }
         }
     }
     return $result;
 }
Exemple #25
0
 /**
  * @param bool $hasMeaningfulField
  * @return Result
  * @throws Main\ArgumentNullException
  * @throws Main\ObjectNotFoundException
  */
 public function doFinalAction($hasMeaningfulField = false)
 {
     $result = new Result();
     if (!$hasMeaningfulField) {
         $this->clearStartField();
         return $result;
     }
     if ($basket = $this->getBasket()) {
         $this->setMathActionOnly(true);
         if ($eventName = static::getEntityEventName()) {
             $event = new Main\Event('sale', 'OnBefore' . $eventName . 'FinalAction', array('ENTITY' => $this, 'HAS_MEANINGFUL_FIELD' => $hasMeaningfulField, 'BASKET' => $basket));
             $event->send();
             if ($event->getResults()) {
                 /** @var Main\EventResult $eventResult */
                 foreach ($event->getResults() as $eventResult) {
                     if ($eventResult->getType() == Main\EventResult::ERROR) {
                         $errorMsg = new ResultError(Main\Localization\Loc::getMessage('SALE_EVENT_ON_BEFORE_' . strtoupper($eventName) . '_FINAL_ACTION_ERROR'), 'SALE_EVENT_ON_BEFORE_' . strtoupper($eventName) . '_FINAL_ACTION_ERROR');
                         if ($eventResultData = $eventResult->getParameters()) {
                             if (isset($eventResultData['ERROR']) && $eventResultData['ERROR'] instanceof ResultError) {
                                 $errorMsg = $eventResultData['ERROR'];
                             }
                         }
                         $result->addError($errorMsg);
                     }
                 }
             }
             if (!$result->isSuccess()) {
                 return $result;
             }
         }
         // discount
         $discount = $this->getDiscount();
         $r = $discount->calculate();
         if (!$r->isSuccess()) {
             //				$this->clearStartField();
             //				$result->addErrors($r->getErrors());
             //				return $result;
         }
         if ($r->isSuccess() && ($discountData = $r->getData()) && !empty($discountData) && is_array($discountData)) {
             /** @var Result $r */
             $r = $this->applyDiscount($discountData);
             if (!$r->isSuccess()) {
                 $result->addErrors($r->getErrors());
                 return $result;
             }
         }
         if (!$this->isExternal()) {
             /** @var Tax $tax */
             $tax = $this->getTax();
             /** @var Result $r */
             $r = $tax->calculate();
             if (!$result->isSuccess()) {
                 return $r;
             }
             $r = $tax->calculateDelivery();
             if (!$result->isSuccess()) {
                 return $r;
             }
             $taxChanged = false;
             $taxResult = $r->getData();
             if (isset($taxResult['TAX_PRICE']) && floatval($taxResult['TAX_PRICE']) >= 0) {
                 if (!$this->isUsedVat()) {
                     $taxChanged = true;
                     $this->setField('TAX_PRICE', $taxResult['TAX_PRICE']);
                     $this->setFieldNoDemand("PRICE", $this->getBasket()->getPrice() + $this->getShipmentCollection()->getPriceDelivery() + $taxResult['TAX_PRICE']);
                 }
             }
             if ($taxChanged || $this->isUsedVat()) {
                 $taxValue = $this->isUsedVat() ? $this->getVatSum() : $this->getField('TAX_PRICE');
                 if (floatval($taxValue) != floatval($this->getField('TAX_VALUE'))) {
                     $this->setField('TAX_VALUE', floatval($taxValue));
                 }
             }
         }
     }
     //
     $this->setMathActionOnly(false);
     //
     /** @var Result $r */
     $r = $this->syncOrderAndPayments();
     if (!$r->isSuccess()) {
         $result->addErrors($r->getErrors());
     }
     $this->clearStartField();
     if ($eventName = static::getEntityEventName()) {
         $event = new Main\Event('sale', 'OnAfter' . $eventName . 'FinalAction', array('ENTITY' => $this));
         $event->send();
     }
     return $result;
 }
Exemple #26
0
 public static function set($moduleId, $name, $value = "", $siteId = "")
 {
     $cacheTtl = self::getCacheTtl();
     if ($cacheTtl !== false) {
         $cache = \Bitrix\Main\Application::getInstance()->getManagedCache();
         $cache->clean("b_option");
     }
     $con = \Bitrix\Main\Application::getDbConnection();
     $sqlHelper = $con->getSqlHelper();
     $strSqlWhere = sprintf("SITE_ID %s AND MODULE_ID = '%s' AND NAME = '%s'", $siteId == "" ? "IS NULL" : "= '" . $sqlHelper->forSql($siteId, 2) . "'", $sqlHelper->forSql($moduleId), $sqlHelper->forSql($name));
     $res = $con->queryScalar("SELECT 'x' " . "FROM b_option " . "WHERE " . $strSqlWhere);
     if ($res != null) {
         $con->queryExecute("UPDATE b_option SET " . "\tVALUE = '" . $sqlHelper->forSql($value, 2000) . "' " . "WHERE " . $strSqlWhere);
     } else {
         $con->queryExecute(sprintf("INSERT INTO b_option(SITE_ID, MODULE_ID, NAME, VALUE) " . "VALUES(%s, '%s', '%s', '%s') ", $siteId == "" ? "NULL" : "'" . $sqlHelper->forSql($siteId, 2) . "'", $sqlHelper->forSql($moduleId, 50), $sqlHelper->forSql($name, 50), $sqlHelper->forSql($value, 2000)));
     }
     if ($siteId == "") {
         $siteId = '-';
     }
     self::$options[$siteId][$moduleId][$name] = $value;
     self::loadTriggers($moduleId);
     $event = new Main\Event("main", "OnAfterSetOption_" . $name, array("value" => $value));
     $event->send();
     return;
 }
 /**
  * Create coupon code.
  *
  * @param bool $check		Check new coupon or no.
  * @return string
  */
 public static function generateCoupon($check = false)
 {
     static $eventExists = null;
     $check = $check === true;
     if ($eventExists === true || $eventExists === null) {
         $event = new Main\Event('sale', self::EVENT_ON_GENERATE_COUPON, array('CHECK' => $check));
         $event->send();
         $resultList = $event->getResults();
         if (!empty($resultList) && is_array($resultList)) {
             /** @var Main\EventResult $eventResult */
             foreach ($resultList as &$eventResult) {
                 if ($eventResult->getType() != Main\EventResult::SUCCESS) {
                     continue;
                 }
                 $eventExists = true;
                 $result = $eventResult->getParameters();
                 if (!empty($result) && is_string($result)) {
                     return $result;
                 }
             }
             unset($eventResult);
         }
         if ($eventExists === null) {
             $eventExists = false;
         }
     }
     $allchars = 'ABCDEFGHIJKLNMOPQRSTUVWXYZ0123456789';
     $charsLen = strlen($allchars) - 1;
     do {
         $resultCorrect = true;
         $partOne = '';
         $partTwo = '';
         for ($i = 0; $i < 5; $i++) {
             $partOne .= substr($allchars, rand(0, $charsLen), 1);
         }
         for ($i = 0; $i < 7; $i++) {
             $partTwo .= substr($allchars, rand(0, $charsLen), 1);
         }
         $result = 'SL-' . $partOne . '-' . $partTwo;
         if ($check) {
             $existCoupon = Sale\DiscountCouponsManager::isExist($result);
             $resultCorrect = empty($existCoupon);
         }
     } while (!$resultCorrect);
     return $result;
 }
Exemple #28
0
 public static function GetCurTemplate()
 {
     /** @noinspection PhpUnusedLocalVariableInspection */
     global $APPLICATION, $USER, $CACHE_MANAGER;
     $connection = Main\Application::getConnection();
     $helper = $connection->getSqlHelper();
     $conditionQuoted = $helper->quote("CONDITION");
     $siteTemplate = "";
     if (CACHED_b_site_template === false) {
         $strSql = "\n\t\t\t\tSELECT\n\t\t\t\t\t" . $conditionQuoted . ",\n\t\t\t\t\tTEMPLATE\n\t\t\t\tFROM\n\t\t\t\t\tb_site_template\n\t\t\t\tWHERE\n\t\t\t\t\tSITE_ID='" . SITE_ID . "'\n\t\t\t\tORDER BY\n\t\t\t\t\tCASE\n\t\t\t\t\t\tWHEN " . $helper->getIsNullFunction($helper->getLengthFunction($conditionQuoted), 0) . "=0 THEN 2\n\t\t\t\t\t\tELSE 1\n\t\t\t\t\tEND,\n\t\t\t\t\tSORT\n\t\t\t\t";
         $dbr = $connection->query($strSql);
         while ($ar = $dbr->fetch()) {
             $strCondition = trim($ar["CONDITION"]);
             if (strlen($strCondition) > 0 && !@eval("return " . $strCondition . ";")) {
                 continue;
             }
             if (($path = getLocalPath("templates/" . $ar["TEMPLATE"], BX_PERSONAL_ROOT)) !== false && is_dir($_SERVER["DOCUMENT_ROOT"] . $path)) {
                 $siteTemplate = $ar["TEMPLATE"];
                 break;
             }
         }
     } else {
         if ($CACHE_MANAGER->Read(CACHED_b_site_template, "b_site_template")) {
             $arSiteTemplateBySite = $CACHE_MANAGER->Get("b_site_template");
         } else {
             $dbr = $connection->query("\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t" . $conditionQuoted . ",\n\t\t\t\t\t\tTEMPLATE,\n\t\t\t\t\t\tSITE_ID\n\t\t\t\t\tFROM\n\t\t\t\t\t\tb_site_template\n\t\t\t\t\tORDER BY\n\t\t\t\t\t\tSITE_ID,\n\t\t\t\t\t\tCASE\n\t\t\t\t\t\t\tWHEN " . $helper->getIsNullFunction($helper->getLengthFunction($conditionQuoted), 0) . "=0 THEN 2\n\t\t\t\t\t\t\tELSE 1\n\t\t\t\t\t\tEND,\n\t\t\t\t\t\tSORT\n\t\t\t\t");
             $arSiteTemplateBySite = array();
             while ($ar = $dbr->fetch()) {
                 $arSiteTemplateBySite[$ar['SITE_ID']][] = $ar;
             }
             $CACHE_MANAGER->Set("b_site_template", $arSiteTemplateBySite);
         }
         if (is_array($arSiteTemplateBySite[SITE_ID])) {
             foreach ($arSiteTemplateBySite[SITE_ID] as $ar) {
                 $strCondition = trim($ar["CONDITION"]);
                 if (strlen($strCondition) > 0 && !@eval("return " . $strCondition . ";")) {
                     continue;
                 }
                 if (($path = getLocalPath("templates/" . $ar["TEMPLATE"], BX_PERSONAL_ROOT)) !== false && is_dir($_SERVER["DOCUMENT_ROOT"] . $path)) {
                     $siteTemplate = $ar["TEMPLATE"];
                     break;
                 }
             }
         }
     }
     if ($siteTemplate == "") {
         $siteTemplate = ".default";
     }
     $event = new Main\Event("main", "OnGetCurrentSiteTemplate", array("template" => $siteTemplate));
     $event->send();
     foreach ($event->getResults() as $evenResult) {
         if (($result = $evenResult->getParameters()) != '') {
             //only the first result matters
             $siteTemplate = $result;
             break;
         }
     }
     return $siteTemplate;
 }
 /**
  * Return array of connectors information by endpoints array.
  *
  * @param array|null
  * @return array
  */
 public static function getConnectorClassList(array $endpointList = null)
 {
     $resultList = array();
     $moduleIdFilter = null;
     $moduleConnectorFilter = null;
     if ($endpointList) {
         $moduleIdFilter = array();
         foreach ($endpointList as $endpoint) {
             $moduleIdFilter[] = $endpoint['MODULE_ID'];
             $moduleConnectorFilter[$endpoint['MODULE_ID']][] = $endpoint['CODE'];
         }
     }
     $data = array();
     $event = new Event('sender', 'OnConnectorList', array($data), $moduleIdFilter);
     $event->send();
     foreach ($event->getResults() as $eventResult) {
         if ($eventResult->getType() == EventResult::ERROR) {
             continue;
         }
         $eventResultParameters = $eventResult->getParameters();
         if ($eventResultParameters && array_key_exists('CONNECTOR', $eventResultParameters)) {
             $connectorClassName = $eventResultParameters['CONNECTOR'];
             if (!is_subclass_of($connectorClassName, '\\Bitrix\\Sender\\Connector')) {
                 continue;
             }
             $connectorCode = call_user_func(array($connectorClassName, 'getCode'));
             if ($moduleConnectorFilter && !in_array($connectorCode, $moduleConnectorFilter[$eventResult->getModuleId()])) {
                 continue;
             }
             $connectorName = call_user_func(array($connectorClassName, 'getName'));
             $connectorRequireConfigure = call_user_func(array($connectorClassName, 'requireConfigure'));
             $resultList[] = array('MODULE_ID' => $eventResult->getModuleId(), 'CLASS_NAME' => $connectorClassName, 'CODE' => $connectorCode, 'NAME' => $connectorName, 'REQUIRE_CONFIGURE' => $connectorRequireConfigure);
         }
     }
     if (!empty($resultList)) {
         usort($resultList, array(__CLASS__, 'sort'));
     }
     return $resultList;
 }
Exemple #30
-1
 protected function createTopic()
 {
     $topic = array('TITLE' => $this->entity->getXmlId(), 'TAGS' => '', 'MESSAGE' => $this->entity->getXmlId(), 'AUTHOR_ID' => 0);
     /** @var $request \Bitrix\Main\HttpRequest */
     $request = \Bitrix\Main\Context::getCurrent()->getRequest();
     $post = array_merge($request->getQueryList()->toArray(), $request->getPostList()->toArray());
     $event = new Event("forum", "OnCommentTopicAdd", array($this->entity->getType(), $this->entity->getId(), $post, &$topic));
     $event->send();
     if (strlen($topic["AUTHOR_NAME"]) <= 0) {
         $topic["AUTHOR_NAME"] = $topic["AUTHOR_ID"] <= 0 ? Loc::getMessage("FORUM_USER_SYSTEM") : self::getUserName($topic["AUTHOR_ID"]);
     }
     $topic = array_merge($topic, array("FORUM_ID" => $this->forum["ID"], 'TITLE' => $topic["TITLE"], 'TAGS' => $topic["TAGS"], 'MESSAGE' => $topic["MESSAGE"], "USER_START_ID" => $topic["AUTHOR_ID"], "USER_START_NAME" => $topic["AUTHOR_NAME"], "LAST_POSTER_NAME" => $topic["AUTHOR_NAME"], "XML_ID" => $this->entity->getXmlId(), "APPROVED" => "Y"));
     if (($tid = \CForumTopic::add($topic)) > 0) {
         if ($this->forum["ALLOW_HTML"] != "Y") {
             $topic['MESSAGE'] = strip_tags($topic['MESSAGE']);
         }
         $fields = array("POST_MESSAGE" => $topic['MESSAGE'], "AUTHOR_ID" => $topic["AUTHOR_ID"], "AUTHOR_NAME" => $topic["AUTHOR_NAME"], "FORUM_ID" => $topic["FORUM_ID"], "TOPIC_ID" => $tid, "APPROVED" => $topic["APPROVED"], "NEW_TOPIC" => "Y", "PARAM1" => $this->entity->getType(), "PARAM2" => $this->entity->getId());
         if (\CForumMessage::Add($fields, false, array("SKIP_INDEXING" => "Y", "SKIP_STATISTIC" => "N")) > 0) {
             $event = new Event("forum", "OnAfterCommentTopicAdd", array($this->entity->getType(), $this->entity->getId(), $tid));
             $event->send();
             self::$topics[$this->entity->getXmlId()] = $topic + array("ID" => $tid);
             return self::$topics[$this->entity->getXmlId()];
         }
         \CForumTopic::Delete($tid);
     }
     $this->errorCollection->add(array(new Error(Loc::getMessage("FORUM_CM_TOPIC_IS_NOT_CREATED"), self::ERROR_PARAMS_TOPIC_ID)));
     return null;
 }