/** * Preps a {@link DbCommand} object for querying for elements, based on a given element criteria. * * @param ElementCriteriaModel &$criteria The element criteria model * @param string &$contentTable The content table that should be joined in. (This variable will * actually get defined by buildElementsQuery(), and is passed by * reference so whatever’s calling the method will have access to its * value.) * @param array &$fieldColumns Info about the content field columns being selected. (This variable * will actually get defined by buildElementsQuery(), and is passed by * reference so whatever’s calling the method will have access to its * value.) * * @return DbCommand|false The DbCommand object, or `false` if the method was able to determine ahead of time that * there’s no chance any elements are going to be found with the given parameters. */ public function buildElementsQuery(&$criteria = null, &$contentTable = null, &$fieldColumns = null) { if (!$criteria instanceof ElementCriteriaModel) { $criteria = $this->getCriteria('Entry', $criteria); } $elementType = $criteria->getElementType(); if (!$elementType->isLocalized()) { // The criteria *must* be set to the primary locale $criteria->locale = craft()->i18n->getPrimarySiteLocaleId(); } else { if (!$criteria->locale) { // Default to the current app locale $criteria->locale = craft()->language; } } // Set up the query // --------------------------------------------------------------------- $query = craft()->db->createCommand()->select('elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated, elements_i18n.slug, elements_i18n.uri, elements_i18n.enabled AS localeEnabled')->from('elements elements')->join('elements_i18n elements_i18n', 'elements_i18n.elementId = elements.id')->where('elements_i18n.locale = :locale', array(':locale' => $criteria->locale))->group('elements.id'); if ($elementType->hasContent()) { $contentTable = $elementType->getContentTableForElementsQuery($criteria); if ($contentTable) { $contentCols = 'content.id AS contentId'; if ($elementType->hasTitles()) { $contentCols .= ', content.title'; } // TODO: Replace this with a call to getFieldsForElementsQuery() in 3.0 $fieldColumns = $elementType->getContentFieldColumnsForElementsQuery($criteria); foreach ($fieldColumns as $column) { $contentCols .= ', content.' . $column['column']; } $query->addSelect($contentCols); $query->join($contentTable . ' content', 'content.elementId = elements.id'); $query->andWhere('content.locale = :locale'); } } // Basic element params // --------------------------------------------------------------------- // If the 'id' parameter is set to any empty value besides `null`, don't return anything if ($criteria->id !== null && empty($criteria->id)) { return false; } if ($criteria->id) { $query->andWhere(DbHelper::parseParam('elements.id', $criteria->id, $query->params)); } if ($criteria->archived) { $query->andWhere('elements.archived = 1'); } else { $query->andWhere('elements.archived = 0'); if ($criteria->status) { $statusConditions = array(); $statuses = ArrayHelper::stringToArray($criteria->status); foreach ($statuses as $status) { $status = StringHelper::toLowerCase($status); // Is this a supported status? if (in_array($status, array_keys($elementType->getStatuses()))) { if ($status == BaseElementModel::ENABLED) { $statusConditions[] = 'elements.enabled = 1'; } else { if ($status == BaseElementModel::DISABLED) { $statusConditions[] = 'elements.enabled = 0'; } else { $elementStatusCondition = $elementType->getElementQueryStatusCondition($query, $status); if ($elementStatusCondition) { $statusConditions[] = $elementStatusCondition; } else { if ($elementStatusCondition === false) { return false; } } } } } } if ($statusConditions) { if (count($statusConditions) == 1) { $statusCondition = $statusConditions[0]; } else { array_unshift($statusConditions, 'or'); $statusCondition = $statusConditions; } $query->andWhere($statusCondition); } } } if ($criteria->dateCreated) { $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', $criteria->dateCreated, $query->params)); } if ($criteria->dateUpdated) { $query->andWhere(DbHelper::parseDateParam('elements.dateUpdated', $criteria->dateUpdated, $query->params)); } if ($elementType->hasTitles() && $criteria->title) { $query->andWhere(DbHelper::parseParam('content.title', $criteria->title, $query->params)); } // i18n params // --------------------------------------------------------------------- if ($criteria->slug) { $query->andWhere(DbHelper::parseParam('elements_i18n.slug', $criteria->slug, $query->params)); } if ($criteria->uri) { $query->andWhere(DbHelper::parseParam('elements_i18n.uri', $criteria->uri, $query->params)); } if ($criteria->localeEnabled) { $query->andWhere('elements_i18n.enabled = 1'); } // Relational params // --------------------------------------------------------------------- // Convert the old childOf and parentOf params to the relatedTo param // childOf(element) => relatedTo({ source: element }) // parentOf(element) => relatedTo({ target: element }) if (!$criteria->relatedTo && ($criteria->childOf || $criteria->parentOf)) { $relatedTo = array('and'); if ($criteria->childOf) { $relatedTo[] = array('sourceElement' => $criteria->childOf, 'field' => $criteria->childField); } if ($criteria->parentOf) { $relatedTo[] = array('targetElement' => $criteria->parentOf, 'field' => $criteria->parentField); } $criteria->relatedTo = $relatedTo; } if ($criteria->relatedTo) { $relationParamParser = new ElementRelationParamParser(); $relConditions = $relationParamParser->parseRelationParam($criteria->relatedTo, $query); if ($relConditions === false) { return false; } $query->andWhere($relConditions); // If there's only one relation criteria and it's specifically for grabbing target elements, allow the query // to order by the relation sort order if ($relationParamParser->isRelationFieldQuery()) { $query->addSelect('sources1.sortOrder'); } } // Give field types a chance to make changes // --------------------------------------------------------------------- if ($elementType->hasContent() && $contentTable) { $contentService = craft()->content; $originalFieldColumnPrefix = $contentService->fieldColumnPrefix; // TODO: $fields should already be defined by now in Craft 3.0 $fields = $elementType->getFieldsForElementsQuery($criteria); $extraCriteriaAttributes = $criteria->getExtraAttributeNames(); foreach ($fields as $field) { $fieldType = $field->getFieldType(); if ($fieldType) { // Was this field's parameter set on the criteria model? if (in_array($field->handle, $extraCriteriaAttributes)) { $fieldCriteria = $criteria->{$field->handle}; } else { $fieldCriteria = null; } // Set the field's column prefix on ContentService if ($field->columnPrefix) { $contentService->fieldColumnPrefix = $field->columnPrefix; } $fieldTypeResponse = $fieldType->modifyElementsQuery($query, $fieldCriteria); // Set it back $contentService->fieldColumnPrefix = $originalFieldColumnPrefix; // Need to bail early? if ($fieldTypeResponse === false) { return false; } } } } // Give the element type a chance to make changes // --------------------------------------------------------------------- if ($elementType->modifyElementsQuery($query, $criteria) === false) { return false; } // Structure params // --------------------------------------------------------------------- if ($query->isJoined('structureelements')) { $query->addSelect('structureelements.root, structureelements.lft, structureelements.rgt, structureelements.level'); if ($criteria->ancestorOf) { if (!$criteria->ancestorOf instanceof BaseElementModel) { $criteria->ancestorOf = craft()->elements->getElementById($criteria->ancestorOf, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->ancestorOf) { return false; } } if ($criteria->ancestorOf) { $query->andWhere(array('and', 'structureelements.lft < :ancestorOf_lft', 'structureelements.rgt > :ancestorOf_rgt', 'structureelements.root = :ancestorOf_root'), array(':ancestorOf_lft' => $criteria->ancestorOf->lft, ':ancestorOf_rgt' => $criteria->ancestorOf->rgt, ':ancestorOf_root' => $criteria->ancestorOf->root)); if ($criteria->ancestorDist) { $query->andWhere('structureelements.level >= :ancestorOf_level', array(':ancestorOf_level' => $criteria->ancestorOf->level - $criteria->ancestorDist)); } } } if ($criteria->descendantOf) { if (!$criteria->descendantOf instanceof BaseElementModel) { $criteria->descendantOf = craft()->elements->getElementById($criteria->descendantOf, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->descendantOf) { return false; } } if ($criteria->descendantOf) { $query->andWhere(array('and', 'structureelements.lft > :descendantOf_lft', 'structureelements.rgt < :descendantOf_rgt', 'structureelements.root = :descendantOf_root'), array(':descendantOf_lft' => $criteria->descendantOf->lft, ':descendantOf_rgt' => $criteria->descendantOf->rgt, ':descendantOf_root' => $criteria->descendantOf->root)); if ($criteria->descendantDist) { $query->andWhere('structureelements.level <= :descendantOf_level', array(':descendantOf_level' => $criteria->descendantOf->level + $criteria->descendantDist)); } } } if ($criteria->siblingOf) { if (!$criteria->siblingOf instanceof BaseElementModel) { $criteria->siblingOf = craft()->elements->getElementById($criteria->siblingOf, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->siblingOf) { return false; } } if ($criteria->siblingOf) { $query->andWhere(array('and', 'structureelements.level = :siblingOf_level', 'structureelements.root = :siblingOf_root', 'structureelements.elementId != :siblingOf_elementId'), array(':siblingOf_level' => $criteria->siblingOf->level, ':siblingOf_root' => $criteria->siblingOf->root, ':siblingOf_elementId' => $criteria->siblingOf->id)); if ($criteria->siblingOf->level != 1) { $parent = $criteria->siblingOf->getParent(); if ($parent) { $query->andWhere(array('and', 'structureelements.lft > :siblingOf_lft', 'structureelements.rgt < :siblingOf_rgt'), array(':siblingOf_lft' => $parent->lft, ':siblingOf_rgt' => $parent->rgt)); } else { return false; } } } } if ($criteria->prevSiblingOf) { if (!$criteria->prevSiblingOf instanceof BaseElementModel) { $criteria->prevSiblingOf = craft()->elements->getElementById($criteria->prevSiblingOf, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->prevSiblingOf) { return false; } } if ($criteria->prevSiblingOf) { $query->andWhere(array('and', 'structureelements.level = :prevSiblingOf_level', 'structureelements.rgt = :prevSiblingOf_rgt', 'structureelements.root = :prevSiblingOf_root'), array(':prevSiblingOf_level' => $criteria->prevSiblingOf->level, ':prevSiblingOf_rgt' => $criteria->prevSiblingOf->lft - 1, ':prevSiblingOf_root' => $criteria->prevSiblingOf->root)); } } if ($criteria->nextSiblingOf) { if (!$criteria->nextSiblingOf instanceof BaseElementModel) { $criteria->nextSiblingOf = craft()->elements->getElementById($criteria->nextSiblingOf, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->nextSiblingOf) { return false; } } if ($criteria->nextSiblingOf) { $query->andWhere(array('and', 'structureelements.level = :nextSiblingOf_level', 'structureelements.lft = :nextSiblingOf_lft', 'structureelements.root = :nextSiblingOf_root'), array(':nextSiblingOf_level' => $criteria->nextSiblingOf->level, ':nextSiblingOf_lft' => $criteria->nextSiblingOf->rgt + 1, ':nextSiblingOf_root' => $criteria->nextSiblingOf->root)); } } if ($criteria->positionedBefore) { if (!$criteria->positionedBefore instanceof BaseElementModel) { $criteria->positionedBefore = craft()->elements->getElementById($criteria->positionedBefore, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->positionedBefore) { return false; } } if ($criteria->positionedBefore) { $query->andWhere(array('and', 'structureelements.rgt < :positionedBefore_rgt', 'structureelements.root = :positionedBefore_root'), array(':positionedBefore_rgt' => $criteria->positionedBefore->lft, ':positionedBefore_root' => $criteria->positionedBefore->root)); } } if ($criteria->positionedAfter) { if (!$criteria->positionedAfter instanceof BaseElementModel) { $criteria->positionedAfter = craft()->elements->getElementById($criteria->positionedAfter, $elementType->getClassHandle(), $criteria->locale); if (!$criteria->positionedAfter) { return false; } } if ($criteria->positionedAfter) { $query->andWhere(array('and', 'structureelements.lft > :positionedAfter_lft', 'structureelements.root = :positionedAfter_root'), array(':positionedAfter_lft' => $criteria->positionedAfter->rgt, ':positionedAfter_root' => $criteria->positionedAfter->root)); } } if ($criteria->level || $criteria->depth) { // TODO: 'depth' is deprecated; use 'level' instead. $level = $criteria->level ? $criteria->level : $criteria->depth; $query->andWhere(DbHelper::parseParam('structureelements.level', $level, $query->params)); } } // Search // --------------------------------------------------------------------- if ($criteria->search) { $elementIds = $this->_getElementIdsFromQuery($query); $scoredSearchResults = $criteria->order == 'score'; $filteredElementIds = craft()->search->filterElementIdsByQuery($elementIds, $criteria->search, $scoredSearchResults); // No results? if (!$filteredElementIds) { return array(); } $query->andWhere(array('in', 'elements.id', $filteredElementIds)); if ($scoredSearchResults) { // Order the elements in the exact order that SearchService returned them in $query->order(craft()->db->getSchema()->orderByColumnValues('elements.id', $filteredElementIds)); } } return $query; }
/** * 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()))); } } }
/** * Preps a {@link DbCommand} object for querying for elements, based on a given element criteria. * * @param Venti_CriteriaModel &$criteria The events criteria model * * @return DbCommand|false The DbCommand object, or `false` if the method was able to determine ahead of time that * there’s no chance any elements are going to be found with the given parameters. */ public function buildEventsQuery(Venti_CriteriaModel $criteria) { $elementType = $criteria->getElementType(); if (!$elementType->isLocalized()) { // The criteria *must* be set to the primary locale $criteria->locale = craft()->i18n->getPrimarySiteLocaleId(); } else { if (!$criteria->locale) { // Default to the current app locale $criteria->locale = craft()->language; } } $query = craft()->db->createCommand()->select('venti.startDate, venti.endDate, venti.allDay, venti.isrepeat, venti.eid, venti.eventid, venti.repeat, venti.rRule, venti.summary, elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated, elements_i18n.slug, elements_i18n.uri, elements_i18n.enabled AS localeEnabled')->from('venti_events venti')->join('elements elements', 'elements.id = venti.eventid')->join('elements_i18n elements_i18n', 'elements_i18n.elementId = venti.eventid')->where('elements_i18n.locale = :locale', array(':locale' => $criteria->locale))->limit($criteria->limit)->offset($criteria->offset)->order($criteria->order); if ($elementType->hasContent()) { $contentTable = 'content'; if ($contentTable) { $contentCols = 'content.id AS contentId'; if ($elementType->hasTitles()) { $contentCols .= ', content.title'; } $fieldColumns = $this->getContentFieldColumnsForElementsQuery($criteria); foreach ($fieldColumns as $column) { $contentCols .= ', content.' . $column['column']; } $query->addSelect($contentCols); $query->join($contentTable . ' content', 'content.elementId = elements.id'); $query->andWhere('content.locale = :locale'); } } if ($elementType->hasTitles() && $criteria->title) { $query->andWhere(DbHelper::parseParam('content.title', $criteria->title, $query->params)); } if ($criteria->id) { $query->andWhere(DbHelper::parseParam('venti.eventid', $criteria->id, $query->params)); } if ($criteria->eid) { $query->andWhere(DbHelper::parseParam('venti.eid', $criteria->eid, $query->params)); } if ($criteria->isrepeat) { $query->andWhere(DbHelper::parseParam('venti.isrepeat', $criteria->isrepeat, $query->params)); } if ($criteria->startDate) { $query->andWhere(DbHelper::parseDateParam('venti.startDate', $criteria->startDate, $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->slug) { $query->andWhere(DbHelper::parseParam('elements_i18n.slug', $criteria->slug, $query->params)); } if ($criteria->uri) { $query->andWhere(DbHelper::parseParam('elements_i18n.uri', $criteria->uri, $query->params)); } if ($criteria->localeEnabled) { $query->andWhere('elements_i18n.enabled = 1'); } if ($criteria->dateCreated) { $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', $criteria->dateCreated, $query->params)); } if ($criteria->dateUpdated) { $query->andWhere(DbHelper::parseDateParam('elements.dateUpdated', $criteria->dateUpdated, $query->params)); } if ($criteria->archived) { $query->andWhere('elements.archived = 1'); } else { $query->andWhere('elements.archived = 0'); if ($criteria->status) { $statusConditions = array(); $statuses = ArrayHelper::stringToArray($criteria->status); foreach ($statuses as $status) { $status = StringHelper::toLowerCase($status); // Is this a supported status? if (in_array($status, array_keys($this->getStatuses()))) { if ($status == BaseElementModel::ENABLED) { $statusConditions[] = 'elements.enabled = 1'; } else { if ($status == BaseElementModel::DISABLED) { $statusConditions[] = 'elements.enabled = 0'; } else { $elementStatusCondition = $this->getElementQueryStatusCondition($query, $status); if ($elementStatusCondition) { $statusConditions[] = $elementStatusCondition; } else { if ($elementStatusCondition === false) { return false; } } } } } } if ($statusConditions) { if (count($statusConditions) == 1) { $statusCondition = $statusConditions[0]; } else { array_unshift($statusConditions, 'or'); $statusCondition = $statusConditions; } $query->andWhere($statusCondition); } } } // Relational params // --------------------------------------------------------------------- if ($criteria->relatedTo) { $relationParamParser = new ElementRelationParamParser(); $relConditions = $relationParamParser->parseRelationParam($criteria->relatedTo, $query); if ($relConditions === false) { return false; } $query->andWhere($relConditions); // If there's only one relation criteria and it's specifically for grabbing target elements, allow the query // to order by the relation sort order if ($relationParamParser->isRelationFieldQuery()) { $query->addSelect('sources1.sortOrder'); } } // Search // --------------------------------------------------------------------- if ($criteria->search) { $elementIds = $this->_getElementIdsFromQuery($query); $scoredSearchResults = $criteria->order == 'score'; $filteredElementIds = craft()->search->filterElementIdsByQuery($elementIds, $criteria->search, $scoredSearchResults); // No results? if (!$filteredElementIds) { return array(); } $query->andWhere(array('in', 'venti.eventid', $filteredElementIds)); if ($scoredSearchResults) { // Order the elements in the exact order that SearchService returned them in $query->order(craft()->db->getSchema()->orderByColumnValues('venti.eventid', $filteredElementIds)); } } return $query; }
/** * Modifies an entries query targeting entries of this type. * * @param DbCommand $query * @param ElementCriteriaModel $criteria * @return mixed */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect('entries.sectionId, entries.authorId, entries.postDate, entries.expiryDate, entries_i18n.slug')->join('entries entries', 'entries.id = elements.id')->join('entries_i18n entries_i18n', 'entries_i18n.entryId = elements.id')->andWhere('entries_i18n.locale = elements_i18n.locale'); if ($criteria->slug) { $query->andWhere(DbHelper::parseParam('entries_i18n.slug', $criteria->slug, $query->params)); } if ($criteria->postDate) { $query->andWhere(DbHelper::parseDateParam('entries.postDate', '=', $criteria->postDate, $query->params)); } else { if ($criteria->after) { $query->andWhere(DbHelper::parseDateParam('entries.postDate', '>=', $criteria->after, $query->params)); } if ($criteria->before) { $query->andWhere(DbHelper::parseDateParam('entries.postDate', '<', $criteria->before, $query->params)); } } if ($criteria->editable) { $user = craft()->userSession->getUser(); if (!$user) { return false; } $editableSectionIds = craft()->sections->getEditableSectionIds(); $query->andWhere(array('in', 'entries.sectionId', $editableSectionIds)); $noPeerConditions = array(); foreach ($editableSectionIds as $sectionId) { if (!$user->can('editPeerEntries:' . $sectionId)) { $noPeerConditions[] = array('or', 'entries.sectionId != ' . $sectionId, 'entries.authorId = ' . $user->id); } } if ($noPeerConditions) { array_unshift($noPeerConditions, 'and'); $query->andWhere($noPeerConditions); } } if (Craft::hasPackage(CraftPackage::PublishPro)) { if ($criteria->sectionId) { $query->andWhere(DbHelper::parseParam('entries.sectionId', $criteria->sectionId, $query->params)); } if ($criteria->section) { $query->join('sections sections', 'entries.sectionId = sections.id'); $query->andWhere(DbHelper::parseParam('sections.handle', $criteria->section, $query->params)); } } if (Craft::hasPackage(CraftPackage::Users)) { if ($criteria->authorId) { $query->andWhere(DbHelper::parseParam('entries.authorId', $criteria->authorId, $query->params)); } if ($criteria->authorGroupId || $criteria->authorGroup) { $query->join('usergroups_users usergroups_users', 'usergroups_users.userId = entries.authorId'); if ($criteria->authorGroupId) { $query->andWhere(DbHelper::parseParam('usergroups_users.groupId', $criteria->authorGroupId, $query->params)); } if ($criteria->authorGroup) { $query->join('usergroups usergroups', 'usergroups.id = usergroups_users.groupId'); $query->andWhere(DbHelper::parseParam('usergroups.handle', $criteria->authorGroup, $query->params)); } } } }
public function actionCsv() { $formId = craft()->request->getPost('form'); $form = craft()->formerly_forms->getFormById($formId); $formQuestions = $form->getQuestions(); $fieldTypes = craft()->fields->getAllFieldTypes(); set_time_limit('1000'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . ($form->handle . '_submissions.csv')); header('Content-Transfer-Encoding: binary'); $stream = fopen('php://output', 'w'); $criteria = craft()->elements->getCriteria('Formerly_Submission'); $criteria->formId = $formId; $query = craft()->elements->buildElementsQuery($criteria, $contentTable, $fieldColumns); $query->limit(500000); $query->order('dateCreated desc'); if (isset($_POST['fromDate']) && !empty($_POST['fromDate']['date']) && isset($_POST['toDate']) && !empty($_POST['toDate']['date'])) { $fromDate = craft()->request->getPost('fromDate'); $fromDate = DateTime::createFromString($fromDate, craft()->timezone); $toDate = craft()->request->getPost('toDate'); $toDate = DateTime::createFromString($toDate, craft()->timezone); $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', '>= ' . $fromDate->format(DateTime::MYSQL_DATETIME), $query->params)); $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', '<= ' . $toDate->format(DateTime::MYSQL_DATETIME), $query->params)); } elseif (isset($_POST['fromDate']) && !empty($_POST['fromDate']['date'])) { $fromDate = craft()->request->getPost('fromDate'); $fromDate = DateTime::createFromString($fromDate, craft()->timezone); $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', '>= ' . $fromDate->format(DateTime::MYSQL_DATETIME), $query->params)); } else { if (isset($_POST['toDate']) && !empty($_POST['toDate']['date'])) { $toDate = craft()->request->getPost('toDate'); $toDate = DateTime::createFromString($toDate, craft()->timezone); $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', '<= ' . $toDate->format(DateTime::MYSQL_DATETIME), $query->params)); } } // Write column names first. $first = true; $queryResult = $query->query(); $elementType = $criteria->getElementType(); while (false !== ($result = $queryResult->read())) { if ($this->enableHooks) { // Make a copy to pass to the onPopulateElement event $originalResult = array_merge($result); } // Separate the content values from the main element attributes $content = array('id' => isset($result['contentId']) ? $result['contentId'] : null, 'elementId' => $result['id'], 'locale' => $criteria->locale, 'title' => isset($result['title']) ? $result['title'] : null); unset($result['title']); if ($fieldColumns) { foreach ($fieldColumns as $column) { // Account for results where multiple fields have the same handle, but from // different columns e.g. two Matrix block types that each have a field with the // same handle $colName = $column['column']; $fieldHandle = $column['handle']; if (!isset($content[$fieldHandle]) || empty($content[$fieldHandle]) && !empty($result[$colName])) { $content[$fieldHandle] = $result[$colName]; } unset($result[$colName]); } } $result['locale'] = $criteria->locale; if ($this->enableHooks) { $submission = $elementType->populateElementModel($result); // Was an element returned? if (!$submission || !$submission instanceof BaseElementModel) { continue; } $submission->setContent($content); // Fire an 'onPopulateElement' event craft()->elements->onPopulateElement(new Event($this, array('element' => $submission, 'result' => $originalResult))); } else { $result['dateCreated'] = DateTime::createFromFormat(DateTime::MYSQL_DATETIME, $result['dateCreated']); $submission = (object) array_merge($content, $result); } $row = array('Id' => $submission->id, 'Time' => $submission->dateCreated->format('d/m/Y H:i:s')); foreach ($formQuestions as $question) { if ($question->type == Formerly_QuestionType::RawHTML) { continue; } $columnName = str_replace(array($form->handle . '_', Formerly_QuestionType::CustomListHandle, Formerly_QuestionType::RawHTMLHandle, Formerly_QuestionType::CustomHandle), '', $question->handle); $columnName = ucwords($columnName); $value = $submission->{$question->handle}; if (!$this->enableHooks && isset($fieldTypes[$question->type])) { $fieldType = clone $fieldTypes[$question->type]; $fieldType->setSettings(array('options' => $question->options)); if ($value && is_string($value) && mb_strpos('{[', $value[0]) !== false) { // Presumably this is JSON. $value = JsonHelper::decode($value); } $value = $fieldType->prepValue($value); } if ($value instanceof MultiOptionsFieldData) { $summary = array(); if ($question->type == Formerly_QuestionType::CustomList) { for ($j = 0; $j < count($value); ++$j) { $v = $value[$j]; if ($v->selected) { $summary[] = $v->value; } } } else { foreach ($value->getOptions() as $option) { if ($option->selected) { $summary[] = $option->value; } } } $row[$columnName] = implode($summary, ', '); } elseif ($question->type == Formerly_QuestionType::MultilineText) { $row[$columnName] = str_replace('<br />', "\n", $value); } else { $row[$columnName] = $value; } } if ($first) { fputcsv($stream, array_keys($row)); $first = false; } fputcsv($stream, $row); } fclose($stream); }
/** * @param DbCommand $query * @param ElementCriteriaModel $criteria * * @return void */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect('orders.id, orders.number, orders.couponCode, orders.itemTotal, orders.baseDiscount, orders.baseShippingCost, orders.totalPrice, orders.totalPaid, orders.orderStatusId, orders.dateOrdered, orders.email, orders.dateOrdered, orders.datePaid, orders.currency, orders.lastIp, orders.message, orders.returnUrl, orders.cancelUrl, orders.orderStatusId, orders.billingAddressId, orders.billingAddressData, orders.shippingAddressId, orders.shippingAddressData, orders.shippingMethodId, orders.paymentMethodId, orders.customerId, orders.dateUpdated')->join('market_orders orders', 'orders.id = elements.id'); if ($criteria->completed) { if ($criteria->completed == true) { $query->andWhere('orders.dateOrdered is not null'); $criteria->completed = null; } } if ($criteria->dateOrdered) { $query->andWhere(DbHelper::parseParam('orders.dateOrdered', $criteria->dateOrdered, $query->params)); } if ($criteria->number) { $query->andWhere(DbHelper::parseParam('orders.number', $criteria->number, $query->params)); } if ($criteria->orderStatus) { if ($criteria->orderStatus instanceof Market_OrderStatusModel) { $criteria->orderStatusId = $criteria->orderStatus->id; $criteria->orderStatus = NULL; } else { $query->andWhere(DbHelper::parseParam('orders.orderStatusId', $criteria->orderStatus, $query->params)); } } if ($criteria->orderStatusId) { $query->andWhere(DbHelper::parseParam('orders.orderStatusId', $criteria->orderStatusId, $query->params)); } if ($criteria->customer) { if ($criteria->customer instanceof Market_CustomerModel) { if ($criteria->customer->id) { $criteria->customerId = $criteria->customer->id; $criteria->customer = null; } else { $query->andWhere(DbHelper::parseParam('orders.customerId', 'IS NULL', $query->params)); } } } if ($criteria->customerId) { $query->andWhere(DbHelper::parseParam('orders.customerId', $criteria->customerId, $query->params)); } if ($criteria->updatedOn) { $query->andWhere(DbHelper::parseDateParam('orders.dateUpdated', $criteria->updatedOn, $query->params)); } else { if ($criteria->updatedAfter) { $query->andWhere(DbHelper::parseDateParam('orders.dateUpdated', '>=' . $criteria->updatedAfter, $query->params)); } if ($criteria->updatedBefore) { $query->andWhere(DbHelper::parseDateParam('orders.dateUpdated', '<' . $criteria->updatedBefore, $query->params)); } } }
public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect(' workflow_submissions.ownerId, workflow_submissions.draftId, workflow_submissions.editorId, workflow_submissions.publisherId, workflow_submissions.status, workflow_submissions.notes, workflow_submissions.dateApproved, workflow_submissions.dateRejected, workflow_submissions.dateRevoked ')->join('workflow_submissions workflow_submissions', 'workflow_submissions.id = elements.id'); if ($criteria->ownerId) { $query->andWhere(DbHelper::parseParam('workflow_submissions.ownerId', $criteria->ownerId, $query->params)); } if ($criteria->draftId) { $query->andWhere(DbHelper::parseParam('workflow_submissions.draftId', $criteria->draftId, $query->params)); } if ($criteria->editorId) { $query->andWhere(DbHelper::parseParam('workflow_submissions.editorId', $criteria->editorId, $query->params)); } if ($criteria->publisherId) { $query->andWhere(DbHelper::parseParam('workflow_submissions.publisherId', $criteria->publisherId, $query->params)); } if ($criteria->status) { $query->andWhere(DbHelper::parseParam('workflow_submissions.status', $criteria->status, $query->params)); } if ($criteria->notes) { $query->andWhere(DbHelper::parseParam('workflow_submissions.notes', $criteria->notes, $query->params)); } if ($criteria->dateApproved) { $query->andWhere(DbHelper::parseDateParam('workflow_submissions.dateApproved', $criteria->dateApproved, $query->params)); } if ($criteria->dateRejected) { $query->andWhere(DbHelper::parseDateParam('workflow_submissions.dateRejected', $criteria->dateRejected, $query->params)); } if ($criteria->dateRevoked) { $query->andWhere(DbHelper::parseDateParam('workflow_submissions.dateRevoked', $criteria->dateRevoked, $query->params)); } if ($criteria->dateCreated) { $query->andWhere(DbHelper::parseDateParam('workflow_submissions.dateCreated', $criteria->dateCreated, $query->params)); } }
/** * @inheritDoc IElementType::modifyElementsQuery() * * @param DbCommand $query * @param ElementCriteriaModel $criteria * * @return bool|false|null|void */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect('entries.sectionId, entries.typeId, entries.authorId, entries.postDate, entries.expiryDate')->join('entries entries', 'entries.id = elements.id')->join('sections sections', 'sections.id = entries.sectionId')->leftJoin('structures structures', 'structures.id = sections.structureId')->leftJoin('structureelements structureelements', array('and', 'structureelements.structureId = structures.id', 'structureelements.elementId = entries.id')); if ($criteria->ref) { $refs = ArrayHelper::stringToArray($criteria->ref); $conditionals = array(); foreach ($refs as $ref) { $parts = array_filter(explode('/', $ref)); if ($parts) { if (count($parts) == 1) { $conditionals[] = DbHelper::parseParam('elements_i18n.slug', $parts[0], $query->params); } else { $conditionals[] = array('and', DbHelper::parseParam('sections.handle', $parts[0], $query->params), DbHelper::parseParam('elements_i18n.slug', $parts[1], $query->params)); } } } if ($conditionals) { if (count($conditionals) == 1) { $query->andWhere($conditionals[0]); } else { array_unshift($conditionals, 'or'); $query->andWhere($conditionals); } } } if ($criteria->type) { $typeIds = array(); if (!is_array($criteria->type)) { $criteria->type = array($criteria->type); } foreach ($criteria->type as $type) { if (is_numeric($type)) { $typeIds[] = $type; } else { if (is_string($type)) { $types = craft()->sections->getEntryTypesByHandle($type); if ($types) { foreach ($types as $type) { $typeIds[] = $type->id; } } else { return false; } } else { if ($type instanceof EntryTypeModel) { $typeIds[] = $type->id; } else { return false; } } } } $query->andWhere(DbHelper::parseParam('entries.typeId', $typeIds, $query->params)); } if ($criteria->postDate) { $query->andWhere(DbHelper::parseDateParam('entries.postDate', $criteria->postDate, $query->params)); } else { if ($criteria->after) { $query->andWhere(DbHelper::parseDateParam('entries.postDate', '>=' . $criteria->after, $query->params)); } if ($criteria->before) { $query->andWhere(DbHelper::parseDateParam('entries.postDate', '<' . $criteria->before, $query->params)); } } if ($criteria->expiryDate) { $query->andWhere(DbHelper::parseDateParam('entries.expiryDate', $criteria->expiryDate, $query->params)); } if ($criteria->editable) { $user = craft()->userSession->getUser(); if (!$user) { return false; } // Limit the query to only the sections the user has permission to edit $editableSectionIds = craft()->sections->getEditableSectionIds(); $query->andWhere(array('in', 'entries.sectionId', $editableSectionIds)); // Enforce the editPeerEntries permissions for non-Single sections $noPeerConditions = array(); foreach (craft()->sections->getEditableSections() as $section) { if ($section->type != SectionType::Single && !$user->can('editPeerEntries:' . $section->id)) { $noPeerConditions[] = array('or', 'entries.sectionId != ' . $section->id, 'entries.authorId = ' . $user->id); } } if ($noPeerConditions) { array_unshift($noPeerConditions, 'and'); $query->andWhere($noPeerConditions); } } if ($criteria->section) { if ($criteria->section instanceof SectionModel) { $criteria->sectionId = $criteria->section->id; $criteria->section = null; } else { $query->andWhere(DbHelper::parseParam('sections.handle', $criteria->section, $query->params)); } } if ($criteria->sectionId) { $query->andWhere(DbHelper::parseParam('entries.sectionId', $criteria->sectionId, $query->params)); } if (craft()->getEdition() >= Craft::Client) { if ($criteria->authorId) { $query->andWhere(DbHelper::parseParam('entries.authorId', $criteria->authorId, $query->params)); } if ($criteria->authorGroupId || $criteria->authorGroup) { $query->join('usergroups_users usergroups_users', 'usergroups_users.userId = entries.authorId'); if ($criteria->authorGroupId) { $query->andWhere(DbHelper::parseParam('usergroups_users.groupId', $criteria->authorGroupId, $query->params)); } if ($criteria->authorGroup) { $query->join('usergroups usergroups', 'usergroups.id = usergroups_users.groupId'); $query->andWhere(DbHelper::parseParam('usergroups.handle', $criteria->authorGroup, $query->params)); } } } }
/** * 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('pushnotifications_notifications.appId, pushnotifications_notifications.title, pushnotifications_notifications.body, pushnotifications_notifications.command, pushnotifications_notifications.schedule')->join('pushnotifications_notifications pushnotifications_notifications', 'pushnotifications_notifications.id = elements.id'); if ($criteria->appId) { $query->andWhere(DbHelper::parseParam('pushnotifications_notifications.appId', $criteria->appId, $query->params)); } if ($criteria->app) { $query->join('pushnotifications_apps pushnotifications_apps', 'pushnotifications_apps.id = pushnotifications_notifications.appId'); $query->andWhere(DbHelper::parseParam('pushnotifications_apps.handle', $criteria->app, $query->params)); } if ($criteria->title) { $query->andWhere(DbHelper::parseParam('pushnotifications_notifications.title', $criteria->title, $query->params)); } if ($criteria->body) { $query->andWhere(DbHelper::parseParam('pushnotifications_notifications.body', $criteria->body, $query->params)); } if ($criteria->command) { $query->andWhere(DbHelper::parseParam('pushnotifications_notifications.command', $criteria->command, $query->params)); } if ($criteria->schedule) { $query->andWhere(DbHelper::parseDateParam('pushnotifications_notifications.schedule', $criteria->schedule, $query->params)); } }
/** * 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)); } }
public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect('comments.elementId, comments.userId, comments.elementType, comments.structureId, comments.status, comments.name, comments.email, comments.url, comments.ipAddress, comments.userAgent, comments.comment, comments.dateCreated AS commentDate')->join('comments comments', 'comments.id = elements.id')->leftJoin('comments_votes comments_votes', 'comments_votes.commentId = comments.id')->leftJoin('structures structures', 'structures.id = comments.structureId')->leftJoin('structureelements structureelements', array('and', 'structureelements.structureId = structures.id', 'structureelements.elementId = comments.id')); if ($criteria->elementId) { $query->andWhere(DbHelper::parseParam('comments.elementId', $criteria->elementId, $query->params)); } if ($criteria->elementType) { $query->andWhere(DbHelper::parseParam('comments.elementType', $criteria->elementType, $query->params)); } if ($criteria->userId) { $query->andWhere(DbHelper::parseParam('comments.userId', $criteria->userId, $query->params)); } if ($criteria->structureId) { $query->andWhere(DbHelper::parseParam('comments.structureId', $criteria->structureId, $query->params)); } if ($criteria->status) { $query->andWhere(DbHelper::parseParam('comments.status', $criteria->status, $query->params)); } if ($criteria->name) { $query->andWhere(DbHelper::parseParam('comments.name', $criteria->name, $query->params)); } if ($criteria->email) { $query->andWhere(DbHelper::parseParam('comments.email', $criteria->email, $query->params)); } if ($criteria->url) { $query->andWhere(DbHelper::parseParam('comments.url', $criteria->url, $query->params)); } if ($criteria->ipAddress) { $query->andWhere(DbHelper::parseParam('comments.ipAddress', $criteria->ipAddress, $query->params)); } if ($criteria->userAgent) { $query->andWhere(DbHelper::parseParam('comments.userAgent', $criteria->userAgent, $query->params)); } if ($criteria->comment) { $query->andWhere(DbHelper::parseParam('comments.comment', $criteria->comment, $query->params)); } if ($criteria->dateCreated) { $query->andWhere(DbHelper::parseDateParam('comments.dateCreated', $criteria->dateCreated, $query->params)); } }
public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect("products.id, products.typeId, products.promotable, products.freeShipping, products.availableOn, products.expiresOn, products.taxCategoryId, products.authorId")->join('market_products products', 'products.id = elements.id')->join('market_producttypes producttypes', 'producttypes.id = products.typeId'); if ($criteria->availableOn) { $query->andWhere(DbHelper::parseDateParam('products.availableOn', $criteria->availableOn, $query->params)); } else { if ($criteria->after) { $query->andWhere(DbHelper::parseDateParam('products.availableOn', '>=' . $criteria->after, $query->params)); } if ($criteria->before) { $query->andWhere(DbHelper::parseDateParam('products.availableOn', '<' . $criteria->before, $query->params)); } } if ($criteria->expiresOn) { $query->andWhere(DbHelper::parseDateParam('products.expiresOn', $criteria->expiresOn, $query->params)); } if ($criteria->type) { if ($criteria->type instanceof Market_ProductTypeModel) { $criteria->typeId = $criteria->type->id; $criteria->type = NULL; } else { $query->andWhere(DbHelper::parseParam('producttypes.handle', $criteria->type, $query->params)); } } if ($criteria->typeId) { $query->andWhere(DbHelper::parseParam('products.typeId', $criteria->typeId, $query->params)); } }
/** * 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; } }
/** * @inheritDoc IElementType::modifyElementsQuery() * * @param DbCommand $query * @param ElementCriteriaModel $criteria * * @return mixed */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { $query->addSelect('users.username, users.photo, users.firstName, users.lastName, users.email, users.admin, users.client, users.locked, users.pending, users.suspended, users.archived, users.lastLoginDate, users.lockoutDate, users.preferredLocale')->join('users users', 'users.id = elements.id'); if ($criteria->admin) { $query->andWhere(DbHelper::parseParam('users.admin', $criteria->admin, $query->params)); } if ($criteria->client && craft()->getEdition() == Craft::Client) { $query->andWhere(DbHelper::parseParam('users.client', $criteria->client, $query->params)); } if ($criteria->can && craft()->getEdition() == Craft::Pro) { // Get the actual permission ID if (is_numeric($criteria->can)) { $permissionId = $criteria->can; } else { $permissionId = craft()->db->createCommand()->select('id')->from('userpermissions')->where('name = :name', array(':name' => strtolower($criteria->can)))->queryScalar(); } // Find the users that have that permission, either directly or through a group $permittedUserIds = array(); // If the permission hasn't been assigned to any groups/users before, it won't have an ID. Don't bail // though, since we still want to look for admins. if ($permissionId) { // Get the user groups that have that permission $permittedGroupIds = craft()->db->createCommand()->select('groupId')->from('userpermissions_usergroups')->where('permissionId = :permissionId', array(':permissionId' => $permissionId))->queryColumn(); if ($permittedGroupIds) { $permittedUserIds = $this->_getUserIdsByGroupIds($permittedGroupIds); } // Get the users that have that permission directly $permittedUserIds = array_merge($permittedUserIds, craft()->db->createCommand()->select('userId')->from('userpermissions_users')->where('permissionId = :permissionId', array(':permissionId' => $permissionId))->queryColumn()); } if ($permittedUserIds) { $permissionConditions = array('or', 'users.admin = 1', array('in', 'elements.id', $permittedUserIds)); } else { $permissionConditions = 'users.admin = 1'; } $query->andWhere($permissionConditions); } if ($criteria->groupId) { $userIds = $this->_getUserIdsByGroupIds($criteria->groupId); if (!$userIds) { return false; } $query->andWhere(array('in', 'elements.id', $userIds)); } if ($criteria->group) { // Get the actual group ID(s) $groupIdsQuery = craft()->db->createCommand()->select('id')->from('usergroups'); $groupIdsQuery->where(DbHelper::parseParam('handle', $criteria->group, $groupIdsQuery->params)); $groupIds = $groupIdsQuery->queryColumn(); // In the case where the group doesn't exist. if (!$groupIds) { return false; } $userIds = $this->_getUserIdsByGroupIds($groupIds); // In case there are no users in the groups. if (!$userIds) { return false; } $query->andWhere(array('in', 'elements.id', $userIds)); } if ($criteria->username) { $query->andWhere(DbHelper::parseParam('users.username', $criteria->username, $query->params)); } if ($criteria->firstName) { $query->andWhere(DbHelper::parseParam('users.firstName', $criteria->firstName, $query->params)); } if ($criteria->lastName) { $query->andWhere(DbHelper::parseParam('users.lastName', $criteria->lastName, $query->params)); } if ($criteria->email) { $query->andWhere(DbHelper::parseParam('users.email', $criteria->email, $query->params)); } if ($criteria->preferredLocale) { $query->andWhere(DbHelper::parseParam('users.preferredLocale', $criteria->preferredLocale, $query->params)); } if ($criteria->lastLoginDate) { $query->andWhere(DbHelper::parseDateParam('users.lastLoginDate', $criteria->lastLoginDate, $query->params)); } }
/** * Modifies an element query targeting elements of this type. * * @param DbCommand $query * @param ElementCriteriaModel $criteria * @return mixed */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { // you must add the columns here when adding a new field $query->addSelect('applications.formId, applications.firstName, applications.lastName, applications.email, applications.status, applications.phone, applications.dateCreated,')->join('applications applications', 'applications.id = elements.id'); if ($criteria->formId) { $query->andWhere(DbHelper::parseParam('applications.formId', $criteria->formId, $query->params)); } if ($criteria->form) { $query->join('applications_forms applications_forms', 'applications_forms.id = applications.formId'); $query->andWhere(DbHelper::parseParam('applications_forms.handle', $criteria->form, $query->params)); } if ($criteria->dateCreated) { $query->andWhere(DbHelper::parseDateParam('entries.dateCreated', $criteria->dateCreated, $query->params)); } }
/** * Returns a DbCommand instance ready to search for elements based on a given element criteria. * * @param mixed &$criteria * @return DbCommand|false */ public function buildElementsQuery(&$criteria = null) { if (!$criteria instanceof ElementCriteriaModel) { $criteria = $this->getCriteria('Entry', $criteria); } $elementType = $criteria->getElementType(); $query = craft()->db->createCommand()->select('elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated, elements_i18n.locale, elements_i18n.uri')->from('elements elements'); if ($elementType->hasTitles() && $criteria) { $query->addSelect('content.title'); $query->join('content content', 'content.elementId = elements.id'); } $query->leftJoin('elements_i18n elements_i18n', 'elements_i18n.elementId = elements.id'); if ($elementType->isTranslatable()) { // Locale conditions if (!$criteria->locale) { $criteria->locale = craft()->language; } $localeIds = array_unique(array_merge(array($criteria->locale), craft()->i18n->getSiteLocaleIds())); $quotedLocaleColumn = craft()->db->quoteColumnName('elements_i18n.locale'); if (count($localeIds) == 1) { $query->andWhere('elements_i18n.locale = :locale'); $query->params[':locale'] = $localeIds[0]; } else { $quotedLocales = array(); $localeOrder = array(); foreach ($localeIds as $localeId) { $quotedLocale = craft()->db->quoteValue($localeId); $quotedLocales[] = $quotedLocale; $localeOrder[] = "({$quotedLocaleColumn} = {$quotedLocale}) DESC"; } $query->andWhere("{$quotedLocaleColumn} IN (" . implode(', ', $quotedLocales) . ')'); $query->order($localeOrder); } } // The rest if ($criteria->id) { $query->andWhere(DbHelper::parseParam('elements.id', $criteria->id, $query->params)); } if ($criteria->uri !== null) { $query->andWhere(DbHelper::parseParam('elements_i18n.uri', $criteria->uri, $query->params)); } if ($criteria->archived) { $query->andWhere('elements.archived = 1'); } else { $query->andWhere('elements.archived = 0'); if ($criteria->status) { $statusConditions = array(); $statuses = ArrayHelper::stringToArray($criteria->status); foreach ($statuses as $status) { $status = strtolower($status); switch ($status) { case BaseElementModel::ENABLED: $statusConditions[] = 'elements.enabled = 1'; break; case BaseElementModel::DISABLED: $statusConditions[] = 'elements.enabled = 0'; default: // Maybe the element type supports another status? $elementStatusCondition = $elementType->getElementQueryStatusCondition($query, $status); if ($elementStatusCondition) { $statusConditions[] = $elementStatusCondition; } else { if ($elementStatusCondition === false) { return false; } } } } if ($statusConditions) { if (count($statusConditions) == 1) { $statusCondition = $statusConditions[0]; } else { array_unshift($statusConditions, 'or'); $statusCondition = $statusConditions; } $query->andWhere($statusCondition); } } } if ($criteria->dateCreated) { $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', '=', $criteria->dateCreated, $query->params)); } if ($criteria->dateUpdated) { $query->andWhere(DbHelper::parseDateParam('elements.dateUpdated', '=', $criteria->dateUpdated, $query->params)); } if ($criteria->parentOf) { list($childIds, $fieldIds) = $this->_normalizeRelationParams($criteria->parentOf, $criteria->parentField); $query->join('relations parents', 'parents.parentId = elements.id'); $query->andWhere(DbHelper::parseParam('parents.childId', $childIds, $query->params)); if ($fieldIds) { $query->andWhere(DbHelper::parseParam('parents.fieldId', $fieldIds, $query->params)); } } if ($criteria->childOf) { list($parentIds, $fieldIds) = $this->_normalizeRelationParams($criteria->childOf, $criteria->childField); $query->join('relations children', 'children.childId = elements.id'); $query->andWhere(DbHelper::parseParam('children.parentId', $parentIds, $query->params)); } if ($elementType->modifyElementsQuery($query, $criteria) !== false) { return $query; } else { return false; } }
/** * @inheritDoc IFieldType::modifyElementsQuery() * * @param DbCommand $query * @param mixed $value * * @return null|false */ public function modifyElementsQuery(DbCommand $query, $value) { if ($value !== null) { $handle = $this->model->handle; $query->andWhere(DbHelper::parseDateParam('content.' . craft()->content->fieldColumnPrefix . $handle, $value, $query->params)); } }
/** * 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('events.calendarId, events.startDate, events.endDate')->join('events events', 'events.id = elements.id'); if ($criteria->calendarId) { $query->andWhere(DbHelper::parseParam('events.calendarId', $criteria->calendarId, $query->params)); } if ($criteria->calendar) { $query->join('events_calendars events_calendars', 'events_calendars.id = events.calendarId'); $query->andWhere(DbHelper::parseParam('events_calendars.handle', $criteria->calendar, $query->params)); } if ($criteria->startDate) { $query->andWhere(DbHelper::parseDateParam('events.startDate', $criteria->startDate, $query->params)); } if ($criteria->endDate) { $query->andWhere(DbHelper::parseDateParam('events.endDate', $criteria->endDate, $query->params)); } }
/** * 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('charges.userId, charges.planCurrency, charges.sourceUrl, charges.planAmount, charges.planType, charges.planInterval, charges.planIntervalCount, charges.cardName, charges.cardExpMonth, charges.cardExpYear, charges.cardAddressLine1, charges.cardAddressLine2, charges.cardAddressCity, charges.cardAddressState, charges.cardAddressZip, charges.cardAddressCountry, charges.cardLast4, charges.cardType, charges.customerName, charges.customerEmail, charges.stripe, charges.mode, charges.description, charges.timestamp, charges.hash, charges.notes, charges.planCoupon, charges.planCouponStripeId, charges.planDiscount, charges.planFullAmount, charges.stripeCustomerId, charges.stripeChargeId, charges.meta')->join('charges charges', 'charges.id = elements.id'); if ($criteria->userId) { $query->andWhere(DbHelper::parseParam('charges.userId', $criteria->userId, $query->params)); } if ($criteria->sourceUrl) { $query->andWhere(DbHelper::parseParam('charges.sourceUrl', $criteria->sourceUrl, $query->params)); } if ($criteria->timestamp) { $query->andWhere(DbHelper::parseDateParam('charges.timestamp', $criteria->timestamp, $query->params)); } if ($criteria->hash) { $query->andWhere(DbHelper::parseParam('charges.hash', $criteria->hash, $query->params)); } if ($criteria->customerEmail) { $query->andWhere(DbHelper::parseParam('charges.customerEmail', $criteria->customerEmail, $query->params)); } if ($criteria->customerName) { $query->andWhere(DbHelper::parseParam('charges.customerName', $criteria->customerName, $query->params)); } if ($criteria->stripeCustomerId) { $query->andWhere(DbHelper::parseParam('charges.stripeCustomerId', $criteria->stripeCustomerId, $query->params)); } if ($criteria->stripeChargeId) { $query->andWhere(DbHelper::parseParam('charges.stripeChargeId', $criteria->stripeChargeId, $query->params)); } if ($criteria->meta) { $query->andWhere(DbHelper::parseParam('charges.meta', $criteria->meta, $query->params)); } }