private function _validateoptions($options)
 {
     if (empty($options)) {
         throw new Exception(Craft::t('vCard Parameters must be supplied'));
     }
     return true;
 }
 /**
  * The "sortByField" filter sorts an array of entries by the specified field's value
  *
  * Usage: {% for entry in craft.entries|sortByField('ordering', 'desc') %}
  */
 public function sortByFieldFilter($content, $sort_by = null, $direction = 'asc')
 {
     if (!is_array($content)) {
         throw new Exception(Craft::t('Variable passed to the sortByField filter is not an array'));
     } elseif (!(isset($content[0]) && is_object($content[0]) && (get_class($content[0]) === 'Craft\\EntryModel' || get_class($content[0]) === 'Craft\\Commerce_ProductModel'))) {
         throw new Exception(Craft::t('Variables passed to the sortByField filter are not entries'));
     } elseif ($sort_by === null) {
         throw new Exception(Craft::t('No sort by parameter passed to the sortByField filter'));
     } elseif (!$content[0]->__isset($sort_by)) {
         throw new Exception(Craft::t('Entries passed to the sortByField filter do not have the field "' . $sort_by . '"'));
     } else {
         // Unfortunately have to suppress warnings here due to __get function
         // causing usort to think that the array has been modified:
         // usort(): Array was modified by the user comparison function
         @usort($content, function ($a, $b) use($sort_by, $direction) {
             $flip = $direction === 'desc' ? -1 : 1;
             $a_sort_value = $a->__get($sort_by);
             $b_sort_value = $b->__get($sort_by);
             if ($a_sort_value == $b_sort_value) {
                 return 0;
             } else {
                 if ($a_sort_value > $b_sort_value) {
                     return 1 * $flip;
                 } else {
                     return -1 * $flip;
                 }
             }
         });
     }
     return $content;
 }
 public function __construct()
 {
     $this->document_root = \Craft\Craft::getPathOfAlias('webroot');
     $this->cache_dir = $this->document_root . "/cache";
     $this->cache_url = $this->makeBaseCacheUrl();
     IOHelper::ensureFolderExists($this->cache_dir);
 }
 public function InfiniteScrollFilter($paginate, $containerSelector = null, $itemSelector = null, $loadingMessage = null, $loadingImage = null, $finishedMessage = null)
 {
     if (!$containerSelector || !$itemSelector) {
         return null;
     }
     $content = '';
     if ($paginate->getNextUrl()) {
         $content .= '<div class="infinite-pagination"><a href="' . $paginate->getNextUrl() . '">' . Craft::t('Next Page') . '</a></div>';
     }
     $content .= craft()->templates->includeJsResource('infinitescroll/js/jquery.infinitescroll.min.js');
     $script = 'var totalNumOfPages = ' . $paginate->totalPages . ';';
     $script .= 'var containerSelector = "' . $containerSelector . '";';
     $script .= 'var itemSelector = "' . $itemSelector . '";';
     $loadingImage = $loadingImage ? $loadingImage : UrlHelper::getResourceUrl('infinitescroll/img/ajax-loader.gif');
     $script .= 'var loadingImage = "' . $loadingImage . '";';
     if ($loadingMessage) {
         $script .= 'var loadingMessage = "' . $loadingMessage . '";';
     }
     if ($finishedMessage) {
         $script .= 'var finishedMessage = "' . $finishedMessage . '";';
     }
     $content .= craft()->templates->includeJs($script);
     $content .= craft()->templates->includeJsResource('infinitescroll/js/infinitescroll.js');
     return $content;
 }
 public function optimizeImage($imageToOptimize)
 {
     if ($this->_settings && $this->_settings->useServerImageOptim) {
         $this->setToolAvailability();
         Craft::import('plugins.amtools.libraries.PHPImageOptim.PHPImageOptim', true);
         Craft::import('plugins.amtools.libraries.PHPImageOptim.Tools.Common', true);
         Craft::import('plugins.amtools.libraries.PHPImageOptim.Tools.ToolsInterface', true);
         $imageOptim = new \PHPImageOptim\PHPImageOptim();
         $imageOptim->setImage($imageToOptimize);
         switch (strtolower(pathinfo($imageToOptimize, PATHINFO_EXTENSION))) {
             case 'gif':
                 return $this->optimizeGif($imageOptim);
                 break;
             case 'png':
                 return $this->optimizePng($imageOptim);
                 break;
             case 'jpg':
             case 'jpeg':
                 return $this->optimizeJpeg($imageOptim);
                 break;
         }
     } elseif ($this->_settings && $this->_settings->useImagickImageOptim) {
         return $this->_optimizeAsset($imageToOptimize);
     }
     return true;
 }
 /**
  * @return ConsoleApp|WebApp
  */
 protected function getCraft()
 {
     if (!$this->craft) {
         $this->craft = Craft::app();
     }
     return $this->craft;
 }
