/** * Sends an email submitted through a contact form. * * @param ContactFormModel $message * @throws Exception * @return bool */ public function sendMessage(ContactFormModel $message) { $settings = craft()->plugins->getPlugin('contactform')->getSettings(); if (!$settings->toEmail) { throw new Exception('The "To Email" address is not set on the plugin’s settings page.'); } // Fire an 'onBeforeSend' event Craft::import('plugins.contactform.events.ContactFormEvent'); $event = new ContactFormEvent($this, array('message' => $message)); $this->onBeforeSend($event); if ($event->isValid) { if (!$event->fakeIt) { $toEmails = ArrayHelper::stringToArray($settings->toEmail); foreach ($toEmails as $toEmail) { $email = new EmailModel(); $emailSettings = craft()->email->getSettings(); $email->fromEmail = $emailSettings['emailAddress']; $email->replyTo = $message->fromEmail; $email->sender = $emailSettings['emailAddress']; $email->fromName = $settings->prependSender . ($settings->prependSender && $message->fromName ? ' ' : '') . $message->fromName; $email->toEmail = $toEmail; $email->subject = $settings->prependSubject . ($settings->prependSubject && $message->subject ? ' - ' : '') . $message->subject; $email->body = $message->message; if ($message->attachment) { $email->addAttachment($message->attachment->getTempName(), $message->attachment->getName(), 'base64', $message->attachment->getType()); } craft()->email->sendEmail($email); } } return true; } return false; }
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)); }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { // Create the categorygroups table if (!craft()->db->tableExists('categorygroups')) { Craft::log('Creating the categorygroups table', LogLevel::Info, true); $this->createTable('categorygroups', array('structureId' => array('column' => ColumnType::Int, 'null' => false), 'fieldLayoutId' => array('column' => ColumnType::Int), 'name' => array('column' => ColumnType::Varchar, 'required' => true), 'handle' => array('column' => ColumnType::Varchar, 'required' => true), 'hasUrls' => array('column' => ColumnType::Bool, 'required' => true, 'default' => true), 'template' => array('column' => ColumnType::Varchar, 'maxLength' => 500))); $this->createIndex('categorygroups', 'name', true); $this->createIndex('categorygroups', 'handle', true); $this->addForeignKey('categorygroups', 'structureId', 'structures', 'id', 'CASCADE'); $this->addForeignKey('categorygroups', 'fieldLayoutId', 'fieldlayouts', 'id', 'SET NULL'); } // Create the categorygroups_i18n table if (!craft()->db->tableExists('categorygroups_i18n')) { Craft::log('Creating the categorygroups_i18n table', LogLevel::Info, true); $this->createTable('categorygroups_i18n', array('groupId' => array('column' => ColumnType::Int, 'required' => true), 'locale' => array('column' => ColumnType::Locale, 'required' => true), 'urlFormat' => array('column' => ColumnType::Varchar), 'nestedUrlFormat' => array('column' => ColumnType::Varchar))); $this->createIndex('categorygroups_i18n', 'groupId,locale', true); $this->addForeignKey('categorygroups_i18n', 'groupId', 'categorygroups', 'id', 'CASCADE'); $this->addForeignKey('categorygroups_i18n', 'locale', 'locales', 'locale', 'CASCADE', 'CASCADE'); } // Create the categories table if (!craft()->db->tableExists('categories')) { Craft::log('Creating the categories table', LogLevel::Info, true); $this->createTable('categories', array('id' => array('column' => ColumnType::Int, 'required' => true, 'primaryKey' => true), 'groupId' => array('column' => ColumnType::Int, 'required' => true)), null, false); $this->addForeignKey('categories', 'id', 'elements', 'id', 'CASCADE'); $this->addForeignKey('categories', 'groupId', 'categorygroups', 'id', 'CASCADE'); } return true; }
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)); } }
/** * 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'); }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { if (!craft()->db->columnExists('elements_i18n', 'slug')) { Craft::log('Creating an elements_i18n.slug column.', LogLevel::Info, true); $this->addColumnAfter('elements_i18n', 'slug', ColumnType::Varchar, 'locale'); } if (craft()->db->tableExists('entries_i18n')) { Craft::log('Copying the slugs from entries_i18n into elements_i18n.', LogLevel::Info, true); $rows = craft()->db->createCommand()->select('entryId, locale, slug')->from('entries_i18n')->queryAll(); foreach ($rows as $row) { $this->update('elements_i18n', array('slug' => $row['slug']), array('elementId' => $row['entryId'], 'locale' => $row['locale'])); } Craft::log('Dropping the entries_i18n table.'); $this->dropTable('entries_i18n'); } if (!craft()->db->columnExists('elements_i18n', 'enabled')) { Craft::log('Creating an elements_i18n.enabled column.', LogLevel::Info, true); $this->addColumnAfter('elements_i18n', 'enabled', array('column' => ColumnType::Bool, 'default' => true), 'uri'); } MigrationHelper::refresh(); MigrationHelper::dropIndexIfExists('elements_i18n', array('slug', 'locale')); MigrationHelper::dropIndexIfExists('elements_i18n', array('enabled')); $this->createIndex('elements_i18n', 'slug,locale'); $this->createIndex('elements_i18n', 'enabled'); return true; }
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); } }
/** * @access protected * @return array */ protected function defineAttributes() { $requiredTitle = isset($this->_requiredFields) && in_array('title', $this->_requiredFields); $attributes = array('id' => AttributeType::Number, 'elementId' => AttributeType::Number, 'locale' => AttributeType::Locale, 'title' => array(AttributeType::String, 'required' => $requiredTitle)); if (Craft::isInstalled() && !craft()->isConsole()) { $allFields = craft()->fields->getAllFields(); foreach ($allFields as $field) { $fieldType = craft()->fields->populateFieldType($field); if ($fieldType) { $attributeConfig = $fieldType->defineContentAttribute(); } // Default to Mixed if (!$fieldType || !$attributeConfig) { $attributeConfig = AttributeType::Mixed; } $attributeConfig = ModelHelper::normalizeAttributeConfig($attributeConfig); $attributeConfig['label'] = $field->name; if (isset($this->_requiredFields) && in_array($field->id, $this->_requiredFields)) { $attributeConfig['required'] = true; } $attributes[$field->handle] = $attributeConfig; } } return $attributes; }
/** * @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; } }
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(); } }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { Craft::log('Dropping the movePermission column from the structures table...', LogLevel::Info, true); $this->dropColumn('structures', 'movePermission'); Craft::log('Done dropping the movePermission column from the structures table.', LogLevel::Info, true); return true; }
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)); } }
/** * 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)); } }
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.')); }
/** * 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)); }
/** * 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; } }
/** * @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; }
/** * @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; } }
/** * @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; }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { $this->addColumnAfter('oauth_tokens', 'accessToken', array(ColumnType::Varchar, 'required' => false), 'pluginHandle'); $this->addColumnAfter('oauth_tokens', 'secret', array(ColumnType::Varchar, 'required' => false), 'accessToken'); $this->addColumnAfter('oauth_tokens', 'endOfLife', array(ColumnType::Varchar, 'required' => false), 'secret'); $this->addColumnAfter('oauth_tokens', 'refreshToken', array(ColumnType::Varchar, 'required' => false), 'endOfLife'); require_once CRAFT_PLUGINS_PATH . 'oauth/vendor/autoload.php'; $rows = craft()->db->createCommand()->select('*')->from('oauth_tokens')->queryAll(); foreach ($rows as $row) { $token = $row['encodedToken']; $token = @unserialize(base64_decode($token)); if ($token && is_object($token)) { $attributes = array(); $attributes['accessToken'] = $token->getAccessToken(); if (method_exists($token, 'getAccessTokenSecret')) { $attributes['secret'] = $token->getAccessTokenSecret(); } $attributes['endOfLife'] = $token->getEndOfLife(); $attributes['refreshToken'] = $token->getRefreshToken(); $this->update('oauth_tokens', $attributes, 'id = :id', array(':id' => $row['id'])); } } Craft::log('Dropping the encodedToken column from the structures table...', LogLevel::Info, true); $this->dropColumn('oauth_tokens', 'encodedToken'); Craft::log('Done dropping the encodedToken column from the structures table.', LogLevel::Info, true); return true; }
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(); } }
/** * 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.')); } }
/** * @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); }
/** * @inheritDoc ITask::runStep() * * @param int $step * * @return bool */ public function runStep($step) { // NOTE: Perhaps much of this should be moved into a service $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build(); // Make the client $client = new \Guzzle\Http\Client(); // Set the Accept header $client->setDefaultOption('headers/Accept', '*/*'); // Loop the paths in this step foreach ($this->_paths[$step] as $path) { // Make the url, stripping 'site:' from the path if it exists $newPath = preg_replace('/site:/', '', $path, 1); $url = UrlHelper::getSiteUrl($newPath); // Create the GET request $request = $client->get($url); // Add it to the batch $batch->add($request); } // Flush the queue and retrieve the flushed items $requests = $batch->flush(); // Log any exceptions foreach ($batch->getExceptions() as $e) { Craft::log('CacheMonster: an exception occurred: ' . $e->getMessage(), LogLevel::Error); } // Clear any exceptions $batch->clearExceptions(); return true; }
/** * Settings * * @return null */ public function actionSettings() { craft()->twitter_plugin->requireDependencies(); $plugin = craft()->plugins->getPlugin('twitter'); $variables = array('provider' => false, 'account' => false, 'token' => false, 'error' => false); $provider = craft()->oauth->getProvider('twitter'); if ($provider && $provider->isConfigured()) { $token = craft()->twitter_oauth->getToken(); if ($token) { try { $account = craft()->twitter_cache->get(['getAccount', $token]); if (!$account) { $account = $provider->getAccount($token); craft()->twitter_cache->set(['getAccount', $token], $account); } if ($account) { Craft::log("Twitter OAuth Account:\r\n" . print_r($account, true), LogLevel::Info); $variables['account'] = $account; $variables['settings'] = $plugin->getSettings(); } } catch (\Exception $e) { if (method_exists($e, 'getResponse')) { Craft::log("Couldn’t get account: " . $e->getResponse(), LogLevel::Error); } else { Craft::log("Couldn’t get account: " . $e->getMessage(), LogLevel::Error); } $variables['error'] = $e->getMessage(); } } $variables['token'] = $token; $variables['provider'] = $provider; } $this->renderTemplate('twitter/settings', $variables); }
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)); }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { // unique index for 'userMapping' and 'provider' $tableName = 'oauth_tokens'; $providersTable = $this->dbConnection->schema->getTable('{{' . $tableName . '}}'); if ($providersTable) { $columns = 'userMapping, provider'; $unique = true; $this->createIndex($tableName, $columns, $unique); } else { Craft::log('Could not find an `' . $tableName . '` table. Wut?', LogLevel::Error); } // unique index for 'userId' and 'provider' $tableName = 'oauth_tokens'; $providersTable = $this->dbConnection->schema->getTable('{{' . $tableName . '}}'); if ($providersTable) { $columns = 'userId, provider'; $unique = true; $this->createIndex($tableName, $columns, $unique); } else { Craft::log('Could not find an `' . $tableName . '` table. Wut?', LogLevel::Error); } // unique index for 'namespace' and 'provider' $tableName = 'oauth_tokens'; $providersTable = $this->dbConnection->schema->getTable('{{' . $tableName . '}}'); if ($providersTable) { $columns = 'namespace, provider'; $unique = true; $this->createIndex($tableName, $columns, $unique); } else { Craft::log('Could not find an `' . $tableName . '` table. Wut?', LogLevel::Error); } return true; }
/** * @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 getProfile() { try { $token = $this->token; if ($token) { // make token compatible with Google library $arrayToken = array(); $arrayToken['created'] = 0; $arrayToken['access_token'] = $token->accessToken; $arrayToken['expires_in'] = $token->endOfLife; $arrayToken = json_encode($arrayToken); // client $client = new Google_Client(); $client->setApplicationName('Google+ PHP Starter Application'); $client->setClientId('clientId'); $client->setClientSecret('clientSecret'); $client->setRedirectUri('redirectUri'); $client->setAccessToken($arrayToken); // $api = new Google_Service_Analytics($client); $service = new Google_Service_Oauth2($client); $response = $service->userinfo->get(); return array('id' => $response->id, 'email' => $response->email, 'photo' => $response->picture, 'locale' => $response->locale, 'firstName' => $response->givenName, 'lastName' => $response->familyName, 'profileUrl' => $response->link, 'gender' => $response->gender); } else { Craft::log(__METHOD__ . ' : No token defined', LogLevel::Info, true); return false; } } catch (\Exception $e) { // todo: catch errors // throw $e; } }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { Craft::log('Renaming social_accounts `gateway` column by `providerHandle`', LogLevel::Info, true); MigrationHelper::renameColumn('social_accounts', 'gateway', 'providerHandle'); Craft::log('Done renaming social_accounts `gateway` column by `providerHandle`', LogLevel::Info, true); return true; }