/**
  * 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;
             }
         }
     }
 }
 /**
  * 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));
     }
 }
Example #3
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);
 }
 /**
  * Crop user photo.
  */
 public function actionCropLogo()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     try {
         $x1 = craft()->request->getRequiredPost('x1');
         $x2 = craft()->request->getRequiredPost('x2');
         $y1 = craft()->request->getRequiredPost('y1');
         $y2 = craft()->request->getRequiredPost('y2');
         $source = craft()->request->getRequiredPost('source');
         // Strip off any querystring info, if any.
         if (($qIndex = strpos($source, '?')) !== false) {
             $source = substr($source, 0, strpos($source, '?'));
         }
         $imagePath = craft()->path->getTempUploadsPath() . $source;
         if (IOHelper::fileExists($imagePath) && craft()->images->setMemoryForImage($imagePath)) {
             $targetPath = craft()->path->getStoragePath() . 'logo/';
             IOHelper::ensureFolderExists($targetPath);
             IOHelper::clearFolder($targetPath);
             craft()->images->loadImage($imagePath)->crop($x1, $x2, $y1, $y2)->scaleToFit(300, 300, false)->saveAs($targetPath . $source);
             IOHelper::deleteFile($imagePath);
             $html = craft()->templates->render('settings/general/_logo');
             $this->returnJson(array('html' => $html));
         }
         IOHelper::deleteFile($imagePath);
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the logo.'));
 }
Example #5
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);
 }
 /**
  * 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();');
     }
 }
 /**
  * Create an image transform.
  *
  * @param array $params
  *
  * @return string
  */
 private function _createImageTransform($params)
 {
     $storeFolder = $this->_getStoreFolder($params);
     // Return existing file if already generated
     if (IOHelper::fileExists($this->_path . $storeFolder . $this->_asset->filename)) {
         return $this->_url . $storeFolder . $this->_asset->filename;
     }
     // Does the asset even exist?
     if (!IOHelper::fileExists($this->_path . $this->_asset->filename)) {
         return false;
     }
     // Create new image
     $this->_instance = new \Imagine\Imagick\Imagine();
     $this->_image = $this->_instance->open($this->_path . $this->_asset->filename);
     if (strtolower($params['mode']) == 'crop') {
         $this->_scaleAndCrop($params['width'], $params['height'], true, $params['position']);
     } else {
         $this->_scaleToFit($params['width'], $params['height']);
     }
     // Effect on image?
     $this->_addImageEffects($params['filters']);
     // Store the image!
     $this->_image->save($this->_path . $storeFolder . $this->_asset->filename, array('jpeg_quality' => $params['quality'], 'flatten' => true));
     // Return stored file
     return $this->_url . $storeFolder . $this->_asset->filename;
 }
 /**
  * Get translations by criteria.
  *
  * @param ElementCriteriaModel $criteria
  *
  * @return array
  */
 public function get(ElementCriteriaModel $criteria)
 {
     // Ensure source is an array
     if (!is_array($criteria->source)) {
         $criteria->source = array($criteria->source);
     }
     // Gather all translatable strings
     $occurences = array();
     // Loop through paths
     foreach ($criteria->source as $path) {
         // Check if this is a folder or a file
         $isFile = IOHelper::fileExists($path);
         // If its not a file
         if (!$isFile) {
             // Set filter - no vendor folders, only template files
             $filter = '^((?!vendor|node_modules).)*(\\.(php|html|twig|js|json|atom|rss)?)$';
             // Get files
             $files = IOHelper::getFolderContents($path, true, $filter);
             // Loop through files and find translate occurences
             foreach ($files as $file) {
                 // Parse file
                 $elements = $this->_parseFile($path, $file, $criteria);
                 // Collect in array
                 $occurences = array_merge($occurences, $elements);
             }
         } else {
             // Parse file
             $elements = $this->_parseFile($path, $path, $criteria);
             // Collect in array
             $occurences = array_merge($occurences, $elements);
         }
     }
     return $occurences;
 }
