/**
  * Returns all sections.
  *
  * @param string|null $indexBy
  * @return array
  */
 public function getAllSections($indexBy = null)
 {
     if (!$this->_fetchedAllSections) {
         $criteria = new \CDbCriteria();
         if (!Craft::hasPackage(CraftPackage::PublishPro)) {
             $criteria->limit = 1;
         }
         $sectionRecords = SectionRecord::model()->ordered()->findAll($criteria);
         $this->_sectionsById = SectionModel::populateModels($sectionRecords, 'id');
         $this->_fetchedAllSections = true;
     }
     if ($indexBy == 'id') {
         $sections = $this->_sectionsById;
     } else {
         if (!$indexBy) {
             $sections = array_values($this->_sectionsById);
         } else {
             $sections = array();
             foreach ($this->_sectionsById as $section) {
                 $sections[$section->{$indexBy}] = $section;
             }
         }
     }
     return $sections;
 }
 /**
  * Saves an asset source.
  */
 public function actionSaveSource()
 {
     craft()->userSession->requireAdmin();
     $this->requirePostRequest();
     $existingSourceId = craft()->request->getPost('sourceId');
     if ($existingSourceId) {
         $source = craft()->assetSources->getSourceById($existingSourceId);
     } else {
         $source = new AssetSourceModel();
     }
     $source->name = craft()->request->getPost('name');
     if (Craft::hasPackage(CraftPackage::Cloud)) {
         $source->type = craft()->request->getPost('type');
     }
     $typeSettings = craft()->request->getPost('types');
     if (isset($typeSettings[$source->type])) {
         if (!$source->settings) {
             $source->settings = array();
         }
         $source->settings = array_merge($source->settings, $typeSettings[$source->type]);
     }
     // Did it save?
     if (craft()->assetSources->saveSource($source)) {
         craft()->userSession->setNotice(Craft::t('Source saved.'));
         $this->redirectToPostedUrl();
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save source.'));
     }
     // Send the source back to the template
     craft()->urlManager->setRouteVariables(array('source' => $source));
 }
 /**
  * @return array
  */
 public function defineRelations()
 {
     $relations = array('element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE), 'section' => array(static::BELONGS_TO, 'SectionRecord', 'required' => true, 'onDelete' => static::CASCADE), 'author' => array(static::BELONGS_TO, 'UserRecord', 'required' => true, 'onDelete' => static::CASCADE));
     if (Craft::hasPackage(CraftPackage::PublishPro)) {
         $relations['versions'] = array(static::HAS_MANY, 'EntryVersionRecord', 'elementId');
     }
     return $relations;
 }
 /**
  * Returns all installed source types.
  *
  * @return array
  */
 public function getAllSourceTypes()
 {
     if (Craft::hasPackage(CraftPackage::Cloud)) {
         return craft()->components->getComponentsByType(ComponentType::AssetSource);
     } else {
         return array(craft()->components->getComponentByTypeAndClass(ComponentType::AssetSource, 'Local'));
     }
 }
 /**
  * @return array
  */
 public function defineRelations()
 {
     $relations = array('element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE), 'preferredLocale' => array(static::BELONGS_TO, 'LocaleRecord', 'preferredLocale', 'onDelete' => static::SET_NULL, 'onUpdate' => static::CASCADE));
     if (Craft::hasPackage(CraftPackage::Users)) {
         $relations['groups'] = array(static::MANY_MANY, 'UserGroupRecord', 'usergroups_users(userId, groupId)');
     }
     $relations['sessions'] = array(static::HAS_MANY, 'SessionRecord', 'userId');
     return $relations;
 }
 /**
  * Gets the widget's title.
  *
  * @return string
  */
 public function getTitle()
 {
     if (Craft::hasPackage(CraftPackage::PublishPro)) {
         $section = $this->_getSection();
         if ($section) {
             return Craft::t('Post a new {section} entry', array('section' => $section->name));
         }
     }
     return $this->getName();
 }
 /**
  * Returns this element type's sources.
  *
  * @param string|null $context
  * @return array|false
  */
 public function getSources($context = null)
 {
     $sources = array('*' => array('label' => Craft::t('All users')));
     if (Craft::hasPackage(CraftPackage::Users)) {
         foreach (craft()->userGroups->getAllGroups() as $group) {
             $key = 'group:' . $group->id;
             $sources[$key] = array('label' => $group->name, 'criteria' => array('groupId' => $group->id));
         }
     }
     return $sources;
 }
 /**
  * Gets the widget's body HTML.
  *
  * @return string
  */
 public function getBodyHtml()
 {
     $params = array();
     if (Craft::hasPackage(CraftPackage::PublishPro)) {
         $sectionId = $this->getSettings()->section;
         if (is_numeric($sectionId)) {
             $params['sectionId'] = (int) $sectionId;
         }
     }
     $js = 'new Craft.RecentEntriesWidget(' . $this->model->id . ', ' . JsonHelper::encode($params) . ');';
     craft()->templates->includeJsResource('js/RecentEntriesWidget.js');
     craft()->templates->includeJs($js);
     craft()->templates->includeTranslations('by {author}');
     return craft()->templates->render('_components/widgets/RecentEntries/body', array('settings' => $this->getSettings()));
 }
 /**
  * Saves a section
  */
 public function actionSaveSection()
 {
     $this->requirePostRequest();
     $section = new SectionModel();
     // Set the simple stuff
     $section->id = craft()->request->getPost('sectionId');
     $section->name = craft()->request->getPost('name');
     $section->handle = craft()->request->getPost('handle');
     $section->titleLabel = craft()->request->getPost('titleLabel');
     $section->hasUrls = (bool) craft()->request->getPost('hasUrls');
     $section->template = craft()->request->getPost('template');
     // Set the locales and URL formats
     $locales = array();
     $urlFormats = craft()->request->getPost('urlFormat');
     if (Craft::hasPackage(CraftPackage::Localize)) {
         $localeIds = craft()->request->getPost('locales');
     } else {
         $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId();
         $localeIds = array($primaryLocaleId);
     }
     foreach ($localeIds as $localeId) {
         $locales[$localeId] = SectionLocaleModel::populateModel(array('locale' => $localeId, 'urlFormat' => isset($urlFormats[$localeId]) ? $urlFormats[$localeId] : null));
     }
     $section->setLocales($locales);
     // Set the field layout
     $fieldLayout = craft()->fields->assembleLayoutFromPost();
     $fieldLayout->type = ElementType::Entry;
     $section->setFieldLayout($fieldLayout);
     // Save it
     if (craft()->sections->saveSection($section)) {
         craft()->userSession->setNotice(Craft::t('Section saved.'));
         // TODO: Remove for 2.0
         if (isset($_POST['redirect']) && strpos($_POST['redirect'], '{sectionId}') !== false) {
             Craft::log('The {sectionId} token within the ‘redirect’ param on sections/saveSection requests has been deprecated. Use {id} instead.', LogLevel::Warning);
             $_POST['redirect'] = str_replace('{sectionId}', '{id}', $_POST['redirect']);
         }
         $this->redirectToPostedUrl($section);
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save section.'));
     }
     // Send the section back to the template
     craft()->urlManager->setRouteVariables(array('section' => $section));
 }
 /**
  * Saves an email message
  */
 public function actionSaveMessage()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     $message = new RebrandEmailModel();
     $message->key = craft()->request->getRequiredPost('key');
     $message->subject = craft()->request->getRequiredPost('subject');
     $message->body = craft()->request->getRequiredPost('body');
     if (Craft::hasPackage(CraftPackage::Localize)) {
         $message->locale = craft()->request->getPost('locale');
     } else {
         $message->locale = craft()->language;
     }
     if (craft()->emailMessages->saveMessage($message)) {
         $this->returnJson(array('success' => true));
     } else {
         $this->returnErrorJson(Craft::t('There was a problem saving your message.'));
     }
 }
 /**
  * Get the sections of the CP.
  *
  * @return array
  */
 public function nav()
 {
     $nav['dashboard'] = array('name' => Craft::t('Dashboard'));
     if (craft()->sections->getTotalEditableSections()) {
         $nav['entries'] = array('name' => Craft::t('Entries'));
     }
     if (craft()->globals->getTotalEditableSets()) {
         $nav['globals'] = array('name' => Craft::t('Globals'));
     }
     if (craft()->assetSources->getTotalViewableSources()) {
         $nav['assets'] = array('name' => Craft::t('Assets'));
     }
     if (Craft::hasPackage(CraftPackage::Users) && craft()->userSession->checkPermission('editUsers')) {
         $nav['users'] = array('name' => Craft::t('Users'));
     }
     // Add any Plugin nav items
     $plugins = craft()->plugins->getPlugins();
     foreach ($plugins as $plugin) {
         if ($plugin->hasCpSection()) {
             if (craft()->userSession->checkPermission('accessPlugin-' . $plugin->getClassHandle())) {
                 $lcHandle = strtolower($plugin->getClassHandle());
                 $nav[$lcHandle] = array('name' => $plugin->getName());
             }
         }
     }
     if (craft()->userSession->checkPermission('performUpdates')) {
         $totalAvailableUpdates = craft()->updates->getTotalAvailableUpdates();
         if ($totalAvailableUpdates > 0) {
             $nav['updates'] = array('name' => Craft::t('Updates'), 'badge' => $totalAvailableUpdates);
         } else {
             $nav['updates'] = array('name' => Craft::t('Updates'));
         }
     }
     if (craft()->userSession->isAdmin()) {
         $nav['settings'] = array('name' => Craft::t('Settings'));
     }
     return $nav;
 }
 /**
  * Sends an email by its key.
  *
  * @param UserModel $user
  * @param string $key
  * @param array $variables
  * @return bool
  * @throws Exception
  */
 public function sendEmailByKey(UserModel $user, $key, $variables = array())
 {
     $emailModel = new EmailModel();
     if (Craft::hasPackage(CraftPackage::Rebrand)) {
         $message = craft()->emailMessages->getMessage($key, $user->preferredLocale);
         $emailModel->subject = $message->subject;
         $emailModel->body = $message->body;
     } else {
         $emailModel->subject = Craft::t($key . '_subject', null, null, 'en_us');
         $emailModel->body = Craft::t($key . '_body', null, null, 'en_us');
     }
     $tempTemplatesPath = '';
     if (Craft::hasPackage(CraftPackage::Rebrand)) {
         // Is there a custom HTML template set?
         $settings = $this->getSettings();
         if (!empty($settings['template'])) {
             $tempTemplatesPath = craft()->path->getSiteTemplatesPath();
             $template = $settings['template'];
         }
     }
     if (empty($template)) {
         $tempTemplatesPath = craft()->path->getCpTemplatesPath();
         $template = '_special/email';
     }
     if (!$emailModel->htmlBody) {
         // Auto-generate the HTML content
         $emailModel->htmlBody = StringHelper::parseMarkdown($emailModel->body);
     }
     $emailModel->htmlBody = "{% extends '{$template}' %}\n" . "{% set body %}\n" . $emailModel->htmlBody . "{% endset %}\n";
     // Temporarily swap the templates path
     $originalTemplatesPath = craft()->path->getTemplatesPath();
     craft()->path->setTemplatesPath($tempTemplatesPath);
     // Send the email
     $return = $this->_sendEmail($user, $emailModel, $variables);
     // Return to the original templates path
     craft()->path->setTemplatesPath($originalTemplatesPath);
     return $return;
 }
Exemple #13
0
 /**
  * Sets the package components.
  */
 private function _setPackageComponents()
 {
     // Set the appropriate package components
     if (isset($this->_packageComponents)) {
         foreach ($this->_packageComponents as $packageName => $packageComponents) {
             if (Craft::hasPackage($packageName)) {
                 $this->setComponents($packageComponents);
             }
         }
         unset($this->_packageComponents);
     }
 }
Exemple #14
0
 /**
  * @param TryPackageModel $model
  * @return bool
  */
 public function tryPackage(TryPackageModel $model)
 {
     $et = new Et(static::StartPackageTrial);
     $et->setData($model);
     $etResponse = $et->phoneHome();
     if (!empty($etResponse->data['success'])) {
         // Install the package.
         if (!Craft::hasPackage($model->packageHandle)) {
             Craft::installPackage($model->packageHandle);
         }
         return true;
     } else {
         // Did they at least say why?
         if (!empty($etResponse->errors)) {
             switch ($etResponse->errors[0]) {
                 // Validation errors
                 case 'package_doesnt_exist':
                     $error = Craft::t('The selected package doesn’t exist anymore.');
                     break;
                 case 'cannot_trial_package':
                     $error = Craft::t('Your license key is invalid.');
                     break;
                 default:
                     $error = $etResponse->errors[0];
             }
         } else {
             // Something terrible must have happened!
             $error = Craft::t('Craft is unable to trial packages at this time.');
         }
         $model->addError('response', $error);
     }
     return false;
 }
 /**
  * Returns the email settings from the post data.
  *
  * @access private
  * @return array
  */
 private function _getEmailSettingsFromPost()
 {
     $emailSettings = new EmailSettingsModel();
     $gMailSmtp = 'smtp.gmail.com';
     $emailSettings->protocol = craft()->request->getPost('protocol');
     $emailSettings->host = craft()->request->getPost('host');
     $emailSettings->port = craft()->request->getPost('port');
     $emailSettings->smtpAuth = (bool) craft()->request->getPost('smtpAuth');
     if ($emailSettings->smtpAuth && $emailSettings->protocol !== EmailerType::Gmail) {
         $emailSettings->username = craft()->request->getPost('smtpUsername');
         $emailSettings->password = craft()->request->getPost('smtpPassword');
     } else {
         $emailSettings->username = craft()->request->getPost('username');
         $emailSettings->password = craft()->request->getPost('password');
     }
     $emailSettings->smtpKeepAlive = (bool) craft()->request->getPost('smtpKeepAlive');
     $emailSettings->smtpSecureTransportType = craft()->request->getPost('smtpSecureTransportType');
     $emailSettings->timeout = craft()->request->getPost('timeout');
     $emailSettings->emailAddress = craft()->request->getPost('emailAddress');
     $emailSettings->senderName = craft()->request->getPost('senderName');
     // Validate user input
     if (!$emailSettings->validate()) {
         return $emailSettings;
     }
     $settings['protocol'] = $emailSettings->protocol;
     $settings['emailAddress'] = $emailSettings->emailAddress;
     $settings['senderName'] = $emailSettings->senderName;
     if (Craft::hasPackage(CraftPackage::Rebrand)) {
         $settings['template'] = craft()->request->getPost('template');
     }
     switch ($emailSettings->protocol) {
         case EmailerType::Smtp:
             if ($emailSettings->smtpAuth) {
                 $settings['smtpAuth'] = 1;
                 $settings['username'] = $emailSettings->username;
                 $settings['password'] = $emailSettings->password;
             }
             $settings['smtpSecureTransportType'] = $emailSettings->smtpSecureTransportType;
             $settings['port'] = $emailSettings->port;
             $settings['host'] = $emailSettings->host;
             $settings['timeout'] = $emailSettings->timeout;
             if ($emailSettings->smtpKeepAlive) {
                 $settings['smtpKeepAlive'] = 1;
             }
             break;
         case EmailerType::Pop:
             $settings['port'] = $emailSettings->port;
             $settings['host'] = $emailSettings->host;
             $settings['username'] = $emailSettings->username;
             $settings['password'] = $emailSettings->password;
             $settings['timeout'] = $emailSettings->timeout;
             break;
         case EmailerType::Gmail:
             $settings['host'] = $gMailSmtp;
             $settings['smtpAuth'] = 1;
             $settings['smtpSecureTransportType'] = 'ssl';
             $settings['username'] = $emailSettings->username;
             $settings['password'] = $emailSettings->password;
             $settings['port'] = $emailSettings->smtpSecureTransportType == 'tls' ? '587' : '465';
             $settings['timeout'] = $emailSettings->timeout;
             break;
     }
     return $settings;
 }
 /**
  * Modifies an entries query targeting entries of this type.
  *
  * @param DbCommand $query
  * @param ElementCriteriaModel $criteria
  * @return mixed
  */
 public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
 {
     $query->addSelect('entries.sectionId, entries.authorId, entries.postDate, entries.expiryDate, entries_i18n.slug')->join('entries entries', 'entries.id = elements.id')->join('entries_i18n entries_i18n', 'entries_i18n.entryId = elements.id')->andWhere('entries_i18n.locale = elements_i18n.locale');
     if ($criteria->slug) {
         $query->andWhere(DbHelper::parseParam('entries_i18n.slug', $criteria->slug, $query->params));
     }
     if ($criteria->postDate) {
         $query->andWhere(DbHelper::parseDateParam('entries.postDate', '=', $criteria->postDate, $query->params));
     } else {
         if ($criteria->after) {
             $query->andWhere(DbHelper::parseDateParam('entries.postDate', '>=', $criteria->after, $query->params));
         }
         if ($criteria->before) {
             $query->andWhere(DbHelper::parseDateParam('entries.postDate', '<', $criteria->before, $query->params));
         }
     }
     if ($criteria->editable) {
         $user = craft()->userSession->getUser();
         if (!$user) {
             return false;
         }
         $editableSectionIds = craft()->sections->getEditableSectionIds();
         $query->andWhere(array('in', 'entries.sectionId', $editableSectionIds));
         $noPeerConditions = array();
         foreach ($editableSectionIds as $sectionId) {
             if (!$user->can('editPeerEntries:' . $sectionId)) {
                 $noPeerConditions[] = array('or', 'entries.sectionId != ' . $sectionId, 'entries.authorId = ' . $user->id);
             }
         }
         if ($noPeerConditions) {
             array_unshift($noPeerConditions, 'and');
             $query->andWhere($noPeerConditions);
         }
     }
     if (Craft::hasPackage(CraftPackage::PublishPro)) {
         if ($criteria->sectionId) {
             $query->andWhere(DbHelper::parseParam('entries.sectionId', $criteria->sectionId, $query->params));
         }
         if ($criteria->section) {
             $query->join('sections sections', 'entries.sectionId = sections.id');
             $query->andWhere(DbHelper::parseParam('sections.handle', $criteria->section, $query->params));
         }
     }
     if (Craft::hasPackage(CraftPackage::Users)) {
         if ($criteria->authorId) {
             $query->andWhere(DbHelper::parseParam('entries.authorId', $criteria->authorId, $query->params));
         }
         if ($criteria->authorGroupId || $criteria->authorGroup) {
             $query->join('usergroups_users usergroups_users', 'usergroups_users.userId = entries.authorId');
             if ($criteria->authorGroupId) {
                 $query->andWhere(DbHelper::parseParam('usergroups_users.groupId', $criteria->authorGroupId, $query->params));
             }
             if ($criteria->authorGroup) {
                 $query->join('usergroups usergroups', 'usergroups.id = usergroups_users.groupId');
                 $query->andWhere(DbHelper::parseParam('usergroups.handle', $criteria->authorGroup, $query->params));
             }
         }
     }
 }
 /**
  * Returns the entry permissions for a given section.
  *
  * @access private
  * @param int|null $sectionId
  * @return array
  */
 private function _getEntryPermissions($sectionId)
 {
     $suffix = ':' . $sectionId;
     $permissions = array("editEntries{$suffix}" => array('label' => Craft::t('Edit entries'), 'nested' => array("createEntries{$suffix}" => array('label' => Craft::t('Create entries')), "publishEntries{$suffix}" => array('label' => Craft::t('Publish entries live')))), "deleteEntries{$suffix}" => array('label' => Craft::t('Delete entries')));
     if (Craft::hasPackage(CraftPackage::Users)) {
         $permissions["editEntries{$suffix}"]['nested']["editPeerEntries{$suffix}"] = array('label' => Craft::t('Edit other authors’ entries'), 'nested' => array("deletePeerEntries{$suffix}" => array('label' => Craft::t('Delete other authors’ entries'))));
         if (Craft::hasPackage(CraftPackage::PublishPro)) {
             $permissions["editEntries{$suffix}"]['nested']["editPeerEntries{$suffix}"]['nested']["editPeerEntryDrafts{$suffix}"] = array('label' => Craft::t('Edit other authors’ drafts'), 'nested' => array("publishPeerEntryDrafts{$suffix}" => array('label' => Craft::t('Publish other authors’ drafts')), "deletePeerEntryDrafts{$suffix}" => array('label' => Craft::t('Delete other authors’ drafts'))));
         }
     }
     return $permissions;
 }
 /**
  * Returns a list of locales that are editable by the current user.
  *
  * @return array
  */
 public function getEditableLocales()
 {
     if (Craft::hasPackage(CraftPackage::Localize)) {
         $locales = $this->getSiteLocales();
         $editableLocales = array();
         foreach ($locales as $locale) {
             if (craft()->userSession->checkPermission('editLocale:' . $locale->getId())) {
                 $editableLocales[] = $locale;
             }
         }
         return $editableLocales;
     } else {
         return $this->getSiteLocales();
     }
 }
 /**
  * Edit an entry.
  *
  * @param array $variables
  * @throws HttpException
  */
 public function actionEditEntry(array $variables = array())
 {
     $variables['section'] = craft()->sections->getSectionByHandle($variables['sectionHandle']);
     if (!$variables['section']) {
         throw new HttpException(404);
     }
     $variables['permissionSuffix'] = ':' . $variables['section']->id;
     // Make sure the user is allowed to edit entries in this section
     craft()->userSession->requirePermission('editEntries' . $variables['permissionSuffix']);
     if (Craft::hasPackage(CraftPackage::Localize)) {
         // Figure out which locales the user is allowed to edit in this section
         $sectionLocaleIds = array_keys($variables['section']->getLocales());
         $editableLocaleIds = craft()->i18n->getEditableLocaleIds();
         $editableSectionLocaleIds = array_intersect($sectionLocaleIds, $editableLocaleIds);
         if (!$editableSectionLocaleIds) {
             throw new HttpException(404);
         }
         if (empty($variables['localeId'])) {
             $variables['localeId'] = craft()->language;
             if (!in_array($variables['localeId'], $editableSectionLocaleIds)) {
                 $variables['localeId'] = $editableSectionLocaleIds[0];
             }
         } else {
             if (!in_array($variables['localeId'], $editableSectionLocaleIds)) {
                 throw new HttpException(404);
             }
         }
     }
     if (empty($variables['entry'])) {
         if (!empty($variables['entryId'])) {
             if (!empty($variables['draftId'])) {
                 $variables['entry'] = craft()->entryRevisions->getDraftById($variables['draftId']);
             } else {
                 if (!empty($variables['versionId'])) {
                     $variables['entry'] = craft()->entryRevisions->getVersionById($variables['versionId']);
                 } else {
                     $criteria = craft()->elements->getCriteria(ElementType::Entry);
                     $criteria->id = $variables['entryId'];
                     $criteria->status = null;
                     if (Craft::hasPackage(CraftPackage::Localize)) {
                         $criteria->locale = $variables['localeId'];
                     }
                     $variables['entry'] = $criteria->first();
                 }
             }
             if (!$variables['entry']) {
                 throw new HttpException(404);
             }
         } else {
             $variables['entry'] = new EntryModel();
             $variables['entry']->sectionId = $variables['section']->id;
             $variables['entry']->authorId = craft()->userSession->getUser()->id;
             $variables['entry']->enabled = true;
         }
     }
     // More permission enforcement
     if (!$variables['entry']->id) {
         craft()->userSession->requirePermission('createEntries' . $variables['permissionSuffix']);
     } else {
         if ($variables['entry']->authorId != craft()->userSession->getUser()->id) {
             craft()->userSession->requirePermission('editPeerEntries' . $variables['permissionSuffix']);
         }
     }
     if ($variables['entry']->id && $variables['entry']->getClassHandle() == 'EntryDraft') {
         if ($variables['entry']->creatorId != craft()->userSession->getUser()->id) {
             craft()->userSession->requirePermission('editPeerEntryDrafts' . $variables['permissionSuffix']);
         }
     }
     // Page title w/ revision label
     if (Craft::hasPackage(CraftPackage::PublishPro)) {
         switch ($variables['entry']->getClassHandle()) {
             case 'EntryDraft':
                 $variables['revisionLabel'] = Craft::t('Draft {id}', array('id' => $variables['draftId']));
                 break;
             case 'EntryVersion':
                 $variables['revisionLabel'] = Craft::t('Version {id}', array('id' => $variables['versionId']));
                 break;
             default:
                 $variables['revisionLabel'] = Craft::t('Current');
         }
     }
     if (!$variables['entry']->id) {
         $variables['title'] = Craft::t('Create a new entry');
     } else {
         $variables['title'] = $variables['entry']->title;
         if (Craft::hasPackage(CraftPackage::PublishPro) && $variables['entry']->getClassHandle() != 'Entry') {
             $variables['title'] .= ' <span class="hidden">(' . $variables['revisionLabel'] . ')</span>';
         }
     }
     // Breadcrumbs
     $variables['crumbs'] = array(array('label' => Craft::t('Entries'), 'url' => UrlHelper::getUrl('entries')));
     if (Craft::hasPackage(CraftPackage::PublishPro)) {
         // Not really necessary, but it's nice to see that section name...
         $variables['crumbs'][] = array('label' => $variables['section']->name, 'url' => UrlHelper::getUrl('entries'));
     }
     // Tabs
     $variables['tabs'] = array();
     foreach ($variables['section']->getFieldLayout()->getTabs() as $index => $tab) {
         // Do any of the fields on this tab have errors?
         $hasErrors = false;
         if ($variables['entry']->hasErrors()) {
             foreach ($tab->getFields() as $field) {
                 if ($variables['entry']->getErrors($field->getField()->handle)) {
                     $hasErrors = true;
                     break;
                 }
             }
         }
         $variables['tabs'][] = array('label' => $tab->name, 'url' => '#tab' . ($index + 1), 'class' => $hasErrors ? 'error' : null);
     }
     // Settings tab
     $hasErrors = $variables['entry']->hasErrors() && ($variables['entry']->getErrors('slug') || $variables['entry']->getErrors('postDate') || $variables['entry']->getErrors('expiryDate'));
     // Enable preview mode?
     $variables['showPreviewBtn'] = false;
     if (!craft()->request->isMobileBrowser(true) && $variables['section']->hasUrls) {
         // Make sure the section's template actually exists
         $templatesPath = craft()->path->getTemplatesPath();
         craft()->path->setTemplatesPath(craft()->path->getSiteTemplatesPath());
         try {
             $templateExists = (bool) craft()->templates->findTemplate($variables['section']->template);
         } catch (TemplateLoaderException $e) {
             $templateExists = false;
         }
         craft()->path->setTemplatesPath($templatesPath);
         if ($templateExists) {
             craft()->templates->includeJsResource('js/EntryPreviewMode.js');
             craft()->templates->includeJs('new Craft.EntryPreviewMode(' . JsonHelper::encode($variables['entry']->getUrl()) . ', "' . $variables['entry']->locale . '");');
             $variables['showPreviewBtn'] = true;
         }
     }
     $variables['tabs'][] = array('label' => Craft::t('Settings'), 'url' => '#entry-settings', 'class' => $hasErrors ? 'error' : null);
     // Render the template!
     craft()->templates->includeCssResource('css/entry.css');
     $this->renderTemplate('entries/_edit', $variables);
 }
 /**
  * Registers a new user, or saves an existing user's account settings.
  */
 public function actionSaveUser()
 {
     $this->requirePostRequest();
     if (Craft::hasPackage(CraftPackage::Users)) {
         $userId = craft()->request->getPost('userId');
         if ($userId) {
             craft()->userSession->requireLogin();
         }
     } else {
         craft()->userSession->requireLogin();
         $userId = craft()->userSession->getUser()->id;
     }
     $publicRegistration = false;
     $canRegisterUsers = false;
     // Are we editing an existing user?
     if ($userId) {
         if ($userId != craft()->userSession->getUser()->id) {
             craft()->userSession->requirePermission('editUsers');
         }
         $user = craft()->users->getUserById($userId);
         if (!$user) {
             throw new Exception(Craft::t('No user exists with the ID “{id}”.', array('id' => $userId)));
         }
     } else {
         // Users package is required
         Craft::requirePackage(CraftPackage::Users);
         // Are they already logged in?
         if (craft()->userSession->getUser()) {
             // Make sure they have permission to register users, regardless of if public registration is enabled or not.
             craft()->userSession->requirePermission('registerUsers');
             $canRegisterUsers = true;
         } else {
             // Is public registration enabled?
             if (craft()->systemSettings->getSetting('users', 'allowPublicRegistration', false)) {
                 $publicRegistration = true;
             }
         }
         // If there is no public registration and the current user can't register users, complain loudly.
         if (!$publicRegistration && !$canRegisterUsers) {
             // Sorry pal.
             throw new HttpException(403);
         }
         $user = new UserModel();
     }
     // Can only change sensitive fields if you are an admin or this is your account.
     if (craft()->userSession->isAdmin() || $user->isCurrent()) {
         // Validate stuff.
         $valid = $this->_validateSensitiveFields($userId, $user, $publicRegistration || $canRegisterUsers);
     } else {
         $valid = true;
     }
     if ($valid) {
         $userName = craft()->request->getPost('username');
         if (!$userId) {
             $user->email = craft()->request->getPost('email');
             // If it is a new user, grab the password from post.
             if (!$userId && !craft()->request->isCpRequest()) {
                 $user->newPassword = craft()->request->getPost('password');
             }
         }
         // If no username was provided, set it to the email.
         $userName = $userName == null ? $user->email : $userName;
         $user->username = $userName;
         $user->firstName = craft()->request->getPost('firstName');
         $user->lastName = craft()->request->getPost('lastName');
         $user->preferredLocale = craft()->request->getPost('preferredLocale');
         // If it's a new user, set the verificationRequired bit.
         if (!$user->id) {
             $user->verificationRequired = true;
         }
         // Only admins can require users to reset their passwords
         if (craft()->userSession->isAdmin()) {
             $user->passwordResetRequired = (bool) craft()->request->getPost('passwordResetRequired');
         }
         try {
             if (craft()->users->saveUser($user)) {
                 if ($publicRegistration) {
                     $this->_assignDefaultGroupToUser($user->id);
                 }
                 craft()->userSession->setNotice(Craft::t('User saved.'));
                 // TODO: Remove for 2.0
                 if (isset($_POST['redirect']) && strpos($_POST['redirect'], '{userId}') !== false) {
                     Craft::log('The {userId} token within the ‘redirect’ param on users/saveUser requests has been deprecated. Use {id} instead.', LogLevel::Warning);
                     $_POST['redirect'] = str_replace('{userId}', '{id}', $_POST['redirect']);
                 }
                 $this->redirectToPostedUrl($user);
             } else {
                 craft()->userSession->setError(Craft::t('Couldn’t save user.'));
             }
         } catch (\phpmailerException $e) {
             craft()->userSession->setError(Craft::t('Registered user, but couldn’t send activation email. Check your email settings.'));
             // Still assign the default group
             if (($publicRegistration || $canRegisterUsers) && !craft()->request->isCpRequest()) {
                 $this->_assignDefaultGroupToUser($user->id);
             }
         }
     }
     // Send the account back to the template
     craft()->urlManager->setRouteVariables(array('account' => $user));
 }
 /**
  * Attempts to match a path with the registered URL routes.
  *
  * @access private
  * @param string $path
  * @return mixed
  */
 private function _getMatchedUrlRoute($path)
 {
     if (craft()->request->isCpRequest()) {
         // Merge in any package-specific routes for packages that are actually installed
         if (isset($this->cpRoutes['pkgRoutes'])) {
             // Merge in the package routes
             foreach ($this->cpRoutes['pkgRoutes'] as $packageName => $packageRoutes) {
                 if (Craft::hasPackage($packageName)) {
                     $this->cpRoutes = array_merge($this->cpRoutes, $packageRoutes);
                 }
             }
             unset($this->cpRoutes['pkgRoutes']);
         }
         if (($route = $this->_matchUrlRoutes($path, $this->cpRoutes)) !== false) {
             return $route;
         }
         // As a last ditch to match routes, check to see if any plugins have routes registered that will match.
         $pluginCpRoutes = craft()->plugins->call('registerCpRoutes');
         foreach ($pluginCpRoutes as $pluginRoutes) {
             if (($route = $this->_matchUrlRoutes($path, $pluginRoutes)) !== false) {
                 return $route;
             }
         }
     } else {
         // Check the user-defined routes
         $siteRoutes = craft()->routes->getAllRoutes();
         if (($route = $this->_matchUrlRoutes($path, $siteRoutes)) !== false) {
             return $route;
         }
     }
     return false;
 }
 /**
  * @return UserPermissionsVariable|null
  */
 public function userPermissions()
 {
     if (Craft::hasPackage(CraftPackage::Users)) {
         return new UserPermissionsVariable();
     }
 }
 /**
  * Performs post-save element operations, such as calling all fieldtypes' onAfterElementSave() methods.
  *
  * @param BaseElementModel $element
  * @param ContentModel $content
  */
 public function postSaveOperations(BaseElementModel $element, ContentModel $content)
 {
     // Get all of the fieldtypes
     $fields = craft()->fields->getAllFields();
     $fieldTypes = array();
     $fieldTypesWithDuplicateContent = array();
     foreach ($fields as $field) {
         $fieldType = craft()->fields->populateFieldType($field);
         if ($fieldType) {
             $fieldType->element = $element;
             $fieldTypes[] = $fieldType;
             if (!$field->translatable && $fieldType->defineContentAttribute()) {
                 $fieldTypesWithDuplicateContent[] = $fieldType;
             }
         }
     }
     // Are we dealing with other locales as well?
     if (Craft::hasPackage(CraftPackage::Localize)) {
         // Get the other locales' content
         $rows = craft()->db->createCommand()->from('content')->where(array('and', 'elementId = :elementId', 'locale != :locale'), array(':elementId' => $element->id, ':locale' => $content->locale))->queryAll();
         $otherContentModels = ContentModel::populateModels($rows);
         if ($otherContentModels) {
             foreach ($fieldTypesWithDuplicateContent as $fieldType) {
                 $handle = $fieldType->model->handle;
                 // Copy the content over!
                 foreach ($otherContentModels as $otherContentModel) {
                     $otherContentModel->{$handle} = $content->{$handle};
                 }
             }
             foreach ($otherContentModels as $otherContentModel) {
                 $this->saveContent($otherContentModel, false);
             }
         }
     } else {
         $otherContentModels = null;
     }
     // Now that all of the content saved for all locales,
     // call all fieldtypes' onAfterElementSave() functions
     foreach ($fieldTypes as $fieldType) {
         $fieldType->onAfterElementSave();
     }
     // Update the search keyword indexes
     $searchKeywordsByLocale = array();
     foreach ($fieldTypes as $fieldType) {
         $field = $fieldType->model;
         $handle = $field->handle;
         // Set the keywords for the content's locale
         $fieldSearchKeywords = $fieldType->getSearchKeywords($element->{$handle});
         $searchKeywordsByLocale[$content->locale][$field->id] = $fieldSearchKeywords;
         // Should we queue up the other locales' new keywords too?
         if ($otherContentModels && in_array($fieldType, $fieldTypesWithDuplicateContent)) {
             foreach ($otherContentModels as $otherContentModel) {
                 $searchKeywordsByLocale[$otherContentModel->locale][$field->id] = $fieldSearchKeywords;
             }
         }
     }
     foreach ($searchKeywordsByLocale as $localeId => $keywords) {
         craft()->search->indexElementFields($element->id, $localeId, $keywords);
     }
 }
 /**
  * Saves an entry.
  *
  * @param EntryModel $entry
  * @throws Exception
  * @return bool
  */
 public function saveEntry(EntryModel $entry)
 {
     $isNewEntry = !$entry->id;
     // Entry data
     if (!$isNewEntry) {
         $entryRecord = EntryRecord::model()->with('element')->findById($entry->id);
         if (!$entryRecord) {
             throw new Exception(Craft::t('No entry exists with the ID “{id}”', array('id' => $entry->id)));
         }
         $elementRecord = $entryRecord->element;
         // if entry->sectionId is null and there is an entryRecord sectionId, we assume this is a front-end edit.
         if ($entry->sectionId === null && $entryRecord->sectionId) {
             $entry->sectionId = $entryRecord->sectionId;
         }
     } else {
         $entryRecord = new EntryRecord();
         $elementRecord = new ElementRecord();
         $elementRecord->type = ElementType::Entry;
     }
     $section = craft()->sections->getSectionById($entry->sectionId);
     if (!$section) {
         throw new Exception(Craft::t('No section exists with the ID “{id}”', array('id' => $entry->sectionId)));
     }
     $sectionLocales = $section->getLocales();
     if (!isset($sectionLocales[$entry->locale])) {
         throw new Exception(Craft::t('The section “{section}” is not enabled for the locale {locale}', array('section' => $section->name, 'locale' => $entry->locale)));
     }
     $entryRecord->sectionId = $entry->sectionId;
     $entryRecord->authorId = $entry->authorId;
     $entryRecord->postDate = $entry->postDate;
     $entryRecord->expiryDate = $entry->expiryDate;
     if ($entry->enabled && !$entryRecord->postDate) {
         // Default the post date to the current date/time
         $entryRecord->postDate = $entry->postDate = DateTimeHelper::currentUTCDateTime();
     }
     $entryRecord->validate();
     $entry->addErrors($entryRecord->getErrors());
     $elementRecord->enabled = $entry->enabled;
     $elementRecord->validate();
     $entry->addErrors($elementRecord->getErrors());
     // Entry locale data
     if ($entry->id) {
         $entryLocaleRecord = EntryLocaleRecord::model()->findByAttributes(array('entryId' => $entry->id, 'locale' => $entry->locale));
         // If entry->slug is null and there is an entryLocaleRecord slug, we assume this is a front-end edit.
         if ($entry->slug === null && $entryLocaleRecord->slug) {
             $entry->slug = $entryLocaleRecord->slug;
         }
     }
     if (empty($entryLocaleRecord)) {
         $entryLocaleRecord = new EntryLocaleRecord();
         $entryLocaleRecord->sectionId = $entry->sectionId;
         $entryLocaleRecord->locale = $entry->locale;
     }
     if ($entryLocaleRecord->isNewRecord() || $entry->slug != $entryLocaleRecord->slug) {
         $this->_generateEntrySlug($entry);
         $entryLocaleRecord->slug = $entry->slug;
     }
     $entryLocaleRecord->validate();
     $entry->addErrors($entryLocaleRecord->getErrors());
     // Element locale data
     if ($entry->id) {
         $elementLocaleRecord = ElementLocaleRecord::model()->findByAttributes(array('elementId' => $entry->id, 'locale' => $entry->locale));
     }
     if (empty($elementLocaleRecord)) {
         $elementLocaleRecord = new ElementLocaleRecord();
         $elementLocaleRecord->locale = $entry->locale;
     }
     if ($section->hasUrls && $entry->enabled) {
         // Make sure the section's URL format is valid. This shouldn't be possible due to section validation,
         // but it's not enforced by the DB, so anything is possible.
         $urlFormat = $sectionLocales[$entry->locale]->urlFormat;
         if (!$urlFormat || strpos($urlFormat, '{slug}') === false) {
             throw new Exception(Craft::t('The section “{section}” doesn’t have a valid URL Format.', array('section' => Craft::t($section->name))));
         }
         $elementLocaleRecord->uri = craft()->templates->renderObjectTemplate($urlFormat, $entry);
     } else {
         $elementLocaleRecord->uri = null;
     }
     $elementLocaleRecord->validate();
     $entry->addErrors($elementLocaleRecord->getErrors());
     // Entry content
     $fieldLayout = $section->getFieldLayout();
     $content = craft()->content->prepElementContentForSave($entry, $fieldLayout);
     $content->validate();
     $entry->addErrors($content->getErrors());
     if (!$entry->hasErrors()) {
         // Save the element record first
         $elementRecord->save(false);
         // Now that we have an element ID, save it on the other stuff
         if (!$entry->id) {
             $entry->id = $elementRecord->id;
             $entryRecord->id = $entry->id;
         }
         $entryRecord->save(false);
         $entryLocaleRecord->entryId = $entry->id;
         $elementLocaleRecord->elementId = $entry->id;
         $content->elementId = $entry->id;
         // Save the other records
         $entryLocaleRecord->save(false);
         $elementLocaleRecord->save(false);
         craft()->content->saveContent($content, false);
         // Update the search index
         craft()->search->indexElementAttributes($entry, $entry->locale);
         // Save a new version
         if (Craft::hasPackage(CraftPackage::PublishPro)) {
             craft()->entryRevisions->saveVersion($entry);
         }
         // Perform some post-save operations
         craft()->content->postSaveOperations($entry, $content);
         // Fire an 'onSaveEntry' event
         $this->onSaveEntry(new Event($this, array('entry' => $entry, 'isNewEntry' => $isNewEntry)));
         return true;
     } else {
         return false;
     }
 }
 /**
  * Sets the draft model's values from the post data.
  *
  * @access private
  * @param EntryDraftModel $draft
  */
 private function _setDraftValuesFromPost(EntryDraftModel $draft)
 {
     $draft->slug = craft()->request->getPost('slug');
     $draft->postDate = craft()->request->getPost('postDate');
     $draft->expiryDate = craft()->request->getPost('expiryDate');
     $draft->enabled = (bool) craft()->request->getPost('enabled');
     $draft->getContent()->title = craft()->request->getPost('title');
     $fields = craft()->request->getPost('fields');
     $draft->getContent()->setAttributes($fields);
     if (Craft::hasPackage(CraftPackage::Users)) {
         $draft->authorId = craft()->request->getPost('author');
     } else {
         $draft->authorId = craft()->userSession->getUser()->id;
     }
 }
Exemple #26
0
 /**
  * Returns the element's CP edit URL.
  *
  * @return string|false
  */
 public function getCpEditUrl()
 {
     if (Craft::hasPackage(CraftPackage::Users)) {
         return UrlHelper::getCpUrl('users/' . $this->id);
     } else {
         return false;
     }
 }