/**
  * Save a note.
  */
 public function actionSaveNote()
 {
     $this->requirePostRequest();
     // Get note if available
     $noteId = craft()->request->getPost('noteId');
     if ($noteId) {
         $note = craft()->amForms_notes->getNoteById($noteId);
         if (!$note) {
             throw new Exception(Craft::t('No note exists with the ID “{id}”.', array('id' => $noteId)));
         }
     } else {
         $note = new AmForms_NoteModel();
     }
     // Note attributes
     $note->submissionId = craft()->request->getPost('submissionId');
     $note->name = craft()->request->getPost('name');
     $note->text = craft()->request->getPost('text');
     // Save note
     if (craft()->amForms_notes->saveNote($note)) {
         craft()->userSession->setNotice(Craft::t('Note saved.'));
         $this->redirectToPostedUrl($note);
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save note.'));
         // Send the note back to the template
         craft()->urlManager->setRouteVariables(array('note' => $note));
     }
 }
 public function actionAdd()
 {
     $this->requirePostRequest();
     //required fields
     $listId = craft()->request->getParam('listId');
     $email = craft()->request->getParam('email');
     //optional fields with defaults
     $name = craft()->request->getParam('name') ?: '';
     $customFields = craft()->request->getParam('customFields') ?: array();
     $resubscribe = craft()->request->getParam('resubscribe') ?: true;
     $error = null;
     try {
         craft()->oneCampaignMonitor_subscribers->add($listId, $email, $name, $customFields, $resubscribe);
     } catch (Exception $e) {
         $error = $e->getMessage();
     }
     //return json for ajax requests, redirect to posted url otherwise
     if (craft()->request->isAjaxRequest()) {
         $this->returnJson(['success' => is_null($error), 'error' => $error]);
     } else {
         craft()->userSession->setFlash('oneCampaignMonitor_addSubscriberSuccess', is_null($error));
         craft()->userSession->setFlash('oneCampaignMonitor_addSubscriberMessage', Craft::t($error ?: 'Success!'));
         $this->redirectToPostedUrl();
     }
 }
 /**
  * Reset count
  */
 public function actionReset()
 {
     $entryId = craft()->request->getRequiredParam('entryId');
     craft()->entryCount->reset($entryId);
     craft()->userSession->setNotice(Craft::t('Entry count reset.'));
     $this->redirect('entrycount');
 }
 /**
  * Saves a new or existing rule.
  *
  * @return null
  */
 public function actionSaveRule()
 {
     $this->requirePostRequest();
     $rule = new AutoExpire_RuleModel();
     $rule->id = craft()->request->getPost('id');
     $rule->name = craft()->request->getPost('name');
     $rule->sectionId = craft()->request->getPost('sectionId');
     $rule->dateTemplate = craft()->request->getPost('dateTemplate');
     $rule->allowOverwrite = craft()->request->getPost('allowOverwrite');
     // Extract the entry type and the field from sections array
     $sections = craft()->request->getPost('sections');
     if (isset($sections[$rule->sectionId])) {
         $rule->entryTypeId = $sections[$rule->sectionId]['entryTypeId'];
         $rule->fieldHandle = $sections[$rule->sectionId][$rule->entryTypeId]['fieldHandle'];
     }
     // Did it save?
     if (craft()->autoExpire->saveRule($rule)) {
         craft()->userSession->setNotice(Craft::t('Rule saved.'));
         $this->redirectToPostedUrl();
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save rule.'));
     }
     // Send the rule back to the template
     craft()->urlManager->setRouteVariables(array('rule' => $rule));
 }
 /**
  * @inheritDoc IElementType::defineTableAttributes()
  *
  * @param string|null $source
  *
  * @return array
  */
 public function defineTableAttributes($source = null)
 {
     $attributes = array('title' => Craft::t('Title'));
     // Allow plugins to modify the attributes
     craft()->plugins->call('modifyTagManagerTableAttributes', array(&$attributes, $source));
     return $attributes;
 }
 /**
  * @param Market_TaxRateModel $model
  *
  * @return bool
  * @throws Exception
  * @throws \CDbException
  * @throws \Exception
  */
 public function save(Market_TaxRateModel $model)
 {
     if ($model->id) {
         $record = Market_TaxRateRecord::model()->findById($model->id);
         if (!$record) {
             throw new Exception(Craft::t('No tax rate exists with the ID “{id}”', ['id' => $model->id]));
         }
     } else {
         $record = new Market_TaxRateRecord();
     }
     $record->name = $model->name;
     $record->rate = $model->rate;
     $record->include = $model->include;
     $record->showInLabel = $model->showInLabel;
     $record->taxCategoryId = $model->taxCategoryId;
     $record->taxZoneId = $model->taxZoneId;
     $record->validate();
     if (!$record->getError('taxZoneId')) {
         $taxZone = craft()->market_taxZone->getById($record->taxZoneId);
         if ($record->include && !$taxZone->default) {
             $record->addError('include', 'Included rates allowed for default tax zone only');
         }
     }
     $model->validate();
     $model->addErrors($record->getErrors());
     if (!$model->hasErrors()) {
         // Save it!
         $record->save(false);
         // Now that we have a record ID, save it on the model
         $model->id = $record->id;
         return true;
     } else {
         return false;
     }
 }
 public function getSettingsHtml()
 {
     // if not set, create a default row for custom links table
     if (!$this->_customLinks) {
         $this->_customLinks = array(array('linkLabel' => '', 'linkUrl' => '', 'adminOnly' => ''));
     }
     // generate table for custom links
     $customLinksTable = craft()->templates->renderMacro('_includes/forms', 'editableTableField', array(array('label' => Craft::t('Custom Links'), 'instructions' => Craft::t('Add your own links to the Admin Bar.'), 'id' => 'customLinks', 'name' => 'customLinks', 'cols' => array('linkLabel' => array('heading' => Craft::t('Label'), 'type' => 'singleline'), 'linkUrl' => array('heading' => Craft::t('URL'), 'type' => 'singleline'), 'adminOnly' => array('heading' => Craft::t('Admins Only'), 'type' => 'checkbox')), 'rows' => $this->_customLinks, 'addRowLabel' => Craft::t('Add a link'))));
     // get links from other plugins
     $pluginLinksHook = craft()->plugins->call('addAdminBarLinks');
     $pluginLinks = array();
     foreach ($pluginLinksHook as $key => $link) {
         $pluginName = craft()->plugins->getPlugin($key)->getName();
         for ($i = 0; $i < count($link); $i++) {
             if (isset($link[$i]['title']) && isset($link[$i]['url']) && isset($link[$i]['type'])) {
                 $link[$i]['id'] = str_replace(' ', '', $link[$i]['title']) . $link[$i]['url'] . $link[$i]['type'];
                 $link[$i]['originator'] = $pluginName;
                 array_push($pluginLinks, $link[$i]);
             }
         }
     }
     $this->clearAdminBarCache();
     // output settings template
     return craft()->templates->render('adminbar/settings', array('autoEmbedValue' => $this->getSettings()->autoEmbed, 'autoEmbedStickyValue' => $this->getSettings()->autoEmbedSticky, 'defaultColorValue' => $this->getSettings()->defaultColor, 'customLinksTable' => $customLinksTable, 'pluginLinks' => $pluginLinks, 'enabledLinks' => $this->getSettings()->enabledLinks));
 }
 /**
  * Get support fields.
  *
  * @param array $fieldTypes
  *
  * @return array
  */
 public function getProperFieldTypes($fieldTypes)
 {
     $basicFields = array();
     $advancedFields = array();
     $fieldTypeGroups = array();
     // Supported & unsupported fields
     $supported = $this->getSupportedFieldTypes();
     $unsupported = $this->getUnsupportedFieldTypes();
     // Set allowed fields
     foreach ($fieldTypes as $key => $fieldType) {
         if (in_array($key, $supported)) {
             $basicFields[$key] = $fieldType;
         } elseif (in_array($key, $unsupported)) {
             $advancedFields[$key] = $fieldType;
         }
     }
     $fieldTypeGroups['basic'] = array('optgroup' => Craft::t('Basic fields'));
     foreach ($basicFields as $key => $fieldType) {
         $fieldTypeGroups[$key] = $fieldType;
     }
     $fieldTypeGroups['advanced'] = array('optgroup' => Craft::t('Advanced fields'));
     foreach ($advancedFields as $key => $fieldType) {
         $fieldTypeGroups[$key] = $fieldType;
     }
     return $fieldTypeGroups;
 }