Example #9
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());
 }
 /**
  * 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;
 }
Example #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);
 }
Example #12
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;
 }
 /**
  * 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';
 }
 /**
  * Test set.
  *
  * @covers ::set
  */
 public final function testSet()
 {
     $file = __DIR__ . '/../translations/test.php';
     IOHelper::changePermissions($file, 0666);
     $service = new TranslateService();
     $service->set('test', array());
     $result = IOHelper::fileExists($file);
     $this->assertTrue((bool) $result);
 }
 public function dimmetsFileExists()
 {
     $path = craft()->analytics_metadata->getDimmetsFilePath();
     if (IOHelper::fileExists($path, false)) {
         return true;
     } else {
         return false;
     }
 }
Example #16
0
 /**
  * Returns the path to the craft/storage/runtime/ folder.
  *
  * @return string The path to the craft/storage/runtime/ folder.
  */
 public function getRuntimePath()
 {
     $path = $this->getStoragePath() . 'runtime/';
     IOHelper::ensureFolderExists($path);
     if (!IOHelper::fileExists($path . '.gitignore')) {
         IOHelper::writeToFile($path . '.gitignore', "*\n!.gitignore\n\n", true);
     }
     return $path;
 }
 /**
  * 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);
     }
 }
 protected function addResources()
 {
     // Get current language and site translations path
     $language = craft()->language;
     $path = craft()->path->getSiteTranslationsPath();
     // Look for translation file from least to most specific. For example, nl.php gets loaded before nl_nl.php.
     $translationFiles = array();
     $parts = explode('_', $language);
     $totalParts = count($parts);
     // If it's Norwegian Bokmål/Nynorsk, add plain ol' Norwegian as a fallback
     if ($parts[0] === 'nb' || $parts[0] === 'nn') {
         $translationFiles[] = 'no';
     }
     for ($i = 1; $i <= $totalParts; $i++) {
         $translationFiles[] = implode('_', array_slice($parts, 0, $i));
     }
     // Get translations
     $translations = array();
     if (IOHelper::folderExists($path)) {
         foreach ($translationFiles as $file) {
             $path = $path . $file . '.php';
             if (IOHelper::fileExists($path)) {
                 $temp = (include $path);
                 if (is_array($temp)) {
                     // If this is framework data and we're not on en_us, then do some special processing.
                     if (strpos($path, 'framework/i18n/data') !== false && $file !== 'en_us') {
                         $temp = $this->_processFrameworkData($file);
                     }
                     $translations = array_merge($translations, $temp);
                 }
             }
         }
     }
     if (empty($translations)) {
         return false;
     }
     craft()->templates->includeJs('(function(window){
         if (window.Craft) {
             Craft.translations = $.extend(Craft.translations, ' . json_encode($translations) . ');
             var selectors = [
                     "#page-title h1",                   // Page titles
                     "#crumbs a",                        // Segments in breadcrumbs
                     ".fld-field > span",                // Field names inside FLD
                     ".fld-tab .tab > span",             // Tab names inside FLD
                     "#sidebar .heading > span",         // CEI heading
                     "#Assets option",                   // Options inside Asset field settings
                 ],
                 $el;
             $(selectors.join(",")).each(function () {
                 $el = $(this);
                 $el.text(Craft.t($el.text()));
             });
         }
     }(window));');
 }
 /**
  * @return Bool
  */
 public function exists()
 {
     if ($this->_exists === null) {
         $realPath = IOHelper::fileExists($this->filenamePath);
         if ($realPath && $realPath !== $this->filenamePath) {
             $this->filenamePath = $realPath;
         }
         $this->_exists = (bool) $realPath;
     }
     return $this->_exists;
 }
 /**
  * Shows the 'offline' template.
  */
 public function actionOffline()
 {
     // If this is a site request, make sure the offline template exists
     if (craft()->request->isSiteRequest()) {
         if (!IOHelper::fileExists(craft()->path->getSiteTemplatesPath() . 'offline.html')) {
             // Set PathService to use the CP templates path instead
             craft()->path->setTemplatesPath(craft()->path->getCpTemplatesPath());
         }
     }
     // Output the offline template
     $this->_render('offline');
 }
