/**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Moving the logo from storage/logo to storage/rebrand/logo', LogLevel::Info, true);
     IOHelper::rename(craft()->path->getStoragePath() . 'logo', craft()->path->getRebrandPath() . 'logo', true);
     Craft::log('Done moving the logo from storage/logo to storage/rebrand/logo', LogLevel::Info, true);
     return true;
 }
Ejemplo n.º 2
0
 /**
  * Initializes the console app by creating the command runner.
  *
  * @return null
  */
 public function init()
 {
     // Set default timezone to UTC
     date_default_timezone_set('UTC');
     // Import all the built-in components
     foreach ($this->componentAliases as $alias) {
         Craft::import($alias);
     }
     // Attach our Craft app behavior.
     $this->attachBehavior('AppBehavior', new AppBehavior());
     // Initialize Cache and LogRouter right away (order is important)
     $this->getComponent('cache');
     $this->getComponent('log');
     // So we can try to translate Yii framework strings
     $this->coreMessages->attachEventHandler('onMissingTranslation', array('Craft\\LocalizationHelper', 'findMissingTranslation'));
     // Set our own custom runtime path.
     $this->setRuntimePath(craft()->path->getRuntimePath());
     // Attach our own custom Logger
     Craft::setLogger(new Logger());
     // No need for these.
     craft()->log->removeRoute('WebLogRoute');
     craft()->log->removeRoute('ProfileLogRoute');
     // Load the plugins
     craft()->plugins->loadPlugins();
     // Validate some basics on the database configuration file.
     craft()->validateDbConfigFile();
     // Call parent::init before the plugin console command logic so craft()->commandRunner will be available to us.
     parent::init();
     foreach (craft()->plugins->getPlugins() as $plugin) {
         $commandsPath = craft()->path->getPluginsPath() . StringHelper::toLowerCase($plugin->getClassHandle()) . '/consolecommands/';
         if (IOHelper::folderExists($commandsPath)) {
             craft()->commandRunner->addCommands(rtrim($commandsPath, '/'));
         }
     }
 }
Ejemplo n.º 3
0
 protected function getBearerToken()
 {
     $settings = craft()->plugins->getPlugin('social')->getSettings();
     if (!$settings->twitter_consumer_key || !$settings->twitter_consumer_secret) {
         return false;
     }
     if ($this->token) {
         return $this->token;
     }
     $store = craft()->path->getStoragePath() . 'social/';
     IOHelper::ensureFolderExists($store);
     if (file_exists($store . '/twitter.bearer-token')) {
         $this->token = trim(file_get_contents($store . '/twitter.bearer-token'));
     } else {
         $curl = curl_init(self::TOKEN_URL);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_POST, true);
         curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
         curl_setopt($curl, CURLOPT_USERPWD, $settings->twitter_consumer_key . ':' . $settings->twitter_consumer_secret);
         curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('grant_type' => 'client_credentials')));
         $response = curl_exec($curl);
         $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
         if ($status == 200) {
             $decoded = json_decode($response);
             $this->token = $decoded->access_token;
         } else {
             return false;
         }
         file_put_contents($store . '/twitter.bearer-token', $this->token);
     }
     return $this->token;
 }
Ejemplo n.º 4
0
 /**
  * Download zipfile.
  *
  * @param array  $files
  * @param string $filename
  *
  * @return string
  */
 public function download($files, $filename)
 {
     // Get assets
     $criteria = craft()->elements->getCriteria(ElementType::Asset);
     $criteria->id = $files;
     $criteria->limit = null;
     $assets = $criteria->find();
     // Set destination zip
     $destZip = craft()->path->getTempPath() . $filename . '_' . time() . '.zip';
     // Create zip
     $zip = new \ZipArchive();
     // Open zip
     if ($zip->open($destZip, $zip::CREATE) === true) {
         // Loop through assets
         foreach ($assets as $asset) {
             // Get asset source
             $source = $asset->getSource();
             // Get asset source type
             $sourceType = $source->getSourceType();
             // Get asset file
             $file = $sourceType->getLocalCopy($asset);
             // Add to zip
             $zip->addFromString($asset->filename, IOHelper::getFileContents($file));
             // Remove the file
             IOHelper::deleteFile($file);
         }
         // Close zip
         $zip->close();
         // Return zip destination
         return $destZip;
     }
     // Something went wrong
     throw new Exception(Craft::t('Failed to generate the zipfile'));
 }
