public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
 {
     // If custom field, get field handle
     if (strncmp($attribute, 'field:', 6) === 0) {
         $fieldId = substr($attribute, 6);
         $field = craft()->fields->getFieldById($fieldId);
         $attribute = $field->handle;
     }
     $attributes = $entry->getAttributes();
     if ($fieldData = craft()->venti_eventManage->getEventFieldData($attributes['id'], $attributes['locale'])) {
         switch ($attribute) {
             case 'ventiStartDate':
                 return $fieldData['startDate']->format('M d, Y');
                 break;
             case 'ventiEndDate':
                 return $fieldData['endDate']->format('M d, Y');
                 break;
             case 'ventiRepeat':
                 return $fieldData['repeat'];
                 break;
             case 'ventiAllDay':
                 return $fieldData['allDay'];
                 break;
             case 'ventiRepeatSummary':
                 return $fieldData['summary'];
                 break;
         }
     } else {
         // throw new Exception(Craft::t('Event with id “{id}” in locale “{locale}”. Try resaving events.', array('id' => $attributes['id'], 'locale' => $attributes['locale'])));
         VentiPlugin::log("Entry table attributes can't be found for Venti attributes.", LogLevel::Error, true);
     }
 }
 /**
  * Returns whether or not the entry meets the criteria necessary to trigger the event
  *
  * @param mixed      $options
  * @param EntryModel $entry
  * @param array      $params
  *
  * @return bool
  */
 public function validateOptions($options, EntryModel $entry, array $params = array())
 {
     $isNewEntry = isset($params['isNewEntry']) && $params['isNewEntry'];
     $whenNew = isset($options['craft']['saveEntry']['whenNew']) && $options['craft']['saveEntry']['whenNew'];
     $whenUpdated = isset($options['craft']['saveEntry']['whenUpdated']) && $options['craft']['saveEntry']['whenUpdated'];
     SproutEmailPlugin::log(Craft::t("Sprout Email '" . $this->getTitle() . "' event has been triggered"));
     // If any section ids were checked, make sure the entry belongs in one of them
     if (!empty($options['craft']['saveEntry']['sectionIds']) && count($options['craft']['saveEntry']['sectionIds'])) {
         if (!in_array($entry->getSection()->id, $options['craft']['saveEntry']['sectionIds'])) {
             SproutEmailPlugin::log(Craft::t('Saved entry not in any selected Section.'));
             return false;
         }
     }
     if (!$whenNew && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No settings have been selected. Please select 'When an entry is created' or 'When\n\t\t\tan entry is updated' from the options on the Rules tab."));
         return false;
     }
     // Make sure new entries are new
     if ($whenNew && !$isNewEntry && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No match. 'When an entry is created' is selected but the entry is being updated\n\t\t\t."));
         return false;
     }
     // Make sure updated entries are not new
     if ($whenUpdated && $isNewEntry && !$whenNew) {
         SproutEmailPlugin::log(Craft::t("No match. 'When an entry is updated' is selected but the entry is new."));
         return false;
     }
     return true;
 }
 /**
  * Enforces all Edit Entry permissions.
  *
  * @param EntryModel $entry
  *
  * @return null
  */
 protected function enforceEditEntryPermissions(EntryModel $entry)
 {
     $userSessionService = craft()->userSession;
     $permissionSuffix = ':' . $entry->sectionId;
     if (craft()->isLocalized()) {
         // Make sure they have access to this locale
         $userSessionService->requirePermission('editLocale:' . $entry->locale);
     }
     // Make sure the user is allowed to edit entries in this section
     $userSessionService->requirePermission('editEntries' . $permissionSuffix);
     // Is it a new entry?
     if (!$entry->id) {
         // Make sure they have permission to create new entries in this section
         $userSessionService->requirePermission('createEntries' . $permissionSuffix);
     } else {
         switch ($entry->getClassHandle()) {
             case 'Entry':
                 // If it's another user's entry (and it's not a Single), make sure they have permission to edit those
                 if ($entry->authorId != $userSessionService->getUser()->id && $entry->getSection()->type != SectionType::Single) {
                     $userSessionService->requirePermission('editPeerEntries' . $permissionSuffix);
                 }
                 break;
             case 'EntryDraft':
                 // If it's another user's draft, make sure they have permission to edit those
                 if ($entry->getClassHandle() == 'EntryDraft' && $entry->creatorId != $userSessionService->getUser()->id) {
                     $userSessionService->requirePermission('editPeerEntryDrafts' . $permissionSuffix);
                 }
                 break;
         }
     }
 }
 private function addElement(EntryModel $entry, $changeFrequency, $priority)
 {
     //Check if manually hidden
     if ($entry->SiteMapPluginHideFromSiteMap) {
         return;
     }
     //Check if entry has URL, some sections don't
     if (!$entry->getUrl()) {
         return;
     }
     $url = $this->dom->createElement('url');
     $urlLoc = $this->dom->createElement('loc');
     $urlLoc->nodeValue = $entry->getUrl();
     $url->appendChild($urlLoc);
     $urlModified = $this->dom->createElement('lastmod');
     $urlModified->nodeValue = $entry->postDate->w3c();
     $url->appendChild($urlModified);
     $urlChangeFreq = $this->dom->createElement('changefreq');
     $urlChangeFreq->nodeValue = $changeFrequency;
     $url->appendChild($urlChangeFreq);
     $urlPriority = $this->dom->createElement('priority');
     $urlPriority->nodeValue = $priority;
     $url->appendChild($urlPriority);
     $this->urlset->appendChild($url);
 }
 public function saveJob()
 {
     $entry = new EntryModel();
     $entry->sectionId = 20;
     $entry->typeId = 20;
     $entry->authorId = 1;
     $entry->enabled = true;
     $entry->getContent()->title = "Hello World!";
     $entry->getContent()->jobsTitle = "MFCEO";
     $entry->getContent()->jobsDescription = "Do som work!";
     $success = craft()->entries->saveEntry($entry);
     if (!$success) {
         Craft::log('Couldn’t save the entry "' . $entry->title . '"', LogLevel::Error);
     }
 }
 /**
  * Returns whether or not the entry meets the criteria necessary to trigger the event
  *
  * @param mixed      $options
  * @param EntryModel $entry
  * @param array      $params
  *
  * @return bool
  */
 public function validateOptions($options, EntryModel $entry, array $params = array())
 {
     $isNewEntry = isset($params['isNewEntry']) && $params['isNewEntry'];
     $onlyWhenNew = isset($options['entriesSaveEntryOnlyWhenNew']) && $options['entriesSaveEntryOnlyWhenNew'];
     // If any section ids were checked
     // Make sure the entry belongs in one of them
     if (!empty($options['entriesSaveEntrySectionIds']) && count($options['entriesSaveEntrySectionIds'])) {
         if (!in_array($entry->getSection()->id, $options['entriesSaveEntrySectionIds'])) {
             return false;
         }
     }
     // If only new entries was checked
     // Make sure the entry is new
     if (!$onlyWhenNew || $onlyWhenNew && $isNewEntry) {
         return true;
     }
     return false;
 }
