/** * Returns the next active announcement. * * @param string $timeInAdvance * * @return AnnouncementModel */ public function getNextAnnouncement($timeInAdvance = '0') { $time = DateTimeHelper::currentUTCDateTime(); $time->modify('+' . $timeInAdvance); $announcementRecord = craft()->db->createCommand()->select('*')->from('maintenance_announcements')->where(array('and', array('or', 'blockSite = 1', 'blockCp = 1'), 'startDate <= :time', array('or', 'endDate >= :now', 'endDate IS NULL')), array(':now' => DateTimeHelper::formatTimeForDb(), ':time' => DateTimeHelper::formatTimeForDb($time)))->order('startDate desc')->queryRow(); if ($announcementRecord) { return Maintenance_AnnouncementModel::populateModel($announcementRecord); } }
/** * Logs a new deprecation error. * * @param string $key * @param string $message * * @return bool */ public function log($key, $message) { $log = new DeprecationErrorModel(); $log->key = $key; $log->message = $message; $log->lastOccurrence = DateTimeHelper::currentTimeForDb(); $log->template = craft()->request->isSiteRequest() ? craft()->templates->getRenderingTemplate() : null; // Everything else requires the stack trace $this->_populateLogWithStackTraceData($log); // Don't log the same key/fingerprint twice in the same request if (!isset($this->_fingerprints[$log->key]) || !in_array($log->fingerprint, $this->_fingerprints[$log->key])) { craft()->db->createCommand()->insertOrUpdate(static::$_tableName, array('key' => $log->key, 'fingerprint' => $log->fingerprint), array('lastOccurrence' => DateTimeHelper::formatTimeForDb($log->lastOccurrence), 'file' => $log->file, 'line' => $log->line, 'class' => $log->class, 'method' => $log->method, 'template' => $log->template, 'templateLine' => $log->templateLine, 'message' => $log->message, 'traces' => JsonHelper::encode($log->traces))); $this->_fingerprints[$key][] = $log->fingerprint; } return true; }
/** * Deletes any pending users that have shown zero sense of urgency and are just taking up space. * * This method will check the * [purgePendingUsersDuration](http://buildwithcraft.com/docs/config-settings#purgePendingUsersDuration) config * setting, and if it is set to a valid duration, it will delete any user accounts that were created that duration * ago, and have still not activated their account. * * @return null */ public function purgeExpiredPendingUsers() { if (($duration = craft()->config->get('purgePendingUsersDuration')) !== false) { $interval = new DateInterval($duration); $expire = DateTimeHelper::currentUTCDateTime(); $pastTimeStamp = $expire->sub($interval)->getTimestamp(); $pastTime = DateTimeHelper::formatTimeForDb($pastTimeStamp); $ids = craft()->db->createCommand()->select('id')->from('users')->where('pending=1 AND verificationCodeIssuedDate < :pastTime', array(':pastTime' => $pastTime))->queryColumn(); $affectedRows = craft()->db->createCommand()->delete('elements', array('in', 'id', $ids)); if ($affectedRows > 0) { Craft::log('Just deleted ' . $affectedRows . ' pending users from the users table, because the were more than ' . $duration . ' old', LogLevel::Info, true); } } }
/** * Takes an attribute's config and value and "normalizes" them either for saving to db or sending across a web * service. * * @param mixed $value * @param bool $jsonEncodeArrays * * @return int|mixed|null|string */ public static function packageAttributeValue($value, $jsonEncodeArrays = false) { if ($value instanceof \DateTime) { return DateTimeHelper::formatTimeForDb($value->getTimestamp()); } if ($value instanceof BaseModel) { $attributes = $value->getAttributes(null, true); if ($value instanceof ElementCriteriaModel) { $attributes['__criteria__'] = $value->getElementType()->getClassHandle(); } else { $attributes['__model__'] = get_class($value); } $value = $attributes; } if (is_array($value)) { // Flatten each of its keys foreach ($value as $key => $val) { $value[$key] = static::packageAttributeValue($val); } if ($jsonEncodeArrays) { return JsonHelper::encode($value); } else { return $value; } } if (is_bool($value)) { return $value ? 1 : 0; } return $value; }
/** * Modifies an element query targeting elements of this type. * * @param DbCommand $query * @param ElementCriteriaModel $criteria * @return mixed */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect('venti.startDate, venti.endDate, venti.allDay, venti.isrepeat, venti.eid, venti.eventid, venti.repeat, venti.rRule, venti.summary, venti.locale, entries.postDate, entries.expiryDate')->leftJoin('venti_events venti', 'venti.eventid = elements.id')->leftJoin('entries entries', 'entries.id = eventid')->group('venti.startDate'); if ($criteria->locale) { $query->andWhere(DbHelper::parseParam('venti.locale', $criteria->locale, $query->params)); } if ($criteria->startDate) { $query->andWhere(DbHelper::parseDateParam('venti.startDate', $criteria->startDate, $query->params)); } if ($criteria->id) { $query->andWhere(DbHelper::parseParam('venti.eventid', $criteria->eventid, $query->params)); } if ($criteria->eventid) { $query->andWhere(DbHelper::parseParam('venti.eventid', $criteria->eventid, $query->params)); } if ($criteria->endDate) { $query->andWhere(DbHelper::parseDateParam('venti.endDate', $criteria->endDate, $query->params)); } if ($criteria->summary) { $query->andWhere(DbHelper::parseParam('venti.summary', $criteria->summary, $query->params)); } if ($criteria->isrepeat) { $query->andWhere(DbHelper::parseParam('venti.isrepeat', $criteria->isrepeat, $query->params)); } if ($criteria->rRule) { $query->andWhere(DbHelper::parseParam('venti.rRule', $criteria->rRule, $query->params)); } if ($criteria->eid) { $query->andWhere(DbHelper::parseParam('venti.eid', $criteria->eid, $query->params)); } if ($criteria->repeat) { $query->andWhere(DbHelper::parseParam('venti.repeat', $criteria->repeat, $query->params)); } if ($criteria->allDay) { $query->andWhere(DbHelper::parseDateParam('venti.allDay', $criteria->allDay, $query->params)); } if ($criteria->between) { $dates = array(); $interval = array(); if (!is_array($criteria->between)) { $criteria->between = ArrayHelper::stringToArray($criteria->between); } if (count($criteria->between) == 2) { foreach ($criteria->between as $ref) { if (!$ref instanceof \DateTime) { $dates[] = DateTime::createFromString($ref, craft()->getTimeZone()); } else { $dates[] = $ref; } } if ($dates[0] > $dates[1]) { $interval[0] = $dates[1]; $interval[1] = $dates[0]; } else { $interval = $dates; } $query->andWhere('(venti.startDate BETWEEN :betweenStartDate AND :betweenEndDate) OR (:betweenStartDate BETWEEN venti.startDate AND venti.endDate)', array(':betweenStartDate' => DateTimeHelper::formatTimeForDb($interval[0]->getTimestamp()), ':betweenEndDate' => DateTimeHelper::formatTimeForDb($interval[1]->getTimestamp()))); } } }
public function prepDate($data, $field) { return DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone)); }
/** * Parses a date param value to a DbCommand where condition. * * @param string $key * @param string $operator * @param string|array|DateTime $dates * @param array &$params * @return mixed */ public static function parseDateParam($key, $operator, $dates, &$params) { $conditions = array(); $dates = ArrayHelper::stringToArray($dates); foreach ($dates as $date) { if (!$date instanceof \DateTime) { $date = DateTime::createFromString($date, Craft::getTimezone()); } $param = ':p' . StringHelper::randomString(9); $params[$param] = DateTimeHelper::formatTimeForDb($date->getTimestamp()); $conditions[] = $key . $operator . $param; } if (count($conditions) == 1) { return $conditions[0]; } else { array_unshift($conditions, 'or'); return $conditions; } }
/** * Convert date to MYSQL_DATETIME in UTC * * @return Craft\DateTime */ public function formatStartDate(\DateTime $date) { $temp = DateTimeHelper::formatTimeForDb($date->getTimestamp()); return DateTime::createFromFormat(DateTime::MYSQL_DATETIME, $temp); }
/** * Prepare fields for fieldtypes. * * @param string &$data * @param string $handle * * @return mixed */ public function prepForFieldType(&$data, $handle) { // Fresh up $data $data = StringHelper::convertToUTF8($data); $data = trim($data); // Get field info $field = craft()->fields->getFieldByHandle($handle); // If it's a field ofcourse if (!is_null($field)) { // For some fieldtypes the're special rules switch ($field->type) { case ImportModel::FieldTypeEntries: // No newlines allowed $data = str_replace("\n", '', $data); $data = str_replace("\r", '', $data); // Don't connect empty fields if (!empty($data)) { // Get field settings $settings = $field->getFieldType()->getSettings(); // Get source id's for connecting $sectionIds = array(); $sources = $settings->sources; if (is_array($sources)) { foreach ($sources as $source) { list($type, $id) = explode(':', $source); $sectionIds[] = $id; } } // Find matching element in sections $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $sectionIds; $criteria->limit = $settings->limit; // Get search strings $search = ArrayHelper::stringToArray($data); // Ability to import multiple Assets at once $data = array(); // Loop through keywords foreach ($search as $query) { // Search $criteria->search = $query; // Add to data $data = array_merge($data, $criteria->ids()); } } else { // Return empty array $data = array(); } break; case ImportModel::FieldTypeCategories: // Don't connect empty fields if (!empty($data)) { // Get field settings $settings = $field->getFieldType()->getSettings(); // Get source id $source = $settings->source; list($type, $id) = explode(':', $source); // Get category data $category = new CategoryModel(); $category->groupId = $id; // This we append before the slugified path $categoryUrl = str_replace('{slug}', '', $category->getUrlFormat()); // Find matching elements in categories $criteria = craft()->elements->getCriteria(ElementType::Category); $criteria->groupId = $id; $criteria->limit = $settings->limit; // Get search strings $search = ArrayHelper::stringToArray($data); // Ability to import multiple Categories at once $data = array(); // Loop through keywords foreach ($search as $query) { // Find matching element by URI (dirty, not all categories have URI's) $criteria->uri = $categoryUrl . $this->slugify($query); // Add to data $data = array_merge($data, $criteria->ids()); } } else { // Return empty array $data = array(); } break; case ImportModel::FieldTypeAssets: // Don't connect empty fields if (!empty($data)) { // Get field settings $settings = $field->getFieldType()->getSettings(); // Get folder id's for connecting $folderIds = array(); $folders = $settings->sources; if (is_array($folders)) { foreach ($folders as $folder) { list($type, $id) = explode(':', $folder); $folderIds[] = $id; } } // Find matching element in folders $criteria = craft()->elements->getCriteria(ElementType::Asset); $criteria->folderId = $folderIds; $criteria->limit = $settings->limit; // Get search strings $search = ArrayHelper::stringToArray($data); // Ability to import multiple Assets at once $data = array(); // Loop through keywords foreach ($search as $query) { // Search $criteria->search = $query; // Add to data $data = array_merge($data, $criteria->ids()); } } else { // Return empty array $data = array(); } break; case ImportModel::FieldTypeUsers: // Don't connect empty fields if (!empty($data)) { // Get field settings $settings = $field->getFieldType()->getSettings(); // Get group id's for connecting $groupIds = array(); $sources = $settings->sources; if (is_array($sources)) { foreach ($sources as $source) { list($type, $id) = explode(':', $source); $groupIds[] = $id; } } // Find matching element in sources $criteria = craft()->elements->getCriteria(ElementType::User); $criteria->groupId = $groupIds; $criteria->limit = $settings->limit; // Get search strings $search = ArrayHelper::stringToArray($data); // Ability to import multiple Users at once $data = array(); // Loop through keywords foreach ($search as $query) { // Search $criteria->search = $query; // Add to data $data = array_merge($data, $criteria->ids()); } } else { // Return empty array $data = array(); } break; case ImportModel::FieldTypeTags: // Get field settings $settings = $field->getFieldType()->getSettings(); // Get tag group id $source = $settings->getAttribute('source'); list($type, $groupId) = explode(':', $source); $tags = ArrayHelper::stringToArray($data); $data = array(); foreach ($tags as $tag) { // Find existing tag $criteria = craft()->elements->getCriteria(ElementType::Tag); $criteria->title = $tag; $criteria->groupId = $groupId; if (!$criteria->total()) { // Create tag if one doesn't already exist $newtag = new TagModel(); $newtag->getContent()->title = $tag; $newtag->groupId = $groupId; // Save tag if (craft()->tags->saveTag($newtag)) { $tagArray = array($newtag->id); } } else { $tagArray = $criteria->ids(); } // Add tags to data array $data = array_merge($data, $tagArray); } break; case ImportModel::FieldTypeNumber: // Parse as number $data = LocalizationHelper::normalizeNumber($data); // Parse as float $data = floatval($data); break; case ImportModel::FieldTypeDate: // Parse date from string $data = DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone)); break; case ImportModel::FieldTypeRadioButtons: case ImportModel::FieldTypeDropdown: //get field settings $settings = $field->getFieldType()->getSettings(); //get field options $options = $settings->getAttribute('options'); // find matching option label $labelSelected = false; foreach ($options as $option) { if ($labelSelected) { continue; } if ($data == $option['label']) { $data = $option['value']; //stop looking after first match $labelSelected = true; } } break; case ImportModel::FieldTypeCheckboxes: case ImportModel::FieldTypeMultiSelect: // Convert to array $data = ArrayHelper::stringToArray($data); break; case ImportModel::FieldTypeLightSwitch: // Convert yes/no values to boolean switch ($data) { case Craft::t('Yes'): $data = true; break; case Craft::t('No'): $data = false; break; } break; } } return $data; }
/** * Returns whether a message is shunned for a user. * * @param int $userId * @param string $message * @return bool */ public function hasUserShunnedMessage($userId, $message) { $row = craft()->db->createCommand()->select('id')->from('shunnedmessages')->where(array('and', 'userId = :userId', 'message = :message', array('or', 'expiryDate IS NULL', 'expiryDate > :now')), array(':userId' => $userId, ':message' => $message, ':now' => DateTimeHelper::formatTimeForDb()))->queryRow(false); return (bool) $row; }
/** * Apply date criteria. * * @param ElementCriteriaModel $criteria * @param DbCommand $query */ private function applyDateCriteria(ElementCriteriaModel $criteria, DbCommand $query) { // Check for date modified if (!empty($criteria->modified)) { $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', $criteria->modified, $query->params)); } // Check for date from if (!empty($criteria->from)) { $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', '>= ' . DateTimeHelper::formatTimeForDb($criteria->from), $query->params)); } // Check for date to if (!empty($criteria->to)) { $criteria->to->add(new DateInterval('PT23H59M59S')); $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', '<= ' . DateTimeHelper::formatTimeForDb($criteria->to), $query->params)); } }
/** * Normalizes date params and then sends them off to parseParam(). * * @param string $column * @param string|array|DateTime $value * @param array &$params * * @return mixed */ public static function parseDateParam($column, $value, &$params) { $normalizedValues = array(); $value = ArrayHelper::stringToArray($value); if (!count($value)) { return ''; } if ($value[0] == 'and' || $value[0] == 'or') { $normalizedValues[] = $value[0]; array_shift($value); } foreach ($value as $val) { // Is this an empty value? static::_normalizeEmptyValue($val); if ($val == ':empty:' || $val == 'not :empty:') { $normalizedValues[] = $val; // Sneak out early continue; } if (is_string($val)) { $operator = static::_parseParamOperator($val); } else { $operator = '='; } if (!$val instanceof \DateTime) { $val = DateTime::createFromString($val, craft()->getTimeZone()); } $normalizedValues[] = $operator . DateTimeHelper::formatTimeForDb($val->getTimestamp()); } return static::parseParam($column, $normalizedValues, $params); }
/** * Prepare fields for fieldtypes. * * @param string &$data * @param string $handle * * @return mixed */ public function prepForFieldType(&$data, $handle) { // Fresh up $data $data = StringHelper::convertToUTF8($data); $data = trim($data); // Get field info $field = craft()->fields->getFieldByHandle($handle); // If it's a field ofcourse if (!is_null($field)) { // For some fieldtypes the're special rules switch ($field->type) { case ImportModel::FieldTypeEntries: // No newlines allowed $data = str_replace("\n", '', $data); $data = str_replace("\r", '', $data); // Don't connect empty fields if (!empty($data)) { $data = $this->prepEntriesFieldType($data, $field); } else { $data = array(); } break; case ImportModel::FieldTypeCategories: if (!empty($data)) { $data = $this->prepCategoriesFieldType($data, $field); } else { $data = array(); } break; case ImportModel::FieldTypeAssets: if (!empty($data)) { $data = $this->prepAssetsFieldType($data, $field); } else { $data = array(); } break; case ImportModel::FieldTypeUsers: if (!empty($data)) { $data = $this->prepUsersFieldType($data, $field); } else { $data = array(); } break; case ImportModel::FieldTypeTags: $data = $this->prepTagsFieldType($data, $field); break; case ImportModel::FieldTypeNumber: // Parse as numberx $data = LocalizationHelper::normalizeNumber($data); // Parse as float $data = floatval($data); break; case ImportModel::FieldTypeDate: // Parse date from string $data = DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone)); break; case ImportModel::FieldTypeRadioButtons: case ImportModel::FieldTypeDropdown: //get field settings $data = $this->prepDropDownFieldType($data, $field); break; case ImportModel::FieldTypeCheckboxes: case ImportModel::FieldTypeMultiSelect: // Convert to array $data = ArrayHelper::stringToArray($data); break; case ImportModel::FieldTypeLightSwitch: // Convert yes/no values to boolean switch ($data) { case Craft::t('Yes'): $data = true; break; case Craft::t('No'): $data = false; break; } break; } } return $data; }
/** * Normalizes date params and then sends them off to parseParam(). * * @param string $key * @param string|array|DateTime $values * @param array &$params * * @return mixed */ public static function parseDateParam($key, $values, &$params) { $normalizedValues = array(); $values = ArrayHelper::stringToArray($values); if (!count($values)) { return ''; } if ($values[0] == 'and' || $values[0] == 'or') { $normalizedValues[] = $values[0]; array_shift($values); } foreach ($values as $value) { if (is_string($value)) { $operator = static::_parseParamOperator($value); } else { $operator = '='; } if (!$value instanceof \DateTime) { $value = DateTime::createFromString($value, craft()->getTimeZone()); } $normalizedValues[] = $operator . DateTimeHelper::formatTimeForDb($value->getTimestamp()); } return static::parseParam($key, $normalizedValues, $params); }
/** * Takes an attribute's config and value and "normalizes" them either for saving to db or sending across a web service. * * @param $value * @param bool $jsonEncodeArrays * @internal param $storedValue * @return int|mixed|null|string */ public static function packageAttributeValue($value, $jsonEncodeArrays = false) { if ($value instanceof \DateTime) { return DateTimeHelper::formatTimeForDb($value->getTimestamp()); } if ($value instanceof \CModel) { $value = $value->getAttributes(); } if (is_array($value)) { // Flatten each of its keys foreach ($value as $key => $val) { $value[$key] = static::packageAttributeValue($val); } if ($jsonEncodeArrays) { return JsonHelper::encode($value); } else { return $value; } } if (is_bool($value)) { return $value ? 1 : 0; } return $value; }
/** * @return null */ private function _cleanStaleSessions() { $interval = new DateInterval('P3M'); $expire = DateTimeHelper::currentUTCDateTime(); $pastTimeStamp = $expire->sub($interval)->getTimestamp(); $pastTime = DateTimeHelper::formatTimeForDb($pastTimeStamp); craft()->db->createCommand()->delete('sessions', 'dateUpdated < :pastTime', array('pastTime' => $pastTime)); }
/** * Deletes any pending users that have shown zero sense of urgency and are just taking up space. * * This method will check the * [purgePendingUsersDuration](http://craftcms.com/docs/config-settings#purgePendingUsersDuration) config * setting, and if it is set to a valid duration, it will delete any user accounts that were created that duration * ago, and have still not activated their account. * * @return null */ public function purgeExpiredPendingUsers() { if (($duration = craft()->config->get('purgePendingUsersDuration')) !== false) { $interval = new DateInterval($duration); $expire = DateTimeHelper::currentUTCDateTime(); $pastTimeStamp = $expire->sub($interval)->getTimestamp(); $pastTime = DateTimeHelper::formatTimeForDb($pastTimeStamp); $userIds = craft()->db->createCommand()->select('id')->from('users')->where('pending=1 AND verificationCodeIssuedDate < :pastTime', array(':pastTime' => $pastTime))->queryColumn(); if ($userIds) { foreach ($userIds as $userId) { $user = $this->getUserById($userId); $this->deleteUser($user); Craft::log('Just deleted pending userId ' . $userId . ' (' . $user->username . '), because the were more than ' . $duration . ' old', LogLevel::Info, true); } } } }
/** * Ends a template cache. * * @param string $key The template cache key. * @param bool $global Whether the cache should be stored globally. * @param string|null $duration How long the cache should be stored for. * @param mixed|null $expiration When the cache should expire. * @param string $body The contents of the cache. * * @throws \Exception * @return null */ public function endTemplateCache($key, $global, $duration, $expiration, $body) { // If there are any transform generation URLs in the body, don't cache it. // Can't use getResourceUrl() here because that will append ?d= or ?x= to the URL. if (strpos($body, UrlHelper::getSiteUrl(craft()->config->getResourceTrigger() . '/transforms'))) { return; } // Figure out the expiration date if ($duration) { $expiration = new DateTime($duration); } if (!$expiration) { $duration = craft()->config->getCacheDuration(); if ($duration <= 0) { $duration = 31536000; // 1 year } $duration += time(); $expiration = new DateTime('@' . $duration); } // Save it $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { craft()->db->createCommand()->insert(static::$_templateCachesTable, array('cacheKey' => $key, 'locale' => craft()->language, 'path' => $global ? null : $this->_getPath(), 'expiryDate' => DateTimeHelper::formatTimeForDb($expiration), 'body' => $body), false); $cacheId = craft()->db->getLastInsertID(); // Tag it with any element criteria that were output within the cache if (!empty($this->_cacheCriteria[$key])) { $values = array(); foreach ($this->_cacheCriteria[$key] as $criteria) { $flattenedCriteria = $criteria->getAttributes(null, true); $values[] = array($cacheId, $criteria->getElementType()->getClassHandle(), JsonHelper::encode($flattenedCriteria)); } craft()->db->createCommand()->insertAll(static::$_templateCacheCriteriaTable, array('cacheId', 'type', 'criteria'), $values, false); unset($this->_cacheCriteria[$key]); } // Tag it with any element IDs that were output within the cache if (!empty($this->_cacheElementIds[$key])) { $values = array(); foreach ($this->_cacheElementIds[$key] as $elementId) { $values[] = array($cacheId, $elementId); } craft()->db->createCommand()->insertAll(static::$_templateCacheElementsTable, array('cacheId', 'elementId'), $values, false); unset($this->_cacheElementIds[$key]); } if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } }
/** * Cancel the elements query. * * @param DbCommand $query * @param ElementCriteriaModel $criteria * * @return bool */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { // Default query $query->select('auditlog.id, auditlog.type, auditlog.userId, auditlog.origin, auditlog.before, auditlog.after, auditlog.status, auditlog.dateCreated, auditlog.dateUpdated')->from('auditlog auditlog'); // Reset default element type query parts $query->setJoin(''); $query->setWhere('1=1'); $query->setGroup(''); unset($query->params[':locale']); unset($query->params[':elementsid1']); // Check for specific id if (!empty($criteria->id)) { $query->andWhere(DbHelper::parseParam('auditlog.id', $criteria->id, $query->params)); } // Check type if (!empty($criteria->type)) { $query->andWhere(DbHelper::parseParam('auditlog.type', $criteria->type, $query->params)); } // Check user id if (!empty($criteria->userId)) { $query->andWhere(DbHelper::parseParam('auditlog.userId', $criteria->userId, $query->params)); } // Check origin if (!empty($criteria->origin)) { $query->andWhere(DbHelper::parseParam('auditlog.origin', $criteria->origin, $query->params)); } // Check for date modified if (!empty($criteria->modified)) { $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', $criteria->modified, $query->params)); } // Check before if (!empty($criteria->before)) { $query->andWhere(DbHelper::parseParam('auditlog.before', $criteria->before, $query->params)); } // Check after if (!empty($criteria->after)) { $query->andWhere(DbHelper::parseParam('auditlog.after', $criteria->after, $query->params)); } // Check for date from if (!empty($criteria->from)) { $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', '>= ' . DateTimeHelper::formatTimeForDb($criteria->from), $query->params)); } // Check for date to if (!empty($criteria->to)) { $criteria->to->add(new DateInterval('PT23H59M59S')); $query->andWhere(DbHelper::parseDateParam('auditlog.dateUpdated', '<= ' . DateTimeHelper::formatTimeForDb($criteria->to), $query->params)); } // Check for type if (!empty($criteria->type)) { $query->andWhere(DbHelper::parseParam('auditlog.type', $criteria->type, $query->params)); } // Check for status if (!empty($criteria->status)) { $query->andWhere(DbHelper::parseParam('auditlog.status', $criteria->status, $query->params)); } // Search if (!empty($criteria->search)) { // Always perform a LIKE search $criteria->search = '*' . $criteria->search . '*'; // Build conditions $conditions = array('or', DbHelper::parseParam('auditlog.origin', $criteria->search, $query->params), DbHelper::parseParam('auditlog.before', $criteria->search, $query->params), DbHelper::parseParam('auditlog.after', $criteria->search, $query->params)); // Add to query $query->andWhere($conditions, $query->params); // Don't perform search logics after this $criteria->search = null; } }