Example #7
0
 /**
  * Exports the Craft datamodel.
  *
  * @param string $file    file to write the schema to
  * @param array  $exclude Data to not export
  *
  * @return int
  */
 public function actionIndex($file = 'craft/config/schema.yml', array $exclude = null)
 {
     $dataTypes = Schematic::getExportableDataTypes();
     // If there are data exclusions.
     if ($exclude !== null) {
         // Find any invalid data to exclude.
         $invalidExcludes = array_diff($exclude, $dataTypes);
         // If any invalid exclusions were specified.
         if (count($invalidExcludes) > 0) {
             $errorMessage = 'Invalid exlude';
             if (count($invalidExcludes) > 1) {
                 $errorMessage .= 's';
             }
             $errorMessage .= ': ' . implode(', ', $invalidExcludes) . '.';
             $errorMessage .= ' Valid exclusions are ' . implode(', ', $dataTypes);
             // Output an error message outlining what invalid exclusions were specified.
             echo "\n" . $errorMessage . "\n\n";
             return 1;
         }
         // Remove any explicitly excluded data types from the list of data types to export.
         $dataTypes = array_diff($dataTypes, $exclude);
     }
     Craft::app()->schematic->exportToYaml($file, $dataTypes);
     Craft::log(Craft::t('Exported schema to {file}', ['file' => $file]));
     return 0;
 }