Esempio n. 7
0
 /**
  * Worklist entries longpoll, retrieves new entries by simulating server pushes
  * to the status page. Refer to client side code at js/status.js to clarify.
  */
 public function longpoll()
 {
     $this->view = new JsonView();
     $ret = array();
     try {
         $since = $_POST['since'];
         $entry = new EntryModel();
         $ret = array();
         // this is a 30 seconds timeout long poll, so let's loop up to 25 times
         // with 1 sec delays at the end of each iteration
         $fromTime = (int) $since;
         for ($i = 0; $i < 25; $i++) {
             $toTime = strtotime(Model::now());
             $seconds_ago = abs($toTime - $fromTime);
             // we are searching for new worklist entries
             $entries = $entry->latest($seconds_ago, 90);
             if ($entries) {
                 $now = 0;
                 foreach ($entries as $entry) {
                     if (!$now) {
                         $now = strtotime(Model::now());
                     }
                     $date = strtotime($entry->date);
                     $relativeDate = Utils::relativeTime($date - $now);
                     $mention_regex = '/(^|\\s)@([a-zA-Z0-9][a-zA-Z0-9-]+)/';
                     $task_regex = '/(^|\\s)\\*\\*#(\\d+)\\*\\*/';
                     $content = preg_replace($mention_regex, '\\1[\\2](./user/\\2)', $entry->entry);
                     $content = preg_replace($task_regex, '\\1[\\\\#\\2](./\\2)', $content);
                     // proccesed entries are returned as markdown-processed html
                     $content = Markdown::defaultTransform($content);
                     $ret[] = array('id' => $entry->id, 'date' => $date, 'relativeDate' => $relativeDate, 'content' => $content);
                 }
                 // if we found new entries, no need to keep looping so we can return data inmediatly
                 break;
             }
             sleep(1);
         }
         $ret = array('success' => true, 'data' => $ret);
     } catch (Exception $e) {
         $ret = array('success' => false, 'message' => $e->getMessage());
     }
     $this->write('output', $ret);
 }
 public function loadEntries($lastRun = false)
 {
     $retVal = true;
     // Use SimpleXML to fetch an XML export of channel data from an ExpressionEngine site
     $xml = simplexml_load_file($this->settings['feedURL']);
     $importTags = false;
     foreach ($xml->channel[0]->item as $importEntry) {
         $success = false;
         $entry = new EntryModel();
         $postData = strip_tags(html_entity_decode($importEntry->description));
         $parts = explode(' ', $postData);
         if (count($parts) > $this->settings['wordMax']) {
             $parts = array_slice($parts, 0, $this->settings['wordMax']);
         }
         $postData = implode(' ', $parts);
         $pubDate = strtotime((string) $importEntry->pubDate);
         if ($pubDate && $lastRun && $pubDate < $lastRun) {
             continue;
         }
         // Find these in craft/app/models/EntryModel
         $entry->sectionId = $this->settings['sectionID'];
         $entry->typeId = $this->settings['typeID'];
         $entry->authorId = 1;
         // 1 for Admin
         $entry->enabled = true;
         $entry->postDate = $importEntry->pubDate;
         $entry->getContent()->setAttributes(array('title' => $importEntry->title, 'summary' => $postData, 'category' => $this->settings['categoryID']));
         $entry->getContent()->setAttributes(array('storyCategories' => array($this->settings['categoryID'])));
         $success = craft()->entries->saveEntry($entry);
         $block = new MatrixBlockModel();
         $block->fieldId = $this->settings['matrixFieldID'];
         $block->ownerId = $entry->id;
         $block->typeId = $this->settings['matrixTypeID'];
         $target = '';
         if ($this->settings['targetNewWindow']) {
             $target = ' target="_blank"';
         }
         $block->getContent()->cbText = sprintf('<a href="%s"%s>%s</a>', (string) $importEntry->link, $target, (string) $importEntry->title);
         craft()->matrix->saveBlock($block, false);
     }
     return $retVal;
 }
 /**
  * Populates a new model instance with a given set of attributes.
  *
  * @static
  * @param mixed $attributes
  * @return EntryVersionModel
  */
 public static function populateModel($attributes)
 {
     if ($attributes instanceof \CModel) {
         $attributes = $attributes->getAttributes();
     }
     // Merge the version and entry data
     $entryData = $attributes['data'];
     $fieldContent = isset($entryData['fields']) ? $entryData['fields'] : null;
     $attributes['versionId'] = $attributes['id'];
     $attributes['id'] = $attributes['entryId'];
     $title = $entryData['title'];
     unset($attributes['data'], $entryData['fields'], $attributes['entryId'], $entryData['title']);
     $attributes = array_merge($attributes, $entryData);
     // Initialize the version
     $version = parent::populateModel($attributes);
     $version->getContent()->title = $title;
     if ($fieldContent) {
         $version->getContent()->setValuesByFieldId($fieldContent);
     }
     return $version;
 }
Esempio n. 10
0
 /**
  * Checks if an entry was submitted with a new parent entry selected.
  *
  * @param EntryModel $entry
  *
  * @return bool
  */
 private function _checkForNewParent(EntryModel $entry)
 {
     // Make sure this is a Structure section
     if ($entry->getSection()->type != SectionType::Structure) {
         return false;
     }
     // Is it a brand new entry?
     if (!$entry->id) {
         return true;
     }
     // Was a parentId actually submitted?
     if ($entry->parentId === null) {
         return false;
     }
     // Is it set to the top level now, but it hadn't been before?
     if ($entry->parentId === '' && $entry->level != 1) {
         return true;
     }
     // Is it set to be under a parent now, but didn't have one before?
     if ($entry->parentId !== '' && $entry->level == 1) {
         return true;
     }
     // Is the parentId set to a different entry ID than its previous parent?
     $criteria = craft()->elements->getCriteria(ElementType::Entry);
     $criteria->ancestorOf = $entry;
     $criteria->ancestorDist = 1;
     $criteria->status = null;
     $criteria->localeEnabled = null;
     $oldParent = $criteria->first();
     $oldParentId = $oldParent ? $oldParent->id : '';
     if ($entry->parentId != $oldParentId) {
         return true;
     }
     // Must be set to the same one then
     return false;
 }
