/** * @param string $name command name (case-insensitive) * * @return \CConsoleCommand The command object. Null if the name is invalid. */ public function createCommand($name) { $name = StringHelper::toLowerCase($name); $command = null; if (isset($this->commands[$name])) { $command = $this->commands[$name]; } else { $commands = array_change_key_case($this->commands); if (isset($commands[$name])) { $command = $commands[$name]; } } if ($command !== null) { if (is_string($command)) { $className = 'NerdsAndCompany\\Schematic\\ConsoleCommands\\' . IOHelper::getFileName($command, false); return new $className($name, $this); } else { // an array configuration return Craft::createComponent($command, $name, $this); } } elseif ($name === 'help') { return new \CHelpCommand('help', $this); } else { return; } }
/** * Gets color palette for image * * @param AssetFileModel|string $image * @param $colorCount * @param $quality * @param $colorValue * @return array * @throws Exception */ public function getColorPalette($image, $colorCount, $quality, $colorValue) { $pathsModel = new Imager_ImagePathsModel($image); if (!IOHelper::getRealPath($pathsModel->sourcePath)) { throw new Exception(Craft::t('Source folder “{sourcePath}” does not exist', array('sourcePath' => $pathsModel->sourcePath))); } if (!IOHelper::fileExists($pathsModel->sourcePath . $pathsModel->sourceFilename)) { throw new Exception(Craft::t('Requested image “{fileName}” does not exist in path “{sourcePath}”', array('fileName' => $pathsModel->sourceFilename, 'sourcePath' => $pathsModel->sourcePath))); } $palette = ColorThief::getPalette($pathsModel->sourcePath . $pathsModel->sourceFilename, $colorCount, $quality); return $colorValue == 'hex' ? $this->_paletteToHex($palette) : $palette; }
/** * Loads config file */ private function loadConfig() { try { if ($yaml = IOHelper::getFileContents(self::UNITTESTSUITE_CONFIG)) { $this->config = Yaml::parse($yaml); } else { $this->logError(sprintf('Unable to load configuration from %s', self::UNITTESTSUITE_CONFIG)); } } catch (\Exception $e) { $this->logError(sprintf('An error occurred loading configuration: %s', $e->getMessage())); } }
/** * server() returns an instance of Leafo\ScssPhp\Server, constructing it if * necessary. * * If you provide an instance of Server as argument, it uses that instead. * * @return Server */ public static function server($instance = null) { if ($instance !== null) { static::$scss_server = $instance; } elseif (static::$scss_server === null) { $sass_cache_dir = craft()->path->getStoragePath() . '/scss_cache'; IOHelper::ensureFolderExists($sass_cache_dir); static::$scss_server = new Server(dirname(craft()->request->getScriptFile()), $sass_cache_dir); static::$scss_server->showErrorsAsCSS(); } return static::$scss_server; }
/** * Export to Yaml file. * * @param string $file * @param bool $autoCreate * * @return Result */ public function exportToYaml($file, $autoCreate = true) { Craft::app()->config->maxPowerCaptain(); $result = new Result(); $dataModel = $this->exportDataModel(); $yaml = Data::toYaml($dataModel); if (!IOHelper::writeToFile($file, $yaml, $autoCreate)) { // Do not auto create $result->addError('errors', "Failed to write contents to \"{$file}\""); } return $result; }
/** * Imports the Craft datamodel. * * @param string $file yml file containing the schema definition * @param string $override_file yml file containing the override values * @param bool $force if set to true items not in the import will be deleted * * @return int */ public function actionIndex($file = 'craft/config/schema.yml', $override_file = 'craft/config/override.yml', $force = false) { if (!IOHelper::fileExists($file)) { $this->usageError(Craft::t('File not found.')); } $result = Craft::app()->schematic->importFromYaml($file, $override_file, $force); if (!$result->hasErrors()) { Craft::log(Craft::t('Loaded schema from {file}', ['file' => $file])); return 0; } Craft::log(Craft::t('There was an error loading schema from {file}', ['file' => $file])); print_r($result->getErrors()); return 1; }
/** * Partially downloads a file from a remote source * * @param string $url The file's URL. * @param string $path The path to write the file to. * @param int $size The max. bytes to be downloaded before the file gets truncated. * * @return bool */ private function _downloadRemoteFile($url, $path, $size) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($size != null) { curl_setopt($ch, CURLOPT_RANGE, '0-' . $size); } $response = curl_exec($ch); curl_close($ch); IOHelper::writeToFile($path, $response); return true; }
protected function updateAsset($asset, $image, $path) { // Update our model $asset->size = IOHelper::getFileSize($path); $asset->width = $image->getWidth(); $asset->height = $image->getHeight(); // Then, make sure we update the asset info as stored in the database $fileRecord = AssetFileRecord::model()->findById($asset->id); $fileRecord->size = $asset->size; $fileRecord->width = $asset->width; $fileRecord->height = $asset->height; $fileRecord->dateModified = IOHelper::getLastTimeModified($path); $fileRecord->save(false); }
/** * Loads the configured providers. */ private function _loadProviders() { Craft::log(__METHOD__, LogLevel::Info, true); if ($this->_providersLoaded) { return; } // providerSources $providerSources = array(); $providersPath = CRAFT_PLUGINS_PATH . 'oauth/providers/'; $providersFolderContents = IOHelper::getFolderContents($providersPath, false); if ($providersFolderContents) { foreach ($providersFolderContents as $path) { $path = IOHelper::normalizePathSeparators($path); $fileName = IOHelper::getFileName($path, false); if ($fileName == 'BaseOAuthProviderSource') { continue; } // Chop off the "OAuthProviderSource" suffix $handle = substr($fileName, 0, strlen($fileName) - 19); $providerSource = $this->getProviderSource($handle); array_push($providerSources, $providerSource); } } // providers foreach ($providerSources as $providerSource) { $lcHandle = strtolower($providerSource->getHandle()); $record = $this->_getProviderRecordByHandle($providerSource->getHandle()); $provider = Oauth_ProviderModel::populateModel($record); $provider->class = $providerSource->getHandle(); if ($record && !empty($provider->clientId)) { $providerSource->setClient($provider->clientId, $provider->clientSecret); $provider->providerSource = $providerSource; $this->_configuredProviders[$lcHandle] = $provider; } else { $provider->providerSource = $providerSource; } $this->_allProviders[$lcHandle] = $provider; } $this->_providersLoaded = true; }
/** * Renders the settings form to configure Minimee * @return String */ public function getSettingsHtml() { $filesystemConfigPath = craft()->path->getConfigPath() . 'minimee.php'; return craft()->templates->render('minimee/settings', array('settings' => $this->getSettings(), 'filesystemConfigExists' => (bool) IOHelper::fileExists($filesystemConfigPath))); }
/** * Loads an image from a file system path, do transform, return transformed image as an Imager_ImageModel * * @param AssetFileModel $image * @param string $sourcePath * @param string $targetPath * @param string $targetUrl * @param Array $transform * * @throws Exception * @return Imager_ImageModel */ private function _getTransformedImage($imageFilename, $sourcePath, $targetPath, $targetUrl, $transform) { // break up the image filename to get extension and actual filename $pathParts = pathinfo($imageFilename); $targetExtension = $pathParts['extension']; $filename = $pathParts['filename']; // do we want to output in a certain format? if (isset($transform['format'])) { $targetExtension = $transform['format']; } // normalize the transform before doing anything more $transform = $this->_normalizeTransform($transform); // create target filename, path and url $targetFilename = $this->_createTargetFilename($filename, $targetExtension, $transform); $targetFilePath = $targetPath . $targetFilename; $targetFileUrl = $targetUrl . $targetFilename; /** * Check if the image already exists, if caching is turned on or if the cache has expired. */ if (!$this->getSetting('cacheEnabled', $transform) || !IOHelper::fileExists($targetFilePath) || IOHelper::getLastTimeModified($targetFilePath)->format('U') + $this->getSetting('cacheDuration') < time()) { // create the imageInstance. only once if reuse is enabled, or always if (!$this->getSetting('instanceReuseEnabled', $transform) || $this->imageInstance == null) { $this->imageInstance = $this->imagineInstance->open($sourcePath . $imageFilename); } // Apply any pre resize filters if (isset($transform['preEffects'])) { $this->_applyImageEffects($this->imageInstance, $transform['preEffects']); } $originalSize = $this->imageInstance->getSize(); $cropSize = $this->_getCropSize($originalSize, $transform); $resizeSize = $this->_getResizeSize($originalSize, $transform); $saveOptions = $this->_getSaveOptions($targetExtension, $transform); $filterMethod = $this->_getFilterMethod($transform); if (!isset($transform['mode']) || mb_strtolower($transform['mode']) == 'crop' || mb_strtolower($transform['mode']) == 'croponly') { $cropPoint = $this->_getCropPoint($resizeSize, $cropSize, $transform); $this->imageInstance->resize($resizeSize, $filterMethod)->crop($cropPoint, $cropSize); } else { $this->imageInstance->resize($resizeSize, $filterMethod); } // Apply post resize filters if (isset($transform['effects'])) { $this->_applyImageEffects($this->imageInstance, $transform['effects']); } $this->imageInstance->save($targetFilePath, $saveOptions); // if file was created, check if optimization should be done if (IOHelper::fileExists($targetFilePath)) { if (($targetExtension == 'jpg' || $targetExtension == 'jpeg') && $this->getSetting('jpegoptimEnabled', $transform)) { $this->runJpegoptim($targetFilePath, $transform); } if ($targetExtension == 'png' && $this->getSetting('optipngEnabled', $transform)) { $this->runOptipng($targetFilePath, $transform); } if ($this->getSetting('tinyPngEnabled', $transform)) { $this->runTinyPng($targetFilePath, $transform); } } } $imageInfo = @getimagesize($targetFilePath); $imagerImage = new Imager_ImageModel(); $imagerImage->url = $targetFileUrl; $imagerImage->width = $imageInfo[0]; $imagerImage->height = $imageInfo[1]; return $imagerImage; }
public function getProviderSource($providerClass) { // Get the full class name $class = $providerClass . 'OAuthProviderSource'; $nsClass = 'OAuthProviderSources\\' . $class; // Skip the autoloader if (!class_exists($nsClass, false)) { $path = CRAFT_PLUGINS_PATH . 'oauth/providers/' . $class . '.php'; if (($path = IOHelper::fileExists($path, false)) !== false) { require_once $path; } else { return null; } } if (!class_exists($nsClass, false)) { return null; } $providerSource = new $nsClass(); if (!$providerSource instanceof \OAuthProviderSources\BaseOAuthProviderSource) { die("this provider doesn't implement BaseOAuthProviderSource abstract class"); } return $providerSource; }
/** * Get the file system path for upload source. * * @param $sourceType * * @return string */ public function getSourceFileSystemPath($sourceType = null) { $path = is_null($sourceType) ? $this->getBasePath($this->source->settings) : $sourceType->getBasePath($this->source->settings); $path = IOHelper::getRealPath($path); return $path; }
/** * Save temporary file and return filename * * @param $imageInstance * @param $sourceExtension * @return string */ private function _saveTemporaryFile($imageInstance, $sourceExtension) { $tempPath = craft()->path->getRuntimePath() . 'imager/temp/'; // check if the path exists if (!IOHelper::getRealPath($tempPath)) { IOHelper::createFolder($tempPath, craft()->config->get('defaultFolderPermissions'), true); if (!IOHelper::getRealPath($tempPath)) { throw new Exception(Craft::t('Temp folder “{tempPath}” does not exist and could not be created', array('tempPath' => $tempPath))); } } $targetFilePath = $tempPath . md5(time()) . '.' . $sourceExtension; $saveOptions = array('jpeg_quality' => 100, 'png_compression_level' => 1, 'flatten' => true); $imageInstance->save($targetFilePath, $saveOptions); return $targetFilePath; }
/** * Strip orientation from EXIF data for an image at a path. * * @param $filePath * * @return bool */ public function stripOrientationFromExifData($filePath) { if (!ImageHelper::canHaveExifData($filePath)) { return null; } // Quick and dirty, if possible if ($this->isImagick() && method_exists('Imagick', 'setImageProperty')) { $image = new \Imagick($filePath); $image->setImageOrientation(\Imagick::ORIENTATION_UNDEFINED); $image->writeImages($filePath, true); return true; } $data = new PelDataWindow(IOHelper::getFileContents($filePath)); // Is this a valid JPEG? if (PelJpeg::isValid($data)) { $jpeg = $file = new PelJpeg(); $jpeg->load($data); $exif = $jpeg->getExif(); if ($exif) { $tiff = $exif->getTiff(); $ifd0 = $tiff->getIfd(); // Delete the Orientation entry and re-save the file $ifd0->offsetUnset(PelTag::ORIENTATION); $file->saveFile($filePath); return true; } } return false; }
public function download($pluginHandle) { Craft::log(__METHOD__, LogLevel::Info, true); // ------------------------------- // Get ready to download & unzip // ------------------------------- $return = array('success' => false); $filesystem = new Filesystem(); $pluginComponent = craft()->plugins->getPlugin($pluginHandle, false); // plugin path $pluginZipDir = CRAFT_PLUGINS_PATH . "_" . $pluginHandle . "/"; $pluginZipPath = CRAFT_PLUGINS_PATH . "_" . $pluginHandle . ".zip"; // remote plugin zip url $remotePlugin = $this->_getRemotePlugin($pluginHandle); if (!$remotePlugin) { $return['msg'] = "Couldn't get plugin last version"; Craft::log(__METHOD__ . ' : Could not get last version', LogLevel::Info, true); return $return; } $remotePluginZipUrl = $remotePlugin['xml']->enclosure['url']; // ------------------------------- // Download & Install // ------------------------------- try { // download remotePluginZipUrl to pluginZipPath $zipContents = file_get_contents($remotePluginZipUrl); file_put_contents($pluginZipPath, $zipContents); // unzip pluginZipPath into pluginZipDir $unzipper = new Unzip(); $contents = $unzipper->extract($pluginZipPath, $pluginZipDir); // remove current files // make a backup of existing plugin (to storage ?) ? $filesystem->rename(CRAFT_PLUGINS_PATH . $pluginHandle, CRAFT_PLUGINS_PATH . '_old_' . $pluginHandle); // move new files to final destination $filesystem->rename($pluginZipDir . $contents[0] . '/' . $pluginHandle . '/', CRAFT_PLUGINS_PATH . $pluginHandle); } catch (\Exception $e) { $return['msg'] = $e->getMessage(); Craft::log(__METHOD__ . ' : Crashed : ' . $e->getMessage(), LogLevel::Info, true); return $return; } // remove download files try { $filesystem->remove($pluginZipDir); $filesystem->remove(CRAFT_PLUGINS_PATH . '_old_' . $pluginHandle); if (!IOHelper::deleteFile($pluginZipPath)) { Craft::log(__METHOD__ . ' : Crashed : ' . "Could not remove plugin zip file", LogLevel::Info, true); } } catch (\Exception $e) { $return['msg'] = $e->getMessage(); Craft::log(__METHOD__ . ' : Crashed : ' . $e->getMessage(), LogLevel::Info, true); return $return; } Craft::log(__METHOD__ . ' : Success : ', LogLevel::Info, true); $return['success'] = true; return $return; }
/** * Test export to yml excluding data types. * * @covers ::exportToYaml */ public function testExportToYamlExcludingDataTypes() { $this->prepExportMockServices(); $exportableDataTypes = Schematic::getExportableDataTypes(); $dataTypesToExport = array_diff($exportableDataTypes, ['pluginData']); $results = $this->schematicService->exportToYaml($this->getYamlExportFile(), $dataTypesToExport); $this->assertFalse($results->hasErrors()); // Read and process the recently created export YAML file. $yaml = IOHelper::getFileContents($this->getYamlExportFile()); $dataModel = Data::fromYaml($yaml, []); // Make sure the excluded data type was not exported. $this->assertEmpty($dataModel->pluginData); }
/** * @return string */ private function getOverrideTestFile() { return IOHelper::getFileContents(__DIR__ . '/../data/test_override.yml'); }
/** * Import the database dump by running mysql from the command line (assumes Bash?) * * @param BaseModel $settings The task's settings * @param mixed $arg An optional second argument * * @return bool */ public function importBackup($settings, $arg = null) { $keepAfterCopy = $this->getSettings()['importBackup']['keepBackup'] === '1' ? true : false; $pathToBackup = craft()->path->getDbBackupPath() . StringHelper::toLowerCase(IOHelper::cleanFilename($settings->backupFileName)); $destination = $this->getSettings()['copyBackup']['destination']; $destination = rtrim($destination, '/') . '/'; $destination = $destination . basename($pathToBackup); $sshHostname = $this->getSettings()['ssh']['remote']['hostname']; $sshUsername = $this->getSettings()['ssh']['remote']['username']; $sshPassword = craft()->goLive_security->decrypt($this->getSettings()['ssh']['remote']['password']); $mysqlHostname = $this->getSettings()['mysql']['hostname']; $mysqlUsername = $this->getSettings()['mysql']['username']; $mysqlPassword = craft()->goLive_security->decrypt($this->getSettings()['mysql']['password']); $mysqlDb = $this->getSettings()['mysql']['dbname']; $ssh = new Net_SSH2($sshHostname); $ssh->login($sshUsername, $sshPassword); $commands = array(array('command' => sprintf('mysql -h %s -u %s -p%s %s < %s', $mysqlHostname, $mysqlUsername, $mysqlPassword, $mysqlDb, $destination), 'output' => '')); if (!$keepAfterCopy) { array_push($commands, array('command' => sprintf('rm %s', $destination), 'output' => '')); } for ($i = 0; $i < count($commands); $i++) { $commands[$i]['output'] = $ssh->exec($commands[$i]['command']); } return true; }
/** * Strip orientation from EXIF data for an image at a path. * * @param $filePath * * @return bool */ public function stripOrientationFromExifData($filePath) { if (!ImageHelper::canHaveExifData($filePath)) { return null; } $data = new PelDataWindow(IOHelper::getFileContents($filePath)); // Is this a valid JPEG? if (PelJpeg::isValid($data)) { $jpeg = $file = new PelJpeg(); $jpeg->load($data); $exif = $jpeg->getExif(); if ($exif) { $tiff = $exif->getTiff(); $ifd0 = $tiff->getIfd(); // Delete the Orientation entry and re-save the file $ifd0->offsetUnset(PelTag::ORIENTATION); $file->saveFile($filePath); return true; } } return false; }
/** * Download */ public function download($pluginHandle) { Craft::log(__METHOD__, LogLevel::Info, true); // ------------------------------- // Get ready to download & unzip // ------------------------------- $return = array('success' => false); $pluginComponent = craft()->plugins->getPlugin($pluginHandle, false); // plugin path $pluginZipDir = CRAFT_PLUGINS_PATH . "_" . $pluginHandle . "/"; $pluginZipPath = CRAFT_PLUGINS_PATH . "_" . $pluginHandle . ".zip"; // remote plugin zip url $remotePlugin = $this->_getRemotePlugin($pluginHandle); if (!$remotePlugin) { $return['msg'] = "Couldn't get plugin last version"; Craft::log(__METHOD__ . ' : Could not get last version', LogLevel::Info, true); return $return; } $remotePluginZipUrl = $remotePlugin['xml']->enclosure['url']; // ------------------------------- // Download & Install // ------------------------------- try { // download remotePluginZipUrl to pluginZipPath $client = new \Guzzle\Http\Client(); $request = $client->get($remotePluginZipUrl); $response = $request->send(); $body = $response->getBody(); // Make sure we're at the beginning of the stream. $body->rewind(); // Write it out to the file IOHelper::writeToFile($pluginZipPath, $body->getStream(), true); // Close the stream. $body->close(); // unzip pluginZipPath into pluginZipDir Zip::unzip($pluginZipPath, $pluginZipDir); $contents = IOHelper::getFiles($pluginZipDir); $pluginUnzipDir = false; foreach ($contents as $content) { if (strrpos($content, "__MACOSX") !== 0) { $pluginUnzipDir = $content; } } // move files we want to keep from their current location to unzipped location // keep : .git if (file_exists(CRAFT_PLUGINS_PATH . $pluginHandle . '/.git') && !$pluginUnzipDir . '/.git') { IOHelper::rename(CRAFT_PLUGINS_PATH . $pluginHandle . '/.git', $pluginUnzipDir . '/.git'); } //rename($path, $newName, $suppressErrors = false) // remove current files // make a backup of existing plugin (to storage ?) ? //deleteFolder($path, $suppressErrors = false) IOHelper::deleteFolder(CRAFT_PLUGINS_PATH . $pluginHandle); // move new files to final destination IOHelper::rename($pluginUnzipDir . '/' . $pluginHandle . '/', CRAFT_PLUGINS_PATH . $pluginHandle); // delete zip IOHelper::deleteFile($pluginZipPath); } catch (\Exception $e) { $return['msg'] = $e->getMessage(); Craft::log(__METHOD__ . ' : Crashed : ' . $e->getMessage(), LogLevel::Info, true); return $return; } // remove download files try { IOHelper::deleteFolder($pluginZipDir); IOHelper::deleteFolder($pluginZipPath); } catch (\Exception $e) { $return['msg'] = $e->getMessage(); Craft::log(__METHOD__ . ' : Crashed : ' . $e->getMessage(), LogLevel::Info, true); return $return; } Craft::log(__METHOD__ . ' : Success : ', LogLevel::Info, true); $return['success'] = true; return $return; }
/** * Remove transforms for a given asset * * @param AssetFileModel $asset */ public function removeTransformsForAsset(AssetFileModel $asset) { $paths = new Imager_ImagePathsModel($asset); if (strpos($paths->targetPath, craft()->imager->getSetting('imagerSystemPath')) !== false) { IOHelper::clearFolder($paths->targetPath); craft()->templateCache->deleteCachesByElementId($asset->id); } }
/** * Get MIME type for file * * @internal Used to get mime types * @param string &$file File path * @return string */ private static function __getMIMEType(&$file) { $extension = \Craft\IOHelper::getMimeType($file); return !is_null($extension) ? $extension : 'application/octet-stream'; }
/** * Get MIME type for file * * @internal Used to get mime types * @param string &$file File path * @return string */ public static function __getMimeType(&$file) { $type = false; // Fileinfo documentation says fileinfo_open() will use the // MAGIC env var for the magic file if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) && ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) { if (($type = finfo_file($finfo, $file)) !== false) { // Remove the charset and grab the last content-type $type = explode(' ', str_replace('; charset=', ';charset=', $type)); $type = array_pop($type); $type = explode(';', $type); $type = trim(array_shift($type)); } finfo_close($finfo); // If anyone is still using mime_content_type() } elseif (function_exists('mime_content_type')) { $type = trim(mime_content_type($file)); } if ($type !== false && strlen($type) > 0) { return $type; } // Otherwise do it the old fashioned way return \Craft\IOHelper::getMimeType($file); }