Example #8
0
 /**
  * @param string $name command name (case-insensitive)
  *
  * @return \CConsoleCommand The command object. Null if the name is invalid.
  */
 public function createCommand($name)
 {
     $name = StringHelper::toLowerCase($name);
     $command = null;
     if (isset($this->commands[$name])) {
         $command = $this->commands[$name];
     } else {
         $commands = array_change_key_case($this->commands);
         if (isset($commands[$name])) {
             $command = $commands[$name];
         }
     }
     if ($command !== null) {
         if (is_string($command)) {
             $className = 'NerdsAndCompany\\Schematic\\ConsoleCommands\\' . IOHelper::getFileName($command, false);
             return new $className($name, $this);
         } else {
             // an array configuration
             return Craft::createComponent($command, $name, $this);
         }
     } elseif ($name === 'help') {
         return new \CHelpCommand('help', $this);
     } else {
         return;
     }
 }
 protected function doDisplay(array $context, array $blocks = array())
 {
     // line 1
     $context["forms"] = $this->env->loadTemplate("_includes/forms");
     // line 2
     echo "\n\n";
     // line 4
     echo $context["forms"]->gettextField(array("label" => \Craft\Craft::t("Placeholder Text"), "instructions" => \Craft\Craft::t("The text that will be shown if the field doesn’t have a value."), "id" => "placeholder", "name" => "placeholder", "value" => $this->getAttribute($this->getContext($context, "settings"), "placeholder"), "translatable" => true, "errors" => $this->getAttribute($this->getContext($context, "settings"), "getErrors", array(0 => "placeholder"), "method")));
     // line 12
     echo "\n\n";
     // line 14
     echo $context["forms"]->gettextField(array("label" => \Craft\Craft::t("Max Length"), "instructions" => \Craft\Craft::t("The maximum length of characters the field is allowed to have."), "id" => "maxLength", "name" => "maxLength", "value" => $this->getAttribute($this->getContext($context, "settings"), "maxLength"), "size" => 3, "errors" => $this->getAttribute($this->getContext($context, "settings"), "getErrors", array(0 => "maxLength"), "method")));
     // line 22
     echo "\n\n";
     // line 24
     echo $context["forms"]->getcheckboxField(array("label" => \Craft\Craft::t("Allow line breaks"), "name" => "multiline", "checked" => $this->getAttribute($this->getContext($context, "settings"), "multiline"), "toggle" => "initialRowsContainer"));
     // line 29
     echo "\n\n\n<div id=\"initialRowsContainer\" class=\"nested-fields";
     // line 32
     if (!$this->getAttribute($this->getContext($context, "settings"), "multiline")) {
         echo " hidden";
     }
     echo "\">\n\t";
     // line 33
     echo $context["forms"]->gettextField(array("label" => \Craft\Craft::t("Initial Rows"), "id" => "initialRows", "name" => "initialRows", "value" => $this->getAttribute($this->getContext($context, "settings"), "initialRows"), "size" => 3, "errors" => $this->getAttribute($this->getContext($context, "settings"), "getErrors", array(0 => "initialRows"), "method")));
     // line 40
     echo "\n</div>\n";
 }
 /**
  * {@inheritdoc}
  */
 protected function fire()
 {
     $caches = '*';
     $tool = craft()->components->getComponentByTypeAndClass(ComponentType::Tool, 'ClearCaches');
     if ($this->option('select')) {
         $reflectionMethod = new ReflectionMethod($tool, '_getFolders');
         $reflectionMethod->setAccessible(true);
         $values = $reflectionMethod->invoke($tool);
         $values['assetTransformIndex'] = Craft::t('Asset transform index');
         $values['assetIndexingData'] = Craft::t('Asset indexing data');
         $values['templateCaches'] = Craft::t('Template caches');
         $keys = array_keys($values);
         $options = array_values($values);
         $dialog = $this->getHelper('dialog');
         $selected = $dialog->select($this->output, 'Select which caches to clear (separate multiple by comma)', $options, null, false, 'Value "%s" is invalid', true);
         $caches = array();
         foreach ($selected as $index) {
             $caches[] = $keys[$index];
         }
     }
     $this->suppressOutput(function () use($tool, $caches) {
         $tool->performAction(compact('caches'));
     });
     $this->info('Cache(s) cleared.');
 }
 /**
  * Returns the requested elements as JSON
  *
  * @param callable|null $configFactory A function for generating the config
  * @param array|null    $config        The API endpoint configuration
  *
  * @throws Exception
  * @throws HttpException
  */
 public function actionGetElements($configFactory = null, array $config = null)
 {
     if ($configFactory !== null) {
         $params = craft()->urlManager->getRouteParams();
         $variables = isset($params['variables']) ? $params['variables'] : null;
         $config = $this->_callWithParams($configFactory, $variables);
     }
     // Merge in default config options
     $config = array_merge(['paginate' => true, 'pageParam' => 'page', 'elementsPerPage' => 100, 'first' => false, 'transformer' => 'Craft\\ElementApi_ElementTransformer'], craft()->config->get('defaults', 'elementapi'), $config);
     if ($config['pageParam'] == 'p') {
         throw new Exception('The pageParam setting cannot be set to "p" because that’s the parameter Craft uses to check the requested path.');
     }
     if (!isset($config['elementType'])) {
         throw new Exception('Element API configs must specify the elementType.');
     }
     /** @var ElementCriteriaModel $criteria */
     $criteria = craft()->elements->getCriteria($config['elementType'], ['limit' => null]);
     if (!empty($config['criteria'])) {
         $criteria->setAttributes($config['criteria']);
     }
     // Load Fractal
     $pluginPath = craft()->path->getPluginsPath() . 'elementapi/';
     require $pluginPath . 'vendor/autoload.php';
     $fractal = new Manager();
     $fractal->setSerializer(new ArraySerializer());
     // Define the transformer
     if (is_callable($config['transformer']) || $config['transformer'] instanceof TransformerAbstract) {
         $transformer = $config['transformer'];
     } else {
         Craft::import('plugins.elementapi.ElementApi_ElementTransformer');
         $transformer = Craft::createComponent($config['transformer']);
     }
     if ($config['first']) {
         $element = $criteria->first();
         if (!$element) {
             throw new HttpException(404);
         }
         $resource = new Item($element, $transformer);
     } else {
         if ($config['paginate']) {
             // Create the paginator
             require $pluginPath . 'ElementApi_PaginatorAdapter.php';
             $paginator = new ElementApi_PaginatorAdapter($config['elementsPerPage'], $criteria->total(), $config['pageParam']);
             // Fetch this page's elements
             $criteria->offset = $config['elementsPerPage'] * ($paginator->getCurrentPage() - 1);
             $criteria->limit = $config['elementsPerPage'];
             $elements = $criteria->find();
             $paginator->setCount(count($elements));
             $resource = new Collection($elements, $transformer);
             $resource->setPaginator($paginator);
         } else {
             $resource = new Collection($criteria, $transformer);
         }
     }
     JsonHelper::sendJsonHeaders();
     echo $fractal->createData($resource)->toJson();
     // End the request
     craft()->end();
 }
 /**
  * @param Market_OrderStatusModel $model
  * @param array $emailsIds
  *
  * @return bool
  * @throws Exception
  * @throws \CDbException
  * @throws \Exception
  */
 public function save(Market_OrderStatusModel $model, array $emailsIds)
 {
     if ($model->id) {
         $record = Market_OrderStatusRecord::model()->findById($model->id);
         if (!$record->id) {
             throw new Exception(Craft::t('No order status exists with the ID “{id}”', ['id' => $model->id]));
         }
     } else {
         $record = new Market_OrderStatusRecord();
     }
     $record->name = $model->name;
     $record->handle = $model->handle;
     $record->color = $model->color;
     $record->default = $model->default;
     $record->validate();
     $model->addErrors($record->getErrors());
     //validating emails ids
     $criteria = new \CDbCriteria();
     $criteria->addInCondition('id', $emailsIds);
     $exist = Market_EmailRecord::model()->exists($criteria);
     $hasEmails = (bool) count($emailsIds);
     if (!$exist && $hasEmails) {
         $model->addError('emails', 'One or more emails do not exist in the system.');
     }
     //saving
     if (!$model->hasErrors()) {
         MarketDbHelper::beginStackedTransaction();
         try {
             //only one default status can be among statuses of one order type
             if ($record->default) {
                 Market_OrderStatusRecord::model()->updateAll(['default' => 0]);
             }
             // Save it!
             $record->save(false);
             //Delete old links
             if ($model->id) {
                 Market_OrderStatusEmailRecord::model()->deleteAllByAttributes(['orderStatusId' => $model->id]);
             }
             //Save new links
             $rows = array_map(function ($id) use($record) {
                 return [$id, $record->id];
             }, $emailsIds);
             $cols = ['emailId', 'orderStatusId'];
             $table = Market_OrderStatusEmailRecord::model()->getTableName();
             craft()->db->createCommand()->insertAll($table, $cols, $rows);
             // Now that we have a calendar ID, save it on the model
             $model->id = $record->id;
             MarketDbHelper::commitStackedTransaction();
         } catch (\Exception $e) {
             MarketDbHelper::rollbackStackedTransaction();
             throw $e;
         }
         return true;
     } else {
         return false;
     }
 }
