public function assureValueObject($value) { if ($value instanceof Type\DateTime) { // oracle sql helper returns datetime instead of date - it doesn't see the difference $value = new Type\Date($value->format(Main\UserFieldTable::MULTIPLE_DATE_FORMAT), Main\UserFieldTable::MULTIPLE_DATE_FORMAT); } return $value; }
/** * @param FieldType $fieldType Document field type. * @param mixed $value Field value. * @param string $toTypeClass Type class name. * @return null|mixed */ public static function convertTo(FieldType $fieldType, $value, $toTypeClass) { /** @var Base $toTypeClass */ $type = $toTypeClass::getType(); switch ($type) { case FieldType::DOUBLE: case FieldType::INT: $value = $value ? (int) strtotime($value) : 0; break; case FieldType::DATE: case FieldType::DATETIME: case FieldType::STRING: case FieldType::TEXT: $value = (string) $value; if ($value) { if ($type == FieldType::DATE) { $format = \FORMAT_DATE; } elseif ($type == FieldType::DATETIME) { $format = \FORMAT_DATETIME; } else { $format = static::getType() == FieldType::DATE ? \FORMAT_DATE : \FORMAT_DATETIME; } if (\CheckDateTime($value, $format)) { $value = date(Type\Date::convertFormatToPhp($format), \MakeTimeStamp($value, $format)); } else { $value = date(Type\Date::convertFormatToPhp($format), strtotime($value)); } } break; default: $value = null; } return $value; }
/** @return \CDBResult */ public function getData() { $groupId = $this->getFieldValue('GROUP_ID', null); $dateRegister = $this->getFieldValue('DATE_REGISTER', null); $active = $this->getFieldValue('ACTIVE', null); $filter = array(); if ($groupId) { $filter['GROUP_ID'] = $groupId; } if (strlen($dateRegister) > 0) { if (\Bitrix\Main\Type\Date::isCorrect($dateRegister)) { $dateRegister = new \Bitrix\Main\Type\Date($dateRegister); $filter['><USER.DATE_REGISTER'] = array($dateRegister->toString(), $dateRegister->add('1 DAY')->toString()); } else { $result = new \CDBResult(); $result->InitFromArray(array()); return $result; } } if ($active == 'Y') { $filter['USER.ACTIVE'] = $active; } elseif ($active == 'N') { $filter['USER.ACTIVE'] = $active; } $userDb = \Bitrix\Main\UserGroupTable::getList(array('select' => array('NAME' => 'USER.NAME', 'EMAIL' => 'USER.EMAIL', 'USER_ID'), 'filter' => $filter, 'group' => array('NAME', 'EMAIL', 'USER_ID'), 'order' => array('USER_ID' => 'ASC'))); return new \CDBResult($userDb); }
/** * @param FieldType $fieldType Document field type. * @param mixed $value Field value. * @param string $toTypeClass Type class name. * @return null|mixed */ public static function convertTo(FieldType $fieldType, $value, $toTypeClass) { /** @var Base $toTypeClass */ $type = $toTypeClass::getType(); switch ($type) { case FieldType::BOOL: $value = (bool) $value ? 'Y' : 'N'; break; case FieldType::DATE: $value = date(Main\Type\Date::convertFormatToPhp(\FORMAT_DATE), (int) $value); break; case FieldType::DATETIME: $value = date(Main\Type\DateTime::convertFormatToPhp(\FORMAT_DATETIME), (int) $value); break; case FieldType::DOUBLE: $value = (double) $value; break; case FieldType::INT: $value = (int) $value; break; case FieldType::STRING: case FieldType::TEXT: $value = (string) $value; break; case FieldType::USER: $value = 'user_' . (int) $value; break; default: $value = null; } return $value; }
public static function generateInitialData(Date $from) { if (($to = Option::get('conversion', 'START_DATE_TIME', 'undefined')) != 'undefined' && DateTime::isCorrect($to, 'Y-m-d H:i:s') && ($to = new DateTime($to, 'Y-m-d H:i:s')) && $to->format('Y-m-d H:i:s') > $from->format('Y-m-d H:i:s') && Option::get('conversion', 'GENERATE_INITIAL_DATA', 'undefined') == 'undefined') { Option::set('conversion', 'GENERATE_INITIAL_DATA', 'generated'); $context = new self(); // generate data $data = array(); foreach (EventManager::getInstance()->findEventHandlers('conversion', 'OnGenerateInitialData') as $handler) { $result = ExecuteModuleEventEx($handler, array($from, $to)); // TODO validate foreach ($result as $row) { $context->id = null; $context->attributes = array(); $context->setAttributes($row['ATTRIBUTES']); $context->save(); if ($dayCounters =& $data[$context->id]) { self::appendDayCounters($dayCounters, $row['DAY_COUNTERS']); } else { $dayCounters = $row['DAY_COUNTERS']; } } } unset($dayCounters); // save data to database $numerators = CounterManager::getTypes(array('GROUP' => 'day')); unset($numerators['conversion_visit_day']); foreach ($data as $id => $dayCounters) { $context->id = $id; foreach ($dayCounters as $day => $counters) { $day = new Date($day, 'Y-m-d'); $visitSum = 0; $visitQuantity = 0; unset($counters['conversion_visit_day']); foreach ($counters as $name => $value) { $context->addCounter($day, $name, $value); if ($numerators[$name]) { $visitSum += $value; $visitQuantity += 1; } } $context->addCounter($day, 'conversion_visit_day', $visitQuantity ? round($visitSum / $visitQuantity * 100) + 1 : 1); } } } }
/** * @param FieldType $fieldType Document field type. * @param mixed $value Field value. * @param string $toTypeClass Type class name. * @return null|mixed */ public static function convertTo(FieldType $fieldType, $value, $toTypeClass) { /** @var Base $toTypeClass */ $type = $toTypeClass::getType(); switch ($type) { case FieldType::BOOL: $value = strtolower((string) $value); $value = in_array($value, array('y', 'yes', 'true', '1')) ? 'Y' : 'N'; break; case FieldType::DATE: $value = date(Main\Type\Date::convertFormatToPhp(\FORMAT_DATE), strtotime($value)); break; case FieldType::DATETIME: $value = date(Main\Type\DateTime::convertFormatToPhp(\FORMAT_DATETIME), strtotime($value)); break; case FieldType::DOUBLE: $value = str_replace(' ', '', str_replace(',', '.', $value)); $value = (double) $value; break; case FieldType::INT: $value = str_replace(' ', '', $value); $value = (int) $value; break; case FieldType::STRING: case FieldType::TEXT: $value = (string) $value; break; case FieldType::USER: $value = trim($value); if (strpos($value, 'user_') === false && strpos($value, 'group_') === false && !preg_match('#^[0-9]+$#', $value)) { $value = null; } break; default: $value = null; } return $value; }
/** * @return boolean */ public static function register($ownerID, array $entityFields = null, array $options = null) { if (!is_int($ownerID)) { $ownerID = (int) $ownerID; } if ($ownerID <= 0) { throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID'); } if (!is_array($options)) { $options = array(); } $date = isset($options['DATE']) ? $options['DATE'] : null; if ($date === null) { $date = new Date(); } $day = (int) $date->format('d'); $month = (int) $date->format('m'); $quarter = $month <= 3 ? 1 : ($month <= 6 ? 2 : ($month <= 9 ? 3 : 4)); $year = (int) $date->format('Y'); if (!is_array($entityFields)) { $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('STAGE_ID', 'ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE')); $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null; if (!is_array($entityFields)) { return false; } } $stageID = isset($entityFields['STAGE_ID']) ? $entityFields['STAGE_ID'] : ''; $semanticID = \CCrmDeal::GetSemanticID($stageID); $isLost = PhaseSemantics::isLost($semanticID); $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0; $callQty = 0; $meetingQty = 0; $emailQty = 0; $startTime = new DateTime($date->format(DateTime::getFormat())); $endTime = new DateTime($date->format(DateTime::getFormat())); $endTime->setTime(23, 59, 59); $query = new Query(Crm\ActivityTable::getEntity()); $query->addSelect('TYPE_ID'); $query->registerRuntimeField('', new ExpressionField('QTY', 'COUNT(*)')); $query->addSelect('QTY'); $query->addFilter('=COMPLETED', 'Y'); $query->addFilter('>=DEADLINE', $startTime); $query->addFilter('<=DEADLINE', $endTime); $query->addGroup('TYPE_ID'); $subQuery = new Query(Crm\ActivityBindingTable::getEntity()); $subQuery->addSelect('ACTIVITY_ID'); $subQuery->addFilter('=OWNER_TYPE_ID', \CCrmOwnerType::Deal); $subQuery->addFilter('=OWNER_ID', $ownerID); $query->registerRuntimeField('', new ReferenceField('B', Base::getInstanceByQuery($subQuery), array('=this.ID' => 'ref.ACTIVITY_ID'), array('join_type' => 'INNER'))); $dbResult = $query->exec(); while ($stats = $dbResult->fetch()) { $typeID = isset($stats['TYPE_ID']) ? (int) $stats['TYPE_ID'] : 0; $qty = isset($stats['QTY']) ? (int) $stats['QTY'] : 0; if ($typeID === \CCrmActivityType::Call) { $callQty = $qty; } elseif ($typeID === \CCrmActivityType::Meeting) { $meetingQty = $qty; } elseif ($typeID === \CCrmActivityType::Email) { $emailQty = $qty; } } if ($callQty === 0 && $meetingQty === 0 && $emailQty === 0) { DealActivityStatisticsTable::delete(array('OWNER_ID' => $ownerID, 'DEADLINE_DATE' => $date)); return true; } $present = self::get($ownerID, $date); if (is_array($present)) { if ($responsibleID === (int) $present['RESPONSIBLE_ID'] && $stageID === $present['STAGE_ID'] && $callQty === (int) $present['CALL_QTY'] && $meetingQty === (int) $present['MEETING_QTY'] && $emailQty === (int) $present['EMAIL_QTY']) { return false; } if ($responsibleID !== (int) $present['RESPONSIBLE_ID']) { DealActivityStatisticsTable::synchronize($ownerID, array('RESPONSIBLE_ID' => $responsibleID)); } } $data = array('OWNER_ID' => $ownerID, 'DEADLINE_DATE' => $date, 'DEADLINE_YEAR' => $year, 'DEADLINE_QUARTER' => $quarter, 'DEADLINE_MONTH' => $month, 'DEADLINE_DAY' => $day, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_SEMANTIC_ID' => $semanticID, 'STAGE_ID' => $stageID, 'IS_LOST' => $isLost ? 'Y' : 'N', 'CALL_QTY' => $callQty, 'MEETING_QTY' => $meetingQty, 'EMAIL_QTY' => $emailQty); DealActivityStatisticsTable::upsert($data); return true; }
use Bitrix\Conversion\AttributeManager; use Bitrix\Conversion\AttributeGroupManager; use Bitrix\Conversion\ReportContext; use Bitrix\Main\Loader; use Bitrix\Main\SiteTable; use Bitrix\Main\Type\Date; use Bitrix\Main\Localization\Loc; Loc::loadMessages(__FILE__); Loader::IncludeModule('conversion'); if ($APPLICATION->GetGroupRight('conversion') < 'W') { $APPLICATION->AuthForm(Loc::getMessage('ACCESS_DENIED')); } $userOptions = CUserOptions::GetOption('conversion', 'filter', array()); // PERIOD $from = ($d = $_GET['from'] ?: $userOptions['from']) && Date::isCorrect($d) ? new Date($d) : Date::createFromPhp(new DateTime('first day of last month')); $to = ($d = $_GET['to'] ?: $userOptions['to']) && Date::isCorrect($d) ? new Date($d) : Date::createFromPhp(new DateTime('last day of this month')); // RATES if (!($rateTypes = RateManager::getTypes())) { die('No rates available!'); } $rateName = $_GET['rate'] ?: $userOptions['rate']; if (!($rateType = $rateTypes[$rateName])) { list($rateName, $rateType) = each($rateTypes); } // SITES $sites = array(); $result = SiteTable::getList(array('select' => array('LID', 'NAME'), 'order' => array('DEF' => 'DESC', 'SORT' => 'ASC'))); while ($row = $result->fetch()) { $sites[$row['LID']] = $row['NAME']; } if (!$sites) {
/** * @param bool $error * @param bool $needRecalculate * @return mixed */ protected static function prepareData($error = false, $needRecalculate = true) { global $USER; static $users = array(); $result['SHIPMENT'] = array(); if ($error) { $fields = self::$defaultFields; } else { $fields = self::$shipment->getFieldValues(); $fields['DELIVERY_STORE_ID'] = self::$shipment->getStoreId(); $fields["EXTRA_SERVICES"] = self::$shipment->getExtraServices(); $fields["STORE"] = self::$shipment->getStoreId(); } $date = new Date($fields['DELIVERY_DOC_DATE']); $fields['DELIVERY_DOC_DATE'] = $date->toString(); $empDeductedId = $fields['EMP_DEDUCTED_ID']; if ($empDeductedId > 0) { if (!array_key_exists($empDeductedId, $users)) { $users[$empDeductedId] = $USER->GetByID($empDeductedId)->Fetch(); } $fields['EMP_DEDUCTED_ID_NAME'] = $users[$empDeductedId]['NAME']; $fields['EMP_DEDUCTED_ID_LAST_NAME'] = $users[$empDeductedId]['LAST_NAME']; } $empAllowDeliveryId = $fields['EMP_ALLOW_DELIVERY_ID']; if ($empAllowDeliveryId > 0) { if (!array_key_exists($empAllowDeliveryId, $users)) { $users[$empAllowDeliveryId] = $USER->GetByID($empAllowDeliveryId)->Fetch(); } $fields['EMP_ALLOW_DELIVERY_ID_NAME'] = $users[$empAllowDeliveryId]['NAME']; $fields['EMP_ALLOW_DELIVERY_ID_LAST_NAME'] = $users[$empAllowDeliveryId]['LAST_NAME']; } $empCanceledId = $fields['EMP_CANCELED_ID']; if ($empCanceledId > 0) { if (!array_key_exists($empCanceledId, $users)) { $users[$empCanceledId] = $USER->GetByID($empCanceledId)->Fetch(); } $fields['EMP_CANCELLED_ID_NAME'] = $users[$empCanceledId]['NAME']; $fields['EMP_CANCELLED_ID_LAST_NAME'] = $users[$empCanceledId]['LAST_NAME']; } $empMarkedId = $fields['EMP_MARKED_ID']; if ($empMarkedId > 0) { if (!array_key_exists($empMarkedId, $users)) { $users[$empMarkedId] = $USER->GetByID($empMarkedId)->Fetch(); } $fields['EMP_MARKED_ID_NAME'] = $users[$empMarkedId]['NAME']; $fields['EMP_MARKED_ID_LAST_NAME'] = $users[$empMarkedId]['LAST_NAME']; } /** @var \Bitrix\Sale\Order $order */ $order = self::$shipment->getCollection()->getOrder(); $fields['CURRENCY'] = $order->getCurrency(); $fields['CUSTOM_PRICE'] = self::getDeliveryPrice(self::$shipment); if ($fields['CUSTOM_PRICE_DELIVERY'] == 'Y' && $fields['ID'] <= 0) { $fields['BASE_PRICE_DELIVERY'] = self::$shipment->getField('BASE_PRICE_DELIVERY'); } $discounts = OrderEdit::getDiscountsApplyResult($order, $needRecalculate); $shipmentIds = $order->getDiscount()->getShipmentsIds(); foreach ($shipmentIds as $shipmentId) { if ($shipmentId == self::$shipment->getId()) { $fields['DISCOUNTS'] = $discounts; } } $result['SHIPMENT'][] = $fields; return $result; }
/** * Creates DateTime object from local user time using global timezone settings and default culture. * * @param string $timeString Full or short formatted time. * * @return Bitrix\Main\Type\DateTime */ public static function createFromUserTime($timeString) { /** @var DateTime $time */ try { //try full datetime format $time = new static($timeString); } catch(Main\ObjectException $e) { //try short date format $time = new static($timeString, Date::getFormat()); $time->setTime(0, 0, 0); } if(\CTimeZone::Enabled()) { static $diff = null; if($diff === null) { $diff = \CTimeZone::GetOffset(); } if($diff <> 0) { $time->add(($diff > 0? "-":"")."PT".abs($diff)."S"); } } return $time; }
/** * <p>Преобразует дату из одного заданного формата в другой заданный формат. В формате допустимы следующие обозначения:</p> <p> </p> <table width="100%" class="tnormal"> <tr> <th width="40%">Обозначение</th> <th width="60%">Описание</th> </tr> <tr> <td>YYYY</td> <td>Год (0001 - 9999)</td> </tr> <tr> <td>MM</td> <td>Месяц (01 - 12)</td> </tr> <tr> <td>DD</td> <td>День (01 - 31)</td> </tr> <tr> <td>HH</td> <td>Часы (00 - 24)</td> </tr> <tr> <td>MI</td> <td>Минуты (00 - 59)</td> </tr> <tr> <td>SS</td> <td>Секунды (00 - 59)</td> </tr> </table> <p>Динамичный метод.</p> * * * @param string $date Год (0001 - 9999)</b * * @param string $format = "DD.MM.YYYY Месяц (01 - 12)</bo * * @param H $H День (01 - 31)</b * * @param M $I Часы (00 - 24)</bo * * @param S $S Минуты (00 - 59)</b * * @param $string Секунды (00 - 59)</bod * * @param new_forma $t = "DD.MM.YYYY * * @param H $H Дата для конвертации. * * @param M $I Текущий формат даты. <br>Необязательный. По умолчанию - "DD.MM.YYYY HH:MI:SS". * * @param S $S В какой формат необходимо преобразовать. <br>Необязательный. По * умолчанию - "DD.MM.YYYY HH:MI:SS". * * @return string * * <h4>Example</h4> * <pre> * <? * // зададим дату * $date = "31.12.2007"; * * // укажем формат этой даты * $format = "DD.MM.YYYY"; * * // получим формат текущего сайта * $new_format = CSite::GetDateFormat("SHORT"); // YYYY-MM-DD * * // переведем дату из одного формата в другой * $new_date = $DB-><b>FormatDate</b>($date, $format, $new_format); * * // в результате получим дату в новом формате * echo $new_date; // 2007-12-31 * ?> * * * <? * // конвертация даты из формата одного сайта в формат другого * * // получим формат сайта ru * $format_ru = CSite::GetDateFormat("SHORT", "ru"); // DD.MM.YYYY * * // получим формат сайта en * $format_en = CSite::GetDateFormat("SHORT", "en"); // YYYY-MM-DD * * // переведем дату из формата сайта ru в формат сайта en * $new_date = $DB-><b>FormatDate</b>($date, $format_ru, $format_en); * * // в результате получим дату в новом формате * echo $date; // 2007-12-31 * ?> * </pre> * * * <h4>See Also</h4> * <ul> <li> <a * href="http://dev.1c-bitrix.ru/api_help/main/reference/cdatabase/dateformattophp.php">CDatabase::DateFormatToPHP</a> * </li> <li> <a href="http://dev.1c-bitrix.ru/api_help/main/reference/csite/getdateformat.php">CSite::GetDateFormat</a> * </li> <li> <a href="http://dev.1c-bitrix.ru/api_help/main/functions/date/convertdatetime.php">ConvertDateTime</a> </li> * <li> <a href="http://dev.1c-bitrix.ru/api_help/main/functions/date/index.php">Функции для работы с * датой и временем</a> </li> </ul> <a name="examples"></a> * * * @static * @link http://dev.1c-bitrix.ru/api_help/main/reference/cdatabase/formatdate.php * @author Bitrix */ public static function FormatDate($strDate, $format = "DD.MM.YYYY HH:MI:SS", $new_format = "DD.MM.YYYY HH:MI:SS") { if (empty($strDate)) { return false; } if ($format === false && defined("FORMAT_DATETIME")) { $format = FORMAT_DATETIME; } $fromPhpFormat = Main\Type\Date::convertFormatToPhp($format); $time = false; try { $time = new Main\Type\DateTime($strDate, $fromPhpFormat); } catch (Main\ObjectException $e) { } if ($time !== false) { //Compatibility issue $fixed_format = preg_replace(array("/(?<!Y)Y(?!Y)/i", "/(?<!M)M(?!M|I)/i", "/(?<!D)D(?!D)/i", "/(?<!H)H:I:S/i"), array("YYYY", "MM", "DD", "HH:MI:SS"), strtoupper($new_format)); $toPhpFormat = Main\Type\Date::convertFormatToPhp($fixed_format); return $time->format($toPhpFormat); } return false; }
function getSenderItemContainer($id, array $chain = array()) { $i = '%SENDER_LETTER_TEMPLATE_BODY_NUM%'; ob_start(); ?> <div class="sender-trigger-chain-container-letter"> <div class="sender-trigger-status-mailing-time"> <?php echo GetMessage("sender_chain_edit_field_time_thr"); ?> <span class="sender_letter_container_time_text">*</span> <?php echo GetMessage("sender_chain_edit_field_time_after"); ?> <span class="sender_letter_container_time_text_first"> <?php echo GetMessage("sender_chain_edit_field_time_event"); ?> </span> <span style="display: none;" class="sender_letter_container_time_text_nonfirst"> <?php echo GetMessage("sender_chain_edit_field_time_letter"); ?> </span> <a id="SENDER_TRIGGER_CHAIN_TIME_BNT_<?php echo $i; ?> " href="javascript: void(0);" class="sender_letter_container_time_button sender-link-email"><?php echo GetMessage("sender_chain_edit_field_time_change"); ?> </a> </div> <div class="sender_letter_container" id="SENDER_TRIGGER_CHAIN_<?php echo $i; ?> "> <input type="hidden" name="CHAIN[<?php echo $i; ?> ][ID]" value="<?php echo htmlspecialcharsbx($chain['ID']); ?> "> <input class="sender_letter_container_sorter" type="hidden" name="CHAIN[<?php echo $i; ?> ][ITEM_SORT]" value="<?php echo $i; ?> "> <input class="sender_letter_container_time" type="hidden" name="CHAIN[<?php echo $i; ?> ][TIME_SHIFT]" value="<?php echo intval($chain['TIME_SHIFT']); ?> "> <div class="sender_letter_container_head"> <div class="sender_letter_container_move"><div class="sender_letter_container_burger"></div></div> <div class="sender_letter_container_sorter_view"> <span class="sender_letter_container_sorter_icon"> <span class="sender_letter_container_sorter_text"><?php echo $i; ?> </span> </span> </div> <h3><span class="sender_letter_container_caption"><?php echo htmlspecialcharsbx($chain['SUBJECT']); ?> </span></h3> <span class="sender_letter_container-info"> <?php if (!empty($chain['ID']) && empty($chain['DATE_INSERT'])) { ?> <span><?php echo GetMessage("sender_chain_edit_field_created_exists_but_not_save"); ?> </span> <?php } elseif (!empty($chain['ID'])) { ?> <span class="sender_letter_container-create"><?php echo GetMessage("sender_chain_edit_field_created"); ?> </span> <span> <?php echo GetMessage("sender_chain_edit_field_created_text", array('%DATE_CREATE%' => htmlspecialcharsbx(is_object($chain['DATE_INSERT']) ? \Bitrix\Main\Type\Date::createFromTimestamp($chain['DATE_INSERT']->getTimestamp()) : $chain['DATE_INSERT']), '%AUTHOR%' => '<a class="sender_letter_container-author" href="/bitrix/admin/user_edit.php?ID=' . htmlspecialcharsbx($chain['CREATED_BY']) . '&lang=' . LANGUAGE_ID . '">' . htmlspecialcharsbx($chain['CREATED_BY_NAME']) . ' ' . htmlspecialcharsbx($chain['CREATED_BY_LAST_NAME']) . '</a>')); ?> </span> <?php } else { ?> <span><?php echo GetMessage("sender_chain_edit_field_created_new"); ?> </span> <?php } ?> </span> <a class="sender_letter_container_button_delete" href="javascript: void(0);" title="<?php echo GetMessage("sender_chain_edit_field_delete"); ?> "></a> <?php if (strlen($chain['SUBJECT']) > 0 && strlen($chain['MESSAGE']) > 0) { ?> <a class="sender_letter_container_button_show" href="javascript: void(0);"> <?php echo GetMessage('SENDER_MAILING_TRIG_LETTER_MESSAGE_SHOW'); ?> </a> <?php } else { ?> <a class="sender_letter_container_button_show sender_letter_container_button_hide" href="javascript: void(0);"> <?php echo GetMessage('SENDER_MAILING_TRIG_LETTER_MESSAGE_HIDE'); ?> </a> <?php } ?> </div> <div class="sender_letter_container_body" <?php echo strlen($chain['SUBJECT']) > 0 && strlen($chain['MESSAGE']) > 0 ? 'style="display:none;"' : ''; ?> > <div class="sender_letter_container_body_tmpl" id="CHAIN_TEMPLATE_NUM_<?php echo $i; ?> " <?php echo strlen($chain['MESSAGE']) > 0 ? 'style="display:none;"' : ''; ?> > <?php echo \Bitrix\Sender\Preset\Template::getTemplateListHtml('SENDER_TRIGGER_CHAIN_' . $i); ?> </div> <div class="sender_letter_container_body_fields" <?php echo strlen($chain['MESSAGE']) > 0 ? '' : 'style="display:none;"'; ?> > <table class="trigger_chain_item"> <tr> <td><?php echo GetMessage("sender_chain_edit_field_sel_templ"); ?> </td> <td> <span class="sender-template-message-caption-container"></span> <a href="javascript:void(0);" class="sender-template-message-caption-container-btn sender-link-email"> <?php echo GetMessage("sender_chain_edit_field_sel_templ_another"); ?> </a> </td> </tr> <tr> <td><?php echo GetMessage("sender_chain_edit_field_subject"); ?> </td> <td> <input class="sender_letter_container_subject" type="text" id="CHAIN_<?php echo $i; ?> _SUBJECT" name="CHAIN[<?php echo $i; ?> ][SUBJECT]" value="<?php echo htmlspecialcharsbx($chain['SUBJECT']); ?> "> </td> </tr> <tr> <td> </td> <td> <?php $arPersonalizeList = \Bitrix\Sender\PostingRecipientTable::getPersonalizeList(); ?> <?php echo GetMessage("sender_chain_edit_field_subject_personalize"); ?> <?php foreach ($arPersonalizeList as $arPersonalize) { ?> <a class="sender-link-email" onclick="SetAddressToControl('CHAIN_<?php echo $i; ?> _SUBJECT', ' #<?php echo htmlspecialcharsbx($arPersonalize['CODE']); ?> #', true)" title="#<?php echo htmlspecialcharsbx($arPersonalize['CODE']); ?> # - <?php echo htmlspecialcharsbx($arPersonalize['DESC']); ?> "> <?php echo htmlspecialcharsbx($arPersonalize['NAME']); ?> </a><?php echo end($arPersonalizeList) === $arPersonalize ? '' : ','; ?> <?php } ?> <span style="cursor: pointer;" class="hidden-when-show-template-list-info" onclick="ShowPersonalizeDescDialog(this);"> </span> </td> </tr> <tr> <td colspan="2"> <b><?php echo GetMessage("sender_chain_edit_field_message"); ?> </b> <br> <br> %SENDER_LETTER_TEMPLATE_MESSAGE% </td> </tr> </table> </div> </div> </div> </div> <?php return ob_get_clean(); }
} if($bShowStats) { if( isset($_REQUEST['date_from']) && isset($_REQUEST['date_to']) && Main\Type\Date::isCorrect($_REQUEST['date_from']) && Main\Type\Date::isCorrect($_REQUEST['date_to']) ) { $statsDateStart = new Main\Type\Date($_REQUEST['date_from']); $statsDateFinish = new Main\Type\Date($_REQUEST['date_to']); } else { $statsDateStart = new Main\Type\Date(); $statsDateStart->add("-".Engine\YandexDirectLive::MAX_STAT_DAYS_DELTA." days"); $statsDateFinish = new Main\Type\Date(); } } if($bShowStats) { $tableID = "tbl_yandex_campaign_banner_stats"; //hack to prevent browser history insertion if (isset($_REQUEST["mode"])&&($_REQUEST["mode"]=='list' || $_REQUEST["mode"]=='frame')) { $_REQUEST['admin_history'] = 'Y'; }
$gaps = $_SESSION[$loadingSession]['GAPS']; } else { $res = array('error' => array('message' => 'loading session broken')); break; } } else { if (in_array($_REQUEST["type"], array("week_ago", "month_ago", "interval"))) { $period = array(); \CGridOptions::CalcDates("", array("_datesel" => $_REQUEST["type"], "_days" => 1, "_from" => $_REQUEST["date_from"], "_to" => $_REQUEST["date_to"]), $period); if (Date::isCorrect($period['_from'])) { $dateStart = new Date($period['_from']); } else { $res = array('error' => array('message' => Loc::getMessage('SEO_ERROR_INCORRECT_DATE') . ': ' . $period['_from'])); break; } if (Date::isCorrect($period['_to'])) { $dateFinish = new Date($period['_to']); } else { $res = array('error' => array('message' => Loc::getMessage('SEO_ERROR_INCORRECT_DATE') . ': ' . $period['_to'])); break; } $statsData = Adv\YandexStatTable::getCampaignStat($campaignId, $dateStart, $dateFinish); $gaps = Adv\YandexStatTable::getMissedPeriods($statsData, $dateStart, $dateFinish); } else { $res = array('error' => array('message' => 'invalid interval type')); } } $errorMessage = null; $finish = true; if (count($gaps) > 0) { $cnt = 0;
public function createInvoices(array $params) { $count = isset($params['COUNT']) ? (int) $params['COUNT'] : 0; if ($count <= 0) { return; } $sum = isset($params['SUM']) ? (int) $params['SUM'] : 0; if ($sum <= 0) { return; } $dealID = isset($params['DEAL_ID']) ? (int) $params['DEAL_ID'] : 0; $companyID = isset($params['COMPANY_ID']) ? (int) $params['COMPANY_ID'] : 0; $contactID = isset($params['CONTACT_ID']) ? (int) $params['CONTACT_ID'] : 0; $userIDs = isset($params['USER_IDS']) && is_array($params['USER_IDS']) ? $params['USER_IDS'] : array(); if (empty($userIDs)) { $userIDs[] = \CCrmSecurityHelper::GetCurrentUserID(); } $prefix = isset($params['PREFIX']) ? $params['PREFIX'] : ''; if ($prefix === '') { $prefix = $this->id; } $date = isset($params['DATE']) ? $params['DATE'] : null; if (!$date) { $date = $date = new Date(); } $maxDateOffset = isset($params['MAX_DATE_OFFSET']) ? (int) $params['MAX_DATE_OFFSET'] : 0; $dateFormat = Date::convertFormatToPhp(FORMAT_DATE); $dateTimeFormat = Date::convertFormatToPhp(FORMAT_DATETIME); $isWon = isset($params['IS_WON']) ? $params['IS_WON'] : false; if ($isWon) { $totalSum = $sum; } else { $totalSum = $sum - mt_rand((int) ($sum / 3), $sum); } $entity = new \CCrmInvoice(false); $invoiceSum = (int) $totalSum / $count; $totalInvoiceSum = 0; for ($i = 1; $i <= $count; $i++) { if ($i == $count) { $invoiceSum = $totalSum - $totalInvoiceSum; } $totalInvoiceSum += $invoiceSum; $time = DateTime::createFromTimestamp($date->getTimestamp()); if ($maxDateOffset > 0) { $time->add(mt_rand(0, $maxDateOffset) . ' days'); } $time->setTime(mt_rand(8, 20), mt_rand(0, 59), 0); $siteTime = $time->format($dateTimeFormat); $siteDate = $time->format($dateFormat); \CCrmOwnerType::GetCaption(\CCrmOwnerType::Company, $companyID, false); $companyInfo = self::getCompanyInfo($companyID); $contactInfo = self::getContactInfo($contactID); $fields = array('ORDER_TOPIC' => "{$prefix} invoice # {$i}", 'STATUS_ID' => $isWon ? 'P' : 'N', 'DATE_INSERT' => $siteTime, 'DATE_BILL' => $siteDate, 'RESPONSIBLE_ID' => self::getRandomItem($userIDs), 'UF_DEAL_ID' => $dealID, 'UF_COMPANY_ID' => $companyID, 'UF_CONTACT_ID' => $contactID, 'PERSON_TYPE_ID' => 1, 'PAY_SYSTEM_ID' => 1, 'INVOICE_PROPERTIES' => array(10 => $companyInfo['TITLE'], 11 => $companyInfo['FULL_ADDRESS'], 12 => $contactInfo['FULL_NAME'], 13 => $contactInfo['EMAIL'], 14 => $contactInfo['PHONE']), 'PRODUCT_ROWS' => array(array('ID' => 0, 'PRODUCT_NAME' => "{$prefix} product", 'QUANTITY' => 1, 'PRICE' => $invoiceSum, 'PRODUCT_ID' => 0, 'CUSTOMIZED' => 'Y'))); $ID = $entity->Add($fields); } }
/** * @return array */ public function getPeriod() { if ($this->isEmpty()) { throw new Main\InvalidOperationException('Could not prepare period. Filter is empty.'); } $result = array(); if ($this->periodTypeID === FilterPeriodType::YEAR) { $year = $this->year; $result['START'] = new Date("{$year}-1-1", 'Y-m-d'); $result['END'] = new Date("{$year}-12-31", 'Y-m-d'); } elseif ($this->periodTypeID === FilterPeriodType::QUARTER) { $year = $this->year; $quarter = $this->quarter; $lastMonth = 3 * $quarter; $firstMonth = $lastMonth - 2; $d = new \DateTime("{$year}-{$lastMonth}-01"); $lastDay = $d->format('t'); $result['START'] = new Date("{$year}-{$firstMonth}-01", 'Y-m-d'); $result['END'] = new Date("{$year}-{$lastMonth}-{$lastDay}", 'Y-m-d'); } elseif ($this->periodTypeID === FilterPeriodType::MONTH) { $year = $this->year; $month = $this->month; $d = new \DateTime("{$year}-{$month}-01"); $lastDay = $d->format('t'); $result['START'] = new Date("{$year}-{$month}-01", 'Y-m-d'); $result['END'] = new Date("{$year}-{$month}-{$lastDay}", 'Y-m-d'); } elseif ($this->periodTypeID === FilterPeriodType::CURRENT_MONTH) { $d = new \DateTime(); $year = $d->format('Y'); $month = $d->format('n'); $lastDay = $d->format('t'); $leftBoundary = new \DateTime(); $leftBoundary->setDate($year, $month, 1); $leftBoundary->setTime(0, 0, 0); $rightBoundary = new \DateTime(); $rightBoundary->setDate($year, $month, $lastDay); $rightBoundary->setTime(0, 0, 0); $result['START'] = Date::createFromPhp($leftBoundary); $result['END'] = Date::createFromPhp($rightBoundary); } elseif ($this->periodTypeID === FilterPeriodType::CURRENT_QUARTER) { $d = new \DateTime(); $year = $d->format('Y'); $month = $d->format('n'); $quarter = $month <= 3 ? 1 : ($month <= 6 ? 2 : ($month <= 9 ? 3 : 4)); $lastMonth = 3 * $quarter; $firstMonth = $lastMonth - 2; $d = new \DateTime("{$year}-{$lastMonth}-01"); $lastDay = $d->format('t'); $result['START'] = new Date("{$year}-{$firstMonth}-01", 'Y-m-d'); $result['END'] = new Date("{$year}-{$lastMonth}-{$lastDay}", 'Y-m-d'); } elseif ($this->periodTypeID === FilterPeriodType::LAST_DAYS_90 || $this->periodTypeID === FilterPeriodType::LAST_DAYS_60 || $this->periodTypeID === FilterPeriodType::LAST_DAYS_30 || $this->periodTypeID === FilterPeriodType::LAST_DAYS_7) { $rightBoundary = new \DateTime(); $rightBoundary->setTime(0, 0, 0); $leftBoundary = new \DateTime(); $leftBoundary->setTime(0, 0, 0); $intervalLength = 7; if ($this->periodTypeID === FilterPeriodType::LAST_DAYS_90) { $intervalLength = 90; } elseif ($this->periodTypeID === FilterPeriodType::LAST_DAYS_60) { $intervalLength = 60; } elseif ($this->periodTypeID === FilterPeriodType::LAST_DAYS_30) { $intervalLength = 30; } $interval = new \DateInterval("P{$intervalLength}D"); $interval->invert = 1; $leftBoundary->add($interval); $result['START'] = Date::createFromPhp($leftBoundary); $result['END'] = Date::createFromPhp($rightBoundary); } return $result; }
/** * @return string * @throws \Bitrix\Main\ArgumentException */ public static function checkPeriod($isAgentExec = true) { $isAgentExecInSetting = \COption::GetOptionString("sender", "reiterate_method") !== 'cron'; if ($isAgentExec && !$isAgentExecInSetting || !$isAgentExec && $isAgentExecInSetting) { return ""; } $dateTodayPhp = new \DateTime(); $datetimeToday = Type\DateTime::createFromPhp(clone $dateTodayPhp); $dateToday = clone $dateTodayPhp; $dateToday = Type\Date::createFromPhp($dateToday->setTime(0, 0, 0)); $dateTomorrow = clone $dateTodayPhp; $dateTomorrow = Type\Date::createFromPhp($dateTomorrow->setTime(0, 0, 0))->add('1 DAY'); $arDateFilter = array($dateToday, $dateTomorrow); $chainDb = MailingChainTable::getList(array('select' => array('ID', 'LAST_EXECUTED', 'POSTING_ID', 'DAYS_OF_MONTH', 'DAYS_OF_WEEK', 'TIMES_OF_DAY'), 'filter' => array('=REITERATE' => 'Y', '=MAILING.ACTIVE' => 'Y', 'STATUS' => MailingChainTable::STATUS_WAIT))); while ($arMailingChain = $chainDb->fetch()) { $lastExecuted = $arMailingChain['LAST_EXECUTED']; /* @var \Bitrix\Main\Type\DateTime $lastExecuted*/ if ($lastExecuted && $lastExecuted->getTimestamp() >= $dateToday->getTimestamp()) { continue; } $timeOfExecute = static::getDateExecute($dateTodayPhp, $arMailingChain["DAYS_OF_MONTH"], $arMailingChain["DAYS_OF_WEEK"], $arMailingChain["TIMES_OF_DAY"]); if ($timeOfExecute) { $arUpdateMailChain = array('LAST_EXECUTED' => $datetimeToday); $postingDb = PostingTable::getList(array('select' => array('ID'), 'filter' => array('=MAILING_CHAIN_ID' => $arMailingChain['ID'], '><DATE_CREATE' => $arDateFilter))); $arPosting = $postingDb->fetch(); if (!$arPosting) { $postingId = MailingChainTable::initPosting($arMailingChain['ID']); } else { $postingId = $arPosting['ID']; $arUpdateMailChain['POSTING_ID'] = $postingId; PostingTable::initGroupRecipients($postingId); } if ($postingId) { $arUpdateMailChain['STATUS'] = MailingChainTable::STATUS_SEND; $arUpdateMailChain['AUTO_SEND_TIME'] = Type\DateTime::createFromPhp($timeOfExecute); } MailingChainTable::update(array('ID' => $arMailingChain['ID']), $arUpdateMailChain); } } return static::getAgentNamePeriod(); }
} $rsList = new CDBResult(); $rsList->InitFromArray($orders); $rsList->NavStart(20); $data = new CAdminResult($rsList, $tableID); $data->NavStart(); $adminList->NavText($data->GetNavPrint(Loc::getMessage("PAGES"), false)); $adminList->AddHeaders(array(array("id" => "provider", "content" => Loc::getMessage("SCALE_ORDER_PROVIDER"), "sort" => "provider", "default" => true), array("id" => "order_id", "content" => Loc::getMessage("SCALE_ORDER_ID"), "sort" => "order_id", "default" => true), array("id" => "status", "content" => Loc::getMessage("SCALE_ORDER_STATUS"), "sort" => "status", "default" => true), array("id" => "mtime", "content" => Loc::getMessage("SCALE_ORDER_MTIME"), "sort" => "mtime", "default" => true), array("id" => "error", "content" => Loc::getMessage("SCALE_ORDER_ERROR"), "default" => false), array("id" => "message", "content" => Loc::getMessage("SCALE_ORDER_MESSAGE"), "default" => true))); while ($order = $data->Fetch()) { $provider = htmlspecialcharsbx($order["provider"]); $order_id = htmlspecialcharsbx($order["order_id"]); $row =& $adminList->AddRow($provider . "::" . $order_id, $order, "?provider=" . $provider . "&order_id=" . $order_id . "&lang=" . LANGUAGE_ID, Loc::getMessage("SCALE_ORDER_EDIT")); $row->AddViewField("provider", $order["provider"]); $row->AddViewField("order_id", $order["order_id"]); $langStatuses = array("finished" => Loc::getMessage("SCALE_ORDER_STATUS_FINISHED"), "complete" => Loc::getMessage("SCALE_ORDER_STATUS_COMPLETED"), "error" => Loc::getMessage("SCALE_ORDER_STATUS_ERROR"), "in_progress" => Loc::getMessage("SCALE_ORDER_STATUS_INPROCESS")); $status = isset($langStatuses[$order["status"]]) ? $langStatuses[$order["status"]] : $order["status"]; $row->AddViewField("status", $status); $date = \Bitrix\Main\Type\Date::createFromTimestamp($order["mtime"]); $row->AddViewField("mtime", $date->toString()); $row->AddViewField("error", $order["error"]); $row->AddViewField("message", $order["message"]); $arActions = array(); if ($order["status"] == "finished") { $arActions[] = array("ICON" => "edit", "TEXT" => Loc::getMessage("SCALE_ORDER_ADD_TO_PULL"), "ACTION" => $adminList->ActionDoGroup($provider . "::" . $order_id, "add_to_pull")); } $row->AddActions($arActions); } $adminList->CheckListMode(); require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_admin_after.php"; $adminList->DisplayList(); require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/epilog_admin.php";
/** * Recounts involvement and activity score for selected day * @param Type\Date $day */ protected static function recountDailyInvolvement(Type\Date $day = null) { // should be called only after recount*ActiveUsers // because we need ACTIVE_USERS already set up $departments = array(); if ($day === null) { $day = new Type\Date(); } // users' departments $usersDepartments = static::getUsersDepartments(); // add "company" for each user foreach ($usersDepartments as &$_usersDepartments) { $_usersDepartments[] = 0; } // count $result = UserDayTable::getList(array('filter' => array('=DAY' => \ConvertTimeStamp($day->getTimestamp(), 'SHORT')))); while ($row = $result->fetch()) { $invCount = 0; if (!isset($usersDepartments[$row['USER_ID']])) { // skip deleted users continue; } foreach ($row as $k => $v) { // skip non-activity fields if ($k == 'USER_ID' || $k == 'DAY') { continue; } // initialize foreach ($usersDepartments[$row['USER_ID']] as $deptId) { if (!isset($departments[$deptId][$k])) { $departments[$deptId][$k] = 0; } } // summarize foreach ($usersDepartments[$row['USER_ID']] as $deptId) { $departments[$deptId][$k] += $v; } // increment involvement count if ($k != 'TOTAL' && $v > 0) { ++$invCount; } } // check involvement if ($invCount >= static::INVOLVEMENT_SERVICE_COUNT) { foreach ($usersDepartments[$row['USER_ID']] as $deptId) { if (!isset($departments[$deptId]['INVOLVED'])) { $departments[$deptId]['INVOLVED'] = 0; } ++$departments[$deptId]['INVOLVED']; } } } // normalize involved count foreach ($departments as &$_department) { if (!isset($_department['INVOLVED'])) { $_department['INVOLVED'] = 0; } } // update db foreach ($departments as $deptId => $activity) { $activity['INVOLVEMENT'] = new SqlExpression('CASE WHEN ?# > 0 THEN ROUND((?i / ?# * 100), 0) ELSE 0 END', 'ACTIVE_USERS', $activity['INVOLVED'], 'ACTIVE_USERS'); unset($activity['INVOLVED']); DepartmentDayTable::update(array('DEPT_ID' => $deptId, 'DAY' => $day), $activity); } }
/** * Returns site traffic capacity * * @param string $id Site ID. * @return array */ public static function getSiteCapacity($id) { $cache = new \CPHPCache(); if ($cache->initCache(time() - strtotime('today'), 'abtest_site_capacity', '/abtest')) { $capacity = $cache->getVars(); } else { if (Loader::includeModule('conversion')) { if ($conversionRates = Conversion\RateManager::getTypes(array('ACTIVE' => true))) { $baseRate = array_slice($conversionRates, 0, 1, true); $reportContext = new Conversion\ReportContext(); $from = new \DateTime('first day of last month'); $to = new \DateTime('today'); $capacity = array(); $res = \Bitrix\Main\SiteTable::getList(); while ($site = $res->fetch()) { $lid = $site['LID']; $reportContext->setAttribute('conversion_site', $lid); $rateData = reset($reportContext->getRatesDeprecated($baseRate, array('>=DAY' => Type\Date::createFromPhp($from), '<=DAY' => Type\Date::createFromPhp($to)), null)); $reportContext->unsetAttribute('conversion_site', $lid); $rate = $rateData['RATE']; $hits = $rateData['DENOMINATOR']; $daily = floor($hits / (date_diff($from, $to)->format('%a') + 1)); $min = $rate > 0 && $rate < 1 ? ceil(16 * (1 / $rate - 1) / pow(MIN_EFFECT, 2)) : 0; $est = $daily ? $min / ($daily / 2) : 0; $capacity[$lid] = array('daily' => $daily, 'min' => $min, 'est' => $est); } $cache->startDataCache(strtotime('tomorrow') - time()); $cache->endDataCache($capacity); } } } $result = array(); foreach ((array) $id as $lid) { $result[$lid] = isset($capacity[$lid]) ? $capacity[$lid] : array('min' => 0, 'est' => 0); } return is_array($id) ? $result : reset($result); }
public static function parseDateString($str) { if ($str === '') { return null; } try { $date = new Date($str, Date::convertFormatToPhp(FORMAT_DATE)); } catch (Main\ObjectException $e) { try { $date = new DateTime($str, Date::convertFormatToPhp(FORMAT_DATETIME)); $date->setTime(0, 0, 0); } catch (Main\ObjectException $e) { return null; } } return $date; }
public static function getMissedPeriods(array $stats, $dateStart, $dateFinish) { $missedPeriods = array(); $datePrevoius = false; $checkDate = new Date($dateStart); $dateCurrent = new Date($dateStart); $dateFinish = new Date($dateFinish); while ($dateCurrent->getTimestamp() <= $dateFinish->getTimestamp()) { if (!array_key_exists($dateCurrent->toString(), $stats)) { if (!$datePrevoius || $dateCurrent->getTimestamp() >= $checkDate->getTimestamp()) { $missedPeriods[] = array($dateCurrent->toString(), $dateCurrent->toString()); $checkDate = new Date($dateCurrent->toString()); $checkDate->add("+" . YandexDirectLive::MAX_STAT_DAYS_DELTA . " days"); $datePrevoius = true; } else { $missedPeriods[count($missedPeriods) - 1][1] = $dateCurrent->toString(); } } else { $datePrevoius = false; } $dateCurrent->add("+1 days"); } return $missedPeriods; }
{ BX(prefix+'_'+i+'_1_'+r).style.display = 'none'; } } } </script> <? if($bShowStats) { $tabControl->BeginNextTab(); CJSCore::Init(array('amcharts_serial')); $dateStart = new Main\Type\Date(); $dateStart->add("-".Engine\YandexDirectLive::MAX_STAT_DAYS_DELTA." days"); $dateFinish = new Main\Type\Date(); $statsData = Adv\YandexStatTable::getBannerStat( $banner['ID'], $dateStart, $dateFinish ); $gaps = Adv\YandexStatTable::getMissedPeriods($statsData, $dateStart, $dateFinish); $graphData = array(); $currency = Loc::getMessage('SEO_YANDEX_STATS_GRAPH_AXIS_CURRENCY');
function DateFormatToPHP($format) { static $cache = array(); if (!isset($cache[$format])) { $cache[$format] = Main\Type\Date::convertFormatToPhp($format); } return $cache[$format]; }