Ejemplo n.º 5
0
 /**
  * Returns a database backup zip file to the browser.
  *
  * @return null
  */
 public function actionDownloadBackupFile()
 {
     $fileName = craft()->request->getRequiredQuery('fileName');
     if (($filePath = IOHelper::fileExists(craft()->path->getTempPath() . $fileName . '.zip')) == true) {
         craft()->request->sendFile(IOHelper::getFileName($filePath), IOHelper::getFileContents($filePath), array('forceDownload' => true));
     }
 }
Ejemplo n.º 6
0
 public function form($elementId, $criteria = array())
 {
     $settings = craft()->plugins->getPlugin('comments')->getSettings();
     $oldPath = craft()->path->getTemplatesPath();
     $element = craft()->elements->getElementById($elementId);
     $criteria = array_merge($criteria, array('elementId' => $element->id, 'level' => '1'));
     $comments = craft()->comments->getCriteria($criteria);
     // Is the user providing their own templates?
     if ($settings->templateFolderOverride) {
         // Check if this file even exists
         $commentTemplate = craft()->path->getSiteTemplatesPath() . $settings->templateFolderOverride . '/comments';
         foreach (craft()->config->get('defaultTemplateExtensions') as $extension) {
             if (IOHelper::fileExists($commentTemplate . "." . $extension)) {
                 $templateFile = $settings->templateFolderOverride . '/comments';
             }
         }
     }
     // If no user templates, use our default
     if (!isset($templateFile)) {
         $templateFile = '_forms/templates/comments';
         craft()->path->setTemplatesPath(craft()->path->getPluginsPath() . 'comments/templates');
     }
     $variables = array('element' => $element, 'comments' => $comments);
     $html = craft()->templates->render($templateFile, $variables);
     craft()->path->setTemplatesPath($oldPath);
     // Finally - none of this matters if the permission to comment on this element is denied
     if (!craft()->comments_settings->checkPermissions($element)) {
         return false;
     }
     return new \Twig_Markup($html, craft()->templates->getTwig()->getCharset());
 }
Ejemplo n.º 7
0
 /**
  * Saves log messages in files.
  *
  * @param array $logs list of log messages
  */
 protected function processLogs($logs)
 {
     $logFile = IOHelper::normalizePathSeparators($this->getLogPath() . '/' . $this->getLogFile());
     if (IOHelper::getFileSize($logFile) > $this->getMaxFileSize() * 1024) {
         $this->rotateFiles();
     }
     $lock = craft()->config->get('useLockWhenWritingToFile') === true;
     $fp = @fopen($logFile, 'a');
     if ($lock) {
         @flock($fp, LOCK_EX);
     }
     foreach ($logs as $log) {
         $message = LoggingHelper::redact($log[0]);
         $level = $log[1];
         $category = $log[2];
         $time = $log[3];
         $force = isset($log[4]) && $log[4] == true ? true : false;
         @fwrite($fp, $this->formatLogMessageWithForce($message, $level, $category, $time, $force));
     }
     @fwrite($fp, PHP_EOL . '******************************************************************************************************' . PHP_EOL);
     if ($lock) {
         @flock($fp, LOCK_UN);
     }
     @fclose($fp);
 }