Example #13
0
 /**
  * @param array $data
  *
  * @return array
  */
 public function export(array $data = [])
 {
     Craft::log(Craft::t('Exporting Locales'));
     $locales = $this->getLocalizationService()->getSiteLocales();
     $localeDefinitions = [];
     foreach ($locales as $locale) {
         $localeDefinitions[] = $locale->getId();
     }
     return $localeDefinitions;
 }
 /**
  * Temporary nav until 2.5 is released.
  */
 private function initMarketNav()
 {
     if (craft()->request->isCpRequest()) {
         craft()->templates->includeCssResource('market/market-nav.css');
         craft()->templates->includeJsResource('market/market-nav.js');
         $nav = [['url' => 'market/orders', 'title' => Craft::t("Orders"), 'selected' => craft()->request->getSegment(2) == 'orders' ? true : false], ['url' => 'market/products', 'title' => Craft::t("Products"), 'selected' => craft()->request->getSegment(2) == 'products' ? true : false], ['url' => 'market/promotions', 'title' => Craft::t("Promotions"), 'selected' => craft()->request->getSegment(2) == 'promotions' ? true : false], ['url' => 'market/customers', 'title' => Craft::t("Customers"), 'selected' => craft()->request->getSegment(2) == 'customers' ? true : false], ['url' => 'market/settings', 'title' => Craft::t("Settings"), 'selected' => craft()->request->getSegment(2) == 'settings' ? true : false]];
         $navJson = JsonHelper::encode($nav);
         craft()->templates->includeJs('new Craft.MarketNav(' . $navJson . ');');
     }
 }
Example #15
0
 /**
  * @param $val
  *
  * @return null
  */
 protected function setApplication($val)
 {
     // Save the original one for tearDown()
     if (!isset($this->_originalApplication)) {
         $this->_originalApplication = craft();
     }
     // Call null to clear the app singleton.
     Craft::setApplication(null);
     // Set the new one.
     Craft::setApplication($val);
 }
 /**
  * @covers ::row
  */
 public function testRowShouldLogErrorWhenColumnsAndDataDoNotMatch()
 {
     $row = 1;
     $historyId = 2;
     $settings = array('map' => array('column1', 'column2', 'column3'), 'history' => $historyId);
     $data = array('row1value1', 'row2', 'value2', 'row3value3');
     $message = array(array(Craft::t('Columns and data did not match, could be due to malformed CSV row.')));
     $this->setMockImportHistoryService($historyId, $row, $message);
     $service = new ImportService();
     $service->row($row, $data, $settings);
 }
 protected function doDisplay(array $context, array $blocks = array())
 {
     // line 1
     $context["__internal_8bc6326091755a7238d5805374fab8e110743b6ddea9106be2b518883cdf1153"] = $this->env->loadTemplate("_includes/forms");
     // line 2
     echo "\n";
     // line 3
     echo $context["__internal_8bc6326091755a7238d5805374fab8e110743b6ddea9106be2b518883cdf1153"]->gettextField(array("label" => \Craft\Craft::t($this->getAttribute($this->getAttribute($this->getContext($context, "entry"), "getType", array(), "method"), "titleLabel")), "id" => "title", "name" => "title", "value" => $this->getAttribute($this->getContext($context, "entry"), "title"), "errors" => $this->getAttribute($this->getContext($context, "entry"), "getErrors", array(0 => "title"), "method"), "first" => true, "autofocus" => true, "required" => true));
     // line 12
     echo "\n";
 }
