public function isOutOfDate()
 {
     if ($this->isOutOfDate === null) {
         $srcLastChanged = UserFieldHistory::getLastChangeTime($this->srcEntityTypeID);
         $dstLastChanged = UserFieldHistory::getLastChangeTime($this->dstEntityTypeID);
         $lastChanged = null;
         if ($srcLastChanged !== null && $dstLastChanged !== null) {
             $lastChanged = $srcLastChanged->getTimestamp() > $dstLastChanged->getTimestamp() ? $srcLastChanged : $dstLastChanged;
         } elseif ($srcLastChanged !== null || $dstLastChanged !== null) {
             $lastChanged = $srcLastChanged !== null ? $srcLastChanged : $dstLastChanged;
         }
         $this->isOutOfDate = $lastChanged !== null && $lastChanged->getTimestamp() > $this->time->getTimestamp();
     }
     return $this->isOutOfDate;
 }
Beispiel #2
0
 /**
  * Возвращает дату в формате прошедшего времени. Например, "15 минут назад", "2 часа назад", "вчера", ...
  * @param \Bitrix\Main\Type\DateTime $datetime
  * @return string
  */
 public static function passed(\Bitrix\Main\Type\DateTime $datetime, $formatDateTime = 'd.m.Y H:i', $formatDay = 'H:i')
 {
     $time = $datetime->getTimestamp();
     $diff = time() - $time;
     //
     if (self::passedYesterday($time, $output)) {
         return $output;
     } elseif ($diff < 60) {
         return "только что";
     } elseif ($diff < 60 * 60) {
         return self::passedMinutes(0, $diff);
     } elseif ($diff < 60 * 60 * 24) {
         return self::passedHours(0, $diff);
     } else {
         return $datetime->format($formatDateTime);
     }
 }
 protected static function modifyFromDb($data)
 {
     $result = array();
     foreach ($data as $name => $value) {
         if ($name == 'date') {
             if ($value instanceof DateTime) {
                 $value = new \DateTime();
                 $value->setTimestamp($value->getTimestamp());
             } else {
                 $value = new \DateTime($value);
             }
         }
         if (in_array($name, array('originalData', 'updateData'))) {
             $value = \WS\Migrations\jsonToArray($value);
         }
         $result[$name] = $value;
     }
     return $result;
 }
 /**
  * Save coupons applyed info.
  *
  * @param array $coupons				Coupons list.
  * @param int $userId					User id.
  * @param Main\Type\DateTime $currentTime	Current datetime.
  * @return array|bool
  */
 public static function saveApplied($coupons, $userId, Main\Type\DateTime $currentTime)
 {
     $currentTimestamp = $currentTime->getTimestamp();
     if ($userId === null || (int) $userId == 0) {
         return false;
     }
     $userId = (int) $userId;
     if (!is_array($coupons)) {
         $coupons = array($coupons);
     }
     if (empty($coupons)) {
         return false;
     }
     Main\Type\Collection::normalizeArrayValuesByInt($coupons);
     if (empty($coupons)) {
         return false;
     }
     $deactivateCoupons = array();
     $incrementalCoupons = array();
     $limitedCoupons = array();
     $couponIterator = self::getList(array('select' => array('ID', 'COUPON', 'DISCOUNT_ID', 'TYPE', 'ACTIVE', 'MAX_USE', 'USE_COUNT', 'USER_ID', 'ACTIVE_TO', 'ACTIVE_FROM', 'DISCOUNT_ACTIVE' => 'DISCOUNT.ACTIVE', 'DISCOUNT_ACTIVE_FROM' => 'DISCOUNT.ACTIVE_FROM', 'DISCOUNT_ACTIVE_TO' => 'DISCOUNT.ACTIVE_TO'), 'filter' => array('@ID' => $coupons, '=ACTIVE' => 'Y'), 'order' => array('ID' => 'ASC')));
     while ($existCoupon = $couponIterator->fetch()) {
         if ($existCoupon['DISCOUNT_ACTIVE'] != 'Y') {
             continue;
         }
         if ($existCoupon['DISCOUNT_ACTIVE_FROM'] instanceof Main\Type\DateTime && $existCoupon['DISCOUNT_ACTIVE_FROM']->getTimestamp() > $currentTimestamp || $existCoupon['DISCOUNT_ACTIVE_TO'] instanceof Main\Type\DateTime && $existCoupon['DISCOUNT_ACTIVE_TO']->getTimestamp() < $currentTimestamp) {
             continue;
         }
         $existCoupon['USER_ID'] = (int) $existCoupon['USER_ID'];
         if ($existCoupon['USER_ID'] > 0 && $existCoupon['USER_ID'] != $userId) {
             continue;
         }
         if ($existCoupon['ACTIVE_FROM'] instanceof Main\Type\DateTime && $existCoupon['ACTIVE_FROM']->getTimestamp() > $currentTimestamp || $existCoupon['ACTIVE_TO'] instanceof Main\Type\DateTime && $existCoupon['ACTIVE_TO']->getTimestamp() < $currentTimestamp) {
             continue;
         }
         if ($existCoupon['TYPE'] == self::TYPE_BASKET_ROW || $existCoupon['TYPE'] == self::TYPE_ONE_ORDER) {
             $deactivateCoupons[$existCoupon['COUPON']] = $existCoupon['ID'];
         } elseif ($existCoupon['TYPE'] == self::TYPE_MULTI_ORDER) {
             $existCoupon['MAX_USE'] = (int) $existCoupon['MAX_USE'];
             $existCoupon['USE_COUNT'] = (int) $existCoupon['USE_COUNT'];
             if ($existCoupon['MAX_USE'] > 0 && $existCoupon['USE_COUNT'] >= $existCoupon['MAX_USE']) {
                 continue;
             }
             if ($existCoupon['MAX_USE'] > 0 && $existCoupon['USE_COUNT'] >= $existCoupon['MAX_USE'] - 1) {
                 $limitedCoupons[$existCoupon['COUPON']] = $existCoupon['ID'];
             } else {
                 $incrementalCoupons[$existCoupon['COUPON']] = $existCoupon['ID'];
             }
         }
     }
     unset($existCoupon, $couponIterator, $coupons);
     if (!empty($deactivateCoupons) || !empty($limitedCoupons) || !empty($incrementalCoupons)) {
         $conn = Application::getConnection();
         $helper = $conn->getSqlHelper();
         $tableName = $helper->quote(self::getTableName());
         if (!empty($deactivateCoupons)) {
             $conn->queryExecute('update ' . $tableName . ' set ' . $helper->quote('ACTIVE') . ' = \'N\', ' . $helper->quote('DATE_APPLY') . ' = ' . $helper->getCurrentDateTimeFunction() . ' where ' . $helper->quote('ID') . ' in (' . implode(',', $deactivateCoupons) . ')');
         }
         if (!empty($incrementalCoupons)) {
             $conn->queryExecute('update ' . $tableName . ' set ' . $helper->quote('DATE_APPLY') . ' = ' . $helper->getCurrentDateTimeFunction() . ', ' . $helper->quote('USE_COUNT') . ' = ' . $helper->quote('USE_COUNT') . ' + 1' . ' where ' . $helper->quote('ID') . ' in (' . implode(',', $incrementalCoupons) . ')');
         }
         if (!empty($limitedCoupons)) {
             $conn->queryExecute('update ' . $tableName . ' set ' . $helper->quote('DATE_APPLY') . ' = ' . $helper->getCurrentDateTimeFunction() . ', ' . $helper->quote('ACTIVE') . ' = \'N\', ' . $helper->quote('USE_COUNT') . ' = ' . $helper->quote('USE_COUNT') . ' + 1' . ' where ' . $helper->quote('ID') . ' in (' . implode(',', $limitedCoupons) . ')');
         }
         unset($tableName, $helper);
     }
     return array('DEACTIVATE' => $deactivateCoupons, 'LIMITED' => $limitedCoupons, 'INCREMENT' => $incrementalCoupons);
 }
 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();
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', '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'] : '';
     if ($stageID === '') {
         return false;
     }
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     $startDate = self::parseDateString(isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '');
     if ($startDate === null) {
         $startDate = new Date();
     }
     $endDate = self::parseDateString(isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '');
     if ($endDate === null) {
         $endDate = new Date('9999-12-31', 'Y-m-d');
     }
     $time = isset($options['TIME']) ? $options['TIME'] : null;
     if ($time === null) {
         $time = new DateTime();
     }
     $month = (int) $time->format('m');
     $quarter = $month <= 3 ? 1 : ($month <= 6 ? 2 : ($month <= 9 ? 3 : 4));
     $year = (int) $time->format('Y');
     $startMonth = (int) $startDate->format('m');
     $startQuarter = $startMonth <= 3 ? 1 : ($startMonth <= 6 ? 2 : ($startMonth <= 9 ? 3 : 4));
     $startYear = (int) $startDate->format('Y');
     $endMonth = (int) $endDate->format('m');
     $endQuarter = $endMonth <= 3 ? 1 : ($endMonth <= 6 ? 2 : ($endMonth <= 9 ? 3 : 4));
     $endYear = (int) $endDate->format('Y');
     $semanticID = \CCrmDeal::GetSemanticID($stageID);
     $isNew = isset($options['IS_NEW']) ? (bool) $options['IS_NEW'] : false;
     $typeID = PhaseSemantics::isFinal($semanticID) ? HistoryEntryType::FINALIZATION : ($isNew ? HistoryEntryType::CREATION : HistoryEntryType::MODIFICATION);
     $date = Date::createFromTimestamp($time->getTimestamp());
     $isLost = PhaseSemantics::isLost($semanticID);
     $latest = self::getLatest($ownerID);
     if ($latest['STAGE_ID'] === $stageID) {
         return false;
     }
     $result = DealStageHistoryTable::add(array('TYPE_ID' => $typeID, 'OWNER_ID' => $ownerID, 'CREATED_TIME' => $time, 'CREATED_DATE' => $date, 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'PERIOD_YEAR' => $year, 'PERIOD_QUARTER' => $quarter, 'PERIOD_MONTH' => $month, 'START_PERIOD_YEAR' => $startYear, 'START_PERIOD_QUARTER' => $startQuarter, 'START_PERIOD_MONTH' => $startMonth, 'END_PERIOD_YEAR' => $endYear, 'END_PERIOD_QUARTER' => $endQuarter, 'END_PERIOD_MONTH' => $endMonth, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_ID' => $stageID, 'STAGE_SEMANTIC_ID' => $semanticID, 'IS_LOST' => $isLost ? 'Y' : 'N'));
     if ($result->isSuccess() && $result->getId() > 0 && is_array($latest) && (int) $latest['TYPE_ID'] === HistoryEntryType::FINALIZATION) {
         DealStageHistoryTable::delete($latest['ID']);
     }
     return true;
 }
Beispiel #6
0
 protected static function getHourlyCompanyActivitySince(Type\DateTime $hour = null)
 {
     $query = new Entity\Query('Bitrix\\Intranet\\UStat\\UserHourTable');
     // set all activity columns
     $uStatFields = UserHourTable::getEntity()->getFields();
     foreach ($uStatFields as $uStatField) {
         if ($uStatField instanceof Entity\ScalarField && !$uStatField->isPrimary()) {
             $query->addSelect(new Entity\ExpressionField($uStatField->getName() . '_SUM', 'SUM(%s)', $uStatField->getName()));
         }
     }
     // add & automatically group by hour
     $query->addSelect('HOUR');
     // add filter by date
     if ($hour !== null) {
         $query->setFilter(array('>=HOUR' => \ConvertTimeStamp($hour->getTimestamp(), 'FULL')));
     }
     // collect activity
     $activity = array();
     $result = $query->exec();
     while ($row = $result->fetch()) {
         foreach ($row as $k => $v) {
             if (substr($k, -4) === '_SUM') {
                 $row[substr($k, 0, -4)] = $v;
                 unset($row[$k]);
             }
         }
         $activity[] = $row;
     }
     return $activity;
 }
Beispiel #7
0
    if ($interval == 'hour') {
        // first, add hour to axis title
        $tmpDate->add('+ 1 ' . $interval);
        // adopt to user time
        $tmpTZTimestamp = $tmpDate->getTimestamp() + CTimeZone::GetOffset();
    }
    $data[$key] = array('date' => FormatDate($axisDateFormat, $tmpTZTimestamp), 'cursor_date' => nl2br(FormatDate($axisCursorDateFormat, $tmpTZTimestamp)));
    if ($interval == 'hour') {
        // remove axis fake hour
        $tmpDate->add('- 1 ' . $interval);
    }
    if ($interval == 'day') {
        // add customday property
        $data[$key]['custom_day'] = $tmpDate->format($dateFormat);
    }
    if ($tmpDate->getTimestamp() < $nowDate->getTimestamp()) {
        $data[$key]['activity'] = 0;
        $data[$key]['company_activity'] = 0;
        $data[$key]['department_activity'] = 0;
        $data[$key]['self_activity'] = 0;
    }
    $tmpDate->add('+ 1 ' . $interval);
}
if ($interval == 'hour') {
    // replace last 00:00 to 24:00
    $data[$key]['date'] = '24';
    $data[$key]['cursor_date'] = str_replace('00:00', '24:00', $data[$key]['cursor_date']);
}
// fill data
foreach ($rawData['data'] as $k => $v) {
    $data[$k]['activity'] = $v[$sectionField];
Beispiel #8
0
 /**
  * Return information coupon.
  *
  * @param string $coupon			Coupon for search.
  * @param bool $checkCoupon			Check coupon data.
  * @return array|false
  */
 public static function getData($coupon, $checkCoupon = true)
 {
     $currentTime = new Type\DateTime();
     $currentTimestamp = $currentTime->getTimestamp();
     if (self::$onlySaleDiscount === null) {
         self::initUseDiscount();
     }
     $coupon = trim((string) $coupon);
     if ($coupon === '') {
         return false;
     }
     $checkCoupon = $checkCoupon === true;
     $result = array('COUPON' => $coupon, 'MODE' => self::COUPON_MODE_SIMPLE, 'STATUS' => self::STATUS_NOT_FOUND, 'CHECK_CODE' => self::COUPON_CHECK_NOT_FOUND, 'MODULE' => '', 'ID' => 0, 'DISCOUNT_ID' => 0, 'DISCOUNT_NAME' => '', 'TYPE' => Internals\DiscountCouponTable::TYPE_UNKNOWN, 'ACTIVE' => '', 'USER_INFO' => array(), 'SAVED' => 'N');
     $resultKeyList = array('ID', 'COUPON', 'DISCOUNT_ID', 'TYPE', 'ACTIVE', 'DISCOUNT_NAME', 'DISCOUNT_ACTIVE', 'DISCOUNT_ACTIVE_FROM', 'DISCOUNT_ACTIVE_TO');
     $couponIterator = Internals\DiscountCouponTable::getList(array('select' => array('ID', 'COUPON', 'DISCOUNT_ID', 'TYPE', 'ACTIVE', 'USER_ID', 'MAX_USE', 'USE_COUNT', 'ACTIVE_FROM', 'ACTIVE_TO', 'DISCOUNT_NAME' => 'DISCOUNT.NAME', 'DISCOUNT_ACTIVE' => 'DISCOUNT.ACTIVE', 'DISCOUNT_ACTIVE_FROM' => 'DISCOUNT.ACTIVE_FROM', 'DISCOUNT_ACTIVE_TO' => 'DISCOUNT.ACTIVE_TO'), 'filter' => array('=COUPON' => $coupon)));
     if ($existCoupon = $couponIterator->fetch()) {
         $result['MODE'] = self::COUPON_MODE_FULL;
         $result['MODULE'] = 'sale';
         $checkCode = self::checkBaseData($existCoupon, self::COUPON_CHECK_OK);
         foreach ($resultKeyList as &$resultKey) {
             $result[$resultKey] = $existCoupon[$resultKey];
         }
         unset($resultKey);
         if ($checkCoupon) {
             $checkCode = self::checkFullData($existCoupon, $result['MODE'], $checkCode, $currentTimestamp);
             self::fillUserInfo($result, $existCoupon, $checkCode);
         }
         $result['STATUS'] = $checkCode == self::COUPON_CHECK_OK ? self::STATUS_ENTERED : self::STATUS_FREEZE;
         $result['CHECK_CODE'] = $checkCode;
         unset($checkCode);
     } elseif (!self::$onlySaleDiscount && !empty(self::$couponProviders)) {
         foreach (self::$couponProviders as &$provider) {
             $existCoupon = call_user_func_array($provider['getData'], array($coupon));
             if (!empty($existCoupon) && is_array($existCoupon)) {
                 $result['MODE'] = $provider['mode'];
                 $result['MODULE'] = $provider['module'];
                 $checkCode = self::checkBaseData($existCoupon, self::COUPON_CHECK_OK);
                 foreach ($resultKeyList as &$resultKey) {
                     $result[$resultKey] = $existCoupon[$resultKey];
                 }
                 unset($resultKey);
                 if ($checkCoupon) {
                     $checkCode = self::checkFullData($existCoupon, $result['MODE'], $checkCode, $currentTimestamp);
                     self::fillUserInfo($result, $existCoupon, $checkCode);
                 }
                 $result['STATUS'] = $checkCode == self::COUPON_CHECK_OK ? self::STATUS_ENTERED : self::STATUS_FREEZE;
                 $result['CHECK_CODE'] = $checkCode;
                 unset($checkCode);
                 break;
             }
         }
         unset($provider);
     }
     return $result;
 }
Beispiel #9
0
 /**
  * Sets the latest time for the Last-Modified header field.
  *
  * @param Type\DateTime $time
  */
 public function setLastModified(Type\DateTime $time)
 {
     if ($this->lastModified === null || $time->getTimestamp() > $this->lastModified->getTimestamp()) {
         $this->lastModified = $time;
     }
 }
Beispiel #10
0
 /**
  * Set coupons list.
  *
  * @param array $couponsList			Coupons list.
  * @param bool $checkCoupons			Find coupons.
  * @return void
  */
 protected static function setCoupons($couponsList, $checkCoupons = true)
 {
     if (empty($couponsList) || !is_array($couponsList)) {
         return;
     }
     $checkCoupons = $checkCoupons !== false;
     if ($checkCoupons) {
         foreach ($couponsList as &$coupon) {
             $coupon = trim((string) $coupon);
             if ($coupon == '') {
                 continue;
             }
             $couponData = self::getData($coupon);
             if (!isset(self::$coupons[$couponData['COUPON']])) {
                 $couponData['SORT'] = self::$couponIndex;
                 self::createApplyFields($couponData);
                 self::$coupons[$couponData['COUPON']] = $couponData;
                 self::$couponIndex++;
             }
         }
         unset($couponData, $coupon);
     } else {
         $currentTime = new Main\Type\DateTime();
         $currentTimestamp = $currentTime->getTimestamp();
         unset($currentTime);
         foreach ($couponsList as $coupon) {
             if (empty($coupon) || !is_array($coupon)) {
                 continue;
             }
             $checkCode = self::checkBaseData($coupon, self::COUPON_CHECK_OK);
             $checkCode = self::checkFullData($coupon, $coupon['MODE'], $checkCode, $currentTimestamp);
             $coupon['STATUS'] = $checkCode == self::COUPON_CHECK_OK ? self::STATUS_ENTERED : self::STATUS_FREEZE;
             $coupon['CHECK_CODE'] = $checkCode;
             unset($checkCode);
             if (!isset(self::$coupons[$coupon['COUPON']])) {
                 $coupon['SORT'] = self::$couponIndex;
                 self::createApplyFields($coupon);
                 self::$coupons[$coupon['COUPON']] = $coupon;
                 self::$couponIndex++;
             }
         }
         unset($coupon, $currentTimestamp);
     }
 }
Beispiel #11
0
 /**
  * Tells if external link is expired.
  * @return bool
  */
 public function isExpired()
 {
     $now = new DateTime();
     return $this->deathTime && $now->getTimestamp() > $this->deathTime->getTimestamp();
 }
Beispiel #12
0
 /**
  * Adds new version to file.
  *
  * The method may joins version with last version.
  *
  * @param array $file Structure like $_FILES.
  * @param int $createdBy Id of user.
  * @param bool $disableJoin If set false the method attempts to join version with last version (@see \Bitrix\Disk\File::SECONDS_TO_JOIN_VERSION).
  * @return Version|null
  * @throws \Bitrix\Main\SystemException
  */
 public function addVersion(array $file, $createdBy, $disableJoin = false)
 {
     $this->errorCollection->clear();
     $now = new DateTime();
     $needToJoin = false;
     if (!$disableJoin && $this->updateTime && $this->updatedBy == $createdBy) {
         $updateTimestamp = $this->updateTime->getTimestamp();
         if ($now->getTimestamp() - $updateTimestamp < self::SECONDS_TO_JOIN_VERSION) {
             $needToJoin = true;
         }
     }
     if (!$this->updateContent($file, $createdBy)) {
         return null;
     }
     if ($needToJoin) {
         $lastVersion = $this->getLastVersion();
         if ($lastVersion) {
             if (!$lastVersion->joinData(array_merge(array('CREATE_TIME' => $now), $this->getHistoricalData()))) {
                 $this->errorCollection->add($lastVersion->getErrors());
                 return null;
             }
             if ($this->prevFileId && $this->prevFileId != $this->fileId) {
                 CFile::delete($this->prevFileId);
             }
             return $lastVersion;
         }
     }
     $versionModel = Version::add(array_merge(array('OBJECT_ID' => $this->id, 'FILE_ID' => $this->fileId, 'NAME' => $this->name, 'CREATED_BY' => $createdBy), $this->getHistoricalData()), $this->errorCollection);
     if (!$versionModel) {
         return null;
     }
     $valueVersionUf = FileUserType::NEW_FILE_PREFIX . $versionModel->getId();
     /** @var User $createUser */
     $createUser = User::loadById($createdBy);
     if (!$createUser) {
         //skip
         return $versionModel;
     }
     $text = Loc::getMessage('DISK_FILE_MODEL_UPLOAD_NEW_VERSION_IN_COMMENT_M');
     if ($createUser->getPersonalGender() == 'F') {
         $text = Loc::getMessage('DISK_FILE_MODEL_UPLOAD_NEW_VERSION_IN_COMMENT_F');
     }
     foreach ($this->getAttachedObjects() as $attache) {
         AttachedObject::storeDataByObjectId($this->getId(), array('IS_EDITABLE' => $attache->isEditable(), 'ALLOW_EDIT' => $attache->getAllowEdit()));
         $attache->getConnector()->addComment($createdBy, array('text' => $text, 'versionId' => $valueVersionUf));
         AttachedObject::storeDataByObjectId($this->getId(), null);
     }
     unset($attache);
     return $versionModel;
 }