Ejemplo n.º 8
0
 /**
  * @return bool
  */
 public function delete()
 {
     if (!IOHelper::deleteFolder($this->getRealPath())) {
         return false;
     }
     return true;
 }
 public function getInputHtml($name, $value)
 {
     // Get site templates path
     $templatesPath = $siteTemplatesPath = craft()->path->getSiteTemplatesPath();
     // Check if the templates path is overriden by configuration
     // TODO: Normalize path
     $limitToSubfolder = craft()->config->get('templateselectSubfolder');
     if ($limitToSubfolder) {
         $templatesPath = $templatesPath . rtrim($limitToSubfolder, '/') . '/';
     }
     // Check if folder exists, or give error
     if (!IOHelper::folderExists($templatesPath)) {
         throw new \InvalidArgumentException('(Template Select) Folder doesn\'t exist: ' . $templatesPath);
     }
     // Get folder contents
     $templates = IOHelper::getFolderContents($templatesPath, TRUE);
     // Add placeholder for when there is no template selected
     $filteredTemplates = array('' => Craft::t('No template selected'));
     // Turn array into ArrayObject
     $templates = new \ArrayObject($templates);
     // Iterate over template list
     // * Remove full path
     // * Remove folders from list
     for ($list = $templates->getIterator(); $list->valid(); $list->next()) {
         $filename = $list->current();
         $filename = str_replace($templatesPath, '', $filename);
         $filenameIncludingSubfolder = $limitToSubfolder ? $limitToSubfolder . $filename : $filename;
         $isTemplate = preg_match("/(.html|.twig)\$/u", $filename);
         if ($isTemplate) {
             $filteredTemplates[$filenameIncludingSubfolder] = $filename;
         }
     }
     // Render field
     return craft()->templates->render('_includes/forms/select', array('name' => $name, 'value' => $value, 'options' => $filteredTemplates));
 }
Ejemplo n.º 10
0
 /**
  * Finds installable records from the models folder.
  *
  * @return array
  */
 public function findInstallableRecords()
 {
     $records = array();
     $recordsFolder = craft()->path->getAppPath() . 'records/';
     $recordFiles = IOHelper::getFolderContents($recordsFolder, false, ".*Record\\.php\$");
     foreach ($recordFiles as $file) {
         if (IOHelper::fileExists($file)) {
             $fileName = IOHelper::getFileName($file, false);
             $class = __NAMESPACE__ . '\\' . $fileName;
             // Ignore abstract classes and interfaces
             $ref = new \ReflectionClass($class);
             if ($ref->isAbstract() || $ref->isInterface()) {
                 Craft::log("Skipping record {$file} because it’s abstract or an interface.", LogLevel::Warning);
                 continue;
             }
             $obj = new $class('install');
             if (method_exists($obj, 'createTable')) {
                 $records[] = $obj;
             } else {
                 Craft::log("Skipping record {$file} because it doesn’t have a createTable() method.", LogLevel::Warning);
             }
         } else {
             Craft::log("Skipping record {$file} because it doesn’t exist.", LogLevel::Warning);
         }
     }
     return $records;
 }
Ejemplo n.º 11
0
 /**
  * Get a display (front-end displayForm) template information.
  *
  * @param string $defaultTemplate  Which default template are we looking for?
  * @param string $overrideTemplate Which override template was given?
  *
  * @return array
  */
 public function getDisplayTemplateInfo($defaultTemplate, $overrideTemplate)
 {
     // Plugin's default template path
     $templatePath = craft()->path->getPluginsPath() . 'amforms/templates/_display/templates/';
     $settingsName = $defaultTemplate == 'email' ? 'notificationTemplate' : $defaultTemplate . 'Template';
     $templateSetting = craft()->amForms_settings->getSettingsByHandleAndType($settingsName, AmFormsModel::SettingsTemplatePaths);
     if (empty($overrideTemplate) && $templateSetting) {
         $overrideTemplate = $templateSetting->value;
     }
     // Is the override template set?
     if ($overrideTemplate) {
         // Is the value a folder, or folder with template?
         $pathParts = explode(DIRECTORY_SEPARATOR, $overrideTemplate);
         $templateFile = craft()->path->getSiteTemplatesPath() . $overrideTemplate;
         if (count($pathParts) < 2) {
             // Seems we only have a folder that will use the default template name
             $templateFile .= DIRECTORY_SEPARATOR . $defaultTemplate;
         }
         // Try to find the template for each available template extension
         foreach (craft()->config->get('defaultTemplateExtensions') as $extension) {
             if (IOHelper::fileExists($templateFile . '.' . $extension)) {
                 if (count($pathParts) > 1) {
                     // We set a specific template
                     $defaultTemplate = $pathParts[count($pathParts) - 1];
                     $templatePath = craft()->path->getSiteTemplatesPath() . str_replace(DIRECTORY_SEPARATOR . $defaultTemplate, '', implode(DIRECTORY_SEPARATOR, $pathParts));
                 } else {
                     // Only a folder was given, so still the default template template
                     $templatePath = craft()->path->getSiteTemplatesPath() . $overrideTemplate;
                 }
             }
         }
     }
     return array('path' => $templatePath, 'template' => $defaultTemplate);
 }
