/** * Upload a logo for the admin panel. */ public function actionUploadLogo() { $this->requireAjaxRequest(); $this->requireAdmin(); // Upload the file and drop it in the temporary folder $uploader = new \qqFileUploader(); try { // Make sure a file was uploaded if ($uploader->file && $uploader->file->getSize()) { $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); $fileName = IOHelper::cleanFilename($uploader->file->getName()); $uploader->file->save($folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->setMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } craft()->images->cleanImage($folderPath . $fileName); $constraint = 500; list($width, $height) = getimagesize($folderPath . $fileName); // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
/** * 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();'); } }
/** * Load Required Scripts * */ public function includeScripts($form) { // Ajax Submit Script if ($form->formSettings["ajaxSubmit"] == "1") { craft()->templates->includeJsFile(UrlHelper::getResourceUrl('formbuilder2/js/ajaxsubmit.js')); } $fieldLayout = $form->fieldLayout->getFieldLayout(); $fields = $fieldLayout->getFields(); foreach ($fields as $key => $value) { $field = $value->getField(); if ($field->type == 'Color') { // Colorpicker craft()->templates->includeCssFile(UrlHelper::getResourceUrl('formbuilder2/css/libs/colorpicker.css')); craft()->templates->includeJsFile(UrlHelper::getResourceUrl('formbuilder2/js/libs/colorpicker.js')); } elseif ($field->type == 'Date') { // Date & Time Picker craft()->templates->includeJsFile(UrlHelper::getResourceUrl('/lib/jquery-ui.min.js')); craft()->templates->includeJsFile(UrlHelper::getResourceUrl('lib/jquery.timepicker/jquery.timepicker.min.js')); craft()->templates->includeCssFile(UrlHelper::getResourceUrl('formbuilder2/css/libs/datetimepicker.css')); } elseif ($field->type == 'RichText') { // WYSIWYG Editor craft()->templates->includeCssResource('/lib/redactor/redactor.css'); craft()->templates->includeJsResource('/lib/redactor/redactor.min.js'); } elseif ($field->type == 'Lightswitch') { // Lightswitch craft()->templates->includeCssFile(UrlHelper::getResourceUrl('formbuilder2/css/libs/lightswitch.css')); } } return; }
protected function includeJs() { $settings = craft()->plugins->getPlugin('npCloudinary')->getSettings(); $cloudinaryResource = UrlHelper::getResourceUrl('npcloudinary/js/cloudinary-jquery.min.js'); craft()->templates->includeJsFile($cloudinaryResource); craft()->templates->includeJs('$.cloudinary.config({ cloud_name: "' . $settings['cloudName'] . '", api_key: "' . $settings['apiKey'] . '"});'); craft()->templates->includeJs('$.cloudinary.responsive();'); }
function init() { if (craft()->request->isCpRequest()) { craft()->templates->includeHeadHtml('<link rel="shortcut icon" type="image/x-icon" href="' . UrlHelper::getResourceUrl('dashboardicons/favicon.ico') . '">'); craft()->templates->includeHeadHtml('<link rel="apple-touch-icon" href="' . UrlHelper::getResourceUrl('dashboardicons/apple-touch-icon.png') . '">'); craft()->templates->includeHeadHtml('<link rel="apple-touch-icon" sizes="76x76" href="' . UrlHelper::getResourceUrl('dashboardicons/apple-touch-icon-76x76.png') . '">'); craft()->templates->includeHeadHtml('<link rel="apple-touch-icon" sizes="120x120" href="' . UrlHelper::getResourceUrl('dashboardicons/apple-touch-icon-120x120.png') . '">'); craft()->templates->includeHeadHtml('<link rel="apple-touch-icon" sizes="152x152" href="' . UrlHelper::getResourceUrl('dashboardicons/apple-touch-icon-152x152.png') . '">'); craft()->templates->includeHeadHtml('<link rel="mask-icon" href="' . UrlHelper::getResourceUrl('dashboardicons/mask-icon.svg') . '" color="#DA5A47">'); } }
public function init() { parent::init(); if (!craft()->isConsole()) { if (craft()->request->isCpRequest() && craft()->request->getSegment(1) == 'mailer') { //Include JS craft()->templates->includeJsFile(UrlHelper::getResourceUrl('mailer/mailer.js')); //Turn Profiler off craft()->log->removeRoute('WebLogRoute'); craft()->log->removeRoute('ProfileLogRoute'); } } }
function init() { if (craft()->request->isCpRequest()) { // Check if IE7 - 9 if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(?i)msie [7-9]/', $_SERVER['HTTP_USER_AGENT'])) { // Extend History API craft()->templates->includeFootHtml('<script type="text/javascript" src="' . UrlHelper::getResourceUrl('compatibility/js/native.history.js') . '"></script>'); craft()->templates->includeFootHtml('<script type="text/javascript">var history = History;</script>'); // CSS fixes craft()->templates->includeCssResource('compatibility/css/style.css'); } } }
/** * Upload a logo for the admin panel. * * @return null */ public function actionUploadSiteImage() { $this->requireAjaxRequest(); $this->requireAdmin(); $type = craft()->request->getRequiredPost('type'); if (!in_array($type, $this->_allowedTypes)) { $this->returnErrorJson(Craft::t('That is not an accepted site image type.')); } // Upload the file and drop it in the temporary folder $file = UploadedFile::getInstanceByName('image-upload'); try { // Make sure a file was uploaded if ($file) { $fileName = AssetsHelper::cleanAssetName($file->getName()); if (!ImageHelper::isImageManipulatable($file->getExtensionName())) { throw new Exception(Craft::t('The uploaded file is not an image.')); } $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); move_uploaded_file($file->getTempName(), $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName); if (IOHelper::getExtension($fileName) != 'svg') { craft()->images->cleanImage($folderPath . $fileName); } else { craft()->images->loadImage($folderPath . $fileName)->saveAs($folderPath . $fileName); } $constraint = 500; // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint, 'fileName' => $fileName)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
/** * Upload a logo for the admin panel. * * @return null */ public function actionUploadLogo() { $this->requireAjaxRequest(); $this->requireAdmin(); // Upload the file and drop it in the temporary folder $file = $_FILES['image-upload']; try { // Make sure a file was uploaded if (!empty($file['name']) && !empty($file['size'])) { $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); $fileName = AssetsHelper::cleanAssetName($file['name']); move_uploaded_file($file['tmp_name'], $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName); if (IOHelper::getExtension($fileName) != 'svg') { craft()->images->cleanImage($folderPath . $fileName); } else { // Resave svg files as png $newFilename = preg_replace('/\\.svg$/i', '.png', $fileName); craft()->images->loadImage($folderPath . $fileName, $width, $height)->saveAs($folderPath . $newFilename); IOHelper::deleteFile($folderPath . $fileName); $fileName = $newFilename; } $constraint = 500; // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint, 'fileName' => $fileName)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
public function getInputHtml($name, $value) { // Settings $settings = $this->getSettings(); $aceBasePath = UrlHelper::getResourceUrl('aceeditor/vendor/ace/'); $inputId = craft()->templates->formatInputId($name); // Data $data = (include CRAFT_PLUGINS_PATH . 'aceeditor/data/AceEditorData.php'); // Resources craft()->templates->includeCssResource('aceeditor/stylesheets/editor.css'); craft()->templates->includeJsFile('https://cloud9ide.github.io/emmet-core/emmet.js'); craft()->templates->includeJsResource('aceeditor/vendor/ace/ace.js'); craft()->templates->includeJsResource('aceeditor/vendor/ace/theme-twilight.js'); craft()->templates->includeJsResource('aceeditor/vendor/ace/ext-emmet.js'); craft()->templates->includeJsResource('aceeditor/vendor/ace/ext-language_tools.js'); craft()->templates->includeJsResource('aceeditor/javascripts/editor.js'); craft()->templates->includeJs('new Craft.AceEditorFT("' . craft()->templates->namespaceInputId($inputId) . '","' . $aceBasePath . '",' . JsonHelper::encode($settings) . ');'); // Template return craft()->templates->render('aceeditor/_fieldtype/index', array("name" => $name, "id" => $inputId, "value" => $value, "settings" => $settings, "modes" => $data['modes'])); }
public function init() { parent::init(); require_once "vendor/class.rc4crypt.php"; require_once "vendor/foxycart.cart_validation.php"; $settings = craft()->plugins->getPlugin('foxycart')->getSettings(); \FoxyCart_Helper::setSecret($settings->apikey); \FoxyCart_Helper::setCartUrl("https://" . $settings->storedomain . "/cart"); if (craft()->request->isCpRequest()) { craft()->templates->includeCssFile(UrlHelper::getResourceUrl('foxycart/css/foxycart.css')); } craft()->on('users.onSaveUser', function (Event $event) { if (craft()->getEdition() == Craft::Pro) { $customerId = craft()->foxyCart->updateFoxyCartCustomer($event->params['user']); if ($customerId) { craft()->foxyCart->saveCustomerId($event->params['user'], $customerId); } } }); }
/** * @access private * @param $match * @return string */ private function _normalizeCssUrl($match) { // ignore root-relative, absolute, and data: URLs if (preg_match('/^(\\/|https?:\\/\\/|data:)/', $match[3])) { return $match[0]; } $url = IOHelper::getFolderName(craft()->request->getPath()) . $match[3]; // Make sure this is a resource URL $resourceTrigger = craft()->config->get('resourceTrigger'); $resourceTriggerPos = strpos($url, $resourceTrigger); if ($resourceTriggerPos !== false) { // Give UrlHelper a chance to add the timestamp $path = substr($url, $resourceTriggerPos + strlen($resourceTrigger)); $url = UrlHelper::getResourceUrl($path); } return $match[1] . $url . $match[4]; }
/** * Get URL for a file. * * @param AssetFileModel $file * @param string $transform * * @return string */ public function getUrlForFile(AssetFileModel $file, $transform = null) { if (!$transform || !ImageHelper::isImageManipulatable(IOHelper::getExtension($file->filename))) { $sourceType = craft()->assetSources->getSourceTypeById($file->sourceId); return AssetsHelper::generateUrl($sourceType, $file); } // Get the transform index model $index = craft()->assetTransforms->getTransformIndex($file, $transform); // Does the file actually exist? if ($index->fileExists) { return craft()->assetTransforms->getUrlForTransformByTransformIndex($index); } else { if (craft()->config->get('generateTransformsBeforePageLoad')) { // Mark the transform as in progress $index->inProgress = true; craft()->assetTransforms->storeTransformIndexData($index); // Generate the transform craft()->assetTransforms->generateTransform($index); // Update the index $index->fileExists = true; craft()->assetTransforms->storeTransformIndexData($index); // Return the transform URL return craft()->assetTransforms->getUrlForTransformByTransformIndex($index); } else { // Queue up a new Generate Pending Transforms task, if there isn't one already if (!craft()->tasks->areTasksPending('GeneratePendingTransforms')) { craft()->tasks->createTask('GeneratePendingTransforms'); } // Return the temporary transform URL return UrlHelper::getResourceUrl('transforms/' . $index->id); } } }
/** * Returns a source by its ID. * * @param int $sourceId * * @return AssetSourceModel|null */ public function getSourceById($sourceId) { // Temporary source? if (is_null($sourceId)) { $source = new AssetSourceModel(); $source->id = $sourceId; $source->name = TempAssetSourceType::sourceName; $source->type = TempAssetSourceType::sourceType; $source->settings = array('path' => craft()->path->getAssetsTempSourcePath(), 'url' => rtrim(UrlHelper::getResourceUrl(), '/') . '/tempassets/'); return $source; } else { // If we've already fetched all sources we can save ourselves a trip to the DB for source IDs that don't // exist if (!$this->_fetchedAllSources && (!isset($this->_sourcesById) || !array_key_exists($sourceId, $this->_sourcesById))) { $result = $this->_createSourceQuery()->where('id = :id', array(':id' => $sourceId))->queryRow(); if ($result) { $source = $this->_populateSource($result); } else { $source = null; } $this->_sourcesById[$sourceId] = $source; } if (!empty($this->_sourcesById[$sourceId])) { return $this->_sourcesById[$sourceId]; } } }
/** * Upload a user photo. * * @return null */ public function actionUploadUserPhoto() { $this->requireAjaxRequest(); craft()->userSession->requireLogin(); $userId = craft()->request->getRequiredPost('userId'); if ($userId != craft()->userSession->getUser()->id) { craft()->userSession->requirePermission('editUsers'); } // Upload the file and drop it in the temporary folder $file = $_FILES['image-upload']; try { // Make sure a file was uploaded if (!empty($file['name']) && !empty($file['size'])) { $user = craft()->users->getUserById($userId); $userName = AssetsHelper::cleanAssetName($user->username, false); $folderPath = craft()->path->getTempUploadsPath() . 'userphotos/' . $userName . '/'; IOHelper::clearFolder($folderPath); IOHelper::ensureFolderExists($folderPath); $fileName = AssetsHelper::cleanAssetName($file['name']); move_uploaded_file($file['tmp_name'], $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } craft()->images->cleanImage($folderPath . $fileName); $constraint = 500; list($width, $height) = getimagesize($folderPath . $fileName); // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('userphotos/temp/' . $userName . '/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { Craft::log('There was an error uploading the photo: ' . $exception->getMessage(), LogLevel::Error); } $this->returnErrorJson(Craft::t('There was an error uploading your photo.')); }
/** * Get URL for a file. * * @param AssetFileModel $file * @param $transform * @return string */ public function getUrlForFile(AssetFileModel $file, $transform = null) { $returnPlaceholder = false; if (!$transform || !in_array(IOHelper::getExtension($file->filename), ImageHelper::getAcceptedExtensions())) { $sourceType = craft()->assetSources->getSourceTypeById($file->sourceId); $base = $sourceType->getBaseUrl(); return $base . $file->getFolder()->fullPath . $file->filename; } // Get the transform index model $existingTransformData = craft()->assetTransforms->getTransformIndex($file, $transform); // Does the file actually exist? if ($existingTransformData->fileExists) { return craft()->assetTransforms->getUrlforTransformByFile($file, $transform); } else { // File doesn't exist yet - load the TransformLoader and set the placeholder URL flag $placeholderUrl = UrlHelper::getResourceUrl('images/blank.gif'); if (!$this->_includedTransformLoader) { $entityPlaceholderUrl = htmlspecialchars($placeholderUrl, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); $spinnerUrl = UrlHelper::getResourceurl('images/spinner_transform.gif'); $actionUrl = UrlHelper::getActionUrl('assets/generateTransform'); craft()->templates->includeJsResource('js/TransformLoader.js'); craft()->templates->includeJs('new TransformLoader(' . JsonHelper::encode($placeholderUrl) . ', ' . JsonHelper::encode($entityPlaceholderUrl) . ', ' . JsonHelper::encode($spinnerUrl) . ', ' . JsonHelper::encode($actionUrl) . ');'); $this->_includedTransformLoader = true; } return $placeholderUrl . '#' . $existingTransformData->id; } }
/** * Upload a user photo. * * @return null */ public function actionUploadUserPhoto() { $this->requireAjaxRequest(); craft()->userSession->requireLogin(); $userId = craft()->request->getRequiredPost('userId'); if ($userId != craft()->userSession->getUser()->id) { craft()->userSession->requirePermission('editUsers'); } // Upload the file and drop it in the temporary folder $file = UploadedFile::getInstanceByName('image-upload'); try { // Make sure a file was uploaded if ($file) { $fileName = AssetsHelper::cleanAssetName($file->getName()); if (!ImageHelper::isImageManipulatable($file->getExtensionName())) { throw new Exception(Craft::t('The uploaded file is not an image.')); } $user = craft()->users->getUserById($userId); $userName = AssetsHelper::cleanAssetName($user->username, false); $folderPath = craft()->path->getTempUploadsPath() . 'userphotos/' . $userName . '/'; IOHelper::clearFolder($folderPath); IOHelper::ensureFolderExists($folderPath); move_uploaded_file($file->getTempName(), $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } craft()->images->loadImage($folderPath . $fileName)->scaleToFit(500, 500, false)->saveAs($folderPath . $fileName); list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName); // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('userphotos/temp/' . $userName . '/' . $fileName), 'width' => $width, 'height' => $height, 'fileName' => $fileName)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo.')); }
/** * @inheritDoc BaseElementModel::getThumbUrl() * * @param int $size * * @return false|null|string */ public function getThumbUrl($size = 100) { $url = $this->getPhotoUrl($size); if (!$url) { $url = UrlHelper::getResourceUrl('defaultuserphoto'); } return $url; }
/** * Return the URL to the logo. * * @return string|null */ public function getUrl() { return UrlHelper::getResourceUrl('logo/' . IOHelper::getFileName($this->path)); }
public function getInputHtml($name, $value) { if (isset($this->element)) { $id = craft()->templates->formatInputId($name); $namespacedId = craft()->templates->namespaceInputId($id); // Include our Javascript & CSS craft()->templates->includeCssResource('seomatic/css/css-reset.css'); craft()->templates->includeCssResource('seomatic/css/prism.min.css'); craft()->templates->includeCssResource('seomatic/css/bootstrap-tokenfield.css'); craft()->templates->includeCssResource('seomatic/css/style.css'); craft()->templates->includeCssResource('seomatic/css/field.css'); craft()->templates->includeJsResource('seomatic/js/field.js'); craft()->templates->includeJsResource('seomatic/js/jquery.bpopup.min.js'); craft()->templates->includeJsResource('seomatic/js/prism.min.js'); craft()->templates->includeJsResource('seomatic/js/bootstrap-tokenfield.min.js'); $variables = array('id' => $id, 'name' => $name, 'meta' => $value, 'element' => $this->element, 'field' => $this->model); $jsonVars = array('id' => $id, 'name' => $name, 'namespace' => $namespacedId, 'prefix' => craft()->templates->namespaceInputId("")); if (isset($variables['locale'])) { $locale = $variables['locale']; } else { $locale = craft()->language; } $siteMeta = craft()->seomatic->getSiteMeta($locale); $titleLength = craft()->config->get("maxTitleLength", "seomatic"); if ($siteMeta['siteSeoTitlePlacement'] == "none") { $variables['titleLength'] = $titleLength; } else { $variables['titleLength'] = $titleLength - strlen(" | ") - strlen($siteMeta['siteSeoName']); } /* -- Prep some parameters */ // Whether any assets sources exist $sources = craft()->assets->findFolders(); $variables['assetsSourceExists'] = count($sources); // URL to create a new assets source $variables['newAssetsSourceUrl'] = UrlHelper::getUrl('settings/assets/sources/new'); // Set asset ID $variables['seoImageId'] = $variables['meta']->seoImageId; // Set asset elements if ($variables['seoImageId']) { if (is_array($variables['seoImageId'])) { $variables['seoImageId'] = $variables['seoImageId'][0]; } $asset = craft()->elements->getElementById($variables['seoImageId']); $variables['elements'] = array($asset); } else { $variables['elements'] = array(); } // Set element type $variables['elementType'] = craft()->elements->getElementType(ElementType::Asset); $variables['assetSources'] = $this->getSettings()->assetSources; $variables['seoTitleSourceChangeable'] = $this->getSettings()->seoTitleSourceChangeable; $variables['seoDescriptionSourceChangeable'] = $this->getSettings()->seoDescriptionSourceChangeable; $variables['seoKeywordsSourceChangeable'] = $this->getSettings()->seoKeywordsSourceChangeable; $variables['seoImageIdSourceChangeable'] = $this->getSettings()->seoImageIdSourceChangeable; $variables['twitterCardTypeChangeable'] = $this->getSettings()->twitterCardTypeChangeable; $variables['openGraphTypeChangeable'] = $this->getSettings()->openGraphTypeChangeable; $variables['robotsChangeable'] = $this->getSettings()->robotsChangeable; /* -- Extract a list of the other plain text fields that are in this entry's layout */ $fieldList = array('title' => 'Title'); $fieldData = array('title' => $this->element->content['title']); $fieldImage = array(); $imageFieldList = array(); $fieldLayouts = $this->element->fieldLayout->getFields(); foreach ($fieldLayouts as $fieldLayout) { $field = craft()->fields->getFieldById($fieldLayout->fieldId); switch ($field->type) { case "PlainText": case "RichText": case "RedactorI": $fieldList[$field->handle] = $field->name; $fieldData[$field->handle] = craft()->seomatic->truncateStringOnWord(strip_tags($this->element->content[$field->handle]), 200); break; case "Matrix": $fieldList[$field->handle] = $field->name; $fieldData[$field->handle] = craft()->seomatic->truncateStringOnWord(craft()->seomatic->extractTextFromMatrix($this->element[$field->handle]), 200); break; case "Tags": $fieldList[$field->handle] = $field->name; $fieldData[$field->handle] = craft()->seomatic->truncateStringOnWord(craft()->seomatic->extractTextFromTags($this->element[$field->handle]), 200); break; case "Assets": $imageFieldList[$field->handle] = $field->name; $img = $this->element[$field->handle]->first(); if ($img) { $fieldImage[$field->handle] = $img->url; } break; } } $variables['fieldList'] = $fieldList; $variables['imageFieldList'] = $imageFieldList; $variables['elementId'] = $this->element->id; $jsonVars['fieldData'] = $fieldData; $jsonVars['fieldImage'] = $fieldImage; $jsonVars['missing_image'] = UrlHelper::getResourceUrl('seomatic/images/missing_image.png'); $jsonVars = json_encode($jsonVars); craft()->templates->includeJs("\$('#{$namespacedId}').SeomaticFieldType(" . $jsonVars . ");"); return craft()->templates->render('seomatic/field', $variables); } }
/** * Returns a user image from a user ID for given size. Default size is 48. * * @param int $userId * @param int $size * @return string|null */ public function getUserImageUrl($userId, $size = 48) { return UrlHelper::getResourceUrl('twitteruserimages/' . $userId . '/' . $size); }
function pluginStyles() { return craft()->templates->includeJsFile(UrlHelper::getResourceUrl('formbuilder/css/formbuilder-form.css')); }
/** * Ends a template cache. * * @param string $key The template cache key. * @param bool $global Whether the cache should be stored globally. * @param string|null $duration How long the cache should be stored for. * @param mixed|null $expiration When the cache should expire. * @param string $body The contents of the cache. * * @throws \Exception * @return null */ public function endTemplateCache($key, $global, $duration, $expiration, $body) { // If there are any transform generation URLs in the body, don't cache it if (strpos($body, UrlHelper::getResourceUrl('transforms'))) { return; } // Figure out the expiration date if ($duration) { $expiration = new DateTime($duration); } if (!$expiration) { $duration = craft()->config->getCacheDuration(); if ($duration <= 0) { $duration = 31536000; // 1 year } $duration += time(); $expiration = new DateTime('@' . $duration); } // Save it $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { craft()->db->createCommand()->insert(static::$_templateCachesTable, array('cacheKey' => $key, 'locale' => craft()->language, 'path' => $global ? null : $this->_getPath(), 'expiryDate' => DateTimeHelper::formatTimeForDb($expiration), 'body' => $body), false); $cacheId = craft()->db->getLastInsertID(); // Tag it with any element criteria that were output within the cache if (!empty($this->_cacheCriteria[$key])) { $values = array(); foreach ($this->_cacheCriteria[$key] as $criteria) { $flattenedCriteria = $criteria->getAttributes(null, true); $values[] = array($cacheId, $criteria->getElementType()->getClassHandle(), JsonHelper::encode($flattenedCriteria)); } craft()->db->createCommand()->insertAll(static::$_templateCacheCriteriaTable, array('cacheId', 'type', 'criteria'), $values, false); unset($this->_cacheCriteria[$key]); } // Tag it with any element IDs that were output within the cache if (!empty($this->_cacheElementIds[$key])) { $values = array(); foreach ($this->_cacheElementIds[$key] as $elementId) { $values[] = array($cacheId, $elementId); } craft()->db->createCommand()->insertAll(static::$_templateCacheElementsTable, array('cacheId', 'elementId'), $values, false); unset($this->_cacheElementIds[$key]); } if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } }
/** * Gets the widget's body HTML. * * @return string */ public function getBodyHtml() { return '<div style="margin: 0 -30px -30px;">' . '<img style="display: block; width: 100%;" src="' . UrlHelper::getResourceUrl('images/prg.jpg') . '">' . '</div>'; }
/** * Returns a given plugin’s icon URL. * * @param string $pluginHandle The plugin’s class handle * @param int $size The size of the icon * * @return string */ public function getPluginIconUrl($pluginHandle, $size = 100) { $lcHandle = StringHelper::toLowerCase($pluginHandle); $iconPath = craft()->path->getPluginsPath() . $lcHandle . '/resources/icon.svg'; if (IOHelper::fileExists($iconPath)) { return UrlHelper::getResourceUrl($lcHandle . '/icon.svg'); } else { return UrlHelper::getResourceUrl('images/default_plugin.svg'); } }
/** * @param $match * * @return string */ private function _normalizeCssUrl($match) { // Ignore root-relative, absolute, and data: URLs if (preg_match('/^(\\/|https?:\\/\\/|data:)/', $match[3])) { return $match[0]; } // Clean up any relative folders at the beginning of the CSS URL $requestFolder = IOHelper::getFolderName(craft()->request->getPath()); $requestFolderParts = array_filter(explode('/', $requestFolder)); $cssUrlParts = array_filter(explode('/', $match[3])); while (isset($cssUrlParts[0]) && $cssUrlParts[0] == '..' && $requestFolderParts) { array_pop($requestFolderParts); array_shift($cssUrlParts); } $pathParts = array_merge($requestFolderParts, $cssUrlParts); $path = implode('/', $pathParts); $url = UrlHelper::getUrl($path); // Is this going to be a resource URL? $rootResourceUrl = UrlHelper::getUrl(craft()->config->getResourceTrigger()) . '/'; $rootResourceUrlLength = strlen($rootResourceUrl); if (strncmp($rootResourceUrl, $url, $rootResourceUrlLength) === 0) { // Isolate the relative resource path $resourcePath = substr($url, $rootResourceUrlLength); // Give UrlHelper a chance to add the timestamp $url = UrlHelper::getResourceUrl($resourcePath); } // Return the normalized CSS URL declaration return $match[1] . $url . $match[4]; }
/** * @inheritDoc BaseElementModel::getThumbUrl() * * @param int $size * * @return string|null */ public function getThumbUrl($size = 125) { if ($this->hasThumb()) { return UrlHelper::getResourceUrl('assetthumbs/' . $this->id . '/' . $size, array(craft()->resources->dateParam => $this->dateModified->getTimestamp())); } else { return UrlHelper::getResourceUrl('icons/' . $this->getExtension()); } }
/** * @inheritDoc BaseElementModel::getIconUrl() * * @param int $size * * @return string */ public function getIconUrl($size = 125) { if ($this->hasThumb()) { return false; } else { return UrlHelper::getResourceUrl('icons/' . $this->getExtension() . '/' . $size); } }
/** * Prepares a JS file from resources/ for inclusion in the template. * * @param string $path The resource path to the JS file. * @param bool $first Whether the JS file should be included before any other JS files that were already * included with this method. * * @return null */ public function includeJsResource($path, $first = false) { $url = UrlHelper::getResourceUrl($path); $this->includeJsFile($url, $first); }
/** * Returns the URL to a rebrand image. * * @param $path * @param $type * * @return string */ private function _getImageUrl($path, $type) { return UrlHelper::getResourceUrl('rebrand/' . $type . '/' . IOHelper::getFileName($path)); }