Example #18
0
 /**
  * @param array                $fieldDefinition
  * @param FieldModel           $field
  * @param string               $fieldHandle
  * @param FieldGroupModel|null $group
  */
 public function populate(array $fieldDefinition, FieldModel $field, $fieldHandle, FieldGroupModel $group = null)
 {
     parent::populate($fieldDefinition, $field, $fieldHandle, $group);
     $settings = $fieldDefinition['settings'];
     $defaultUploadLocationSourceId = $settings['defaultUploadLocationSource'];
     $defaultUploadLocationSource = Craft::app()->schematic_assetSources->getSourceTypeByHandle($defaultUploadLocationSourceId);
     $settings['defaultUploadLocationSource'] = $defaultUploadLocationSource ? $defaultUploadLocationSource->id : '';
     $singleUploadLocationSourceId = $settings['singleUploadLocationSource'];
     $singleUploadLocationSource = Craft::app()->schematic_assetSources->getSourceTypeByHandle($singleUploadLocationSourceId);
     $settings['singleUploadLocationSource'] = $singleUploadLocationSource ? $singleUploadLocationSource->id : '';
     $field->settings = $settings;
 }
 /**
  * Gets color palette for image
  *
  * @param AssetFileModel|string $image
  * @param $colorCount
  * @param $quality
  * @param $colorValue
  * @return array
  * @throws Exception
  */
 public function getColorPalette($image, $colorCount, $quality, $colorValue)
 {
     $pathsModel = new Imager_ImagePathsModel($image);
     if (!IOHelper::getRealPath($pathsModel->sourcePath)) {
         throw new Exception(Craft::t('Source folder “{sourcePath}” does not exist', array('sourcePath' => $pathsModel->sourcePath)));
     }
     if (!IOHelper::fileExists($pathsModel->sourcePath . $pathsModel->sourceFilename)) {
         throw new Exception(Craft::t('Requested image “{fileName}” does not exist in path “{sourcePath}”', array('fileName' => $pathsModel->sourceFilename, 'sourcePath' => $pathsModel->sourcePath)));
     }
     $palette = ColorThief::getPalette($pathsModel->sourcePath . $pathsModel->sourceFilename, $colorCount, $quality);
     return $colorValue == 'hex' ? $this->_paletteToHex($palette) : $palette;
 }
 public function authenticate()
 {
     \Craft\Craft::log(__METHOD__, \Craft\LogLevel::Info, true);
     $socialUser = \Craft\craft()->social->getSocialUserById($this->socialUserId);
     if ($socialUser) {
         $this->_id = $socialUser->user->id;
         $this->username = $socialUser->user->username;
         $this->errorCode = static::ERROR_NONE;
         return true;
     } else {
         return false;
     }
 }
 public function init()
 {
     $parcelType = $this;
     $this->craft()->on('email.beforeSendEmail', function (Event $event) use($parcelType) {
         if ($parcelType->parcel->service->is('craft')) {
             throw new \Craft\Exception(\Craft\Craft::t('You cannot override Craft system emails and use the Craft Postmaster service. To fix this error, edit your system email parcel and change the service to something other than Craft. If you cannot edit parcels in Postmaster or have no idea what a parcel or Postmaster is, it\'s probably best to contact your site administrator'));
         }
         $event->performAction = false;
         $parcelType->parse($event->params);
         $obj = new Postmaster_TransportModel(array('service' => $parcelType->parcel->service, 'settings' => $parcelType->settings, 'data' => $event->params));
         $parcelType->parcel->send($obj);
     });
 }
 private function handle(Request $request, Response $response)
 {
     $route = $request->getRoute();
     if ($route->is('GET', '/api/commerce/{me}')) {
         $customer = \Craft\craft()->commerce_customers->getCustomer();
         $response = $response->withItem($customer);
     }
     if ($route->is('GET', '/api/commerce/product')) {
         \Craft\Craft::dd($request->getCriteria());
         $products = \Craft\craft()->elements->getCriteria('Commerce_Product', $request->getCriteria())->find();
         $response = $response->withCollection($products);
     }
     return $response;
 }