Ejemplo n.º 12
0
 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);
 }
 /**
  * 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();');
     }
 }
Ejemplo n.º 14
0
 /**
  * Includes resources for the Control Panel from the craft/config/diywidget/ folder.
  */
 protected function includeCustomCpResources()
 {
     $templatePaths = [];
     $folderPath = craft()->path->getConfigPath() . 'diywidget/';
     if (IOHelper::folderExists($folderPath)) {
         $filePaths = glob($folderPath . '*.{twig,html,css,js}', GLOB_BRACE);
         foreach ($filePaths as $filePath) {
             $pathInFolder = str_replace($folderPath, '', $filePath);
             $resourcePath = 'config/diywidget/' . $pathInFolder;
             switch (IOHelper::getExtension($filePath)) {
                 case 'twig':
                 case 'html':
                     $templatePaths[] = $pathInFolder;
                     break;
                 case 'css':
                     craft()->templates->includeCssResource($resourcePath);
                     break;
                 case 'js':
                     craft()->templates->includeJsResource($resourcePath);
                     break;
             }
         }
     }
     craft()->diyWidget->templatePaths = $templatePaths;
 }
 /**
  * Prepare asset for cropping.
  */
 public function actionPrepareForCrop()
 {
     $this->requireAjaxRequest();
     $elementId = craft()->request->getParam('elementId');
     // Get the asset file
     $asset = craft()->assets->getFileById($elementId);
     $source = $asset->getSource();
     $sourceType = $source->getSourceType();
     $file = $sourceType->getLocalCopy($asset);
     try {
         // Test if we will be able to perform image actions on this image
         if (!craft()->images->checkMemoryForImage($file)) {
             IOHelper::deleteFile($file);
             $this->returnErrorJson(Craft::t('The selected image is too large.'));
         }
         // Scale to fit 500x500 for fitting in CP modal
         craft()->images->loadImage($file)->scaleToFit(500, 500, false)->saveAs($file);
         list($width, $height) = ImageHelper::getImageSize($file);
         // If the file is in the format badscript.php.gif perhaps.
         if ($width && $height) {
             $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => $asset->url, 'width' => $width, 'height' => $height, 'fileName' => $asset->filename));
             $this->returnJson(array('html' => $html));
         }
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
 }
Ejemplo n.º 16
0
 /**
  * Download zipfile.
  *
  * @param array  $files
  * @param string $filename
  *
  * @return string
  */
 public function download($files, $filename)
 {
     // Get assets
     $criteria = craft()->elements->getCriteria(ElementType::Asset);
     $criteria->id = $files;
     $criteria->limit = null;
     $assets = $criteria->find();
     // Set destination zip
     $destZip = craft()->path->getTempPath() . $filename . '_' . time() . '.zip';
     // Create the zipfile
     IOHelper::createFile($destZip);
     // Loop through assets
     foreach ($assets as $asset) {
         // Get asset source
         $source = $asset->getSource();
         // Get asset source type
         $sourceType = $source->getSourceType();
         // Get asset file
         $file = $sourceType->getLocalCopy($asset);
         // Add to zip
         Zip::add($destZip, $file, dirname($file));
     }
     // Return zip destination
     return $destZip;
 }
