/** * Convert allowed source storage format from just an integer to "folder:X" format. * * @return bool */ public function safeUp() { // Grab all the Assets fields. $fields = craft()->db->createCommand()->select('id, settings')->from('fields')->where('type = :type', array(':type' => "Assets"))->queryAll(); if ($fields) { // Grab all of the top-level folder IDs $folders = craft()->db->createCommand()->select('id, sourceId')->from('assetfolders')->where('parentId is null')->queryAll(); if ($folders) { // Create an associative array of them by source ID $folderIdsBySourceId = array(); foreach ($folders as $folder) { $folderIdsBySourceId[$folder['sourceId']] = $folder['id']; } // Now update the fields foreach ($fields as $field) { $settings = JsonHelper::decode($field['settings']); if (isset($settings['sources']) && is_array($settings['sources'])) { // Are there any source IDs? $anySourceIds = false; foreach ($settings['sources'] as $key => $source) { if (isset($folderIdsBySourceId[$source])) { $settings['sources'][$key] = 'folder:' . $folderIdsBySourceId[$source]; $anySourceIds = true; } } if ($anySourceIds) { $this->update('fields', array('settings' => JsonHelper::encode($settings)), array('id' => $field['id'])); } } } } } return true; }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { // Get all of the Tags fields $tagFields = craft()->db->createCommand()->select('id, settings')->from('fields')->where(array('type' => 'Tags'))->queryAll(); foreach ($tagFields as $field) { $settings = JsonHelper::decode($field['settings']); if (!empty($settings['source']) && strncmp($settings['source'], 'tagset:', 7) == 0) { $tagSetId = (int) mb_substr($settings['source'], 7); // Does that tag set still exist? $count = craft()->db->createCommand()->from('tagsets')->where(array('id' => $tagSetId))->count('id'); if ($count) { // Now make sure all of the tags connected to this field actually belong to that set. // Otherwise we should duplicate the tag into the correct set $tags = craft()->db->createCommand()->select('r.id relationId, t.name')->from('relations r')->join('tags t', 't.id = r.childId')->where(array('and', 'r.fieldId = :fieldId', 't.setId != :setId'), array(':fieldId' => $field['id'], ':setId' => $tagSetId))->queryAll(); foreach ($tags as $tag) { // Is there already a tag in the correct tag set with that name? $newTagId = craft()->db->createCommand()->select('id')->from('tags')->where(array('setId' => $tagSetId, 'name' => $tag['name']))->queryScalar(); if (!$newTagId) { // Create a new row in elements craft()->db->createCommand()->insert('elements', array('type' => ElementType::Tag, 'enabled' => 1, 'archived' => 0)); // Get the new element ID $newTagId = craft()->db->getLastInsertID(); $this->insert('tags', array('id' => $newTagId, 'setId' => $tagSetId, 'name' => $tag['name'])); } // Update the relation $this->update('relations', array('childId' => $newTagId), array('id' => $tag['relationId'])); } } else { // Just delete any relations with this field $this->delete('relations', array('fieldId' => $field['id'])); } } } return true; }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { // Get all Assets fields $fields = craft()->db->createCommand()->select('fields.id, fields.settings')->from('fields fields')->where('fields.type = "Assets"')->queryAll(); $affectedFields = array(); // Select those, that have a dynamic default upload location set. foreach ($fields as $field) { $settings = JsonHelper::decode($field['settings']); if (empty($settings['useSingleFolder']) && !empty($settings['defaultUploadLocationSubpath']) && strpos($settings['defaultUploadLocationSubpath'], '{') !== false) { $affectedFields[] = $field; } } $affectedElements = array(); // Get the element ids, that have Assets linked to them via affected fields that still reside in a temporary source. if (!empty($affectedFields)) { foreach ($affectedFields as $field) { $data = $this->_getAffectedElements($field); foreach ($data as $row) { $affectedElements[$row['type']][] = $row['elementId']; } } } foreach ($affectedElements as $elementType => $ids) { $criteria = craft()->elements->getCriteria($elementType); $criteria->status = null; $criteria->limit = null; $criteria->id = $ids; craft()->tasks->createTask('ResaveElements', Craft::t('Resaving {element} elements affected by Assets bug', array('element' => $elementType)), array('elementType' => $elementType, 'criteria' => $criteria->getAttributes())); } return true; }
function __toString() { $json_config = JsonHelper::encode($this->config); $this->afterHTML = HtmlHelper::inlineJavascript('jQuery(function(){$("#' . $this->getId() . '").datepicker(' . $json_config . ')});'); $this->setAttribute('class', 'form_input_text form_ycalendar'); return parent::__toString(); }
/** * @param mixed|null $element * * @throws \Exception * @return array|string */ public function getRecipients($element = null) { $recipientsString = $this->getAttribute('recipients'); // Possibly called from entry edit screen if (is_null($element)) { return $recipientsString; } // Previously converted to array somehow? if (is_array($recipientsString)) { return $recipientsString; } // Previously stored as JSON string? if (stripos($recipientsString, '[') === 0) { return JsonHelper::decode($recipientsString); } // Still a string with possible twig generator code? if (stripos($recipientsString, '{') !== false) { try { $recipients = craft()->templates->renderObjectTemplate($recipientsString, $element); return array_unique(ArrayHelper::filterEmptyStringsFromArray(ArrayHelper::stringToArray($recipients))); } catch (\Exception $e) { throw $e; } } // Just a regular CSV list if (!empty($recipientsString)) { return ArrayHelper::filterEmptyStringsFromArray(ArrayHelper::stringToArray($recipientsString)); } return array(); }
public static function Decode($object, $data) { foreach ($data as $value) { $object->{$value} = JsonHelper::JsonDecode($object->{$value}); } return $object; }
/** * @inheritDoc IElementAction::getTriggerHtml() * * @return string|null */ public function getTriggerHtml() { $maxLevels = JsonHelper::encode($this->getParams()->maxLevels); $newChildUrl = JsonHelper::encode($this->getParams()->newChildUrl); $js = <<<EOT (function() { \tvar trigger = new Craft.ElementActionTrigger({ \t\thandle: 'NewChild', \t\tbatch: false, \t\tvalidateSelection: function(\$selectedItems) \t\t{ \t\t\treturn (!{$maxLevels} || {$maxLevels} > \$selectedItems.find('.element').data('level')); \t\t}, \t\tactivate: function(\$selectedItems) \t\t{ \t\t\tCraft.redirectTo(Craft.getUrl({$newChildUrl}, 'parentId='+\$selectedItems.find('.element').data('id'))); \t\t} \t}); \tif (Craft.elementIndex.view.structureTableSort) \t{ \t\tCraft.elementIndex.view.structureTableSort.on('positionChange', \$.proxy(trigger, 'updateTrigger')); \t} })(); EOT; craft()->templates->includeJs($js); }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { $rows = craft()->db->createCommand()->select('*')->from('widgets')->where('type=:type', array(':type' => 'Analytics_Explorer'))->queryAll(); if ($rows) { foreach ($rows as $row) { $oldSettings = JsonHelper::decode($row['settings']); // old to new $newSettings = []; if (isset($oldSettings['chart'])) { $newSettings['chart'] = $oldSettings['chart']; } if (isset($oldSettings['period'])) { $newSettings['period'] = $oldSettings['period']; } $newSettings['options'] = []; if (isset($oldSettings['dimension'])) { $newSettings['options']['dimension'] = $oldSettings['dimension']; } if (isset($oldSettings['metric'])) { $newSettings['options']['metric'] = $oldSettings['metric']; } switch ($oldSettings['menu']) { case 'realtimeVisitors': $type = 'Analytics_Realtime'; break; default: $type = 'Analytics_Report'; } // update row $newSettings = JsonHelper::encode($newSettings); $updateCmd = craft()->db->createCommand()->update('widgets', array('type' => $type, 'settings' => $newSettings), 'id=:id', array('id' => $row['id'])); } } return true; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($request->method() == 'POST' && $request->input('api_key') != getenv('API_KEY')) { return response()->json(\JsonHelper::getErrorResponse(\HttpResponse::HTTP_UNAUTHORIZED, 'API key is invalid.'), \HttpResponse::HTTP_UNAUTHORIZED); } return $next($request); }
/** * Searches for a token, and possibly returns a route for the request. * * @param string $token * * @return array|false */ public function getTokenRoute($token) { // Take the opportunity to delete any expired tokens $this->deleteExpiredTokens(); $result = craft()->db->createCommand()->select('id, route, usageLimit, usageCount')->from('tokens')->where('token = :token', array(':token' => $token))->queryRow(); if ($result) { // Usage limit enforcement (for future requests) if ($result['usageLimit']) { // Does it have any more life after this? if ($result['usageCount'] < $result['usageLimit'] - 1) { // Increment its count $this->incrementTokenUsageCountById($result['id']); } else { // Just delete it $this->deleteTokenById($result['id']); } } // Figure out where we should route the request $route = $result['route']; if (is_string($route) && mb_strlen($route) && ($route[0] == '[' || $route[0] == '{')) { $route = JsonHelper::decode($route); } return $route; } else { return false; } }
public static function populateFromAsset(AssetFileModel $asset) { if ($asset->kind === 'json' && strpos($asset->filename, EmbeddedAssetsPlugin::getFileNamePrefix(), 0) === 0) { try { $url = $asset->getUrl(); if (!UrlHelper::isAbsoluteUrl($url)) { $protocol = craft()->request->isSecureConnection() ? 'https' : 'http'; $url = UrlHelper::getUrlWithProtocol($url, $protocol); } // See http://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-file-get-contents-function-in-php $rawData = @file_get_contents($url); if ($rawData) { $data = JsonHelper::decode($rawData); if ($data['__embeddedasset__']) { unset($data['__embeddedasset__']); $embed = new EmbeddedAssetsModel(); $embed->id = $asset->id; foreach ($data as $key => $value) { $embed->{$key} = $value; } return $embed; } } } catch (\Exception $e) { return null; } } return null; }
/** * @inheritDoc IElementAction::getTriggerHtml() * * @return string|null */ public function getTriggerHtml() { $userId = JsonHelper::encode(craft()->userSession->getUser()->id); $js = <<<EOT (function() { \tvar trigger = new Craft.ElementActionTrigger({ \t\thandle: 'SuspendUsers', \t\tbatch: true, \t\tvalidateSelection: function(\$selectedItems) \t\t{ \t\t\tfor (var i = 0; i < \$selectedItems.length; i++) \t\t\t{ \t\t\t\tif (\$selectedItems.eq(i).find('.element').data('id') == {$userId}) \t\t\t\t{ \t\t\t\t\treturn false; \t\t\t\t} \t\t\t} \t\t\treturn true; \t\t} \t}); })(); EOT; craft()->templates->includeJs($js); }
/** * Includes the plugin's resources for the Control Panel. */ protected function includeCpResources() { // Prepare config $config = []; $config['iconMapping'] = craft()->config->get('iconMapping', 'redactoriconbuttons'); $iconAdminPath = craft()->path->getConfigPath() . 'redactoriconbuttons/icons.svg'; $iconPublicPath = craft()->config->get('iconFile', 'redactoriconbuttons'); if (IOHelper::fileExists($iconAdminPath)) { $config['iconFile'] = UrlHelper::getResourceUrl('config/redactoriconbuttons/icons.svg'); } elseif ($iconPublicPath) { $config['iconFile'] = craft()->config->parseEnvironmentString($iconPublicPath); } else { $config['iconFile'] = UrlHelper::getResourceUrl('redactoriconbuttons/icons/redactor-i.svg'); } // Include JS $config = JsonHelper::encode($config); $js = "var RedactorIconButtons = {}; RedactorIconButtons.config = {$config};"; craft()->templates->includeJs($js); craft()->templates->includeJsResource('redactoriconbuttons/redactoriconbuttons.js'); // Include CSS craft()->templates->includeCssResource('redactoriconbuttons/redactoriconbuttons.css'); // Add external spritemap support for IE9+ and Edge 12 $ieShim = craft()->config->get('ieShim', 'redactoriconbuttons'); if (filter_var($ieShim, FILTER_VALIDATE_BOOLEAN)) { craft()->templates->includeJsResource('redactoriconbuttons/lib/svg4everybody.min.js'); craft()->templates->includeJs('svg4everybody();'); } }
public static function populateFromAsset(AssetFileModel $asset) { if ($asset->kind === 'json' && strpos($asset->filename, EmbeddedAssetsPlugin::getFileNamePrefix(), 0) === 0) { try { $rawData = craft()->embeddedAssets->readAssetFile($asset); if ($rawData) { $data = JsonHelper::decode($rawData); if ($data['__embeddedasset__']) { unset($data['__embeddedasset__']); $embed = new EmbeddedAssetsModel(); $embed->id = $asset->id; foreach ($embed->attributeNames() as $key) { if (isset($data[$key])) { $embed->{$key} = $data[$key]; } } // For embedded assets saved with version 0.2.1 or below, this will provide a usable fallback if (empty($embed->requestUrl)) { $embed->requestUrl = $embed->url; } return $embed; } } } catch (\Exception $e) { EmbeddedAssetsPlugin::log("Error reading embedded asset data on asset {$asset->id} (\"{$e->getMessage()}\")", LogLevel::Error); return null; } } return null; }
/** * Updates the rules sort order. * * @return null */ public function actionReorderRules() { $this->requirePostRequest(); $this->requireAjaxRequest(); $ruleIds = JsonHelper::decode(craft()->request->getRequiredPost('ids')); craft()->autoExpire->reorderRules($ruleIds); $this->returnJson(array('success' => true)); }
private function _updateSaveUserOptions($options) { $oldOptions = JsonHelper::decode($options); $whenNew = isset($oldOptions['usersSaveUserOnlyWhenNew']) ? $oldOptions['usersSaveUserOnlyWhenNew'] : ''; $userGroupIds = isset($oldOptions['usersSaveUserGroupIds']) ? $oldOptions['usersSaveUserGroupIds'] : ''; $newOptions = array('craft' => array('saveUser' => array('whenNew' => $whenNew, 'whenUpdated' => '', 'userGroupIds' => $userGroupIds))); return JsonHelper::encode($newOptions); }
/** * Saves the new locale order. * * @return null */ public function actionReorderLocales() { $this->requirePostRequest(); $this->requireAjaxRequest(); $localeIds = JsonHelper::decode(craft()->request->getRequiredPost('ids')); $success = craft()->i18n->reorderSiteLocales($localeIds); $this->returnJson(array('success' => $success)); }
/** * Reorders widgets. */ public function actionReorderUserWidgets() { $this->requirePostRequest(); $this->requireAjaxRequest(); $widgetIds = JsonHelper::decode(craft()->request->getRequiredPost('ids')); craft()->dashboard->reorderUserWidgets($widgetIds); $this->returnJson(array('success' => true)); }
public function actionReorderNav() { $this->requirePostRequest(); $this->requireAjaxRequest(); $navIds = JsonHelper::decode(craft()->request->getRequiredPost('ids')); $navs = craft()->cpNav_nav->reorderNav($navIds); $this->returnJson(array('success' => true, 'navs' => $navs)); }
/** * Updates the announcements sort order. * * @return null */ public function actionReorderAnnouncements() { $this->requirePostRequest(); $this->requireAjaxRequest(); $announcementIds = JsonHelper::decode(craft()->request->getRequiredPost('ids')); $announcementIds = array_reverse($announcementIds); craft()->maintenance->reorderAnnouncements($announcementIds); $this->returnJson(array('success' => true)); }
/** * Save Settings to the Database * * @return mixed Return to Page */ public function actionSettingsIndexTemplate() { $settingsModel = new SproutForms_SettingsModel(); $settings = craft()->db->createCommand()->select('settings')->from('plugins')->where('class=:class', array(':class' => 'SproutForms'))->queryScalar(); $settings = JsonHelper::decode($settings); $settingsModel->setAttributes($settings); $variables['settings'] = $settingsModel; // Load our template $this->renderTemplate('sproutforms/settings', $variables); }
/** * @inheritDoc IWidget::getBodyHtml() * * @return string|false */ public function getBodyHtml() { $id = $this->model->id; $url = JsonHelper::encode($this->getSettings()->url); $limit = $this->getSettings()->limit; $js = "new Craft.FeedWidget({$id}, {$url}, {$limit});"; craft()->templates->includeJsResource('js/FeedWidget.js'); craft()->templates->includeJs($js); return craft()->templates->render('_components/widgets/Feed/body', array('limit' => $limit)); }
function __toString() { $this->setAttribute('class', 'tinymce_textarea'); $this->innerHTML = HtmlHelper::escape($this->_value); $config = JsonHelper::encode($this->config); $script = HtmlHelper::inlineJavascript('tinyMCE.init(' . $config . ');'); $this->afterHTML = $script; self::$instances_included++; return parent::__toString(); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, \Closure $next) { if (!($token = $this->auth->setRequest($request)->getToken())) { return response()->json(\JsonHelper::getErrorResponse(\HttpResponse::HTTP_BAD_REQUEST, 'Token is missing.'), \HttpResponse::HTTP_BAD_REQUEST); } $user = $this->auth->authenticate($token); if (!$user) { return response()->json(\JsonHelper::getErrorResponse(\HttpResponse::HTTP_NOT_FOUND, 'User not found.'), \HttpResponse::HTTP_NOT_FOUND); } return $next($request); }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { $matrixFields = craft()->db->createCommand()->select('id, settings')->from('fields')->where('type = "Matrix"')->queryAll(); foreach ($matrixFields as $field) { $settings = JsonHelper::decode($field['settings']); if (isset($settings['__model__'])) { unset($settings['__model__']); $this->update('fields', array('settings' => JsonHelper::encode($settings)), array('id' => $field['id'])); } } return true; }
/** * Separate initialisation function to be called inside the NeoPlugin init method. */ public function pluginInit() { if (craft()->plugins->getPlugin('reasons') && craft()->request->isCpRequest() && !craft()->isConsole()) { if (craft()->request->isAjaxRequest()) { // TODO } else { $data = ['conditionals' => $this->getConditionals()]; craft()->templates->includeJs('if(window.Craft && Craft.ReasonsPlugin) Craft.ReasonsPlugin.Neo = ' . JsonHelper::encode($data)); } craft()->on('fields.saveFieldLayout', [$this, 'onSaveFieldLayout']); } }
public function actionExport() { $this->requirePostRequest(); $result = new ArtVandelay_ExportedDataModel(array('assets' => $this->_exportAssets(), 'categories' => $this->_exportCategories(), 'fields' => $this->_exportFields(), 'globals' => $this->_exportGlobals(), 'sections' => $this->_exportSections(), 'tags' => $this->_exportTags())); $json = $result->toJson(); if (craft()->request->getParam('download')) { HeaderHelper::setDownload('export.json', strlen($json)); } JsonHelper::sendJsonHeaders(); echo $json; craft()->end(); }
/** * Save Settings to the Database * * @return mixed Return to Page */ public function actionSettingsIndex() { $settingsModel = new SproutSeo_SettingsModel(); // Create any variables you want available in your template // $variables['items'] = craft()->pluginName->getAllItems(); $settings = craft()->db->createCommand()->select('settings')->from('plugins')->where('class=:class', array(':class' => 'SproutSeo'))->queryScalar(); $settings = JsonHelper::decode($settings); $settingsModel->setAttributes($settings); $variables['settings'] = $settingsModel; // Load a particular template and with all of the variables you've created $this->renderTemplate('sproutseo/settings', $variables); }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { if (!craft()->db->tableExists('tagsets')) { // Create the tagsets table craft()->db->createCommand()->createTable('tagsets', array('name' => array('maxLength' => 100, 'column' => ColumnType::Varchar, 'null' => false), 'handle' => array('maxLength' => 45, 'column' => ColumnType::Char, 'null' => false), 'fieldLayoutId' => array('column' => ColumnType::Int, 'length' => 10, 'unsigned' => false))); $this->createIndex('tagsets', 'name', true); $this->createIndex('tagsets', 'handle', true); // Create the Default tag group $this->insert('tagsets', array('name' => 'Default', 'handle' => 'default')); $tagSetId = craft()->db->getLastInsertID(); // Rename the entrytags table MigrationHelper::renameTable('entrytags', 'tags'); // Convert the tags to elements MigrationHelper::makeElemental('tags', 'Tag'); // Make some tweaks on the tags table $this->alterColumn('tags', 'name', array('column' => ColumnType::Varchar, 'null' => false)); $this->dropColumn('tags', 'count'); $this->addColumnBefore('tags', 'setId', array('column' => ColumnType::Int, 'null' => false), 'name'); $this->dropIndex('tags', 'name', true); // Place all current tags into the Default group $this->update('tags', array('setId' => $tagSetId)); $this->createIndex('tags', 'setId, name', true); $this->addForeignKey('tags', 'setId', 'tagsets', 'id', 'CASCADE', null); // Create a new field group $this->insert('fieldgroups', array('name' => 'Tags (Auto-created)')); $groupId = craft()->db->getLastInsertID(); // Create a new Tags field // Find a unique handle for ($i = 0; true; $i++) { $handle = 'tags' . ($i != 0 ? "-{$i}" : ''); $totalFields = craft()->db->createCommand()->from('fields')->where(array('handle' => $handle))->count('id'); if ($totalFields == 0) { break; } } $this->insert('fields', array('groupId' => $groupId, 'name' => 'Tags', 'handle' => $handle, 'type' => 'Tags', 'settings' => JsonHelper::encode(array('source' => 'tagset:' . $tagSetId)))); $fieldId = craft()->db->getLastInsertID(); // Migrate entrytags_enrtries data into relations $tagRelations = craft()->db->createCommand()->select('entryId, tagId, dateCreated, dateUpdated, uid')->from('entrytags_entries')->queryAll(false); foreach ($tagRelations as &$relation) { array_unshift($relation, $fieldId); } $this->insertAll('relations', array('fieldId', 'parentId', 'childId', 'dateCreated', 'dateUpdated', 'uid'), $tagRelations, false); // Update the search indexes $this->update('searchindex', array('attribute' => 'field', 'fieldId' => $fieldId), array('attribute' => 'tags'), array(), false); // Drop the old entrytags_entries table $this->dropTable('entrytags_entries'); } else { Craft::log('Tried to add the `tagsets` table, but it already exists.', LogLevel::Warning); } return true; }
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if ($e instanceof ModelNotFoundException) { $e = new NotFoundHttpException($e->getMessage(), $e); } if ($e instanceof TokenInvalidException || $e instanceof JWTException) { return response()->json(\JsonHelper::getErrorResponse(\HttpResponse::HTTP_UNAUTHORIZED, 'Token is invalid.'), \HttpResponse::HTTP_UNAUTHORIZED); } if ($e instanceof TokenExpiredException) { return response()->json(\JsonHelper::getErrorResponse(\HttpResponse::HTTP_UNAUTHORIZED, 'Token has expired.'), \HttpResponse::HTTP_UNAUTHORIZED); } return parent::render($request, $e); }