Esempio n. 9
0
 public function getSettingsHtml()
 {
     $pluginSettings = craft()->plugins->getPlugin('placid')->getSettings();
     // Get placid requests and send them to the widget settings
     $requests = craft()->placid_requests->findAllRequests();
     $requestsArray = array('' => 'No request selected');
     foreach ($requests as $request) {
         $requestsArray[$request->handle] = $request->name;
     }
     $templatesPath = craft()->path->getSiteTemplatesPath() . $pluginSettings->widgetTemplatesPath;
     $templates = IOHelper::getFolderContents($templatesPath, TRUE);
     $templatesArray = array('' => Craft::t('No template selected'));
     if (!$templates) {
         $templatesArray = array('' => 'Cannot find templates');
         Craft::log('Cannot find templates in path "' . $templatesPath . '"', LogLevel::Error);
     } else {
         // Turn array into ArrayObject
         $templates = new \ArrayObject($templates);
         // Iterate over template list
         // * Remove full path
         // * Remove folders from list
         for ($list = $templates->getIterator(); $list->valid(); $list->next()) {
             $filename = $list->current();
             $filename = str_replace($templatesPath, '', $filename);
             $filenameIncludingSubfolder = $filename;
             $isTemplate = preg_match("/(.html|.twig)\$/u", $filename);
             if ($isTemplate) {
                 $templatesArray[$filenameIncludingSubfolder] = $filename;
             }
         }
     }
     return craft()->templates->render('placid/_widgets/request/settings', array('requests' => $requestsArray, 'templates' => $templatesArray, 'settings' => $this->getSettings()));
 }