Ejemplo n.º 17
0
 /**
  * Looks for a missing translation string in Yii's core translations.
  *
  * @param \CMissingTranslationEvent $event
  *
  * @return null
  */
 public static function findMissingTranslation(\CMissingTranslationEvent $event)
 {
     // Look for translation file from most to least specific.  So nl_nl.php gets checked before nl.php, for example.
     $translationFiles = array();
     $parts = explode('_', $event->language);
     $totalParts = count($parts);
     for ($i = 1; $i <= $totalParts; $i++) {
         $translationFiles[] = implode('_', array_slice($parts, 0, $i));
     }
     $translationFiles = array_reverse($translationFiles);
     // First see if we have any cached info.
     foreach ($translationFiles as $translationFile) {
         // We've loaded the translation file already, just check for the translation.
         if (isset(static::$_translations[$translationFile])) {
             if (isset(static::$_translations[$translationFile][$event->message])) {
                 $event->message = static::$_translations[$translationFile][$event->message];
             }
             // No translation... just give up.
             return;
         }
     }
     // No luck in cache, check the file system.
     $frameworkMessagePath = IOHelper::normalizePathSeparators(Craft::getPathOfAlias('app.framework.messages'));
     foreach ($translationFiles as $translationFile) {
         $path = $frameworkMessagePath . $translationFile . '/yii.php';
         if (IOHelper::fileExists($path)) {
             // Load it up.
             static::$_translations[$translationFile] = (include $path);
             if (isset(static::$_translations[$translationFile][$event->message])) {
                 $event->message = static::$_translations[$translationFile][$event->message];
                 return;
             }
         }
     }
 }
Ejemplo n.º 18
0
 /**
  * @param $id
  * @return bool
  */
 public static function exists($id)
 {
     $id = static::getCanonicalID($id);
     $dataPath = static::$dataPath === null ? craft()->path->getFrameworkPath() . 'i18n/data' : static::$dataPath;
     $dataFile = $dataPath . '/' . $id . '.php';
     return IOHelper::fileExists($dataFile);
 }
Ejemplo n.º 19
0
 /**
  * Get a display (front-end displayForm) template information.
  *
  * @param string $defaultTemplate  Which default template are we looking for?
  * @param string $overrideTemplate Which override template was given?
  *
  * @return array
  */
 public function getDisplayTemplateInfo($defaultTemplate, $overrideTemplate)
 {
     // Plugin's default template path
     $templatePath = craft()->path->getPluginsPath() . 'amforms/templates/_display/templates/';
     $settingsName = $defaultTemplate . 'Template';
     $templateSetting = craft()->amForms_settings->getSettingsByHandleAndType($settingsName, AmFormsModel::SettingsTemplatePaths);
     if (empty($overrideTemplate) && $templateSetting) {
         $overrideTemplate = $templateSetting->value;
     }
     // Is the override template set?
     if ($overrideTemplate) {
         // Is the value a folder, or folder with template?
         $templateFile = craft()->path->getSiteTemplatesPath() . $overrideTemplate;
         if (is_dir($templateFile)) {
             // Only a folder was given, so still the default template template
             $templatePath = $templateFile;
         } else {
             // Try to find the template for each available template extension
             foreach (craft()->config->get('defaultTemplateExtensions') as $extension) {
                 if (IOHelper::fileExists($templateFile . '.' . $extension)) {
                     $pathParts = explode('/', $overrideTemplate);
                     $defaultTemplate = $pathParts[count($pathParts) - 1];
                     $templatePath = craft()->path->getSiteTemplatesPath() . implode('/', array_slice($pathParts, 0, count($pathParts) - 1));
                 }
             }
         }
     }
     return array('path' => $templatePath, 'template' => $defaultTemplate);
 }
Ejemplo n.º 20
0
 /**
  * Downloads a file and cleans up old temporary assets
  */
 public function actionDownloadFile()
 {
     // Clean up temp assets files that are more than a day old
     $fileResults = array();
     $files = IOHelper::getFiles(craft()->path->getTempPath(), true);
     foreach ($files as $file) {
         $lastModifiedTime = IOHelper::getLastTimeModified($file, true);
         if (substr(IOHelper::getFileName($file, false, true), 0, 6) === "assets" && DateTimeHelper::currentTimeStamp() - $lastModifiedTime->getTimestamp() >= 86400) {
             IOHelper::deleteFile($file);
         }
     }
     // Sort out the file we want to download
     $id = craft()->request->getParam('id');
     $criteria = craft()->elements->getCriteria(ElementType::Asset);
     $criteria->id = $id;
     $asset = $criteria->first();
     if ($asset) {
         // Get a local copy of the file
         $sourceType = craft()->assetSources->getSourceTypeById($asset->sourceId);
         $localCopy = $sourceType->getLocalCopy($asset);
         // Send it to the browser
         craft()->request->sendFile($asset->filename, IOHelper::getFileContents($localCopy), array('forceDownload' => true));
         craft()->end();
     }
 }