Example #22
0
 /**
  * Performs the tool's action.
  *
  * @param array $params
  * @return array
  */
 public function performAction($params = array())
 {
     $file = craft()->db->backup();
     if (IOHelper::fileExists($file) && isset($params['downloadBackup']) && (bool) $params['downloadBackup']) {
         $destZip = craft()->path->getTempPath() . IOHelper::getFileName($file, false) . '.zip';
         if (IOHelper::fileExists($destZip)) {
             IOHelper::deleteFile($destZip, true);
         }
         IOHelper::createFile($destZip);
         if (Zip::add($destZip, $file, craft()->path->getDbBackupPath())) {
             return array('backupFile' => IOHelper::getFileName($destZip, false));
         }
     }
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     $filesToDelete = array('elementtypes/MatrixRecordElementType.php', 'etc/assets/fileicons/56.png', 'etc/console/commands/MigrateCommand.php', 'etc/console/commands/QuerygenCommand.php', 'migrations/m130917_000000_drop_users_enctype.php', 'migrations/m130917_000001_big_names_and_handles.php', 'migrations/m130917_000002_entry_types.php', 'migrations/m130917_000003_section_types.php', 'migrations/m131105_000000_content_column_field_prefixes.php', 'migrations/m131105_000001_add_missing_content_and_i18n_rows.php', 'migrations/m131105_000001_element_content.php', 'migrations/m131105_000002_schema_version.php', 'migrations/m131105_000003_field_contexts.php', 'migrations/m131105_000004_matrix.php', 'migrations/m131105_000004_matrix_blocks.php', 'migrations/m131105_000005_correct_tag_field_layouts.php', 'migrations/m131105_000006_remove_gethelp_widget_for_non_admins.php', 'migrations/m131105_000007_new_relation_column_names.php', 'migrations/m131105_000008_add_values_for_unknown_asset_kinds.php', 'models/MatrixRecordModel.php', 'models/MatrixRecordTypeModel.php', 'models/TagSetModel.php', 'records/EntryLocaleRecord.php', 'records/MatrixRecordRecord.php', 'records/MatrixRecordTypeRecord.php', 'records/StructuredEntryRecord.php', 'records/TagSetRecord.php', 'resources/images/whats-new/entrytypes.png', 'resources/images/whats-new/single.png', 'resources/images/whats-new/structure.png', 'resources/js/compressed/dashboard.js', 'resources/js/compressed/dashboard.min.map', 'resources/js/dashboard.js', 'templates/assets/_nav_folder.html', 'templates/users/_edit/_userphoto.html', 'templates/users/_edit/account.html', 'templates/users/_edit/admin.html', 'templates/users/_edit/layout.html', 'templates/users/_edit/profile.html', 'translations/fr_fr.php');
     $appPath = craft()->path->getAppPath();
     foreach ($filesToDelete as $fileToDelete) {
         if (IOHelper::fileExists($appPath . $fileToDelete)) {
             $fullPath = $appPath . $fileToDelete;
             Craft::log('Deleting file: ' . $fullPath . ' because it is not supposed to exist.', LogLevel::Info, true);
             IOHelper::deleteFile($appPath . $fileToDelete);
         } else {
             Craft::log('File: ' . $fileToDelete . ' does not exist.  Good.', LogLevel::Info, true);
         }
     }
     return true;
 }
Example #24
0
 /**
  * @param $filePath
  *
  * @throws Exception
  */
 public function restore($filePath)
 {
     if (!IOHelper::fileExists($filePath)) {
         throw new Exception(Craft::t('Could not find the SQL file to restore: {filePath}', array('filePath' => $filePath)));
     }
     $this->_nukeDb();
     $sql = IOHelper::getFileContents($filePath, true);
     array_walk($sql, array($this, 'trimValue'));
     $sql = array_filter($sql);
     $statements = $this->_buildSQLStatements($sql);
     foreach ($statements as $statement) {
         Craft::log('Executing SQL statement: ' . $statement);
         $command = craft()->db->createCommand($statement);
         $command->execute();
     }
 }
 /**
  * Loads an image from a file system path.
  *
  * @param string $path
  *
  * @throws Exception
  * @return Image
  */
 public function loadImage($path)
 {
     if (!IOHelper::fileExists($path)) {
         throw new Exception(Craft::t('No file exists at the path “{path}”', array('path' => $path)));
     }
     list($width, $height) = ImageHelper::getImageSize($path);
     $svg = IOHelper::getFileContents($path);
     // If the size is defined by viewbox only, add in width and height attributes
     if (!preg_match(static::SVG_WIDTH_RE, $svg) && preg_match(static::SVG_HEIGHT_RE, $svg)) {
         $svg = preg_replace(static::SVG_TAG_RE, "<svg width=\"{$width}px\" height=\"{$height}px\" ", $svg);
     }
     $this->_height = $height;
     $this->_width = $width;
     $this->_svgContent = $svg;
     return $this;
 }
