/** * @return DateTime */ public function getLastTimeModified() { if ($this->_lastTimeModified === null) { $this->_lastTimeModified = DateTime::createFromString(self::TimestampZero); } return $this->_lastTimeModified; }
/** * Returns the data needed to display a New Users chart. * * @return void */ public function actionGetNewUsersData() { $userGroupId = craft()->request->getRequiredPost('userGroupId'); $startDateParam = craft()->request->getRequiredPost('startDate'); $endDateParam = craft()->request->getRequiredPost('endDate'); $startDate = DateTime::createFromString($startDateParam, craft()->timezone); $endDate = DateTime::createFromString($endDateParam, craft()->timezone); $endDate->modify('+1 day'); $intervalUnit = 'day'; // Prep the query $query = craft()->db->createCommand()->from('users users')->select('COUNT(*) as value'); if ($userGroupId) { $query->join('usergroups_users userGroupUsers', 'userGroupUsers.userId = users.id'); $query->where('userGroupUsers.groupId = :userGroupId', array(':userGroupId' => $userGroupId)); } // Get the chart data table $dataTable = ChartHelper::getRunChartDataFromQuery($query, $startDate, $endDate, 'users.dateCreated', array('intervalUnit' => $intervalUnit, 'valueLabel' => Craft::t('New Users'))); // Get the total number of new users $total = 0; foreach ($dataTable['rows'] as $row) { $total = $total + $row[1]; } // Return everything $this->returnJson(array('dataTable' => $dataTable, 'total' => $total, 'formats' => ChartHelper::getFormats(), 'orientation' => craft()->locale->getOrientation(), 'scale' => $intervalUnit)); }
public function savePlainMeta(BaseFieldType $fieldType) { $handle = $fieldType->model->handle; $elementId = $fieldType->element->id; $content = $fieldType->element->getContent(); $attr = $content->getAttribute($handle); if (!$attr) { return false; } $plainMetaRecord = PlainMeta_PlainMetaRecord::model()->findByAttributes(array('elementId' => $elementId, 'handle' => $handle)); if (!$plainMetaRecord) { $plainMetaRecord = new PlainMeta_PlainMetaRecord(); $attr['elementId'] = $elementId; $attr['handle'] = $handle; } /* Assets */ $assetFields = array('socialOGImageId', 'socialTwitterGalleryImagesId', 'socialTwitterPhotoId', 'socialTwitterProductImageId', 'socialTwitterSummaryImageId', 'socialTwitterSummaryLargeImageId'); foreach ($assetFields as $field) { $attr[$field] = !empty($attr[$field]) ? $attr[$field][0] : null; } /* DateTime */ $dateFields = array(); foreach ($dateFields as $field) { $attr[$field] = ($date = $attr[$field]) ? DateTime::createFromString($date, craft()->timezone) : null; } /* Set Attributes */ $plainMetaRecord->setAttributes($attr, false); return $plainMetaRecord->save(); }
/** * Converts a date to an ISO-8601 string. * * @param mixed $date The date, in any format that {@link toDateTime()} supports. * * @return string|false The date formatted as an ISO-8601 string, or `false` if $date was not a valid date */ public static function toIso8601($date) { $date = DateTime::createFromString($date); if ($date) { return $date->format(\DateTime::ATOM); } else { return false; } }
public function prepValue($value) { $dates = array(); @($dates = json_decode($value)); $dd = array(); if (is_array($dates)) { foreach ($dates as $date) { $dd[] = $date == null ? null : DateTime::createFromString($date, craft()->getTimeZone()); } } $out_value = array('json' => $value, 'dates' => $dd); return $out_value; }
/** * Loops through the data and converts the times to DateTime objects. * * @access private * @param array &$value */ private function _convertTimes(&$value, $timezone = null) { if (is_array($value)) { foreach ($value as &$day) { if (is_string($day['open']) && $day['open'] || is_array($day['open']) && $day['open']['time']) { $day['open'] = DateTime::createFromString($day['open'], $timezone); } else { $day['open'] = ''; } if (is_string($day['close']) && $day['close'] || is_array($day['close']) && $day['close']['time']) { $day['close'] = DateTime::createFromString($day['close'], $timezone); } else { $day['close'] = ''; } } } }
/** * Saves a new or existing announcement. * * @return null */ public function actionSaveAnnouncement() { $this->requirePostRequest(); $announcement = new Maintenance_AnnouncementModel(); $announcement->id = craft()->request->getPost('id'); $announcement->message = craft()->request->getPost('message'); $announcement->startDate = ($startDate = craft()->request->getPost('startDate')) ? DateTime::createFromString($startDate, craft()->timezone) : null; $announcement->endDate = ($endDate = craft()->request->getPost('endDate')) ? DateTime::createFromString($endDate, craft()->timezone) : null; $announcement->blockCp = (bool) craft()->request->getPost('blockCp'); $announcement->blockSite = (bool) craft()->request->getPost('blockSite'); if (craft()->maintenance->saveAnnouncement($announcement)) { craft()->userSession->setNotice(Craft::t('Announcement saved.')); $this->redirectToPostedUrl(); } else { craft()->userSession->setError(Craft::t('Couldn’t save announcement.')); } // Send the announcement back to the template craft()->urlManager->setRouteVariables(array('announcement' => $announcement)); }
/** * Runs a task step. * * @param int $step * @return bool */ public function runStep($step) { try { $element = $this->_elements[$step]; $query = craft()->db->createCommand()->select('venti.eventid,venti.startDate,venti.endDate,venti.allDay,venti.repeat,venti.rRule,venti.summary,venti.isrepeat')->from('venti_events venti'); $query->andWhere(array("venti.eventid" => $element->id)); $query->andWhere("venti.isrepeat is NULL"); $attributes = $query->queryAll(); $attributes[0]['startDate'] = DateTime::createFromString($attributes[0]['startDate'], null, true); $attributes[0]['endDate'] = DateTime::createFromString($attributes[0]['endDate'], null, true); if (craft()->venti_eventManage->saveEventData($element, $attributes[0])) { return true; } else { VentiPlugin::log('Recurring event with ID ' . $element->id . " was not saved.", LogLevel::Error); return 'Recurring event with ID ' . $element->id . " was not saved."; } } catch (Exception $e) { VentiPlugin::log('An exception was thrown while trying to save the recurring event with the ID “' . $this->_elementIds[$step] . '”: ' . $e->getMessage(), LogLevel::Error); return 'An exception was thrown while trying to save the recurring event with the ID “' . $this->_elementIds[$step] . '”: ' . $e->getMessage(); } }
/** * Returns the data needed to display a stats chart. */ public function actionGetStatsData() { $statHandle = craft()->request->getRequiredPost('statHandle'); $startDateParam = craft()->request->getRequiredPost('startDate'); $endDateParam = craft()->request->getRequiredPost('endDate'); $stat = craft()->elementStats_stats->getStatByHandle($statHandle); if (!$stat) { $this->returnErrorJson(Craft::t('Could not find the selected stat.')); } if (!$stat->elementType || !$stat->dateColumn) { $this->returnErrorJson(Craft::t('The stat does not support chart view.')); } // Prep the query try { $criteria = $stat->getCriteria(); } catch (\Exception $e) { ElementStatsPlugin::log('There was an error while generating the stats. ' . $e->getMessage(), LogLevel::Error); $this->returnErrorJson(Craft::t('There was an error while generating the stats.')); } $query = craft()->elements->buildElementsQuery($criteria); $query->select('COUNT(*) as value'); // Query debugging // ElementStatsPlugin::log(print_r($query->getText(), true), LogLevel::Info, true); // Prep the dates $startDate = DateTime::createFromString($startDateParam, craft()->timezone); $endDate = DateTime::createFromString($endDateParam, craft()->timezone); $endDate->modify('+1 day'); $intervalUnit = 'day'; // Get the chart data table $dataTable = ChartHelper::getRunChartDataFromQuery($query, $startDate, $endDate, $stat->dateColumn, ['intervalUnit' => $intervalUnit, 'valueLabel' => Craft::t('Value')]); // Get the total number of elements $total = 0; foreach ($dataTable['rows'] as $row) { $total = $total + $row[1]; } // Return everything $this->returnJson(['dataTable' => $dataTable, 'total' => $total, 'formats' => ChartHelper::getFormats(), 'orientation' => craft()->locale->getOrientation(), 'scale' => $intervalUnit]); }
public function prepForElementModel(&$fields, EntryModel $element) { // Set author $author = FeedMe_Element::Author; if (isset($fields[$author])) { $user = craft()->users->getUserByUsernameOrEmail($fields[$author]); $element->{$author} = is_numeric($fields[$author]) ? $fields[$author] : ($user ? $user->id : 1); //unset($fields[$author]); } else { $user = craft()->userSession->getUser(); $element->{$author} = $element->{$author} ? $element->{$author} : ($user ? $user->id : 1); } // Set slug $slug = FeedMe_Element::Slug; if (isset($fields[$slug])) { $element->{$slug} = ElementHelper::createSlug($fields[$slug]); //unset($fields[$slug]); } // Set postdate $postDate = FeedMe_Element::PostDate; if (isset($fields[$postDate])) { $d = date_parse($fields[$postDate]); $date_string = date('Y-m-d H:i:s', mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year'])); $element->{$postDate} = DateTime::createFromString($date_string, craft()->timezone); //unset($fields[$postDate]); } // Set expiry date $expiryDate = FeedMe_Element::ExpiryDate; if (isset($fields[$expiryDate])) { $d = date_parse($fields[$expiryDate]); $date_string = date('Y-m-d H:i:s', mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year'])); $element->{$expiryDate} = DateTime::createFromString($date_string, craft()->timezone); //unset($fields[$expiryDate]); } // Set enabled $enabled = FeedMe_Element::Enabled; if (isset($fields[$enabled])) { $element->{$enabled} = (bool) $fields[$enabled]; //unset($fields[$enabled]); } // Set title $title = FeedMe_Element::Title; if (isset($fields[$title])) { $element->getContent()->{$title} = $fields[$title]; //unset($fields[$title]); } // Set parent or ancestors $parent = FeedMe_Element::Parent; $ancestors = FeedMe_Element::Ancestors; if (isset($fields[$parent])) { $data = $fields[$parent]; // Don't connect empty fields if (!empty($data)) { // Find matching element $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; $criteria->search = '"' . $data . '"'; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } //unset($fields[$parent]); } elseif (isset($fields[$ancestors])) { $data = $fields[$ancestors]; // Don't connect empty fields if (!empty($data)) { // Get section data $section = new SectionModel(); $section->id = $element->sectionId; // This we append before the slugified path $sectionUrl = str_replace('{slug}', '', $section->getUrlFormat()); // Find matching element by URI (dirty, not all structures have URI's) $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; $criteria->uri = $sectionUrl . craft()->feedMe->slugify($data); $criteria->limit = 1; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } //unset($fields[$ancestors]); } // Return element return $element; }
/** * Parses a date param value to a DbCommand where condition. * * @param string $key * @param string $operator * @param string|array|DateTime $dates * @param array &$params * @return mixed */ public static function parseDateParam($key, $operator, $dates, &$params) { $conditions = array(); $dates = ArrayHelper::stringToArray($dates); foreach ($dates as $date) { if (!$date instanceof \DateTime) { $date = DateTime::createFromString($date, Craft::getTimezone()); } $param = ':p' . StringHelper::randomString(9); $params[$param] = DateTimeHelper::formatTimeForDb($date->getTimestamp()); $conditions[] = $key . $operator . $param; } if (count($conditions) == 1) { return $conditions[0]; } else { array_unshift($conditions, 'or'); return $conditions; } }
/** * Populates an EntryModel with post data. * * @param EntryModel $entry * * @return null */ private function _populateEntryModel(EntryModel $entry) { // Set the entry attributes, defaulting to the existing values for whatever is missing from the post data $entry->typeId = craft()->request->getPost('typeId', $entry->typeId); $entry->authorId = craft()->request->getPost('author', $entry->authorId ? $entry->authorId : craft()->userSession->getUser()->id); $entry->slug = craft()->request->getPost('slug', $entry->slug); $entry->postDate = ($postDate = craft()->request->getPost('postDate')) ? DateTime::createFromString($postDate, craft()->timezone) : $entry->postDate; $entry->expiryDate = ($expiryDate = craft()->request->getPost('expiryDate')) ? DateTime::createFromString($expiryDate, craft()->timezone) : null; $entry->enabled = (bool) craft()->request->getPost('enabled', $entry->enabled); $entry->localeEnabled = (bool) craft()->request->getPost('localeEnabled', $entry->localeEnabled); $entry->getContent()->title = craft()->request->getPost('title', $entry->title); $fieldsLocation = craft()->request->getParam('fieldsLocation', 'fields'); $entry->setContentFromPost($fieldsLocation); $entry->parentId = craft()->request->getPost('parentId'); $entry->revisionNotes = craft()->request->getPost('revisionNotes'); }
/** * Check plugins’ release feeds and include any pending updates in the given UpdateModel * * @param UpdateModel $updateModel */ public function checkPluginReleaseFeeds(UpdateModel $updateModel) { $userAgent = 'Craft/' . craft()->getVersion() . '.' . craft()->getBuild(); foreach ($updateModel->plugins as $pluginUpdateModel) { // Only check plugins where the update status isn't already known from the ET response if ($pluginUpdateModel->status != PluginUpdateStatus::Unknown) { continue; } // Get the plugin and its feed URL $plugin = craft()->plugins->getPlugin($pluginUpdateModel->class); $feedUrl = $plugin->getReleaseFeedUrl(); // Skip if the plugin doesn't have a feed URL if ($feedUrl === null) { continue; } // Make sure it's HTTPS if (strncmp($feedUrl, 'https://', 8) !== 0) { Craft::log('The “' . $plugin->getName() . '” plugin has a release feed URL, but it doesn’t begin with https://, so it’s getting skipped (' . $feedUrl . ').', LogLevel::Warning); continue; } try { // Fetch it $client = new \Guzzle\Http\Client(); $client->setUserAgent($userAgent, true); $options = array('timeout' => 5, 'connect_timeout' => 2, 'allow_redirects' => true, 'verify' => false); $request = $client->get($feedUrl, null, $options); // Potentially long-running request, so close session to prevent session blocking on subsequent requests. craft()->session->close(); $response = $request->send(); if (!$response->isSuccessful()) { Craft::log('Error in calling ' . $feedUrl . '. Response: ' . $response->getBody(), LogLevel::Warning); continue; } $responseBody = $response->getBody(); $releases = JsonHelper::decode($responseBody); if (!$releases) { Craft::log('The “' . $plugin->getName() . "” plugin release feed didn’t come back as valid JSON:\n" . $responseBody, LogLevel::Warning); continue; } $releaseModels = array(); $releaseTimestamps = array(); foreach ($releases as $release) { // Validate ite info $errors = array(); // Any missing required attributes? $missingAttributes = array(); foreach (array('version', 'downloadUrl', 'date', 'notes') as $attribute) { if (empty($release[$attribute])) { $missingAttributes[] = $attribute; } } if ($missingAttributes) { $errors[] = 'Missing required attributes (' . implode(', ', $missingAttributes) . ')'; } // Invalid URL? if (strncmp($release['downloadUrl'], 'https://', 8) !== 0) { $errors[] = 'Download URL doesn’t begin with https:// (' . $release['downloadUrl'] . ')'; } // Invalid date? $date = DateTime::createFromString($release['date']); if (!$date) { $errors[] = 'Invalid date (' . $release['date'] . ')'; } // Validation complete. Were there any errors? if ($errors) { Craft::log('A “' . $plugin->getName() . "” release was skipped because it is invalid:\n - " . implode("\n - ", $errors), LogLevel::Warning); continue; } // All good! Let's make sure it's a pending update if (!version_compare($release['version'], $plugin->getVersion(), '>')) { continue; } // Create the release note HTML if (!is_array($release['notes'])) { $release['notes'] = array_filter(preg_split('/[\\r\\n]+/', $release['notes'])); } $notes = ''; $inList = false; foreach ($release['notes'] as $line) { // Escape any HTML $line = htmlspecialchars($line, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); // Is this a heading? if (preg_match('/^#\\s+(.+)/', $line, $match)) { if ($inList) { $notes .= "</ul>\n"; $inList = false; } $notes .= '<h3>' . $match[1] . "</h3>\n"; } else { if (!$inList) { $notes .= "<ul>\n"; $inList = true; } if (preg_match('/^\\[(\\w+)\\]\\s+(.+)/', $line, $match)) { $class = strtolower($match[1]); $line = $match[2]; } else { $class = null; } // Parse Markdown code $line = StringHelper::parseMarkdownLine($line); $notes .= '<li' . ($class ? ' class="' . $class . '"' : '') . '>' . $line . "</li>\n"; } } if ($inList) { $notes .= "</ul>\n"; } $critical = !empty($release['critical']); // Populate the release model $releaseModel = new PluginNewReleaseModel(); $releaseModel->version = $release['version']; $releaseModel->date = $date; $releaseModel->localizedDate = $date->localeDate(); $releaseModel->notes = $notes; $releaseModel->critical = $critical; $releaseModel->manualDownloadEndpoint = $release['downloadUrl']; $releaseModels[] = $releaseModel; $releaseTimestamps[] = $date->getTimestamp(); if ($critical) { $pluginUpdateModel->criticalUpdateAvailable = true; } } if ($releaseModels) { // Sort release models by timestamp array_multisort($releaseTimestamps, SORT_DESC, $releaseModels); $latestRelease = $releaseModels[0]; $pluginUpdateModel->displayName = $plugin->getName(); $pluginUpdateModel->localVersion = $plugin->getVersion(); $pluginUpdateModel->latestDate = $latestRelease->date; $pluginUpdateModel->latestVersion = $latestRelease->version; $pluginUpdateModel->manualDownloadEndpoint = $latestRelease->manualDownloadEndpoint; $pluginUpdateModel->manualUpdateRequired = true; $pluginUpdateModel->releases = $releaseModels; $pluginUpdateModel->status = PluginUpdateStatus::UpdateAvailable; } else { $pluginUpdateModel->status = PluginUpdateStatus::UpToDate; } } catch (\Exception $e) { Craft::log('There was a problem getting the update feed for “' . $plugin->getName() . '”, so it was skipped: ' . $e->getMessage(), LogLevel::Error); continue; } } }
/** * Normalizes date params and then sends them off to parseParam(). * * @param string $column * @param string|array|DateTime $value * @param array &$params * * @return mixed */ public static function parseDateParam($column, $value, &$params) { $normalizedValues = array(); $value = ArrayHelper::stringToArray($value); if (!count($value)) { return ''; } if ($value[0] == 'and' || $value[0] == 'or') { $normalizedValues[] = $value[0]; array_shift($value); } foreach ($value as $val) { // Is this an empty value? static::_normalizeEmptyValue($val); if ($val == ':empty:' || $val == 'not :empty:') { $normalizedValues[] = $val; // Sneak out early continue; } if (is_string($val)) { $operator = static::_parseParamOperator($val); } else { $operator = '='; } if (!$val instanceof \DateTime) { $val = DateTime::createFromString($val, craft()->getTimeZone()); } $normalizedValues[] = $operator . DateTimeHelper::formatTimeForDb($val->getTimestamp()); } return static::parseParam($column, $normalizedValues, $params); }
/** * Sets a draft's attributes from the post data. * * @param EntryDraftModel $draft * * @return null */ private function _setDraftAttributesFromPost(EntryDraftModel $draft) { $draft->typeId = craft()->request->getPost('typeId'); $draft->slug = craft()->request->getPost('slug'); $draft->postDate = ($postDate = craft()->request->getPost('postDate')) ? DateTime::createFromString($postDate, craft()->timezone) : $draft->postDate; $draft->expiryDate = ($expiryDate = craft()->request->getPost('expiryDate')) ? DateTime::createFromString($expiryDate, craft()->timezone) : null; $draft->enabled = (bool) craft()->request->getPost('enabled'); $draft->getContent()->title = craft()->request->getPost('title'); // Author $authorId = craft()->request->getPost('author', $draft->authorId ? $draft->authorId : craft()->userSession->getUser()->id); if (is_array($authorId)) { $authorId = isset($authorId[0]) ? $authorId[0] : null; } $draft->authorId = $authorId; // Parent $parentId = craft()->request->getPost('parentId'); if (is_array($parentId)) { $parentId = isset($parentId[0]) ? $parentId[0] : null; } $draft->parentId = $parentId; }
/** * Prepare reserved ElementModel values. * * @param array &$fields * @param BaseElementModel $element * * @return BaseElementModel */ public function prepForElementModel(array &$fields, BaseElementModel $element) { // Set author $author = Import_ElementModel::HandleAuthor; if (isset($fields[$author])) { $user = craft()->users->getUserByUsernameOrEmail($fields[$author]); $element->{$author} = is_numeric($fields[$author]) ? $fields[$author] : ($user ? $user->id : 1); unset($fields[$author]); } else { $user = craft()->userSession->getUser(); $element->{$author} = $element->{$author} ? $element->{$author} : ($user ? $user->id : 1); } // Set slug $slug = Import_ElementModel::HandleSlug; if (isset($fields[$slug])) { $element->{$slug} = ElementHelper::createSlug($fields[$slug]); unset($fields[$slug]); } // Set postdate $postDate = Import_ElementModel::HandlePostDate; if (isset($fields[$postDate])) { $element->{$postDate} = DateTime::createFromString($fields[$postDate], craft()->timezone); unset($fields[$postDate]); } // Set expiry date $expiryDate = Import_ElementModel::HandleExpiryDate; if (isset($fields[$expiryDate])) { $element->{$expiryDate} = DateTime::createFromString($fields[$expiryDate], craft()->timezone); unset($fields[$expiryDate]); } // Set enabled $enabled = Import_ElementModel::HandleEnabled; if (isset($fields[$enabled])) { $element->{$enabled} = (bool) $fields[$enabled]; unset($fields[$enabled]); } // Set title $title = Import_ElementModel::HandleTitle; if (isset($fields[$title])) { $element->getContent()->{$title} = $fields[$title]; unset($fields[$title]); } // Set parent or ancestors $parent = Import_ElementModel::HandleParent; $ancestors = Import_ElementModel::HandleAncestors; if (isset($fields[$parent])) { // Get data $data = $fields[$parent]; // Fresh up $data $data = str_replace("\n", '', $data); $data = str_replace("\r", '', $data); $data = trim($data); // Don't connect empty fields if (!empty($data)) { // Find matching element $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; // Exact match $criteria->search = '"' . $data . '"'; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } unset($fields[$parent]); } elseif (isset($fields[$ancestors])) { // Get data $data = $fields[$ancestors]; // Fresh up $data $data = str_replace("\n", '', $data); $data = str_replace("\r", '', $data); $data = trim($data); // Don't connect empty fields if (!empty($data)) { // Get section data $section = new SectionModel(); $section->id = $element->sectionId; // This we append before the slugified path $sectionUrl = str_replace('{slug}', '', $section->getUrlFormat()); // Find matching element by URI (dirty, not all structures have URI's) $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; $criteria->uri = $sectionUrl . craft()->import->slugify($data); $criteria->limit = 1; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } unset($fields[$ancestors]); } // Return element return $element; }
/** * Saves an event. */ public function actionSaveEvent() { $this->requirePostRequest(); $eventId = craft()->request->getPost('eventId'); if ($eventId) { $event = craft()->events->getEventById($eventId); if (!$event) { throw new Exception(Craft::t('No event exists with the ID “{id}”', array('id' => $eventId))); } } else { $event = new Events_EventModel(); } // Set the event attributes, defaulting to the existing values for whatever is missing from the post data $event->calendarId = craft()->request->getPost('calendarId', $event->calendarId); $event->startDate = ($startDate = craft()->request->getPost('startDate')) ? DateTime::createFromString($startDate, craft()->timezone) : null; $event->endDate = ($endDate = craft()->request->getPost('endDate')) ? DateTime::createFromString($endDate, craft()->timezone) : null; $event->getContent()->title = craft()->request->getPost('title', $event->title); $event->setContentFromPost('fields'); if (craft()->events->saveEvent($event)) { craft()->userSession->setNotice(Craft::t('Event saved.')); $this->redirectToPostedUrl($event); } else { craft()->userSession->setError(Craft::t('Couldn’t save event.')); // Send the event back to the template craft()->urlManager->setRouteVariables(array('event' => $event)); } }
public function convertTimes($value) { $timezone = craft()->getTimeZone(); if (is_array($value)) { foreach ($value as &$day) { if (is_string($day['open']) && $day['open'] || is_array($day['open']) && $day['open']['time']) { $day['open'] = DateTime::createFromString($day['open'], $timezone); } else { $day['open'] = ''; } if (is_string($day['close']) && $day['close'] || is_array($day['close']) && $day['close']['time']) { $day['close'] = DateTime::createFromString($day['close'], $timezone); } else { $day['close'] = ''; } } } return $value; }
/** * Populates an EntryModel with post data. * * @access private * @return EntryModel */ private function _populateEntryModel() { $entryId = craft()->request->getPost('entryId'); if ($entryId) { $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->id = $entryId; $criteria->status = null; $entry = $criteria->first(); if (!$entry) { throw new Exception(Craft::t('No entry exists with the ID “{id}”', array('id' => $entryId))); } } else { $entry = new EntryModel(); } $entry->sectionId = craft()->request->getRequiredPost('sectionId'); $entry->locale = craft()->request->getPost('locale', craft()->i18n->getPrimarySiteLocaleId()); $entry->id = craft()->request->getPost('entryId'); $entry->authorId = craft()->request->getPost('author', craft()->userSession->getUser()->id); $entry->slug = craft()->request->getPost('slug'); $entry->postDate = ($postDate = craft()->request->getPost('postDate')) ? DateTime::createFromString($postDate, craft()->timezone) : null; $entry->expiryDate = ($expiryDate = craft()->request->getPost('expiryDate')) ? DateTime::createFromString($expiryDate, craft()->timezone) : null; $entry->enabled = (bool) craft()->request->getPost('enabled'); $entry->getContent()->title = craft()->request->getPost('title'); $fields = craft()->request->getPost('fields'); $entry->getContent()->setAttributes($fields); return $entry; }
/** * Re-saves an entry with the date from a rule. * * @param EntryModel $entry * @param AutoExpire_RuleModel $rule */ public function applyRule($entry, $rule) { $fieldHandle = $rule['fieldHandle']; $fieldIsEmpty = $this->fieldIsEmpty($entry, $fieldHandle); if ($fieldIsEmpty || !$rule->allowOverwrite) { try { $newDateString = craft()->templates->renderObjectTemplate($rule->dateTemplate, $entry); } catch (\Exception $e) { AutoExpirePlugin::log('Couldn’t render template for entry with id “' . $entry->id . '” and Auto Expire rule “' . $rule->name . '” (' . $e->getMessage() . ').', LogLevel::Error); return null; } $newDate = DateTime::createFromString($newDateString); if (!$newDate instanceof \DateTime) { AutoExpirePlugin::log('Couldn’t create date from string “' . $newDateString . '” for entry with id “' . $entry->id . '” and Auto Expire rule “' . $rule->name . '”.', LogLevel::Error); return null; } if (in_array($fieldHandle, static::$_dateAttributes)) { $entry->{$fieldHandle} = $newDate; } else { $entry->setContentFromPost(array($fieldHandle => $newDate)); } $success = craft()->entries->saveEntry($entry); if (!$success) { AutoExpirePlugin::log('Couldn’t save entry with id “' . $entry->id . '” and Auto Expire rule “' . $rule->name . '”.', LogLevel::Error); } } }
/** * Sets an attribute's value. * * @param string $name * @param mixed $value * * @return bool */ public function setAttribute($name, $value) { if (!$this->strictAttributes || in_array($name, $this->attributeNames())) { // Is this a normal attribute? if (array_key_exists($name, $this->_attributeConfigs)) { $attributes = $this->getAttributeConfigs(); $config = $attributes[$name]; // Handle special case attribute types switch ($config['type']) { case AttributeType::DateTime: if ($value) { if (!$value instanceof \DateTime) { if (DateTimeHelper::isValidTimeStamp($value)) { $value = new DateTime('@' . $value); } else { $value = DateTime::createFromString($value); } } } else { // No empty strings allowed! $value = null; } break; case AttributeType::Mixed: if ($value && is_string($value) && mb_strpos('{[', $value[0]) !== false) { // Presumably this is JSON. $value = JsonHelper::decode($value); } if (is_array($value)) { if ($config['model']) { $class = __NAMESPACE__ . '\\' . $config['model']; $value = $class::populateModel($value); } else { $value = ModelHelper::expandModelsInArray($value); } } break; } } else { if (!array_key_exists($name, $this->_extraAttributeNames)) { $this->_extraAttributeNames[] = $name; } } $this->_attributes[$name] = $value; return true; } else { return false; } }
/** * @inheritDoc IFieldType::prepValueFromPost() * * @param mixed $value * * @return mixed */ public function prepValueFromPost($value) { return DateTime::createFromString($value, craft()->getTimeZone()); }
/** * 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()))); } } }
/** * Normalizes date params and then sends them off to parseParam(). * * @param string $key * @param string|array|DateTime $values * @param array &$params * * @return mixed */ public static function parseDateParam($key, $values, &$params) { $normalizedValues = array(); $values = ArrayHelper::stringToArray($values); if (!count($values)) { return ''; } if ($values[0] == 'and' || $values[0] == 'or') { $normalizedValues[] = $values[0]; array_shift($values); } foreach ($values as $value) { if (is_string($value)) { $operator = static::_parseParamOperator($value); } else { $operator = '='; } if (!$value instanceof \DateTime) { $value = DateTime::createFromString($value, craft()->getTimeZone()); } $normalizedValues[] = $operator . DateTimeHelper::formatTimeForDb($value->getTimestamp()); } return static::parseParam($key, $normalizedValues, $params); }
/** * Returns the info model, or just a particular attribute. * * @param string|null $attribute * * @throws Exception * @return mixed */ public function getInfo($attribute = null) { if (!isset($this->_info)) { if ($this->isInstalled()) { $row = craft()->db->createCommand()->from('info')->limit(1)->queryRow(); if (!$row) { throw new Exception(Craft::t('Craft appears to be installed but the info table is empty.')); } // Prevent an infinite loop in createFromString. $row['releaseDate'] = DateTime::createFromString($row['releaseDate'], null, false); $this->_info = new InfoModel($row); } else { $this->_info = new InfoModel(); } } if ($attribute) { return $this->_info->getAttribute($attribute); } else { return $this->_info; } }
/** * Populates an EntryModel with post data. * * @access private * @param $settings * @throws HttpException * @return EntryModel */ private function _populateEntryModel($settings) { $entry = new EntryModel(); $entry->sectionId = craft()->request->getRequiredPost('sectionId'); $this->_section = craft()->sections->getSectionById($entry->sectionId); if (!$this->_section) { throw new HttpException(404); } // If we're allowing guest submissions and we've got a default author specified, grab the authorId. if ($settings->allowGuestSubmissions && isset($settings->defaultAuthors[$this->_section->handle]) && $settings->defaultAuthors[$this->_section->handle] !== 'none') { // We found a defaultAuthor $authorId = $settings->defaultAuthors[$this->_section->handle]; } else { // Otherwise, complain loudly. throw new HttpException(403); } $localeId = craft()->request->getPost('locale'); if ($localeId) { $entry->locale = $localeId; } $entry->typeId = craft()->request->getPost('typeId'); $postDate = craft()->request->getPost('postDate'); if ($postDate) { DateTime::createFromString($postDate, craft()->timezone); } $expiryDate = craft()->request->getPost('expiryDate'); if ($expiryDate) { DateTime::createFromString($expiryDate, craft()->timezone); } $entry->authorId = $authorId; $entry->slug = craft()->request->getPost('slug'); $entry->postDate = $postDate; $entry->expiryDate = $expiryDate; $entry->enabled = (bool) $settings->enabledByDefault[$this->_section->handle]; if (($localeEnabled = craft()->request->getPost('localeEnabled', null)) === null) { $localeEnabled = true; } $entry->localeEnabled = (bool) $localeEnabled; $entry->getContent()->title = craft()->request->getPost('title'); $fieldsLocation = craft()->request->getParam('fieldsLocation', 'fields'); $entry->setContentFromPost($fieldsLocation); $entry->parentId = craft()->request->getPost('parentId'); return $entry; }
/** * Loops through the data and converts the times to DateTime objects. * * @access private * @param array &$value */ private function _convertTimes(&$value) { if (is_array($value)) { if (is_string($value['startDate']) && $value['startDate'] || is_array($value['startDate']) && $value['startDate']['time']) { $value['startDate'] = DateTime::createFromString($value['startDate'], craft()->getTimeZone()); } else { $value['startDate'] = ''; } if (is_string($value['endDate']) && $value['endDate'] || is_array($value['endDate']) && $value['endDate']['time']) { $value['endDate'] = DateTime::createFromString($value['endDate'], craft()->getTimeZone()); } else { $value['endDate'] = ''; } } }
public function actionCsv() { $dataToProcess = true; $first = true; $offset = 0; $blocksize = 500; $maximumLoops = 1000; $loops = 0; $formId = craft()->request->getPost('form'); $form = craft()->formerly_forms->getFormById($formId); set_time_limit('1000'); //ini_set('memory_limit', '1024M'); 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'); while ($dataToProcess && $loops <= $maximumLoops) { $dataToProcess = false; $loops++; $criteria = craft()->elements->getCriteria('Formerly_Submission'); $criteria->formId = $formId; $criteria->limit = $blocksize; $criteria->offset = $offset; 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); //A bit of a hack, I can't work out how to do a betweendates or AND query. These fields are always the same anyway $criteria->dateCreated = '>= ' . $fromDate->format(DateTime::MYSQL_DATETIME); $criteria->dateUpdated = '<= ' . $toDate->format(DateTime::MYSQL_DATETIME); } elseif (isset($_POST['fromDate']) && !empty($_POST['fromDate']['date'])) { $fromDate = craft()->request->getPost('fromDate'); $fromDate = DateTime::createFromString($fromDate, craft()->timezone); $criteria->dateCreated = '>= ' . $fromDate->format(DateTime::MYSQL_DATETIME); } else { if (isset($_POST['toDate']) && !empty($_POST['toDate']['date'])) { $toDate = craft()->request->getPost('toDate'); $toDate = DateTime::createFromString($toDate, craft()->timezone); $criteria->dateCreated = '<= ' . $toDate->format(DateTime::MYSQL_DATETIME); } } $criteria->order = 'dateCreated desc'; // Write column names first. $first = true; foreach ($criteria->find() as $submission) { $dataToProcess = true; $row = array('Id' => $submission->id, 'Time' => $submission->dateCreated->format('d/m/Y H:i:s')); foreach ($form->getQuestions() as $question) { if ($question->type != 'RawHTML') { $columnName = str_replace($form->handle . '_', '', $question->handle); $columnName = str_replace(Formerly_QuestionType::CustomListHandle, '', $columnName); $columnName = str_replace(Formerly_QuestionType::RawHTMLHandle, '', $columnName); $columnName = str_replace(Formerly_QuestionType::CustomHandle, '', $columnName); $columnName = ucwords($columnName); $row[$columnName] = $submission->{$question->handle}; $value = $submission->{$question->handle}; if ($value instanceof MultiOptionsFieldData) { $options = $value->getOptions(); $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 { for ($j = 0; $j < count($options); ++$j) { $option = $options[$j]; if ($option->selected) { $summary[] = $option->value; } } } $row[$columnName] = implode($summary, ', '); } elseif ($question->type == Formerly_QuestionType::MultilineText) { $row[$columnName] = str_replace('<br />', "\n", $value); } else { if ($question->type != Formerly_QuestionType::RawHTML) { $row[$columnName] = $value; } } } } if ($first) { fputcsv($stream, array_keys($row)); $first = false; } fputcsv($stream, $row); } $first = true; $offset += $blocksize; } fclose($stream); }
/** * Loads the enabled plugins. * * @return null */ public function loadPlugins() { if (!$this->_pluginsLoaded && !$this->_loadingPlugins) { if (craft()->isInstalled()) { // Prevent this function from getting called twice. $this->_loadingPlugins = true; // Find all of the enabled plugins $rows = craft()->db->createCommand()->select('id, class, version, settings, installDate')->from('plugins')->where('enabled=1')->queryAll(); $names = array(); foreach ($rows as $row) { $plugin = $this->_getPlugin($row['class']); if ($plugin) { $this->_autoloadPluginClasses($plugin); // Clean it up a bit $row['settings'] = JsonHelper::decode($row['settings']); $row['installDate'] = DateTime::createFromString($row['installDate']); $this->_enabledPluginInfo[$row['class']] = $row; $lcPluginHandle = mb_strtolower($plugin->getClassHandle()); $this->_plugins[$lcPluginHandle] = $plugin; $this->_enabledPlugins[$lcPluginHandle] = $plugin; $names[] = $plugin->getName(); $plugin->setSettings($row['settings']); $plugin->isInstalled = true; $plugin->isEnabled = true; } } // Sort plugins by name array_multisort($names, $this->_enabledPlugins); // Now that all of the components have been imported, initialize all the plugins foreach ($this->_enabledPlugins as $plugin) { $plugin->init(); } $this->_loadingPlugins = false; } $this->_pluginsLoaded = true; // Fire an 'onLoadPlugins' event $this->onLoadPlugins(new Event($this)); } }
/** * Loads the enabled plugins. * * @return null */ public function loadPlugins() { if (!$this->_pluginsLoaded && !$this->_loadingPlugins) { if (craft()->isInstalled()) { // Prevent this function from getting called twice. $this->_loadingPlugins = true; // Find all of the enabled plugins // TODO: swap the SELECT statements after next breakpoint $rows = craft()->db->createCommand()->select('*')->from('plugins')->where('enabled=1')->queryAll(); $names = array(); foreach ($rows as $row) { $plugin = $this->_getPlugin($row['class']); if ($plugin) { $this->_autoloadPluginClasses($plugin); // Clean it up a bit $row['settings'] = JsonHelper::decode($row['settings']); $row['installDate'] = DateTime::createFromString($row['installDate']); $this->_enabledPluginInfo[$row['class']] = $row; $lcPluginHandle = mb_strtolower($plugin->getClassHandle()); $this->_plugins[$lcPluginHandle] = $plugin; $this->_enabledPlugins[$lcPluginHandle] = $plugin; $names[] = $plugin->getName(); $plugin->setSettings($row['settings']); $plugin->isInstalled = true; $plugin->isEnabled = true; // If we're not updating, check if the plugin's version number changed, but not its schema version. if (!craft()->isInMaintenanceMode() && $this->hasPluginVersionNumberChanged($plugin) && !$this->doesPluginRequireDatabaseUpdate($plugin)) { // Update our record of the plugin's version number craft()->db->createCommand()->update('plugins', array('version' => $plugin->getVersion()), 'id = :id', array(':id' => $row['id'])); } } } // Sort plugins by name $this->_sortPlugins($names, $this->_enabledPlugins); // Now that all of the components have been imported, initialize all the plugins foreach ($this->_enabledPlugins as $plugin) { $plugin->init(); } $this->_loadingPlugins = false; } $this->_pluginsLoaded = true; // Fire an 'onLoadPlugins' event $this->onLoadPlugins(new Event($this)); } }