Ejemplo n.º 21
0
 public function getSettingsHtml()
 {
     $pluginSettings = craft()->plugins->getPlugin('placid')->getSettings();
     // Get placid requests and send them to the widget settings
     $requests = craft()->placid_requests->findAllRequests();
     $requestsArray = array('' => 'No request selected');
     foreach ($requests as $request) {
         $requestsArray[$request->handle] = $request->name;
     }
     $templatesPath = craft()->path->getSiteTemplatesPath() . $pluginSettings->widgetTemplatesPath;
     $templates = IOHelper::getFolderContents($templatesPath, TRUE);
     $templatesArray = array('' => Craft::t('No template selected'));
     if (!$templates) {
         $templatesArray = array('' => 'Cannot find templates');
         Craft::log('Cannot find templates in path "' . $templatesPath . '"', LogLevel::Error);
     } else {
         // Turn array into ArrayObject
         $templates = new \ArrayObject($templates);
         // Iterate over template list
         // * Remove full path
         // * Remove folders from list
         for ($list = $templates->getIterator(); $list->valid(); $list->next()) {
             $filename = $list->current();
             $filename = str_replace($templatesPath, '', $filename);
             $filenameIncludingSubfolder = $filename;
             $isTemplate = preg_match("/(.html|.twig)\$/u", $filename);
             if ($isTemplate) {
                 $templatesArray[$filenameIncludingSubfolder] = $filename;
             }
         }
     }
     return craft()->templates->render('placid/_widgets/request/settings', array('requests' => $requestsArray, 'templates' => $templatesArray, 'settings' => $this->getSettings()));
 }