Example #23
0
 /**
  * Imports the Craft datamodel.
  *
  * @param string $file          yml file containing the schema definition
  * @param string $override_file yml file containing the override values
  * @param bool   $force         if set to true items not in the import will be deleted
  *
  * @return int
  */
 public function actionIndex($file = 'craft/config/schema.yml', $override_file = 'craft/config/override.yml', $force = false)
 {
     if (!IOHelper::fileExists($file)) {
         $this->usageError(Craft::t('File not found.'));
     }
     $result = Craft::app()->schematic->importFromYaml($file, $override_file, $force);
     if (!$result->hasErrors()) {
         Craft::log(Craft::t('Loaded schema from {file}', ['file' => $file]));
         return 0;
     }
     Craft::log(Craft::t('There was an error loading schema from {file}', ['file' => $file]));
     print_r($result->getErrors());
     return 1;
 }
 protected function doDisplay(array $context, array $blocks = array())
 {
     // line 1
     $context["allLabel"] = array_key_exists("allLabel", $context) ? $this->getContext($context, "allLabel") : \Craft\Craft::t("All");
     // line 2
     $context["allValue"] = array_key_exists("allValue", $context) ? $this->getContext($context, "allValue") : "*";
     // line 3
     $context["options"] = array_key_exists("options", $context) ? $this->getContext($context, "options") : array();
     // line 4
     $context["values"] = array_key_exists("values", $context) ? $this->getContext($context, "values") : array();
     // line 5
     $context["allChecked"] = twig_test_empty($this->getContext($context, "values")) || $this->getContext($context, "values") == $this->getContext($context, "allValue");
     // line 6
     echo "\n<div class=\"checkbox-select";
     // line 7
     if (array_key_exists("class", $context)) {
         echo " ";
         echo twig_escape_filter($this->env, $this->getContext($context, "class"), "html", null, true);
     }
     echo "\">\n\t<div>\n\t\t";
     // line 9
     $this->env->loadTemplate("_includes/forms/checkbox")->display(array("id" => array_key_exists("id", $context) ? $this->getContext($context, "id") : null, "class" => "all", "label" => "<b>" . (array_key_exists("allLabel", $context) ? $this->getContext($context, "allLabel") : \Craft\Craft::t("All")) . "</b>", "name" => array_key_exists("name", $context) ? $this->getContext($context, "name") : null, "value" => $this->getContext($context, "allValue"), "checked" => $this->getContext($context, "allChecked"), "autofocus" => array_key_exists("autofocus", $context) && $this->getContext($context, "autofocus") && !$this->getAttribute($this->getAttribute($this->getContext($context, "craft"), "request"), "isMobileBrowser", array(0 => true), "method")));
     // line 18
     echo "\t</div>";
     // line 19
     $context['_parent'] = (array) $context;
     $context['_seq'] = twig_ensure_traversable($this->getContext($context, "options"));
     foreach ($context['_seq'] as $context["key"] => $context["option"]) {
         // line 20
         $context["optionLabel"] = $this->getAttribute($this->getContext($context, "option", true), "label", array(), "any", true, true) ? $this->getAttribute($this->getContext($context, "option"), "label") : $this->getContext($context, "option");
         // line 21
         $context["optionValue"] = $this->getAttribute($this->getContext($context, "option", true), "value", array(), "any", true, true) ? $this->getAttribute($this->getContext($context, "option"), "value") : $this->getContext($context, "key");
         // line 22
         if ($this->getContext($context, "optionValue") != $this->getContext($context, "allValue")) {
             // line 23
             echo "\t\t\t<div>\n\t\t\t\t";
             // line 24
             $this->env->loadTemplate("_includes/forms/checkbox")->display(array("label" => $this->getContext($context, "optionLabel"), "name" => array_key_exists("name", $context) ? $this->getContext($context, "name") . "[]" : null, "value" => $this->getContext($context, "optionValue"), "checked" => $this->getContext($context, "allChecked") || twig_in_filter($this->getContext($context, "optionValue"), $this->getContext($context, "values")), "disabled" => $this->getContext($context, "allChecked")));
             // line 31
             echo "\t\t\t</div>\n\t\t";
         }
         // line 33
         echo "\t";
     }
     $_parent = $context['_parent'];
     unset($context['_seq'], $context['_iterated'], $context['key'], $context['option'], $context['_parent'], $context['loop']);
     $context = array_intersect_key($context, $_parent) + $_parent;
     // line 34
     echo "</div>\n";
 }
 protected function doDisplay(array $context, array $blocks = array())
 {
     // line 1
     if (!array_key_exists("value", $context)) {
         // line 2
         $context["value"] = null;
     }
     // line 5
     $context["id"] = $this->getContext($context, "id") . "-date";
     // line 7
     if (array_key_exists("name", $context) && $this->getContext($context, "name")) {
         // line 8
         $context["name"] = $this->getContext($context, "name") . "[date]";
     }
     // line 11
     echo "<div class=\"datewrapper\">";
     // line 12
     $this->env->loadTemplate("_includes/forms/text")->display(array_merge($context, array("autocomplete" => false, "size" => 10, "value" => $this->getContext($context, "value") ? $this->getAttribute($this->getContext($context, "value"), "localeDate", array(), "method") : "")));
     // line 13
     echo "</div>";
     // line 15
     ob_start();
     // line 16
     echo "\n\tvar \$datePicker = \$('#";
     // line 17
     echo twig_escape_filter($this->env, twig_escape_filter($this->env, \Craft\craft()->templates->namespaceInputId($this->getContext($context, "id")), "js"), "html", null, true);
     echo "');\n\t\$datePicker.datepicker({\n\t\tconstrainInput: false,\n\t\tdateFormat: '";
     // line 20
     echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getContext($context, "craft"), "i18n"), "datepickerJsFormat"), "html", null, true);
     echo "',\n\t\tdefaultDate: new Date(";
     // line 21
     if ($this->getContext($context, "value")) {
         echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "value"), "year"), "html", null, true);
         echo ", ";
         echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "value"), "month") - 1, "html", null, true);
         echo ", ";
         echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "value"), "day"), "html", null, true);
     }
     echo "),\n\t\tprevText:   '";
     // line 22
     echo twig_escape_filter($this->env, twig_escape_filter($this->env, \Craft\Craft::t("Prev"), "js"), "html", null, true);
     echo "',\n\t\tnextText:   '";
     // line 23
     echo twig_escape_filter($this->env, twig_escape_filter($this->env, \Craft\Craft::t("Next"), "js"), "html", null, true);
     echo "',\n\t});";
     $context["js"] = '' === ($tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
     // line 27
     \Craft\craft()->templates->includeJs($this->getContext($context, "js"));
 }