Example #26
0
 /**
  * @inheritDoc ITool::performAction()
  *
  * @param array $params
  *
  * @return array
  */
 public function performAction($params = array())
 {
     // In addition to the default tables we want to ignore data in, we also don't care about data in the session
     // table in this tools' case.
     $file = craft()->db->backup(array('sessions'));
     if (IOHelper::fileExists($file) && isset($params['downloadBackup']) && (bool) $params['downloadBackup']) {
         $destZip = craft()->path->getTempPath() . IOHelper::getFileName($file, false) . '.zip';
         if (IOHelper::fileExists($destZip)) {
             IOHelper::deleteFile($destZip, true);
         }
         IOHelper::createFile($destZip);
         if (Zip::add($destZip, $file, craft()->path->getDbBackupPath())) {
             return array('backupFile' => IOHelper::getFileName($destZip, false));
         }
     }
 }
Example #27
0
 /**
  * Returns the routes defined in craft/config/routes.php
  *
  * @return array
  */
 public function getConfigFileRoutes()
 {
     $path = craft()->path->getConfigPath() . 'routes.php';
     if (IOHelper::fileExists($path)) {
         $routes = (require_once $path);
         if (is_array($routes)) {
             // Check for any locale-specific routes
             $locale = craft()->language;
             if (isset($routes[$locale]) && is_array($routes[$locale])) {
                 $localizedRoutes = $routes[$locale];
                 unset($routes[$locale]);
                 // Merge them so that the localized routes come first
                 $routes = array_merge($localizedRoutes, $routes);
             }
             return $routes;
         }
     }
     return array();
 }
Example #28
0
 /**
  * Loads an image from a file system path.
  *
  * @param string $path
  * @return Image
  * @throws Exception
  */
 public function loadImage($path)
 {
     if (!IOHelper::fileExists($path)) {
         throw new Exception(Craft::t('No file exists at the path “{path}”', array('path' => $path)));
     }
     if (!craft()->images->setMemoryForImage($path)) {
         throw new Exception(Craft::t("Not enough memory available to perform this image operation."));
     }
     $imageInfo = @getimagesize($path);
     if (!is_array($imageInfo)) {
         throw new Exception(Craft::t('The file “{path}” does not appear to be an image.', array('path' => $path)));
     }
     $this->_image = $this->_instance->open($path);
     $this->_extension = IOHelper::getExtension($path);
     $this->_imageSourcePath = $path;
     $this->_width = $this->_image->getSize()->getWidth();
     $this->_height = $this->_image->getSize()->getHeight();
     return $this;
 }
Example #29
0
 /**
  * Returns all of the routes.
  *
  * @return array
  */
 public function getAllRoutes()
 {
     if (!isset($this->_routes)) {
         $this->_routes = array();
         // Where should we look for routes?
         if (craft()->config->get('siteRoutesSource') == 'file') {
             $path = craft()->path->getConfigPath() . 'routes.php';
             if (IOHelper::fileExists($path)) {
                 $this->_routes = (require_once $path);
             }
         } else {
             $records = RouteRecord::model()->ordered()->findAll();
             foreach ($records as $record) {
                 $this->_routes[$record->urlPattern] = $record->template;
             }
         }
     }
     return $this->_routes;
 }
 /**
  * Loads the message translation for the specified language and category.
  *
  * @param string $category the message category
  * @param string $language the target language
  * @return array the loaded messages
  */
 protected function loadMessages($category, $language)
 {
     if ($category != 'craft') {
         return parent::loadMessages($category, $language);
     }
     if (!isset($this->_translations[$language])) {
         $this->_translations[$language] = array();
         $paths[] = craft()->path->getCpTranslationsPath();
         $paths[] = craft()->path->getSiteTranslationsPath();
         foreach ($paths as $path) {
             $file = $path . $language . '.php';
             if (IOHelper::fileExists($file)) {
                 $translations = (include $file);
                 if (is_array($translations)) {
                     $this->_translations[$language] = array_merge($this->_translations[$language], $translations);
                 }
             }
         }
     }
     return $this->_translations[$language];
 }