Ejemplo n.º 22
0
 /**
  * Get the sections of the CP.
  *
  * @return array
  */
 public function nav($iconSize = 32)
 {
     $nav['dashboard'] = array('label' => Craft::t('Dashboard'), 'icon' => 'gauge');
     if (craft()->sections->getTotalEditableSections()) {
         $nav['entries'] = array('label' => Craft::t('Entries'), 'icon' => 'section');
     }
     $globals = craft()->globals->getEditableSets();
     if ($globals) {
         $nav['globals'] = array('label' => Craft::t('Globals'), 'url' => 'globals/' . $globals[0]->handle, 'icon' => 'globe');
     }
     if (craft()->categories->getEditableGroupIds()) {
         $nav['categories'] = array('label' => Craft::t('Categories'), 'icon' => 'categories');
     }
     if (craft()->assetSources->getTotalViewableSources()) {
         $nav['assets'] = array('label' => Craft::t('Assets'), 'icon' => 'assets');
     }
     if (craft()->getEdition() == Craft::Pro && craft()->userSession->checkPermission('editUsers')) {
         $nav['users'] = array('label' => Craft::t('Users'), 'icon' => 'users');
     }
     // Add any Plugin nav items
     $plugins = craft()->plugins->getPlugins();
     foreach ($plugins as $plugin) {
         if ($plugin->hasCpSection()) {
             $pluginHandle = $plugin->getClassHandle();
             if (craft()->userSession->checkPermission('accessPlugin-' . $pluginHandle)) {
                 $lcHandle = StringHelper::toLowerCase($pluginHandle);
                 $iconPath = craft()->path->getPluginsPath() . $lcHandle . '/resources/icon-mask.svg';
                 if (IOHelper::fileExists($iconPath)) {
                     $iconSvg = IOHelper::getFileContents($iconPath);
                 } else {
                     $iconSvg = false;
                 }
                 $nav[$lcHandle] = array('label' => $plugin->getName(), 'iconSvg' => $iconSvg);
             }
         }
     }
     if (craft()->userSession->isAdmin()) {
         $nav['settings'] = array('label' => Craft::t('Settings'), 'icon' => 'settings');
     }
     // Allow plugins to modify the nav
     craft()->plugins->call('modifyCpNav', array(&$nav));
     // Figure out which item is selected, and normalize the items
     $firstSegment = craft()->request->getSegment(1);
     if ($firstSegment == 'myaccount') {
         $firstSegment = 'users';
     }
     foreach ($nav as $handle => &$item) {
         if (is_string($item)) {
             $item = array('label' => $item);
         }
         $item['sel'] = $handle == $firstSegment;
         if (isset($item['url'])) {
             $item['url'] = UrlHelper::getUrl($item['url']);
         } else {
             $item['url'] = UrlHelper::getUrl($handle);
         }
     }
     return $nav;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Clearing asset caches', LogLevel::Info, true);
     $path = craft()->path->getRuntimePath() . 'assets';
     IOHelper::clearFolder($path);
     Craft::log('Done clearing asset caches', LogLevel::Info, true);
     return true;
 }
 /**
  * Test set with failure.
  *
  * @expectedException Craft\Exception
  *
  * @covers ::set
  */
 public final function testSetWithFailure()
 {
     // Lock it for writing
     $file = __DIR__ . '/../translations/test.php';
     IOHelper::changePermissions($file, 0444);
     $service = new TranslateService();
     $service->set('test', array());
 }
 /**
  * Get template file by its name
  * 		
  * @param  string $templateName Template file name
  * @return array               Returns template file information
  */
 public function getTemplateByName($templateName)
 {
     $template = [];
     $path = craft()->path->getPluginsPath() . 'formbuilder2/templates/email/templates/' . $templateName;
     $file = IOHelper::getFile($path);
     $template = ['fileName' => $file->getFileName(false), 'fileOriginalName' => $file->getFileName(), 'fileNameCleaned' => IOHelper::cleanFilename(IOHelper::getFileName($file->getRealPath(), false)), 'fileExtension' => $file->getExtension(), 'filePath' => $file->getRealPath(), 'fileContents' => $file->getContents()];
     return $template;
 }
Ejemplo n.º 26
0
 /**
  * Clean an Asset's filename.
  *
  * @param $fileName
  *
  * @return mixed
  */
 public static function cleanAssetName($fileName)
 {
     $separator = craft()->config->get('filenameWordSeparator');
     if (!is_string($separator)) {
         $separator = null;
     }
     return IOHelper::cleanFilename($fileName, false, $separator);
 }
Ejemplo n.º 27
0
 /**
  * Get Version
  */
 public function getVersion()
 {
     $path = CRAFT_PLUGINS_PATH . 'analytics/Info.php';
     if (IOHelper::fileExists($path)) {
         require_once $path;
         return ANALYTICS_VERSION;
     }
     return '3.2.0';
 }
 private function deleteTempFiles($fileName)
 {
     $tempPath = craft()->path->getTempPath();
     IOHelper::deleteFile($tempPath . $fileName, true);
     $info = pathinfo($fileName);
     $fileNameNoExtension = $info['filename'];
     $ext = $info['extension'];
     IOHelper::deleteFile($tempPath . $fileNameNoExtension . '-temp.' . $ext, true);
 }
Ejemplo n.º 29
0
 /**
  * Get Version
  */
 public function getVersion()
 {
     $path = CRAFT_PLUGINS_PATH . 'oauth/Info.php';
     if (IOHelper::fileExists($path)) {
         require_once $path;
         return OAUTH_VERSION;
     }
     return '1.0.0';
 }
 /**
  * @param $fileName
  *
  * @return array|bool|string
  *
  * @throws Exception
  */
 private function getFileContents($fileName)
 {
     $filePath = craft()->path->getLogPath() . $fileName;
     if (IOHelper::fileExists($filePath) === false) {
         $message = sprintf('Requested logfile "%s" does not seem to exist', $fileName);
         throw new Exception($message);
     } else {
         return IOHelper::getFileContents($filePath);
     }
 }