Example #26
0
 /**
  * Autoload Files
  *
  * @return void
  */
 public function autoload_files()
 {
     $autoload = craft()->config->get('autoload', 'restfulApi');
     if ($autoload['transformers']) {
         Craft::import('plugins.*.transformers.*', true);
     } else {
         Craft::import('plugins.restfulapi.transformers.*', true);
     }
     if ($autoload['validators']) {
         Craft::import('plugins.*.validators.*', true);
     } else {
         Craft::import('plugins.restfulapi.validators.*', true);
     }
     Craft::import('plugins.restfulapi.vendor.autoload', true);
 }
 /**
  * Perform our clean up task. Remove any orphan assets from our crop source.
  */
 public function cleanUp()
 {
     $plugin = craft()->plugins->getPlugin('ImageCropper');
     $settings = $plugin->getSettings();
     $sourceId = $settings->source;
     $assets = craft()->assets->getFilesBySourceId($sourceId);
     $validAssetIds = craft()->db->createCommand()->selectDistinct('targetId')->from('relations')->query();
     $targetIds = array();
     foreach ($validAssetIds as $idArr) {
         $targetIds[] = $idArr['targetId'];
     }
     $task = craft()->tasks->createTask('ImageCropper', 'Cleaning up images', array('assets' => $assets, 'validAssetIds' => $targetIds));
     $taskSuccessful = craft()->tasks->runTask($task);
     if (!$taskSuccessful) {
         Craft::log('Unable to complete ImageCropperTask. Some failure occurred.');
     }
 }
 public function save(Market_OrderSettingsModel $orderSettings)
 {
     if ($orderSettings->id) {
         $orderSettingsRecord = Market_OrderSettingsRecord::model()->findById($orderSettings->id);
         if (!$orderSettingsRecord) {
             throw new Exception(Craft::t('No order settings exists with the ID “{id}”', ['id' => $orderSettings->id]));
         }
         $oldOrderSettings = Market_OrderSettingsModel::populateModel($orderSettingsRecord);
         $isNewOrderSettings = false;
     } else {
         $orderSettingsRecord = new Market_OrderSettingsRecord();
         $isNewOrderSettings = true;
     }
     $orderSettingsRecord->name = $orderSettings->name;
     $orderSettingsRecord->handle = $orderSettings->handle;
     $orderSettingsRecord->validate();
     $orderSettings->addErrors($orderSettingsRecord->getErrors());
     if (!$orderSettings->hasErrors()) {
         MarketDbHelper::beginStackedTransaction();
         try {
             if (!$isNewOrderSettings && $oldOrderSettings->fieldLayoutId) {
                 // Drop the old field layout
                 craft()->fields->deleteLayoutById($oldOrderSettings->fieldLayoutId);
             }
             // Save the new one
             $fieldLayout = $orderSettings->getFieldLayout();
             craft()->fields->saveLayout($fieldLayout);
             // Update the calendar record/model with the new layout ID
             $orderSettings->fieldLayoutId = $fieldLayout->id;
             $orderSettingsRecord->fieldLayoutId = $fieldLayout->id;
             // Save it!
             $orderSettingsRecord->save(false);
             // Now that we have a calendar ID, save it on the model
             if (!$orderSettings->id) {
                 $orderSettings->id = $orderSettingsRecord->id;
             }
             MarketDbHelper::commitStackedTransaction();
         } catch (\Exception $e) {
             MarketDbHelper::rollbackStackedTransaction();
             throw $e;
         }
         return true;
     } else {
         return false;
     }
 }
 public function block_sidebar($context, array $blocks = array())
 {
     // line 17
     echo "\t";
     if (twig_length_filter($this->env, $this->getContext($context, "newEntrySections"))) {
         // line 18
         echo "\t\t<div class=\"buttons\">\n\t\t\t";
         // line 19
         if (twig_length_filter($this->env, $this->getContext($context, "newEntrySections")) > 1) {
             // line 20
             echo "\t\t\t\t<div class=\"btn submit menubtn add icon\">";
             echo twig_escape_filter($this->env, \Craft\Craft::t("New Entry"), "html", null, true);
             echo "</div>\n\t\t\t\t<div class=\"menu\">\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t";
             // line 23
             $context['_parent'] = (array) $context;
             $context['_seq'] = twig_ensure_traversable($this->getContext($context, "newEntrySections"));
             foreach ($context['_seq'] as $context["_key"] => $context["section"]) {
                 // line 24
                 echo "\t\t\t\t\t\t\t<li><a href=\"";
                 echo twig_escape_filter($this->env, \Craft\UrlHelper::getUrl("entries/" . $this->getAttribute($this->getContext($context, "section"), "handle") . "/new"), "html", null, true);
                 echo "\">";
                 echo twig_escape_filter($this->env, \Craft\Craft::t($this->getAttribute($this->getContext($context, "section"), "name")), "html", null, true);
                 echo "</a></li>\n\t\t\t\t\t\t";
             }
             $_parent = $context['_parent'];
             unset($context['_seq'], $context['_iterated'], $context['_key'], $context['section'], $context['_parent'], $context['loop']);
             $context = array_intersect_key($context, $_parent) + $_parent;
             // line 26
             echo "\t\t\t\t\t</ul>\n\t\t\t\t</div>\n\t\t\t";
         } else {
             // line 29
             echo "\t\t\t\t<a class=\"btn submit add icon\" href=\"";
             echo twig_escape_filter($this->env, \Craft\UrlHelper::getUrl("entries/" . $this->getAttribute($this->getAttribute($this->getContext($context, "newEntrySections"), 0, array(), "array"), "handle") . "/new"), "html", null, true);
             echo "\">";
             echo twig_escape_filter($this->env, \Craft\Craft::t("New Entry"), "html", null, true);
             echo "</a>\n\t\t\t";
         }
         // line 31
         echo "\t\t</div>\n\t";
     }
     // line 33
     echo "\n\t";
     // line 34
     $this->displayParentBlock("sidebar", $context, $blocks);
     echo "\n";
 }
Example #30
0
 /**
  * Attempt to import user settings.
  *
  * @param array $user_settings
  * @param bool  $force         If set to true user settings not included in the import will be deleted
  *
  * @return Result
  */
 public function import(array $user_settings, $force = true)
 {
     Craft::log(Craft::t('Importing Users'));
     // always delete existing fieldlayout first
     Craft::app()->fields->deleteLayoutsByType(ElementType::User);
     if (isset($user_settings['fieldLayout'])) {
         $fieldLayoutDefinition = (array) $user_settings['fieldLayout'];
     } else {
         $fieldLayoutDefinition = [];
     }
     $fieldLayout = Craft::app()->schematic_fields->getFieldLayout($fieldLayoutDefinition);
     $fieldLayout->type = ElementType::User;
     if (!Craft::app()->fields->saveLayout($fieldLayout)) {
         // Save fieldlayout via craft
         $this->addErrors($fieldLayout->getAllErrors());
     }
     return $this->getResultModel();
 }