Esempio n. 10
0
 /**
  * Returns the field's input HTML.
  *
  * @param string $name
  * @param mixed  $value
  * @return string
  */
 public function getInputHtml($name, $value)
 {
     $id = craft()->templates->formatInputId($name);
     craft()->templates->includeCssResource('twitter/css/tweet.css');
     craft()->templates->includeJsResource('twitter/js/TweetInput.js');
     craft()->templates->includeJs('new TweetInput("' . craft()->templates->namespaceInputId($id) . '");');
     $tweet = $value;
     $html = "";
     if ($tweet && isset($tweet['id_str'])) {
         $url = 'https://twitter.com/' . $tweet['user']['screen_name'] . '/status/' . $tweet['id_str'];
         if (craft()->request->isSecureConnection()) {
             $profileImageUrl = $tweet['user']['profile_image_url_https'];
         } else {
             $profileImageUrl = $tweet['user']['profile_image_url'];
         }
         if (craft()->twitter_plugin->checkDependencies()) {
             $html .= '<div class="tweet-preview">' . '<div class="tweet-image" style="background-image: url(' . $profileImageUrl . ');"></div> ' . '<div class="tweet-user">' . '<span class="tweet-user-name">' . $tweet['user']['name'] . '</span> ' . '<a class="tweet-user-screenname light" href="http://twitter.com/' . $tweet['user']['screen_name'] . '" target="_blank">@' . $tweet['user']['screen_name'] . '</a>' . '</div>' . '<div class="tweet-text">' . $tweet['text'] . '</div>' . '</div>';
         }
     } else {
         $url = $value;
         $preview = '';
     }
     if (!craft()->twitter_plugin->checkDependencies()) {
         $html .= '<p class="light">' . Craft::t("Twitter plugin is not configured properly. Please check {url} for more informations.", array('url' => Craft::t('<a href="' . UrlHelper::getUrl('twitter/settings') . '">{title}</a>', array('title' => 'Twitter plugin settings')))) . '</p>';
     }
     return '<div class="tweet">' . craft()->templates->render('_includes/forms/text', array('id' => $id, 'name' => $name, 'value' => $url, 'placeholder' => Craft::t('Enter a tweet URL or ID'))) . '<div class="spinner hidden"></div>' . $html . '</div>';
 }
