/**
  * Paginates an ElementCriteriaModel instance.
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return array
  */
 public static function paginateCriteria(ElementCriteriaModel $criteria)
 {
     $currentPage = craft()->request->getPageNum();
     $limit = $criteria->limit;
     $total = $criteria->total() - $criteria->offset;
     $totalPages = ceil($total / $limit);
     if ($currentPage > $totalPages) {
         $currentPage = $totalPages;
     }
     $offset = $limit * ($currentPage - 1);
     // Is there already an offset set?
     if ($criteria->offset) {
         $offset += $criteria->offset;
     }
     $last = $offset + $limit;
     if ($last > $total) {
         $last = $total;
     }
     $paginateVariable = new PaginateVariable();
     $paginateVariable->first = $offset + 1;
     $paginateVariable->last = $last;
     $paginateVariable->total = $total;
     $paginateVariable->currentPage = $currentPage;
     $paginateVariable->totalPages = $totalPages;
     // Get the entities
     $criteria->offset = $offset;
     $entities = $criteria->find();
     return array($paginateVariable, $entities);
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     // Get all submission
     $submissions = $criteria->find();
     // Gather submissions based on form
     $formSubmissions = array();
     foreach ($submissions as $submission) {
         if (!isset($formSubmissions[$submission->formId])) {
             $formSubmissions[$submission->formId] = array();
         }
         $formSubmissions[$submission->formId][] = $submission->id;
     }
     // Export submission(s)
     foreach ($formSubmissions as $formId => $submissionIds) {
         $total = count($submissionIds);
         $export = new AmForms_ExportModel();
         $export->name = Craft::t('{total} submission(s)', array('total' => $total));
         $export->formId = $formId;
         $export->total = $total;
         $export->totalCriteria = $total;
         $export->submissions = $submissionIds;
         craft()->amForms_exports->saveExport($export);
     }
     // Success!
     $this->setMessage(Craft::t('Submissions exported.'));
     return true;
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $status = $this->getParams()->status;
     //False by default
     $enable = 0;
     switch ($status) {
         case SproutSeo_RedirectStatuses::ON:
             $enable = '1';
             break;
         case SproutSeo_RedirectStatuses::OFF:
             $enable = '0';
             break;
     }
     $elementIds = $criteria->ids();
     // Update their statuses
     craft()->db->createCommand()->update('elements', array('enabled' => $enable), array('in', 'id', $elementIds));
     if ($status == SproutSeo_RedirectStatuses::ON) {
         // Enable their locale as well
         craft()->db->createCommand()->update('elements_i18n', array('enabled' => $enable), array('and', array('in', 'elementId', $elementIds), 'locale = :locale'), array(':locale' => $criteria->locale));
     }
     // Clear their template caches
     craft()->templateCache->deleteCachesByElementId($elementIds);
     // Fire an 'onSetStatus' event
     $this->onSetStatus(new Event($this, array('criteria' => $criteria, 'elementIds' => $elementIds, 'status' => $status)));
     $this->setMessage(Craft::t('Statuses updated.'));
     return true;
 }
 /**
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $status = $this->getParams()->status;
     $archived = $enable = 0;
     switch ($status) {
         case SproutEmail_EntryModel::ENABLED:
             $enable = 1;
             break;
         case SproutEmail_EntryModel::DISABLED:
             $enable = 0;
             break;
         case SproutEmail_EntryModel::ARCHIVED:
             $archived = 1;
             break;
     }
     $elementIds = $criteria->ids();
     // Update their statuses
     craft()->db->createCommand()->update('elements', array('enabled' => $enable, 'archived' => $archived), array('in', 'id', $elementIds));
     if ($status == SproutEmail_EntryModel::ENABLED) {
         // Enable their locale as well
         craft()->db->createCommand()->update('elements_i18n', array('enabled' => $enable), array('and', array('in', 'elementId', $elementIds), 'locale = :locale'), array(':locale' => $criteria->locale));
     }
     // Clear their template caches
     craft()->templateCache->deleteCachesByElementId($elementIds);
     // Fire an 'onSetStatus' event
     $this->onSetStatus(new Event($this, array('criteria' => $criteria, 'elementIds' => $elementIds, 'status' => $status)));
     $this->setMessage(Craft::t('Statuses updated.'));
     return true;
 }
 public function performAction(ElementCriteriaModel $criteria)
 {
     if (craft()->varnishpurge->getSetting('varnishPurgeEnabled')) {
         $elements = $criteria->find();
         craft()->varnishpurge->purgeElements($elements, false);
         $this->setMessage(Craft::t('Varnish cache was purged.'));
         return true;
     }
 }
 /**
  * Perform action
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $entries = $criteria->find();
     foreach ($entries as $entry) {
         craft()->entryCount->reset($entry->id);
     }
     $this->setMessage(Craft::t('Entry Count Successfully Reset'));
     return true;
 }
 public function performAction(ElementCriteriaModel $criteria)
 {
     $assets = $criteria->find();
     foreach ($assets as $asset) {
         craft()->imager->removeTransformsForAsset($asset);
     }
     $this->setMessage(Craft::t('Transforms were removed'));
     return true;
 }
    /**
     * @inheritDoc IElementAction::performAction()
     *
     * @param ElementCriteriaModel $criteria
     *
     * @return bool
     */
    public function performAction(ElementCriteriaModel $criteria)
    {
        craft()->httpSession->add('__exportJob', $criteria->getAttributes());
        $this->setMessage($this->getParams()->successMessage);
        craft()->templates->includeJs('
			var exportUrl = Craft.getActionUrl("sproutEmail/defaultMailer/export");
			setTimeout(function() { window.location=exportUrl; }, 1500);
		');
        return true;
    }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $elementIds = $criteria->ids();
     $response = false;
     // Call updateMethods service
     $response = sproutSeo()->redirects->updateMethods($elementIds, SproutSeo_RedirectMethods::Temporary);
     $message = sproutSeo()->redirects->getMethodUpdateResponse($response);
     $this->setMessage($message);
     return $response;
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     // Get the users that are suspended
     $criteria->status = UserStatus::Suspended;
     $users = $criteria->find();
     foreach ($users as $user) {
         craft()->users->unsuspendUser($user);
     }
     $this->setMessage(Craft::t('Users unsuspended.'));
     return true;
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     // Get the users that aren't already suspended
     $criteria->status = array(UserStatus::Active, UserStatus::Locked, UserStatus::Pending);
     $users = $criteria->find();
     foreach ($users as $user) {
         if (!$user->isCurrent()) {
             craft()->users->suspendUser($user);
         }
     }
     $this->setMessage(Craft::t('Users suspended.'));
     return true;
 }
 public function performAction(ElementCriteriaModel $criteria)
 {
     $status = $this->getParams()->status;
     // Figure out which element IDs we need to update
     $elementIds = $criteria->ids();
     // Update their statuses
     craft()->db->createCommand()->update('workflow_submissions', array('status' => $status), array('in', 'id', $elementIds));
     // Clear their template caches
     craft()->templateCache->deleteCachesByElementId($elementIds);
     // Fire an 'onSetStatus' event
     $this->onSetStatus(new Event($this, array('criteria' => $criteria, 'elementIds' => $elementIds, 'status' => $status)));
     $this->setMessage(Craft::t('Statuses updated.'));
     return true;
 }
 /**
  * Dump the results of our query in array form,
  * before the results get populated into EntryModels.
  */
 public function showResults()
 {
     if (!$this->dbCommand) {
         Craft::dd($this->criteria->find());
     }
     Craft::dd($this->dbCommand->queryAll());
 }
 public function performAction(ElementCriteriaModel $criteria)
 {
     // Get the selected category
     $categoryId = $this->getParams()->category;
     $category = craft()->forumCategories->getCategoryById($categoryId);
     // Make sure it's a valid one
     if (!$category) {
         $this->setMessage(Craft::t('The selected category could not be found.'));
         return false;
     }
     // Add the category to the selected elements
     $elements = $criteria->find();
     foreach ($elements as $element) {
         craft()->forumCategories->addCategoryToElement($element, $category);
     }
     // Success!
     $this->setMessage(Craft::t('Category added successfully.'));
     return true;
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $variants = $criteria->find();
     $attributes = ['price', 'minQty', 'maxQty', 'width', 'height', 'length', 'weight'];
     try {
         foreach ($variants as $variant) {
             foreach ($attributes as $attribute) {
                 $set = $this->getParams()->{'set' . ucfirst($attribute)};
                 if ($set) {
                     $variant->{$attribute} = $this->getParams()->{$attribute};
                 }
             }
             craft()->market_variant->save($variant);
         }
     } catch (Exception $e) {
         $this->setMessage(Craft::t('Error'));
         return false;
     }
     $this->setMessage(Craft::t('Variants updated.'));
     return true;
 }
 /**
  * Sets a filter value for the criteria model, then reruns Live Preview filtering.
  *
  * @param string $name
  * @param mixed $value
  * @return bool
  */
 public function setAttribute($name, $value)
 {
     if (parent::setAttribute($name, $value)) {
         $method = '__' . $name;
         // Only bother setting and rerunning the filter if there exists a filtering method for it.
         if (method_exists($this, $method)) {
             $this->_currentFilters[$name] = $value;
             $this->_runCriteria();
         }
         return true;
     }
     return false;
 }
 /**
  * Paginates an ElementCriteriaModel instance.
  */
 public static function paginateCriteria(ElementCriteriaModel $criteria)
 {
     $currentPage = craft()->request->getPageNum();
     $limit = $criteria->limit;
     $total = $criteria->total();
     $totalPages = ceil($total / $limit);
     if ($currentPage > $totalPages) {
         $currentPage = $totalPages;
     }
     $offset = $limit * ($currentPage - 1);
     $path = craft()->request->getPath();
     $pageUrlPrefix = ($path ? $path . '/' : '') . craft()->config->get('pageTrigger');
     $last = $offset + $limit;
     if ($last > $total) {
         $last = $total;
     }
     $info = array('first' => $offset + 1, 'last' => $last, 'total' => $total, 'currentPage' => $currentPage, 'totalPages' => $totalPages, 'prevUrl' => $currentPage > 1 ? UrlHelper::getUrl($pageUrlPrefix . ($currentPage - 1)) : null, 'nextUrl' => $currentPage < $totalPages ? UrlHelper::getUrl($pageUrlPrefix . ($currentPage + 1)) : null);
     // Get the entities
     $criteria->offset = $offset;
     $entities = $criteria->find();
     return array($info, $entities);
 }
 /**
  * Performs an action on one or more selected elements.
  *
  * @throws HttpException
  * @return null
  */
 public function actionPerformAction()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     $requestService = craft()->request;
     $actionHandle = $requestService->getRequiredPost('elementAction');
     $elementIds = $requestService->getRequiredPost('elementIds');
     // Find that action from the list of available actions for the source
     if ($this->_actions) {
         foreach ($this->_actions as $availableAction) {
             if ($actionHandle == $availableAction->getClassHandle()) {
                 $action = $availableAction;
                 break;
             }
         }
     }
     if (!isset($action)) {
         throw new HttpException(400);
     }
     // Check for any params in the post data
     $params = $action->getParams();
     foreach ($params->attributeNames() as $paramName) {
         $paramValue = $requestService->getPost($paramName);
         if ($paramValue !== null) {
             $params->setAttribute($paramName, $paramValue);
         }
     }
     // Make sure they validate
     if (!$params->validate()) {
         throw new HttpException(400);
     }
     // Perform the action
     $actionCriteria = $this->_criteria->copy();
     $actionCriteria->offset = 0;
     $actionCriteria->limit = null;
     $actionCriteria->order = null;
     $actionCriteria->positionedAfter = null;
     $actionCriteria->positionedBefore = null;
     $actionCriteria->id = $elementIds;
     $success = $action->performAction($actionCriteria);
     // Respond
     $response = array('success' => $success, 'message' => $action->getMessage());
     if ($success) {
         // Send a new set of elements
         $response['html'] = $this->_getElementHtml(false);
         $includeLoadMoreInfo = true;
     } else {
         $includeLoadMoreInfo = false;
     }
     $this->_respond($response, $includeLoadMoreInfo);
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $status = $this->getParams()->status;
     // Figure out which element IDs we need to update
     if ($status == BaseElementModel::ENABLED) {
         $sqlNewStatus = '1';
     } else {
         $sqlNewStatus = '0';
     }
     $elementIds = $criteria->ids();
     // Update their statuses
     craft()->db->createCommand()->update('elements', array('enabled' => $sqlNewStatus), array('in', 'id', $elementIds));
     if ($status == BaseElementModel::ENABLED) {
         // Enable their locale as well
         craft()->db->createCommand()->update('elements_i18n', array('enabled' => $sqlNewStatus), array('and', array('in', 'elementId', $elementIds), 'locale = :locale'), array(':locale' => $criteria->locale));
     }
     // Clear their template caches
     craft()->templateCache->deleteCachesByElementId($elementIds);
     // Fire an 'onSetStatus' event
     $this->onSetStatus(new Event($this, array('criteria' => $criteria, 'elementIds' => $elementIds, 'status' => $status)));
     $this->setMessage(Craft::t('Statuses updated.'));
     return true;
 }
 /**
  * Paginates an ElementCriteriaModel instance.
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return array
  */
 public static function paginateCriteria(ElementCriteriaModel $criteria)
 {
     $currentPage = craft()->request->getPageNum();
     $limit = $criteria->limit;
     $total = $criteria->total() - $criteria->offset;
     // If they specified limit as null or 0 (for whatever reason), just assume it's all going to be on one page.
     if (!$limit) {
         $limit = $total;
     }
     $totalPages = ceil($total / $limit);
     $paginateVariable = new PaginateVariable();
     if ($totalPages == 0) {
         return array($paginateVariable, array());
     }
     if ($currentPage > $totalPages) {
         $currentPage = $totalPages;
     }
     $offset = $limit * ($currentPage - 1);
     // Is there already an offset set?
     if ($criteria->offset) {
         $offset += $criteria->offset;
     }
     $last = $offset + $limit;
     if ($last > $total) {
         $last = $total;
     }
     $paginateVariable->first = $offset + 1;
     $paginateVariable->last = $last;
     $paginateVariable->total = $total;
     $paginateVariable->currentPage = $currentPage;
     $paginateVariable->totalPages = $totalPages;
     // Copy the criteria, set the offset, and get the elements
     $criteria = $criteria->copy();
     $criteria->offset = $offset;
     $elements = $criteria->find();
     return array($paginateVariable, $elements);
 }
 /**
  * Deletes caches that include elements that match a given criteria.
  *
  * @param ElementCriteriaModel $criteria The criteria that should be used to find elements whose caches should be
  *                                       deleted.
  *
  * @return bool
  */
 public function deleteCachesByCriteria(ElementCriteriaModel $criteria)
 {
     if ($this->_deletedAllCaches) {
         return false;
     }
     $criteria->limit = null;
     $elementIds = $criteria->ids();
     return $this->deleteCachesByElementId($elementIds);
 }
 /**
  * @inheritDoc BaseModel::defineAttributes()
  *
  * @return array
  */
 protected function defineAttributes()
 {
     return array_merge(parent::defineAttributes(), array('id' => AttributeType::Number, 'eid' => AttributeType::Number, 'eventid' => AttributeType::Number, 'startDate' => AttributeType::Mixed, 'endDate' => AttributeType::Mixed, 'allDay' => AttributeType::Number, 'repeat' => AttributeType::Number, 'rRule' => AttributeType::String, 'summary' => AttributeType::String, 'isrepeat' => AttributeType::Number, 'limit' => array('default' => 1000, AttributeType::Number), 'order' => array(AttributeType::String, 'default' => 'venti.startDate asc')));
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $users = $criteria->find();
     $undeletableIds = $this->_getUndeletableUserIds();
     // Are we transfering the user's content to a different user?
     $transferContentToId = $this->getParams()->transferContentTo;
     if (is_array($transferContentToId) && isset($transferContentToId[0])) {
         $transferContentToId = $transferContentToId[0];
     }
     if ($transferContentToId) {
         $transferContentTo = craft()->users->getUserById($transferContentToId);
         if (!$transferContentTo) {
             throw new Exception(Craft::t('No user exists with the ID “{id}”.', array('id' => $transferContentTo)));
         }
     } else {
         $transferContentTo = null;
     }
     // Delete the users
     foreach ($users as $user) {
         if (!in_array($user->id, $undeletableIds)) {
             craft()->users->deleteUser($user, $transferContentTo);
         }
     }
     $this->setMessage(Craft::t('Users deleted.'));
     return true;
 }
 /**
  * @inheritDoc IFieldType::getSearchKeywords()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return string
  */
 public function getSearchKeywords($criteria)
 {
     $titles = array();
     foreach ($criteria->find() as $element) {
         $titles[] = (string) $element;
     }
     return parent::getSearchKeywords($titles);
 }
 /**
  * @inheritDoc IElementType::modifyElementsQuery()
  *
  * @param DbCommand            $query
  * @param ElementCriteriaModel $criteria
  *
  * @return mixed
  */
 public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
 {
     $query->addSelect('assetfiles.sourceId, assetfiles.folderId, assetfiles.filename, assetfiles.kind, assetfiles.width, assetfiles.height, assetfiles.size, assetfiles.dateModified, assetfolders.path as folderPath')->join('assetfiles assetfiles', 'assetfiles.id = elements.id')->join('assetfolders assetfolders', 'assetfolders.id = assetfiles.folderId');
     if (!empty($criteria->source)) {
         $query->join('assetsources assetsources', 'assetfiles.sourceId = assetsources.id');
     }
     if ($criteria->sourceId) {
         $query->andWhere(DbHelper::parseParam('assetfiles.sourceId', $criteria->sourceId, $query->params));
     }
     if ($criteria->source) {
         $query->andWhere(DbHelper::parseParam('assetsources.handle', $criteria->source, $query->params));
     }
     if ($criteria->folderId) {
         if ($criteria->includeSubfolders) {
             $folders = craft()->assets->getAllDescendantFolders(craft()->assets->getFolderById($criteria->folderId));
             $query->andWhere(DbHelper::parseParam('assetfiles.folderId', array_keys($folders), $query->params));
         } else {
             $query->andWhere(DbHelper::parseParam('assetfiles.folderId', $criteria->folderId, $query->params));
         }
     }
     if ($criteria->filename) {
         $query->andWhere(DbHelper::parseParam('assetfiles.filename', $criteria->filename, $query->params));
     }
     if ($criteria->kind) {
         if (is_array($criteria->kind)) {
             $query->andWhere(DbHelper::parseParam('assetfiles.kind', array_merge(array('or'), $criteria->kind), $query->params));
         } else {
             $query->andWhere(DbHelper::parseParam('assetfiles.kind', $criteria->kind, $query->params));
         }
     }
     if ($criteria->width) {
         $query->andWhere(DbHelper::parseParam('assetfiles.width', $criteria->width, $query->params));
     }
     if ($criteria->height) {
         $query->andWhere(DbHelper::parseParam('assetfiles.height', $criteria->height, $query->params));
     }
     if ($criteria->size) {
         $query->andWhere(DbHelper::parseParam('assetfiles.size', $criteria->size, $query->params));
     }
     // Clear out existing onPopulateElements handlers
     $criteria->detachEventHandler('onPopulateElements', array($this, 'eagerLoadTransforms'));
     // Are we eager-loading any transforms?
     if ($criteria->withTransforms) {
         $criteria->attachEventHandler('onPopulateElements', array($this, 'eagerLoadTransforms'));
     }
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     craft()->assets->deleteFiles($criteria->ids());
     $this->setMessage(Craft::t('Assets deleted.'));
     return true;
 }