Esempio n. 11
0
 /**
  * Generates an entry slug based on its title.
  *
  * @access private
  * @param EntryModel $entry
  */
 private function _generateEntrySlug(EntryModel $entry)
 {
     $slug = $entry->slug ? $entry->slug : $entry->getTitle();
     // Remove HTML tags
     $slug = preg_replace('/<(.*?)>/', '', $slug);
     // Remove apostrophes
     $slug = str_replace(array('\'', '’'), array('', ''), $slug);
     // Make it lowercase
     $slug = strtolower($slug);
     // Convert extended ASCII characters to basic ASCII
     $slug = StringHelper::asciiString($slug);
     // Slug must start and end with alphanumeric characters
     $slug = preg_replace('/^[^a-z0-9]+/', '', $slug);
     $slug = preg_replace('/[^a-z0-9]+$/', '', $slug);
     // Get the "words"
     $words = preg_split('/[^a-z0-9]+/', $slug);
     $words = ArrayHelper::filterEmptyStringsFromArray($words);
     $slug = implode('-', $words);
     if ($slug) {
         // Make it unique
         $conditions = array('and', 'sectionId = :sectionId', 'locale = :locale', 'slug = :slug');
         $params = array(':sectionId' => $entry->sectionId, ':locale' => $entry->locale);
         if ($entry->id) {
             $conditions[] = 'id != :entryId';
             $params[':entryId'] = $entry->id;
         }
         for ($i = 0; true; $i++) {
             $testSlug = $slug . ($i != 0 ? "-{$i}" : '');
             $params[':slug'] = $testSlug;
             $totalEntries = craft()->db->createCommand()->select('count(id)')->from('entries_i18n')->where($conditions, $params)->queryScalar();
             if ($totalEntries == 0) {
                 break;
             }
         }
         $entry->slug = $testSlug;
     } else {
         $entry->slug = '';
     }
 }
 /**
  * Creates initial database content for InstaBlog.
  *
  * @return null
  */
 private function _createInstaBlogContent()
 {
     // InstaBlog tag group
     Craft::log('Creating the InstaBlog tag group.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $tagGroup = new TagGroupModel();
     $tagGroup->name = 'InstaBlog Tags';
     $tagGroup->handle = 'instaBlogTags';
     // Save it
     if (craft()->tags->saveTagGroup($tagGroup)) {
         Craft::log('InstaBlog tag group created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog tag group.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // InstaBlog field group
     Craft::log('Creating the InstaBlog field group.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $group = new FieldGroupModel();
     $group->name = 'InstaBlog';
     if (craft()->fields->saveGroup($group)) {
         Craft::log('InstaBlog field group created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog field group.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Body field
     Craft::log('Creating the InstaBlog Body field.');
     $bodyField = new FieldModel();
     $bodyField->groupId = $group->id;
     $bodyField->name = 'InstaBlog Body';
     $bodyField->handle = 'instaBlogBody';
     $bodyField->translatable = true;
     $bodyField->type = 'RichText';
     $bodyField->settings = array('configFile' => 'Standard.json', 'columnType' => ColumnType::Text);
     if (craft()->fields->saveField($bodyField)) {
         Craft::log('InstaBlog Body field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog Body field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Facebook field
     Craft::log('Creating the InstaBlog Facebook field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $facebookField = new FieldModel();
     $facebookField->groupId = $group->id;
     $facebookField->name = 'Facebook';
     $facebookField->handle = 'instaBlogFacebook';
     $facebookField->translatable = false;
     $facebookField->type = 'PlainText';
     $facebookField->instructions = 'Add your personal Facebook profile link. Example: https://www.facebook.com/xxxxxxxxxx';
     if (craft()->fields->saveField($facebookField)) {
         Craft::log('Facebook field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the Facebook field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Twitter Handle field
     Craft::log('Creating the InstaBlog Twitter field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $twitterField = new FieldModel();
     $twitterField->groupId = $group->id;
     $twitterField->name = 'Twitter';
     $twitterField->handle = 'instaBlogTwitter';
     $twitterField->translatable = false;
     $twitterField->type = 'PlainText';
     $twitterField->instructions = 'Add your personal Twitter handle. Example: @johndoe';
     if (craft()->fields->saveField($twitterField)) {
         Craft::log('Twitter field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the Twitter field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Google+ field
     Craft::log('Creating the InstaBlog Google+ field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $googlePlusField = new FieldModel();
     $googlePlusField->groupId = $group->id;
     $googlePlusField->name = 'Google+';
     $googlePlusField->handle = 'instaBlogGooglePlus';
     $googlePlusField->translatable = false;
     $googlePlusField->type = 'PlainText';
     $googlePlusField->instructions = 'Add your personal Google+ profile link. Example: https://plus.google.com/+JohnDoe';
     if (craft()->fields->saveField($googlePlusField)) {
         Craft::log('Google+ field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the Google+ field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // LinkedIn field
     Craft::log('Creating the InstaBlog LinkedIn field.');
     $linkedinField = new FieldModel();
     $linkedinField->groupId = $group->id;
     $linkedinField->name = 'LinkedIn';
     $linkedinField->handle = 'instaBlogLinkedin';
     $linkedinField->translatable = false;
     $linkedinField->type = 'PlainText';
     $linkedinField->instructions = 'Add your personal LinkedIn profile link. Example: https://www.linkedin.com/pub/john-doe/3/7aa/91b';
     if (craft()->fields->saveField($linkedinField)) {
         Craft::log('LinkedIn field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the LinkedIn field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Create the new user field layout
     Craft::log('Creating the new user profile layout.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $userFieldLayout = craft()->fields->getLayoutByType(ElementType::User);
     $fieldsIds = $userFieldLayout->getFieldIds();
     $fieldsIds[] = $facebookField->id;
     $fieldsIds[] = $twitterField->id;
     $fieldsIds[] = $googlePlusField->id;
     $fieldsIds[] = $linkedinField->id;
     craft()->fields->deleteLayoutsByType(ElementType::User);
     $userFieldLayout = craft()->fields->assembleLayout(array(Craft::t('Profile') => $fieldsIds), array(), false);
     $userFieldLayout->type = ElementType::User;
     if (craft()->fields->saveLayout($userFieldLayout, false)) {
         Craft::log('User profile layout saved successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the user profile layout.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Tags field
     Craft::log('Creating the Tags field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $tagsField = new FieldModel();
     $tagsField->groupId = $group->id;
     $tagsField->name = 'InstaBlog Tags';
     $tagsField->handle = 'instaBlogTags';
     $tagsField->type = 'Tags';
     $tagsField->settings = array('source' => 'taggroup:' . $tagGroup->id);
     if (craft()->fields->saveField($tagsField)) {
         Craft::log('InstaBlog Tags field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog Tags field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // InstaBlog category group
     Craft::log('Creating the InstaBlog category group.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $categoryGroup = new CategoryGroupModel();
     $categoryGroup->name = 'InstaBlog Categories';
     $categoryGroup->handle = 'instaBlogCategories';
     $categoryGroup->template = 'blog/category';
     $categoryGroup->maxLevels = 1;
     // Locale-specific URL formats
     $locales = array();
     foreach (craft()->i18n->getSiteLocaleIds() as $localeId) {
         $locales[$localeId] = new CategoryGroupLocaleModel(array('locale' => $localeId, 'urlFormat' => 'blog/category/{slug}', 'nestedUrlFormat' => null));
     }
     $categoryGroup->setLocales($locales);
     // Group the field layout
     $categoryFieldLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id)), array());
     $categoryFieldLayout->type = ElementType::Category;
     $categoryGroup->setFieldLayout($categoryFieldLayout);
     // Save it
     if (craft()->categories->saveGroup($categoryGroup)) {
         Craft::log('InstaBlog category group created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog category group.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Categories field
     Craft::log('Creating the InstaBlog Category field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $categoriesField = new FieldModel();
     $categoriesField->groupId = $group->id;
     $categoriesField->name = 'InstaBlog Categories';
     $categoriesField->handle = 'instaBlogCategories';
     $categoriesField->type = 'Categories';
     $categoriesField->settings = array('source' => 'group:' . $categoryGroup->id);
     if (craft()->fields->saveField($categoriesField)) {
         Craft::log('InstaBlog Category field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog Category field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // Asset field
     Craft::log('Creating the InstaBlog Asset field.');
     $assetField = new FieldModel();
     $assetField->groupId = $group->id;
     $assetField->name = 'Featured Image';
     $assetField->handle = 'instaBlogImage';
     $assetField->translatable = false;
     $assetField->type = 'Assets';
     $assetField->settings = array('sources' => '*');
     if (craft()->fields->saveField($assetField)) {
         Craft::log('Asset field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the Asset field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // InstaBlog section
     Craft::log('Creating the InstaBlog section.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $instaBlogSection = new SectionModel();
     $instaBlogSection->type = SectionType::Channel;
     $instaBlogSection->name = 'InstaBlog';
     $instaBlogSection->handle = 'instaBlog';
     $instaBlogSection->hasUrls = true;
     $instaBlogSection->template = 'blog/_entry';
     // Locale-specific URL formats
     $locales = array();
     if (craft()->isLocalized()) {
         $localeIds = craft()->i18n->getSiteLocaleIds();
     } else {
         $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId();
         $localeIds = array($primaryLocaleId);
     }
     foreach ($localeIds as $localeId) {
         $locales[$localeId] = new SectionLocaleModel(array('locale' => $localeId, 'enabledByDefault' => true, 'urlFormat' => 'blog/{slug}'));
     }
     $instaBlogSection->setLocales($locales);
     if (craft()->sections->saveSection($instaBlogSection)) {
         Craft::log('InstaBlog section created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog section.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // InstaBlog section entry type layout
     Craft::log('Saving the InstaBlog entry type.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     $instaBlogLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id, $assetField->id, $categoriesField->id, $tagsField->id)), array($bodyField->id));
     $instaBlogLayout->type = ElementType::Entry;
     $instaBlogEntryTypes = $instaBlogSection->getEntryTypes();
     $instaBlogEntryType = $instaBlogEntryTypes[0];
     $instaBlogEntryType->setFieldLayout($instaBlogLayout);
     if (craft()->sections->saveEntryType($instaBlogEntryType)) {
         Craft::log('InstaBlog entry type saved successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog entry type.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     // InstaBlog entry
     Craft::log('Creating a InstaBlog entry.');
     $instaBlogEntry = new EntryModel();
     $instaBlogEntry->sectionId = $instaBlogSection->id;
     $instaBlogEntry->typeId = $instaBlogEntryType->id;
     $instaBlogEntry->locale = $primaryLocaleId;
     $instaBlogEntry->authorId = craft()->userSession->getId();
     $instaBlogEntry->enabled = true;
     $instaBlogEntry->getContent()->title = 'We just installed InstaBlog!';
     $instaBlogEntry->getContent()->setAttributes(array('instaBlogBody' => '<p>' . 'Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits. Dramatically visualize customer directed convergence without revolutionary ROI.' . '</p><p>Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions.' . '</p><p>Completely synergize resource taxing relationships via premier niche markets. Professionally cultivate one-to-one customer service with robust ideas. Dynamically innovate resource-leveling customer service for state of the art customer service.' . '</p>'));
     if (craft()->entries->saveEntry($instaBlogEntry)) {
         Craft::log('InstaBlog entry created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog entry.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     //Create Route for Tags
     $urlParts = array('blog/tag/', array('*', '[^\\/]+'));
     $template = 'blog/tag';
     if (craft()->routes->saveRoute($urlParts, $template)) {
         Craft::log('InstaBlog tag route created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not create the InstaBlog tag route.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
     //Create Route for Tags
     $urlParts = array('blog/author/', array('*', '[^\\/]+'));
     $template = 'blog/author';
     if (craft()->routes->saveRoute($urlParts, $template)) {
         Craft::log('InstaBlog author route created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog');
     } else {
         Craft::log('Could not create the InstaBlog author route.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog');
     }
 }
Esempio n. 13
0
 public static function systemNotification($message)
 {
     $entry = new EntryModel();
     return $entry->notify($message);
 }
 /**
  * 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;
 }
Esempio n. 15
0
 /**
  * Applies the rules which relate to a given entry.
  *
  * @param EntryModel $entry
  */
 public function applyRules($entry)
 {
     foreach (craft()->autoExpire->getRules() as $rule) {
         if ($entry->sectionId == $rule->sectionId && $entry->getType()->id == $rule->entryTypeId) {
             $ruleName = $entry->id . '::' . $rule->id;
             // Did we already re-save the entry for this rule? Necessary because of the recursive
             // call of EntriesService::saveEntry().
             if (!in_array($ruleName, $this->_handledRules)) {
                 $this->_handledRules[] = $ruleName;
                 $this->applyRule($entry, $rule);
             }
         }
     }
 }
Esempio n. 16
0
 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);
     } 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]);
     }
     // 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);
     }
     // 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);
     }
     // Set enabled
     $enabled = FeedMe_Element::Enabled;
     if (isset($fields[$enabled])) {
         $element->{$enabled} = (bool) $fields[$enabled];
     }
     // Set title
     $title = FeedMe_Element::Title;
     if (isset($fields[$title])) {
         $element->getContent()->{$title} = $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;
             }
         }
     } 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;
             }
         }
     }
     // Return element
     return $element;
 }
 /**
  * When users are not allowed to publish live changes any new entries they create will be disabled entries
  * which are not technically drafts
  *
  * @param EntryModel $entry
  * @return bool
  */
 private function isDraft(EntryModel $entry)
 {
     return $entry instanceof EntryDraftModel || $entry->getStatus() == 'disabled';
 }
Esempio n. 18
0
 /**
  * Creates initial database content for the install.
  *
  * @param $inputs
  *
  * @return null
  */
 private function _createDefaultContent($inputs)
 {
     // Default tag group
     Craft::log('Creating the Default tag group.');
     $tagGroup = new TagGroupModel();
     $tagGroup->name = 'Default';
     $tagGroup->handle = 'default';
     // Save it
     if (craft()->tags->saveTagGroup($tagGroup)) {
         Craft::log('Default tag group created successfully.');
     } else {
         Craft::log('Could not save the Default tag group.', LogLevel::Warning);
     }
     // Default field group
     Craft::log('Creating the Default field group.');
     $group = new FieldGroupModel();
     $group->name = 'Default';
     if (craft()->fields->saveGroup($group)) {
         Craft::log('Default field group created successfully.');
     } else {
         Craft::log('Could not save the Default field group.', LogLevel::Warning);
     }
     // Body field
     Craft::log('Creating the Body field.');
     $bodyField = new FieldModel();
     $bodyField->groupId = $group->id;
     $bodyField->name = 'Body';
     $bodyField->handle = 'body';
     $bodyField->translatable = true;
     $bodyField->type = 'RichText';
     $bodyField->settings = array('configFile' => 'Standard.json', 'columnType' => ColumnType::Text);
     if (craft()->fields->saveField($bodyField)) {
         Craft::log('Body field created successfully.');
     } else {
         Craft::log('Could not save the Body field.', LogLevel::Warning);
     }
     // Tags field
     Craft::log('Creating the Tags field.');
     $tagsField = new FieldModel();
     $tagsField->groupId = $group->id;
     $tagsField->name = 'Tags';
     $tagsField->handle = 'tags';
     $tagsField->type = 'Tags';
     $tagsField->settings = array('source' => 'taggroup:' . $tagGroup->id);
     if (craft()->fields->saveField($tagsField)) {
         Craft::log('Tags field created successfully.');
     } else {
         Craft::log('Could not save the Tags field.', LogLevel::Warning);
     }
     // Homepage single section
     Craft::log('Creating the Homepage single section.');
     $homepageLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id)), array($bodyField->id));
     $homepageLayout->type = ElementType::Entry;
     $homepageSingleSection = new SectionModel();
     $homepageSingleSection->name = 'Homepage';
     $homepageSingleSection->handle = 'homepage';
     $homepageSingleSection->type = SectionType::Single;
     $homepageSingleSection->hasUrls = false;
     $homepageSingleSection->template = 'index';
     $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId();
     $locales[$primaryLocaleId] = new SectionLocaleModel(array('locale' => $primaryLocaleId, 'urlFormat' => '__home__'));
     $homepageSingleSection->setLocales($locales);
     // Save it
     if (craft()->sections->saveSection($homepageSingleSection)) {
         Craft::log('Homepage single section created successfully.');
     } else {
         Craft::log('Could not save the Homepage single section.', LogLevel::Warning);
     }
     $homepageEntryTypes = $homepageSingleSection->getEntryTypes();
     $homepageEntryType = $homepageEntryTypes[0];
     $homepageEntryType->hasTitleField = true;
     $homepageEntryType->titleLabel = 'Title';
     $homepageEntryType->setFieldLayout($homepageLayout);
     if (craft()->sections->saveEntryType($homepageEntryType)) {
         Craft::log('Homepage single section entry type saved successfully.');
     } else {
         Craft::log('Could not save the Homepage single section entry type.', LogLevel::Warning);
     }
     // Homepage content
     $siteName = ucfirst(craft()->request->getServerName());
     Craft::log('Setting the Homepage content.');
     $criteria = craft()->elements->getCriteria(ElementType::Entry);
     $criteria->sectionId = $homepageSingleSection->id;
     $entryModel = $criteria->first();
     $entryModel->locale = $inputs['locale'];
     $entryModel->getContent()->title = 'Welcome to ' . $siteName . '!';
     $entryModel->setContentFromPost(array('body' => '<p>It’s true, this site doesn’t have a whole lot of content yet, but don’t worry. Our web developers have just installed the CMS, and they’re setting things up for the content editors this very moment. Soon ' . $siteName . ' will be an oasis of fresh perspectives, sharp analyses, and astute opinions that will keep you coming back again and again.</p>'));
     // Save the content
     if (craft()->entries->saveEntry($entryModel)) {
         Craft::log('Homepage an entry to the Homepage single section.');
     } else {
         Craft::log('Could not save an entry to the Homepage single section.', LogLevel::Warning);
     }
     // News section
     Craft::log('Creating the News section.');
     $newsSection = new SectionModel();
     $newsSection->type = SectionType::Channel;
     $newsSection->name = 'News';
     $newsSection->handle = 'news';
     $newsSection->hasUrls = true;
     $newsSection->template = 'news/_entry';
     $newsSection->setLocales(array($inputs['locale'] => SectionLocaleModel::populateModel(array('locale' => $inputs['locale'], 'urlFormat' => 'news/{postDate.year}/{slug}'))));
     if (craft()->sections->saveSection($newsSection)) {
         Craft::log('News section created successfully.');
     } else {
         Craft::log('Could not save the News section.', LogLevel::Warning);
     }
     Craft::log('Saving the News entry type.');
     $newsLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id, $tagsField->id)), array($bodyField->id));
     $newsLayout->type = ElementType::Entry;
     $newsEntryTypes = $newsSection->getEntryTypes();
     $newsEntryType = $newsEntryTypes[0];
     $newsEntryType->setFieldLayout($newsLayout);
     if (craft()->sections->saveEntryType($newsEntryType)) {
         Craft::log('News entry type saved successfully.');
     } else {
         Craft::log('Could not save the News entry type.', LogLevel::Warning);
     }
     // News entry
     Craft::log('Creating a News entry.');
     $newsEntry = new EntryModel();
     $newsEntry->sectionId = $newsSection->id;
     $newsEntry->typeId = $newsEntryType->id;
     $newsEntry->locale = $inputs['locale'];
     $newsEntry->authorId = $this->_user->id;
     $newsEntry->enabled = true;
     $newsEntry->getContent()->title = 'We just installed Craft!';
     $newsEntry->getContent()->setAttributes(array('body' => '<p>' . 'Craft is the CMS that’s powering ' . $siteName . '. It’s beautiful, powerful, flexible, and easy-to-use, and it’s made by Pixel &amp; Tonic. We can’t wait to dive in and see what it’s capable of!' . '</p><!--pagebreak--><p>' . 'This is even more captivating content, which you couldn’t see on the News index page because it was entered after a Page Break, and the News index template only likes to show the content on the first page.' . '</p><p>' . 'Craft: a nice alternative to Word, if you’re making a website.' . '</p>'));
     if (craft()->entries->saveEntry($newsEntry)) {
         Craft::log('News entry created successfully.');
     } else {
         Craft::log('Could not save the News entry.', LogLevel::Warning);
     }
 }
 /**
  * Parse entry fields.
  *
  * @param EntryModel $entry
  * @param bool       $empty
  *
  * @return array
  */
 public function fields(EntryModel $entry, $empty = false)
 {
     // Always save id and title
     $fields = array('id' => array('label' => Craft::t('ID'), 'value' => $entry->id), 'title' => array('label' => Craft::t('Title'), 'value' => (string) $entry->getTitle()), 'section' => array('label' => Craft::t('Section'), 'value' => (string) $entry->getSection()));
     // Get element type
     $elementType = craft()->elements->getElementType(ElementType::Entry);
     // Get nice attributes
     $availableAttributes = $elementType->defineAvailableTableAttributes();
     // Make 'em fit
     $attributes = array();
     foreach ($availableAttributes as $key => $result) {
         $attributes[$key] = $result['label'];
     }
     // Get static "fields"
     foreach ($entry->getAttributes() as $handle => $value) {
         // Only show nice attributes
         if (array_key_exists($handle, $attributes)) {
             $fields[$handle] = array('label' => $attributes[$handle], 'value' => StringHelper::arrayToString(is_array($value) ? array_filter(ArrayHelper::flattenArray($value), 'strlen') : $value, ', '));
         }
     }
     // Get fieldlayout
     $entrytype = $entry->getType();
     if ($entrytype) {
         $tabs = craft()->fields->getLayoutById($entrytype->fieldLayoutId)->getTabs();
         foreach ($tabs as $tab) {
             foreach ($tab->getFields() as $field) {
                 // Get field values
                 $field = $field->getField();
                 $handle = $field->handle;
                 $label = $field->name;
                 $value = $empty ? '' : craft()->auditLog->parseFieldData($handle, $entry->{$handle});
                 // Set on fields
                 $fields[$handle] = array('label' => $label, 'value' => $value);
             }
         }
     }
     // Return
     return $fields;
 }
 /**
  * Import WP Post into InstaBlog Section
  *
  * @param mixed $settings Array of settings
  * @param mixed $post Entry Posts array from WP XML
  * @param number $categoryGroupId Category Group ID for InstaBlog Categories
  * @param number $tagGroupId Tag Group ID for InstaBlog Tags
  * @param string $baseUrl Base url of WP blog
  * 
  * @return Null
  */
 protected function _importPost($settings, $post, $categoryGroupId, $tagGroupId, $baseUrl)
 {
     $postContent = $post['post_content'];
     $featuredImage = array();
     $categoryIds = array();
     $tagIds = array();
     // If entry slug exists abort
     if ($this->_getEntry($post['post_name'])) {
         Craft::log('Could not save the InstaBlog entry:' . $post['post_name'] . ' It already exists.', LogLevel::Info, false, 'application', 'InstaBlog');
         return;
     }
     // Import Tags / Categories associated with post
     if (array_key_exists('terms', $post)) {
         foreach ($post['terms'] as $term) {
             switch ($term['domain']) {
                 case 'category':
                     $categoryIds[] = $this->_importCategory($term['name'], $categoryGroupId);
                     break;
                 case 'post_tag':
                     $tagIds[] = $this->_importTag($term['name'], $tagGroupId);
                     break;
             }
         }
     }
     // Import Featured Images
     foreach ($post['postmeta'] as $postmetaArray) {
         if ($postmetaArray['key'] === '_thumbnail_id') {
             $featuredImage[] = $this->_importFeaturedImage($settings, $post['post_link'], $baseUrl);
         }
     }
     // Import Images referenced in post_content
     $postContent = $this->_importImages($settings, $postContent, $baseUrl);
     // Replace missing paragraph elements. Nice goin' WordPress.
     $postContent = $this->_wpautop($postContent);
     // Get values for entry
     $section = craft()->sections->getSectionByHandle('instaBlog');
     $entryTypes = $section->getEntryTypes();
     $entryType = $entryTypes[0];
     // Save Entry
     $entry = new EntryModel();
     $entry->sectionId = $section->id;
     $entry->typeId = $entryType->id;
     $entry->locale = craft()->i18n->getPrimarySiteLocaleId();
     $entry->authorId = $this->_getUserId($post['post_author']);
     $entry->enabled = $post['status'] === 'publish' ? true : false;
     $entry->postDate = $post['post_date'];
     $entry->slug = $post['post_name'];
     $entry->getContent()->title = $post['post_title'];
     $entry->setContentFromPost(array('instaBlogBody' => $postContent, 'instaBlogImage' => $featuredImage, 'instaBlogCategories' => $categoryIds, 'instaBlogTags' => $tagIds));
     if (craft()->entries->saveEntry($entry)) {
         Craft::log('InstaBlog entry created successfully.', LogLevel::Info, false, '_importPost', 'InstaBlog');
     } else {
         Craft::log('Could not save the InstaBlog entry.', LogLevel::Error, true, '_importPost', 'InstaBlog');
     }
 }
 /**
  * @return array
  */
 protected function defineAttributes()
 {
     return array_merge(parent::defineAttributes(), array('creatorId' => AttributeType::Number, 'dateUpdated' => AttributeType::DateTime, 'dateCreated' => AttributeType::DateTime));
 }
 /**
  * Duplicate an entry.
  *
  * @param array $variables
  *
  * @return bool
  */
 public function duplicateAnEntry($variables)
 {
     if (!isset($variables['entryId']) || !isset($variables['searchText'])) {
         return false;
     } elseif (empty($variables['searchText'])) {
         craft()->amCommand->setReturnMessage(Craft::t('Title isn’t set.'));
         return false;
     }
     $result = false;
     $duplicatePrimaryLocaleEntry = false;
     foreach (craft()->i18n->getSiteLocales() as $locale) {
         // Current entry based on locale
         $currentEntry = craft()->entries->getEntryById($variables['entryId'], $locale->getId());
         if (is_null($currentEntry)) {
             continue;
         }
         // We don't want to duplicate Single type entries
         $currentSection = $currentEntry->getSection();
         if ($currentSection->type == SectionType::Single) {
             return false;
         }
         // Current entry data
         $currentParent = $currentEntry->getParent();
         $currentTitle = $currentEntry->getContent()->title;
         $currentAttributes = $this->_getAttributesForModel($currentEntry);
         // Override title?
         if ($locale->id == $variables['locale']) {
             $currentTitle = $variables['searchText'];
         }
         // New entry
         $newEntry = new EntryModel();
         $newEntry->sectionId = $currentEntry->sectionId;
         $newEntry->typeId = $currentEntry->typeId;
         $newEntry->locale = $currentEntry->locale;
         $newEntry->authorId = $currentEntry->authorId;
         $newEntry->enabled = $currentEntry->enabled;
         $newEntry->postDate = $currentEntry->postDate;
         $newEntry->expiryDate = $currentEntry->expiryDate;
         if (!is_null($currentParent)) {
             $newEntry->parentId = $currentParent->id;
             // Structure type entry
         }
         // Set element ID, because we already have created the duplicated primary locale entry
         if ($duplicatePrimaryLocaleEntry !== false) {
             $newEntry->id = $duplicatePrimaryLocaleEntry->id;
         }
         // Set entry title and content
         $newEntry->getContent()->title = $currentTitle;
         $newEntry->getContent()->setAttributes($currentAttributes);
         // Save duplicate entry
         $result = craft()->entries->saveEntry($newEntry);
         // Remember element ID, because we don't want new entries for each locale...
         if ($result && $duplicatePrimaryLocaleEntry === false) {
             $duplicatePrimaryLocaleEntry = $newEntry;
         }
     }
     // Update other locales URIs since somehow the uri is the same as the primary locale
     if ($duplicatePrimaryLocaleEntry !== false) {
         craft()->elements->updateElementSlugAndUriInOtherLocales($duplicatePrimaryLocaleEntry);
     }
     // Return duplication result
     if ($result) {
         if ($duplicatePrimaryLocaleEntry !== false) {
             craft()->amCommand->setReturnUrl($duplicatePrimaryLocaleEntry->getCpEditUrl());
         }
         craft()->amCommand->setReturnMessage(Craft::t('Entry duplicated.'));
     } else {
         craft()->amCommand->setReturnMessage(Craft::t('Couldn’t duplicate entry.'));
     }
     return $result;
 }
Esempio n. 23
0
 protected function getTaskPosts($item_id)
 {
     $entry = new EntryModel();
     return $entry->latestFromTask($item_id);
 }
 /**
  * @inheritDoc IElementType::populateElementModel()
  *
  * @param array $row
  *
  * @return BaseElementModel|BaseModel|void
  */
 public function populateElementModel($row)
 {
     return EntryModel::populateModel($row);
 }
Esempio n. 25
0
 /**
  * Creates initial database content for the install.
  *
  * @access private
  * @param $inputs
  * @return null
  */
 private function _createDefaultContent($inputs)
 {
     // Default tag set
     Craft::log('Creating the Default tag set.');
     $tagSet = new TagSetModel();
     $tagSet->name = Craft::t('Default');
     $tagSet->handle = 'default';
     // Save it
     if (craft()->tags->saveTagSet($tagSet)) {
         Craft::log('Default tag set created successfully.');
     } else {
         Craft::log('Could not save the Default tag set.', LogLevel::Warning);
     }
     // Default field group
     Craft::log('Creating the Default field group.');
     $group = new FieldGroupModel();
     $group->name = Craft::t('Default');
     if (craft()->fields->saveGroup($group)) {
         Craft::log('Default field group created successfully.');
     } else {
         Craft::log('Could not save the Default field group.', LogLevel::Warning);
     }
     // Heading field
     Craft::log('Creating the Heading field.');
     $headingField = new FieldModel();
     $headingField->groupId = $group->id;
     $headingField->name = Craft::t('Heading');
     $headingField->handle = 'heading';
     $headingField->translatable = true;
     $headingField->type = 'PlainText';
     if (craft()->fields->saveField($headingField)) {
         Craft::log('Heading field created successfully.');
     } else {
         Craft::log('Could not save the Heading field.', LogLevel::Warning);
     }
     // Body field
     Craft::log('Creating the Body field.');
     $bodyField = new FieldModel();
     $bodyField->groupId = $group->id;
     $bodyField->name = Craft::t('Body');
     $bodyField->handle = 'body';
     $bodyField->translatable = true;
     $bodyField->type = 'RichText';
     $bodyField->settings = array('configFile' => 'Standard.json');
     if (craft()->fields->saveField($bodyField)) {
         Craft::log('Body field created successfully.');
     } else {
         Craft::log('Could not save the Body field.', LogLevel::Warning);
     }
     // Tags field
     Craft::log('Creating the Tags field.');
     $tagsField = new FieldModel();
     $tagsField->groupId = $group->id;
     $tagsField->name = Craft::t('Tags');
     $tagsField->handle = 'tags';
     $tagsField->type = 'Tags';
     $tagsField->settings = array('source' => 'tagset:' . $tagSet->id);
     if (craft()->fields->saveField($tagsField)) {
         Craft::log('Tags field created successfully.');
     } else {
         Craft::log('Could not save the Tags field.', LogLevel::Warning);
     }
     // Homepage global set
     Craft::log('Creating the Homepage global set.');
     $homepageLayoutFields = array(array('fieldId' => $headingField->id, 'sortOrder' => 1), array('fieldId' => $bodyField->id, 'sortOrder' => 2));
     $homepageLayout = new FieldLayoutModel();
     $homepageLayout->type = ElementType::GlobalSet;
     $homepageLayout->setFields($homepageLayoutFields);
     $homepageGlobalSet = new GlobalSetModel();
     $homepageGlobalSet->name = Craft::t('Homepage');
     $homepageGlobalSet->handle = 'homepage';
     $homepageGlobalSet->setFieldLayout($homepageLayout);
     if (craft()->globals->saveSet($homepageGlobalSet)) {
         Craft::log('Homepage global set created successfully.');
     } else {
         Craft::log('Could not save the Homepage global set.', LogLevel::Warning);
     }
     // Homepage content
     $vars = array('siteName' => ucfirst(craft()->request->getServerName()));
     Craft::log('Setting the Homepage content.');
     $homepageGlobalSet->locale = $inputs['locale'];
     $homepageGlobalSet->getContent()->setAttributes(array('heading' => Craft::t('Welcome to {siteName}!', $vars), 'body' => '<p>' . Craft::t('It’s true, this site doesn’t have a whole lot of content yet, but don’t worry. Our web developers have just installed the CMS, and they’re setting things up for the content editors this very moment. Soon {siteName} will be an oasis of fresh perspectives, sharp analyses, and astute opinions that will keep you coming back again and again.', $vars) . '</p>'));
     if (craft()->globals->saveContent($homepageGlobalSet)) {
         Craft::log('Homepage content set successfully.');
     } else {
         Craft::log('Could not set the Homepage content.', LogLevel::Warning);
     }
     // News section
     Craft::log('Creating the News section.');
     $newsLayoutFields = array(array('fieldId' => $bodyField->id, 'required' => true, 'sortOrder' => 1), array('fieldId' => $tagsField->id, 'sortOrder' => 2));
     $newsLayoutTabs = array(array('name' => Craft::t('Content'), 'sortOrder' => 1, 'fields' => $newsLayoutFields));
     $newsLayout = new FieldLayoutModel();
     $newsLayout->type = ElementType::Entry;
     $newsLayout->setTabs($newsLayoutTabs);
     $newsLayout->setFields($newsLayoutFields);
     $newsSection = new SectionModel();
     $newsSection->name = Craft::t('News');
     $newsSection->handle = 'news';
     $newsSection->hasUrls = true;
     $newsSection->template = 'news/_entry';
     $newsSection->setLocales(array($inputs['locale'] => SectionLocaleModel::populateModel(array('locale' => $inputs['locale'], 'urlFormat' => 'news/{postDate.year}/{slug}'))));
     $newsSection->setFieldLayout($newsLayout);
     if (craft()->sections->saveSection($newsSection)) {
         Craft::log('News section created successfully.');
     } else {
         Craft::log('Could not save the News section.', LogLevel::Warning);
     }
     // News entry
     Craft::log('Creating a News entry.');
     $newsEntry = new EntryModel();
     $newsEntry->sectionId = $newsSection->id;
     $newsEntry->locale = $inputs['locale'];
     $newsEntry->authorId = $this->_user->id;
     $newsEntry->enabled = true;
     $newsEntry->getContent()->title = Craft::t('We just installed Craft!');
     $newsEntry->getContent()->setAttributes(array('body' => '<p>' . Craft::t('Craft is the CMS that’s powering {siteName}. It’s beautiful, powerful, flexible, and easy-to-use, and it’s made by Pixel &amp; Tonic. We can’t wait to dive in and see what it’s capable of!', $vars) . '</p><!--pagebreak--><p>' . Craft::t('This is even more captivating content, which you couldn’t see on the News index page because it was entered after a Page Break, and the News index template only likes to show the content on the first page.') . '</p><p>' . Craft::t('Craft: a nice alternative to Word, if you’re making a website.') . '</p>'));
     if (craft()->entries->saveEntry($newsEntry)) {
         Craft::log('News entry created successfully.');
     } else {
         Craft::log('Could not save the News entry.', LogLevel::Warning);
     }
 }
 /**
  * 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;
 }
 /**
  * Displays an entry.
  *
  * @param EntryModel $entry
  *
  * @throws HttpException
  * @return null
  */
 private function _showEntry(EntryModel $entry)
 {
     $section = $entry->getSection();
     $type = $entry->getType();
     if (!$section || !$type) {
         Craft::log('Attempting to preview an entry that doesn’t have a section/type', LogLevel::Error);
         throw new HttpException(404);
     }
     craft()->setLanguage($entry->locale);
     if (!$entry->postDate) {
         $entry->postDate = new DateTime();
     }
     // Have this entry override any freshly queried entries with the same ID/locale
     craft()->elements->setPlaceholderElement($entry);
     craft()->templates->getTwig()->disableStrictVariables();
     $this->renderTemplate($section->template, array('entry' => $entry));
 }
Esempio n. 28
0
 /**
  * Saves a section.
  *
  * @param SectionModel $section
  *
  * @throws \Exception
  * @return bool
  */
 public function saveSection(SectionModel $section)
 {
     if ($section->id) {
         $sectionRecord = SectionRecord::model()->with('structure')->findById($section->id);
         if (!$sectionRecord) {
             throw new Exception(Craft::t('No section exists with the ID “{id}”.', array('id' => $section->id)));
         }
         $oldSection = SectionModel::populateModel($sectionRecord);
         $isNewSection = false;
     } else {
         $sectionRecord = new SectionRecord();
         $isNewSection = true;
     }
     // Shared attributes
     $sectionRecord->name = $section->name;
     $sectionRecord->handle = $section->handle;
     $sectionRecord->type = $section->type;
     $sectionRecord->enableVersioning = $section->enableVersioning;
     // Type-specific attributes
     if ($section->type == SectionType::Single) {
         $sectionRecord->hasUrls = $section->hasUrls = true;
     } else {
         $sectionRecord->hasUrls = $section->hasUrls;
     }
     if ($section->hasUrls) {
         $sectionRecord->template = $section->template;
     } else {
         $sectionRecord->template = $section->template = null;
     }
     $sectionRecord->validate();
     $section->addErrors($sectionRecord->getErrors());
     // Make sure that all of the URL formats are set properly
     $sectionLocales = $section->getLocales();
     if (!$sectionLocales) {
         $section->addError('localeErrors', Craft::t('At least one locale must be selected for the section.'));
     }
     $firstSectionLocale = null;
     foreach ($sectionLocales as $localeId => $sectionLocale) {
         // Is this the first one?
         if ($firstSectionLocale === null) {
             $firstSectionLocale = $sectionLocale;
         }
         if ($section->type == SectionType::Single) {
             $errorKey = 'urlFormat-' . $localeId;
             if (empty($sectionLocale->urlFormat)) {
                 $section->addError($errorKey, Craft::t('URI cannot be blank.'));
             } else {
                 if ($section) {
                     // Make sure no other elements are using this URI already
                     $query = craft()->db->createCommand()->from('elements_i18n elements_i18n')->where(array('and', 'elements_i18n.locale = :locale', 'elements_i18n.uri = :uri'), array(':locale' => $localeId, ':uri' => $sectionLocale->urlFormat));
                     if ($section->id) {
                         $query->join('entries entries', 'entries.id = elements_i18n.elementId')->andWhere('entries.sectionId != :sectionId', array(':sectionId' => $section->id));
                     }
                     $count = $query->count('elements_i18n.id');
                     if ($count) {
                         $section->addError($errorKey, Craft::t('This URI is already in use.'));
                     }
                 }
             }
             $sectionLocale->nestedUrlFormat = null;
         } else {
             if ($section->hasUrls) {
                 $urlFormatAttributes = array('urlFormat');
                 $sectionLocale->urlFormatIsRequired = true;
                 if ($section->type == SectionType::Structure && $section->maxLevels != 1) {
                     $urlFormatAttributes[] = 'nestedUrlFormat';
                     $sectionLocale->nestedUrlFormatIsRequired = true;
                 } else {
                     $sectionLocale->nestedUrlFormat = null;
                 }
                 foreach ($urlFormatAttributes as $attribute) {
                     if (!$sectionLocale->validate(array($attribute))) {
                         $section->addError($attribute . '-' . $localeId, $sectionLocale->getError($attribute));
                     }
                 }
             } else {
                 $sectionLocale->urlFormat = null;
                 $sectionLocale->nestedUrlFormat = null;
             }
         }
     }
     if (!$section->hasErrors()) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             // Fire an 'onBeforeSaveSection' event
             $event = new Event($this, array('section' => $section, 'isNewSection' => $isNewSection));
             $this->onBeforeSaveSection($event);
             // Is the event giving us the go-ahead?
             if ($event->performAction) {
                 // Do we need to create a structure?
                 if ($section->type == SectionType::Structure) {
                     if (!$isNewSection && $oldSection->type == SectionType::Structure) {
                         $structure = craft()->structures->getStructureById($oldSection->structureId);
                         $isNewStructure = false;
                     }
                     if (empty($structure)) {
                         $structure = new StructureModel();
                         $isNewStructure = true;
                     }
                     $structure->maxLevels = $section->maxLevels;
                     craft()->structures->saveStructure($structure);
                     $sectionRecord->structureId = $structure->id;
                     $section->structureId = $structure->id;
                 } else {
                     if (!$isNewSection && $oldSection->structureId) {
                         // Delete the old one
                         craft()->structures->deleteStructureById($oldSection->structureId);
                         $sectionRecord->structureId = null;
                     }
                 }
                 $sectionRecord->save(false);
                 // Now that we have a section ID, save it on the model
                 if ($isNewSection) {
                     $section->id = $sectionRecord->id;
                 }
                 // Might as well update our cache of the section while we have it. (It's possible that the URL format
                 //includes {section.handle} or something...)
                 $this->_sectionsById[$section->id] = $section;
                 // Update the sections_i18n table
                 $newLocaleData = array();
                 if (!$isNewSection) {
                     // Get the old section locales
                     $oldSectionLocaleRecords = SectionLocaleRecord::model()->findAllByAttributes(array('sectionId' => $section->id));
                     $oldSectionLocales = SectionLocaleModel::populateModels($oldSectionLocaleRecords, 'locale');
                 }
                 foreach ($sectionLocales as $localeId => $locale) {
                     // Was this already selected?
                     if (!$isNewSection && isset($oldSectionLocales[$localeId])) {
                         $oldLocale = $oldSectionLocales[$localeId];
                         // Has anything changed?
                         if ($locale->enabledByDefault != $oldLocale->enabledByDefault || $locale->urlFormat != $oldLocale->urlFormat || $locale->nestedUrlFormat != $oldLocale->nestedUrlFormat) {
                             craft()->db->createCommand()->update('sections_i18n', array('enabledByDefault' => (int) $locale->enabledByDefault, 'urlFormat' => $locale->urlFormat, 'nestedUrlFormat' => $locale->nestedUrlFormat), array('id' => $oldLocale->id));
                         }
                     } else {
                         $newLocaleData[] = array($section->id, $localeId, (int) $locale->enabledByDefault, $locale->urlFormat, $locale->nestedUrlFormat);
                     }
                 }
                 // Insert the new locales
                 craft()->db->createCommand()->insertAll('sections_i18n', array('sectionId', 'locale', 'enabledByDefault', 'urlFormat', 'nestedUrlFormat'), $newLocaleData);
                 if (!$isNewSection) {
                     // Drop any locales that are no longer being used, as well as the associated entry/element locale
                     // rows
                     $droppedLocaleIds = array_diff(array_keys($oldSectionLocales), array_keys($sectionLocales));
                     if ($droppedLocaleIds) {
                         craft()->db->createCommand()->delete('sections_i18n', array('and', 'sectionId = :sectionId', array('in', 'locale', $droppedLocaleIds)), array(':sectionId' => $section->id));
                     }
                 }
                 // Make sure there's at least one entry type for this section
                 $entryTypeId = null;
                 if (!$isNewSection) {
                     // Let's grab all of the entry type IDs to save ourselves a query down the road if this is a Single
                     $entryTypeIds = craft()->db->createCommand()->select('id')->from('entrytypes')->where('sectionId = :sectionId', array(':sectionId' => $section->id))->queryColumn();
                     if ($entryTypeIds) {
                         $entryTypeId = array_shift($entryTypeIds);
                     }
                 }
                 if (!$entryTypeId) {
                     $entryType = new EntryTypeModel();
                     $entryType->sectionId = $section->id;
                     $entryType->name = $section->name;
                     $entryType->handle = $section->handle;
                     if ($section->type == SectionType::Single) {
                         $entryType->hasTitleField = false;
                         $entryType->titleLabel = null;
                         $entryType->titleFormat = '{section.name|raw}';
                     } else {
                         $entryType->hasTitleField = true;
                         $entryType->titleLabel = Craft::t('Title');
                         $entryType->titleFormat = null;
                     }
                     $this->saveEntryType($entryType);
                     $entryTypeId = $entryType->id;
                 }
                 // Now, regardless of whether the section type changed or not, let the section type make sure
                 // everything is cool
                 switch ($section->type) {
                     case SectionType::Single:
                         // Make sure that there is one and only one Entry Type and Entry for this section.
                         $singleEntryId = null;
                         if (!$isNewSection) {
                             // Make sure there's only one entry in this section
                             $entryIds = craft()->db->createCommand()->select('id')->from('entries')->where('sectionId = :sectionId', array(':sectionId' => $section->id))->queryColumn();
                             if ($entryIds) {
                                 $singleEntryId = array_shift($entryIds);
                                 // If there are any more, get rid of them
                                 if ($entryIds) {
                                     craft()->elements->deleteElementById($entryIds);
                                 }
                                 // Make sure it's enabled and all that.
                                 craft()->db->createCommand()->update('elements', array('enabled' => 1, 'archived' => 0), array('id' => $singleEntryId));
                                 craft()->db->createCommand()->update('entries', array('typeId' => $entryTypeId, 'authorId' => null, 'postDate' => DateTimeHelper::currentTimeForDb(), 'expiryDate' => null), array('id' => $singleEntryId));
                             }
                             // Make sure there's only one entry type for this section
                             if ($entryTypeIds) {
                                 $this->deleteEntryTypeById($entryTypeIds);
                             }
                         }
                         if (!$singleEntryId) {
                             // Create it, baby
                             $singleEntry = new EntryModel();
                             $singleEntry->locale = $firstSectionLocale->locale;
                             $singleEntry->sectionId = $section->id;
                             $singleEntry->typeId = $entryTypeId;
                             $singleEntry->getContent()->title = $section->name;
                             craft()->entries->saveEntry($singleEntry);
                         }
                         break;
                     case SectionType::Structure:
                         if (!$isNewSection && $isNewStructure) {
                             // Add all of the entries to the structure
                             $criteria = craft()->elements->getCriteria(ElementType::Entry);
                             $criteria->locale = ArrayHelper::getFirstKey($oldSectionLocales);
                             $criteria->sectionId = $section->id;
                             $criteria->status = null;
                             $criteria->localeEnabled = null;
                             $criteria->order = 'elements.id';
                             $criteria->limit = 25;
                             do {
                                 $batchEntries = $criteria->find();
                                 foreach ($batchEntries as $entry) {
                                     craft()->structures->appendToRoot($section->structureId, $entry, 'insert');
                                 }
                                 $criteria->offset += 25;
                             } while ($batchEntries);
                         }
                         break;
                 }
                 // Finally, deal with the existing entries...
                 if (!$isNewSection) {
                     $criteria = craft()->elements->getCriteria(ElementType::Entry);
                     // Get the most-primary locale that this section was already enabled in
                     $locales = array_values(array_intersect(craft()->i18n->getSiteLocaleIds(), array_keys($oldSectionLocales)));
                     if ($locales) {
                         $criteria->locale = $locales[0];
                         $criteria->sectionId = $section->id;
                         $criteria->status = null;
                         $criteria->localeEnabled = null;
                         $criteria->limit = null;
                         craft()->tasks->createTask('ResaveElements', Craft::t('Resaving {section} entries', array('section' => $section->name)), array('elementType' => ElementType::Entry, 'criteria' => $criteria->getAttributes()));
                     }
                 }
                 $success = true;
             } else {
                 $success = false;
             }
             // Commit the transaction regardless of whether we saved the section, in case something changed
             // in onBeforeSaveSection
             if ($transaction !== null) {
                 $transaction->commit();
             }
         } catch (\Exception $e) {
             if ($transaction !== null) {
                 $transaction->rollback();
             }
             throw $e;
         }
     } else {
         $success = false;
     }
     if ($success) {
         // Fire an 'onSaveSection' event
         $this->onSaveSection(new Event($this, array('section' => $section, 'isNewSection' => $isNewSection)));
     }
     return $success;
 }
 /**
  * Displays an entry.
  *
  * @param EntryModel $entry
  *
  * @throws HttpException
  * @return null
  */
 private function _showEntry(EntryModel $entry)
 {
     $section = $entry->getSection();
     $type = $entry->getType();
     if ($section && $type) {
         craft()->setLanguage($entry->locale);
         if (!$entry->postDate) {
             $entry->postDate = new DateTime();
         }
         craft()->templates->getTwig()->disableStrictVariables();
         $this->renderTemplate($section->template, array('entry' => $entry));
     } else {
         Craft::log('Attempting to preview an entry that doesn’t have a section/type', LogLevel::Error);
         throw new HttpException(404);
     }
 }