Esempio n. 11
0
 /**
  * Uploads a file directly to a field for an entry.
  *
  * @throws Exception
  * @return null
  */
 public function actionExpressUpload()
 {
     $this->requireAjaxRequest();
     $fieldId = craft()->request->getPost('fieldId');
     $elementId = craft()->request->getPost('elementId');
     if (empty($_FILES['files']) || !isset($_FILES['files']['error'][0]) || $_FILES['files']['error'][0] != 0) {
         throw new Exception(Craft::t('The upload failed.'));
     }
     $field = craft()->fields->populateFieldType(craft()->fields->getFieldById($fieldId));
     if (!$field instanceof AssetsFieldType) {
         throw new Exception(Craft::t('That is not an Assets field.'));
     }
     if ($elementId) {
         $field->element = craft()->elements->getElementById($elementId);
     }
     $targetFolderId = $field->resolveSourcePath();
     try {
         $this->_checkUploadPermissions($targetFolderId);
     } catch (Exception $e) {
         $this->returnErrorJson($e->getMessage());
     }
     $fileName = $_FILES['files']['name'][0];
     $fileLocation = AssetsHelper::getTempFilePath(pathinfo($fileName, PATHINFO_EXTENSION));
     move_uploaded_file($_FILES['files']['tmp_name'][0], $fileLocation);
     $response = craft()->assets->insertFileByLocalPath($fileLocation, $fileName, $targetFolderId, AssetConflictResolution::KeepBoth);
     $fileId = $response->getDataItem('fileId');
     // Render and return
     $element = craft()->elements->getElementById($fileId);
     $html = craft()->templates->render('_elements/element', array('element' => $element));
     $css = craft()->templates->getHeadHtml();
     $this->returnJson(array('html' => $html, 'css' => $css));
 }
 public function getInputHtml($name, $value)
 {
     $settings = $this->getSettings();
     if ($value) {
         $value = new DateTime($value);
     }
     $dayRange = range(1, 31);
     $dayOption = array('label' => Craft::t('day'), 'disabled' => true);
     $dayVariables = array('name' => $name . '[day]', 'value' => $value ? $value->format('d') : false, 'options' => array($dayOption) + array_combine($dayRange, $dayRange));
     $monthRange = range(1, 12);
     $monthOption = array('label' => Craft::t('month'), 'disabled' => true);
     $monthVariables = array('name' => $name . '[month]', 'value' => $value ? $value->format('m') : false, 'options' => array($monthOption) + array_combine($monthRange, $monthRange));
     $yearStart = is_numeric($settings->yearRangeStart) ? $settings->yearRangeStart : date('Y', strtotime($settings->yearRangeStart));
     $yearEnd = is_numeric($settings->yearRangeEnd) ? $settings->yearRangeEnd : date('Y', strtotime($settings->yearRangeEnd));
     $yearRange = range($yearEnd, $yearStart);
     $yearOption = array('label' => Craft::t('year'), 'disabled' => true);
     $yearVariables = array('name' => $name . '[year]', 'value' => $value ? $value->format('Y') : false, 'options' => array($yearOption) + array_combine($yearRange, $yearRange));
     $input = '';
     $input .= craft()->templates->render('_includes/forms/select', $dayVariables);
     $input .= ' ';
     $input .= craft()->templates->render('_includes/forms/select', $monthVariables);
     $input .= ' ';
     $input .= craft()->templates->render('_includes/forms/select', $yearVariables);
     return $input;
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     $status = $this->getParams()->status;
     //False by default
     $enable = 0;
     switch ($status) {
         case SproutSeo_RedirectStatuses::ON:
             $enable = '1';
             break;
         case SproutSeo_RedirectStatuses::OFF:
             $enable = '0';
             break;
     }
     $elementIds = $criteria->ids();
     // Update their statuses
     craft()->db->createCommand()->update('elements', array('enabled' => $enable), array('in', 'id', $elementIds));
     if ($status == SproutSeo_RedirectStatuses::ON) {
         // Enable their locale as well
         craft()->db->createCommand()->update('elements_i18n', array('enabled' => $enable), array('and', array('in', 'elementId', $elementIds), 'locale = :locale'), array(':locale' => $criteria->locale));
     }
     // Clear their template caches
     craft()->templateCache->deleteCachesByElementId($elementIds);
     // Fire an 'onSetStatus' event
     $this->onSetStatus(new Event($this, array('criteria' => $criteria, 'elementIds' => $elementIds, 'status' => $status)));
     $this->setMessage(Craft::t('Statuses updated.'));
     return true;
 }
 /**
  * @param null $attributes
  * @param bool $clearErrors
  * @return bool|void
  */
 public function validate($attributes = null, $clearErrors = true)
 {
     //ClearErrors?
     if ($clearErrors) {
         $this->clearErrors();
     }
     //Any recipients specified?
     if ($this->sendto_usergroups == false && $this->sendto_users == false) {
         $this->addError('sendto', Craft::t('No recipients specified'));
     }
     //UserGroup recipients
     if ($this->sendto_usergroups) {
         if (!$this->usergroups) {
             $this->addError('usergroups', Craft::t('No usergroups specified'));
         } elseif (array_filter($this->usergroups, 'is_int') === $this->usergroups) {
             $this->addError('usergroups', Craft::t('Invalid usergroups specified'));
         }
     }
     //User recipients
     if ($this->sendto_users) {
         if (!$this->users) {
             $this->addError('users', Craft::t('No users specified'));
         } elseif (array_filter($this->users, 'is_int') === $this->users) {
             $this->addError('users', Craft::t('Invalid users specified'));
         }
     }
     //Return
     return parent::validate($attributes, false);
 }
 /**
  * @param Market_TaxCategoryModel $model
  *
  * @return bool
  * @throws Exception
  * @throws \CDbException
  * @throws \Exception
  */
 public function save(Market_TaxCategoryModel $model)
 {
     if ($model->id) {
         $record = Market_TaxCategoryRecord::model()->findById($model->id);
         if (!$record) {
             throw new Exception(Craft::t('No tax category exists with the ID “{id}”', ['id' => $model->id]));
         }
     } else {
         $record = new Market_TaxCategoryRecord();
     }
     $record->name = $model->name;
     $record->code = $model->code;
     $record->description = $model->description;
     $record->default = $model->default;
     $record->validate();
     $model->addErrors($record->getErrors());
     if (!$model->hasErrors()) {
         // Save it!
         $record->save(false);
         // Now that we have a record ID, save it on the model
         $model->id = $record->id;
         //If this was the default make all others not the default.
         if ($model->default) {
             Market_TaxCategoryRecord::model()->updateAll(['default' => 0], 'id != ?', [$record->id]);
         }
         return true;
     } else {
         return false;
     }
 }
 /**
  * Start import task.
  */
 public function actionStart()
 {
     $this->requirePostRequest();
     craft()->userSession->requireAdmin();
     // Get posts
     $file = craft()->request->getParam('file');
     $backup = craft()->request->getParam('backup');
     $assetDestination = craft()->request->getParam('assetDestination');
     $import = craft()->request->getParam('import');
     // Set more settings
     $settings = array('file' => $file, 'backup' => $backup, 'assetDestination' => $assetDestination, 'import' => $import);
     // If backup requested, run backup task
     if ($backup) {
         craft()->tasks->createTask('InstaBlog_ImportBackup', null, $settings);
     }
     // Create the import task
     if ($task = craft()->tasks->createTask('InstaBlog_ImportWordpress', null, $settings)) {
         // Create link update task
         craft()->tasks->createTask('InstaBlog_ImportWordpressUpdateLinks', null, $settings);
         // Notify user
         craft()->userSession->setNotice(Craft::t('Import process started.'));
         // Redirect
         $this->redirect('instablog/settings/import?task=' . $task->id);
     } else {
         // Warn User
         craft()->userSession->setError(Craft::t('Import failed.'));
         // Redirect
         $this->redirect('instablog/settings/import');
     }
 }
 /**
  * Add commands to a&m command through this hook function.
  *
  * @return array
  */
 public function addCommands()
 {
     if (craft()->userSession->isAdmin()) {
         $commands = array(array('name' => Craft::t('Globals') . ': ' . Craft::t('Create field in "{globalSetName}"', array('globalSetName' => Craft::t('Number of views'))), 'info' => Craft::t('Quickly create a field in the global set and add it to the field layout.'), 'call' => 'createFieldAction', 'service' => 'amCommandPlus_globals', 'vars' => array('globalSetName' => Craft::t('Number of views'))), array('name' => Craft::t('Globals') . ': ' . Craft::t('Create field in "{globalSetName}"', array('globalSetName' => Craft::t('Entry IDs'))), 'info' => Craft::t('Quickly create a field in the global set and add it to the field layout.'), 'call' => 'createFieldAction', 'service' => 'amCommandPlus_globals', 'vars' => array('globalSetName' => Craft::t('Entry IDs'))));
         return $commands;
     }
 }
 /**
  * @param Market_CountryModel $model
  *
  * @return bool
  * @throws Exception
  * @throws \CDbException
  * @throws \Exception
  */
 public function save(Market_CountryModel $model)
 {
     if ($model->id) {
         $record = Market_CountryRecord::model()->findById($model->id);
         if (!$record) {
             throw new Exception(Craft::t('No country exists with the ID “{id}”', ['id' => $model->id]));
         }
     } else {
         $record = new Market_CountryRecord();
     }
     $record->name = $model->name;
     $record->iso = strtoupper($model->iso);
     $record->stateRequired = $model->stateRequired;
     $record->validate();
     $model->addErrors($record->getErrors());
     if (!$model->hasErrors()) {
         // Save it!
         $record->save(false);
         // Now that we have a record ID, save it on the model
         $model->id = $record->id;
         return true;
     } else {
         return false;
     }
 }
 /**
  * Saves the Customize Sources modal settings.
  */
 public function actionSaveCustomizeSourcesModalSettings()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     $elementType = $this->getElementType();
     $elementTypeClass = $elementType->getClassHandle();
     $sourceOrder = craft()->request->getPost('sourceOrder', array());
     $sources = craft()->request->getPost('sources', array());
     // Normalize to the way it's stored in the DB
     foreach ($sourceOrder as $i => $source) {
         if (isset($source['heading'])) {
             $sourceOrder[$i] = array('heading', $source['heading']);
         } else {
             $sourceOrder[$i] = array('key', $source['key']);
         }
     }
     // Remove the blank table attributes
     foreach ($sources as &$source) {
         $source['tableAttributes'] = array_filter($source['tableAttributes']);
     }
     $settings = array('sourceOrder' => $sourceOrder, 'sources' => $sources);
     if (craft()->elementIndexes->saveSettings($elementTypeClass, $settings)) {
         $this->returnJson(array('success' => true));
     } else {
         $this->returnErrorJson(Craft::t('An unknown error occurred.'));
     }
 }
 public function getInputHtml($name, $value)
 {
     // Get site templates path
     $templatesPath = $siteTemplatesPath = craft()->path->getSiteTemplatesPath();
     // Check if the templates path is overriden by configuration
     // TODO: Normalize path
     $limitToSubfolder = craft()->config->get('templateselectSubfolder');
     if ($limitToSubfolder) {
         $templatesPath = $templatesPath . rtrim($limitToSubfolder, '/') . '/';
     }
     // Check if folder exists, or give error
     if (!IOHelper::folderExists($templatesPath)) {
         throw new \InvalidArgumentException('(Template Select) Folder doesn\'t exist: ' . $templatesPath);
     }
     // Get folder contents
     $templates = IOHelper::getFolderContents($templatesPath, TRUE);
     // Add placeholder for when there is no template selected
     $filteredTemplates = array('' => Craft::t('No template selected'));
     // Turn array into ArrayObject
     $templates = new \ArrayObject($templates);
     // Iterate over template list
     // * Remove full path
     // * Remove folders from list
     for ($list = $templates->getIterator(); $list->valid(); $list->next()) {
         $filename = $list->current();
         $filename = str_replace($templatesPath, '', $filename);
         $filenameIncludingSubfolder = $limitToSubfolder ? $limitToSubfolder . $filename : $filename;
         $isTemplate = preg_match("/(.html|.twig)\$/u", $filename);
         if ($isTemplate) {
             $filteredTemplates[$filenameIncludingSubfolder] = $filename;
         }
     }
     // Render field
     return craft()->templates->render('_includes/forms/select', array('name' => $name, 'value' => $value, 'options' => $filteredTemplates));
 }
 /**
  * @inheritDoc ITask::runStep()
  *
  * @param int $step
  *
  * @return bool
  */
 public function runStep($step)
 {
     if ($this->_skipRemainingEntries) {
         return true;
     }
     $elementsService = craft()->elements;
     $settings = $this->getSettings();
     $element = $elementsService->getElementById($this->_elementIds[$step], $settings->elementType, $settings->locale);
     // Make sure they haven't deleted this element
     if (!$element) {
         return true;
     }
     $oldSlug = $element->slug;
     $oldUri = $element->uri;
     $elementsService->updateElementSlugAndUri($element, $settings->updateOtherLocales, false, false);
     // Only go deeper if something just changed
     if ($settings->updateDescendants && ($element->slug !== $oldSlug || $element->uri !== $oldUri)) {
         $criteria = $elementsService->getCriteria($element->getElementType());
         $criteria->descendantOf = $element;
         $criteria->descendantDist = 1;
         $criteria->status = null;
         $criteria->localeEnabled = null;
         $criteria->locale = $element->locale;
         $childIds = $criteria->ids();
         if ($childIds) {
             $this->runSubTask('UpdateElementSlugsAndUris', Craft::t('Updating children'), array('elementId' => $childIds, 'elementType' => $settings->elementType, 'locale' => $settings->locale, 'updateOtherLocales' => $settings->updateOtherLocales, 'updateDescendants' => true));
         }
     } else {
         if ($step === 0) {
             // Don't bother updating the other entries
             $this->_skipRemainingEntries = true;
         }
     }
     return true;
 }
 public function actionCropSaveAction()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     try {
         $x1 = craft()->request->getRequiredPost('x1');
         $x2 = craft()->request->getRequiredPost('x2');
         $y1 = craft()->request->getRequiredPost('y1');
         $y2 = craft()->request->getRequiredPost('y2');
         $source = craft()->request->getRequiredPost('source');
         $assetId = craft()->request->getPost('assetId');
         // We're editing an existing image
         if ($assetId) {
             $asset = craft()->assets->getFileById($assetId);
             $result = craft()->imageResizer->crop($asset, $x1, $x2, $y1, $y2);
             if ($result) {
                 $this->returnJson(array('success' => true));
             } else {
                 $this->returnErrorJson(Craft::t('Could not crop the image.'));
             }
         }
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the image.'));
 }
 /**
  * @inheritDoc IElementAction::performAction()
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return bool
  */
 public function performAction(ElementCriteriaModel $criteria)
 {
     // Get all submission
     $submissions = $criteria->find();
     // Gather submissions based on form
     $formSubmissions = array();
     foreach ($submissions as $submission) {
         if (!isset($formSubmissions[$submission->formId])) {
             $formSubmissions[$submission->formId] = array();
         }
         $formSubmissions[$submission->formId][] = $submission->id;
     }
     // Export submission(s)
     foreach ($formSubmissions as $formId => $submissionIds) {
         $total = count($submissionIds);
         $export = new AmForms_ExportModel();
         $export->name = Craft::t('{total} submission(s)', array('total' => $total));
         $export->formId = $formId;
         $export->total = $total;
         $export->totalCriteria = $total;
         $export->submissions = $submissionIds;
         craft()->amForms_exports->saveExport($export);
     }
     // Success!
     $this->setMessage(Craft::t('Submissions exported.'));
     return true;
 }
 /**
  * Trigger a command.
  */
 public function actionTriggerCommand()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     // Get POST data and trigger the command
     $command = craft()->request->getPost('command', false);
     $service = craft()->request->getPost('service', false);
     $vars = craft()->request->getPost('vars', false);
     $result = craft()->amCommand->triggerCommand($command, $service, $vars);
     $title = craft()->amCommand->getReturnTitle();
     $message = craft()->amCommand->getReturnMessage();
     $redirect = craft()->amCommand->getReturnUrl();
     $action = craft()->amCommand->getReturnAction();
     $commands = craft()->amCommand->getReturnCommands();
     $delete = craft()->amCommand->getDeleteStatus();
     // Overwrite result with overwritten commands?
     if ($commands) {
         $result = $commands;
     }
     // Return the result
     if ($result === false) {
         $this->returnJson(array('success' => false, 'message' => $message ? $message : Craft::t('Couldn’t trigger the command.')));
     } else {
         $this->returnJson(array('success' => true, 'title' => $title, 'message' => $message, 'result' => $result, 'redirect' => $redirect, 'isNewSet' => !is_bool($result), 'isAction' => $action, 'deleteCommand' => $delete));
     }
 }