Example #27
0
 /**
  * Populates element models from a given element query's result set.
  *
  * @param array                $results      The result set of an element query
  * @param ElementCriteriaModel $criteria     The element criteria model
  * @param string               $contentTable The content table that was joined in by buildElementsQuery()
  * @param array                $fieldColumns Info about the content field columns being selected
  *
  * @return BaseElementModel[] The populated element models.
  */
 public function populateElements($results, ElementCriteriaModel $criteria, $contentTable, $fieldColumns)
 {
     $elements = array();
     $locale = $criteria->locale;
     $elementType = $criteria->getElementType();
     $indexBy = $criteria->indexBy;
     $lastElement = null;
     foreach ($results as $result) {
         // Do we have a placeholder for this element?
         if (isset($this->_placeholderElements[$result['id']][$locale])) {
             $element = $this->_placeholderElements[$result['id']][$locale];
         } else {
             // Make a copy to pass to the onPopulateElement event
             $originalResult = array_merge($result);
             if ($contentTable) {
                 // Separate the content values from the main element attributes
                 $content = array('id' => isset($result['contentId']) ? $result['contentId'] : null, 'elementId' => $result['id'], 'locale' => $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'] = $locale;
             // Should we set a search score on the element?
             if (isset($this->_searchResults[$result['id']])) {
                 $result['searchScore'] = $this->_searchResults[$result['id']];
             }
             $element = $elementType->populateElementModel($result);
             // Was an element returned?
             if (!$element || !$element instanceof BaseElementModel) {
                 continue;
             }
             if ($contentTable) {
                 $element->setContent($content);
             }
             // Fire an 'onPopulateElement' event
             $this->onPopulateElement(new Event($this, array('element' => $element, 'result' => $originalResult)));
         }
         if ($indexBy) {
             $elements[$element->{$indexBy}] = $element;
         } else {
             $elements[] = $element;
         }
         if ($lastElement) {
             $lastElement->setNext($element);
             $element->setPrev($lastElement);
         } else {
             $element->setPrev(false);
         }
         $lastElement = $element;
     }
     $lastElement->setNext(false);
     // Should we eager-load some elements onto these?
     if ($criteria->with) {
         $this->eagerLoadElements($elementType, $elements, $criteria->with);
     }
     // Fire an 'onPopulateElements' event
     $this->onPopulateElements(new Event($this, array('elements' => $elements, 'criteria' => $criteria)));
     // Fire the criteria's 'onPopulateElements' event
     $criteria->onPopulateElements(new Event($criteria, array('elements' => $elements)));
     return $elements;
 }
 /**
  * @param ElementCriteriaModel $criteria
  * @param array                $disabledElementIds
  * @param array                $viewState
  * @param null|string          $sourceKey
  * @param null|string          $context
  * @param                      $includeContainer
  * @param                      $showCheckboxes
  *
  * @return string
  */
 public function getIndexHtml($criteria, $disabledElementIds, $viewState, $sourceKey, $context, $includeContainer, $showCheckboxes)
 {
     craft()->templates->includeJsResource('sproutemail/js/sproutmodal.js');
     craft()->templates->includeJs('var sproutModalInstance = new SproutModal(); sproutModalInstance.init();');
     sproutEmail()->mailers->includeMailerModalResources();
     $order = isset($viewState['order']) ? $viewState['order'] : 'dateCreated';
     $sort = isset($viewState['sort']) ? $viewState['sort'] : 'desc';
     $criteria->limit = null;
     $criteria->order = sprintf('%s %s', $order, $sort);
     return craft()->templates->render('sproutemail/entries/_entryindex', array('context' => $context, 'elementType' => new ElementTypeVariable($this), 'disabledElementIds' => $disabledElementIds, 'elements' => $criteria->find()));
 }
 /**
  * Returns an element at a specific offset.
  *
  * @param int $offset The offset.
  *
  * @return BaseElementModel|null The element, if there is one.
  */
 public function nth($offset)
 {
     if (!isset($this->_matchedElementsAtOffsets) || !array_key_exists($offset, $this->_matchedElementsAtOffsets)) {
         $criteria = new ElementCriteriaModel($this->getAttributes(), $this->_elementType);
         $criteria->offset = $offset;
         $criteria->limit = 1;
         $elements = $criteria->find();
         if ($elements) {
             $this->_matchedElementsAtOffsets[$offset] = $elements[0];
         } else {
             $this->_matchedElementsAtOffsets[$offset] = null;
         }
     }
     return $this->_matchedElementsAtOffsets[$offset];
 }
 /**
  * @inheritDoc IElementType::getIndexHtml()
  *
  * @param ElementCriteriaModel $criteria
  * @param array                $disabledElementIds
  * @param array                $viewState
  * @param null|string          $sourceKey
  * @param null|string          $context
  * @param bool                 $includeContainer
  * @param bool                 $showCheckboxes
  *
  * @return string
  */
 public function getIndexHtml($criteria, $disabledElementIds, $viewState, $sourceKey, $context, $includeContainer, $showCheckboxes)
 {
     $variables = array('viewMode' => $viewState['mode'], 'context' => $context, 'elementType' => new ElementTypeVariable($this), 'disabledElementIds' => $disabledElementIds, 'collapsedElementIds' => craft()->request->getParam('collapsedElementIds'), 'showCheckboxes' => $showCheckboxes);
     // Special case for sorting by structure
     if (isset($viewState['order']) && $viewState['order'] == 'structure') {
         $source = $this->getSource($sourceKey, $context);
         if (isset($source['structureId'])) {
             $criteria->order = 'lft asc';
             $variables['structure'] = craft()->structures->getStructureById($source['structureId']);
             // Are they allowed to make changes to this structure?
             if ($context == 'index' && $variables['structure'] && !empty($source['structureEditable'])) {
                 $variables['structureEditable'] = true;
                 // Let StructuresController know that this user can make changes to the structure
                 craft()->userSession->authorize('editStructure:' . $variables['structure']->id);
             }
         } else {
             unset($viewState['order']);
         }
     } else {
         if (!empty($viewState['order']) && $viewState['order'] == 'score') {
             $criteria->order = 'score';
         } else {
             $sortableAttributes = $this->defineSortableAttributes();
             if ($sortableAttributes) {
                 $order = !empty($viewState['order']) && isset($sortableAttributes[$viewState['order']]) ? $viewState['order'] : ArrayHelper::getFirstKey($sortableAttributes);
                 $sort = !empty($viewState['sort']) && in_array($viewState['sort'], array('asc', 'desc')) ? $viewState['sort'] : 'asc';
                 // Combine them, accounting for the possibility that $order could contain multiple values,
                 // and be defensive about the possibility that the first value actually has "asc" or "desc"
                 // typeId             => typeId [sort]
                 // typeId, title      => typeId [sort], title
                 // typeId, title desc => typeId [sort], title desc
                 // typeId desc        => typeId [sort]
                 $criteria->order = preg_replace('/^(.*?)(?:\\s+(?:asc|desc))?(,.*)?$/i', "\$1 {$sort}\$2", $order);
             }
         }
     }
     switch ($viewState['mode']) {
         case 'table':
             // Get the table columns
             $variables['attributes'] = $this->getTableAttributesForSource($sourceKey);
             break;
     }
     $variables['elements'] = $criteria->find();
     $template = '_elements/' . $viewState['mode'] . 'view/' . ($includeContainer ? 'container' : 'elements');
     return craft()->templates->render($template, $variables);
 }