Esempio n. 25
0
    private function _loadCodeMirror()
    {
        if ($this->_actualSettingsPage()) {
            craft()->templates->includeCssResource('cpcss/css/codemirror.css');
            craft()->templates->includeCssResource('cpcss/css/blackboard.css');
            craft()->templates->includeJsResource('cpcss/js/codemirror-css.js');
            craft()->templates->includeJs('
$(function () {
    var $redirect = $("' . addslashes('input[type="hidden"][name="redirect"][value$="settings/plugins"]') . '"),
        $saveBtn = $("' . addslashes('input[type="submit"') . '").wrap("' . addslashes('<div class="btngroup" />') . '"),
        $menuBtn = $("' . addslashes('<div class="btn submit menubtn" />') . '").appendTo($saveBtn.parent()),
        $menu = $("' . addslashes('<div class="menu" />') . '").appendTo($saveBtn.parent()),
        $items = $("<ul />").appendTo($menu),
        $continueOpt = $("' . addslashes('<li><a class="formsubmit" data-redirect="' . UrlHelper::getCpUrl('settings/plugins/cpcss') . '">' . Craft::t('Save and continue editing') . '<span class="shortcut">' . (craft()->request->getClientOs() === 'Mac' ? '⌘' : 'Ctrl+') . 'S</span></a></li>') . '").appendTo($items);
    new Garnish.MenuBtn($menuBtn, {
        onOptionSelect : function (option) {
            Craft.cp.submitPrimaryForm();
        }
    });
    $saveBtn.on("click", function (e) { $redirect.attr("value", "' . UrlHelper::getCpUrl('settings/plugins') . '"); });
    $redirect.attr("value", "' . UrlHelper::getCpUrl('settings/plugins/cpcss') . '");
    CodeMirror.fromTextArea(document.getElementById("settings-additionalCss"), {
        indentUnit: 4,
        styleActiveLine: true,
        lineNumbers: true,
        lineWrapping: true,
        theme: "blackboard"
    });
});', true);
        }
    }
Esempio n. 26
0
 private function _getInputHtml($name, $value, $static)
 {
     $columns = $this->getSettings()->columns;
     $tableData = $this->getSettings()->tableData;
     if ($columns) {
         // Translate the column headings
         foreach ($columns as &$column) {
             if (!empty($column['heading'])) {
                 $column['heading'] = Craft::t($column['heading']);
             }
         }
         // Minor fix for Backwards-compatibility - migrate old data into new key
         foreach ($value as $key => $val) {
             if (is_numeric($key)) {
                 $value['row' . ($key + 1)] = $val;
                 unset($value[$key]);
             }
         }
         if (!$value) {
             if (is_array($tableData)) {
                 $value = $tableData;
             }
         } else {
             // Merge the saved existing values and any new rows
             foreach ($tableData as $key => $val) {
                 if (!isset($value[$key])) {
                     $value[$key] = $val;
                 }
             }
         }
         $id = craft()->templates->formatInputId($name);
         return craft()->templates->render('settable/field', array('id' => $id, 'name' => $name, 'cols' => $columns, 'rows' => $value));
     }
 }
 /**
  * @param string $template
  *
  * @return TemplateLoaderException
  */
 public function __construct($template)
 {
     $this->template = $template;
     $message = Craft::t('Unable to find the template “{template}”.', array('template' => $this->template));
     Craft::log($message, LogLevel::Error);
     parent::__construct($message);
 }
 public function actionNew()
 {
     $this->requirePostRequest();
     $settings = craft()->request->getRequiredPost('settings');
     $layoutId = $settings['layoutId'];
     $label = $settings['label'];
     $handle = $settings['handle'];
     $url = $settings['url'];
     $newWindow = (bool) $settings['newWindow'];
     $variables = array('layoutId' => $layoutId, 'handle' => $handle, 'label' => $label, 'url' => $url, 'manual' => true, 'newWindow' => $newWindow);
     if ($label && $url) {
         $result = craft()->cpNav_nav->createNav($variables);
         if ($result['success']) {
             craft()->userSession->setNotice(Craft::t('Menu item added.'));
         } else {
             craft()->userSession->setError(Craft::t('Could not create menu item.'));
         }
     } else {
         craft()->userSession->setError(Craft::t('Label and URL are required.'));
     }
     if (craft()->request->isAjaxRequest()) {
         $this->returnJson(array('success' => true, 'nav' => $result['nav']));
     } else {
         $this->redirectToPostedUrl();
     }
 }
 public function actionSaveDefault()
 {
     $this->requirePostRequest();
     // check if this is a new or existing default
     if (craft()->request->getPost('sproutseo_fields[id]') == null) {
         $id = false;
     } else {
         $id = craft()->request->getPost('sproutseo_fields[id]');
     }
     $model = new SproutSeo_MetaModel();
     $model->id = $id;
     $defaultFields = craft()->request->getPost('sproutseo_fields');
     // Convert Checkbox Array into comma-delimited String
     if (isset($defaultFields['robots'])) {
         $defaultFields['robots'] = SproutSeoMetaHelper::prepRobotsAsString($defaultFields['robots']);
     }
     // Make our images single IDs instead of an array
     $defaultFields['ogImage'] = !empty($defaultFields['ogImage']) ? $defaultFields['ogImage'][0] : null;
     $defaultFields['twitterImage'] = !empty($defaultFields['twitterImage']) ? $defaultFields['twitterImage'][0] : null;
     $model->setAttributes($defaultFields);
     if (sproutSeo()->defaults->saveDefault($model)) {
         craft()->userSession->setNotice(Craft::t('New default saved.'));
         $this->redirectToPostedUrl();
     } else {
         craft()->userSession->setError(Craft::t("Couldn't save the default."));
         // Send the field back to the template
         craft()->urlManager->setRouteVariables(array('default' => $model));
     }
 }
 /**
  * Process Successful Login
  */
 private function _handleSuccessfulLogin($setNotice)
 {
     // Get the current user
     $currentUser = craft()->userSession->getUser();
     // Were they trying to access a URL beforehand?
     $returnUrl = craft()->userSession->getReturnUrl(null, true);
     if ($returnUrl === null || $returnUrl == craft()->request->getPath()) {
         // If this is a CP request and they can access the control panel, send them wherever
         // postCpLoginRedirect tells us
         if (craft()->request->isCpRequest() && $currentUser->can('accessCp')) {
             $postCpLoginRedirect = craft()->config->get('postCpLoginRedirect');
             $returnUrl = UrlHelper::getCpUrl($postCpLoginRedirect);
         } else {
             // Otherwise send them wherever postLoginRedirect tells us
             $postLoginRedirect = craft()->config->get('postLoginRedirect');
             $returnUrl = UrlHelper::getSiteUrl($postLoginRedirect);
         }
     }
     // If this was an Ajax request, just return success:true
     if (craft()->request->isAjaxRequest()) {
         $this->returnJson(array('success' => true, 'returnUrl' => $returnUrl));
     } else {
         if ($setNotice) {
             craft()->userSession->setNotice(Craft::t('Logged in.'));
         }
         $this->redirectToPostedUrl($currentUser, $returnUrl);
     }
 }