Пример #1
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;
 }
 /**
  * Download the image
  * @param  string $url      a url to download
  * @param  string $imageId  the instagram imageid for the filename
  * @return mixed            return if it saved the image
  */
 public function downloadImage($url, $imageId = '')
 {
     $size = getimagesize($url);
     // if image is valid in php
     if (!empty($size) && !empty($size["mime"])) {
         $newImageData = $this->download($url);
         if (!empty($newImageData)) {
             return IOHelper::writeToFile(CRAFT_STORAGE_PATH . (string) $imageId . '.jpg', $newImageData);
         }
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 public static function setUpBeforeClass()
 {
     // Set up parent
     parent::setUpBeforeClass();
     // Require dependencies
     require_once __DIR__ . '/../services/TranslateService.php';
     require_once __DIR__ . '/../elementtypes/TranslateElementType.php';
     require_once __DIR__ . '/../models/TranslateModel.php';
     // Create test translation file
     $file = __DIR__ . '/../translations/test.php';
     IOHelper::writeToFile($file, '<?php return array (\'test\' => \'test\');');
 }
Пример #4
0
 /**
  * Dump all tables
  *
  * @return string
  */
 public function run()
 {
     $this->_currentVersion = 'v' . Craft::getVersion() . '.' . Craft::getBuild();
     $result = $this->_processHeader();
     foreach (craft()->db->getSchema()->getTables() as $tableName => $val) {
         $result .= $this->_processTable($tableName);
     }
     $result .= $this->_processConstraints();
     $result .= $this->_processFooter();
     $fileName = IOHelper::cleanFilename(Craft::getSiteName()) . '_' . gmdate('ymd_His') . '_' . $this->_currentVersion . '.sql';
     $filePath = craft()->path->getDbBackupPath() . strtolower($fileName);
     IOHelper::writeToFile($filePath, $result);
     return $filePath;
 }
 public function saveImage($folderId, $fileName, $aviaryPath, $imageOverwrite)
 {
     $folder = craft()->assets->getFolderById($folderId);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $aviaryPath);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $newImageData = curl_exec($ch);
     curl_close($ch);
     $tempPath = craft()->path->getTempPath();
     IOHelper::writeToFile($tempPath . $fileName, $newImageData);
     $success = craft()->assets->insertFileByLocalPath($tempPath . $fileName, $fileName, $folderId, $imageOverwrite);
     $this->deleteTempFiles($fileName);
     return $success;
 }
 private function importMetadata()
 {
     $columns = [];
     $metadataColumns = craft()->analytics_api->getMetadataColumns();
     if ($metadataColumns) {
         $items = $metadataColumns->listMetadataColumns('ga');
         if ($items) {
             foreach ($items as $item) {
                 if ($item->attributes['status'] == 'DEPRECATED') {
                     continue;
                 }
                 if (isset($item->attributes['minTemplateIndex'])) {
                     for ($i = $item->attributes['minTemplateIndex']; $i <= $item->attributes['maxTemplateIndex']; $i++) {
                         $column = [];
                         $column['id'] = str_replace('XX', $i, $item->id);
                         $column['type'] = $item->attributes['type'];
                         $column['group'] = $item->attributes['group'];
                         $column['status'] = $item->attributes['status'];
                         $column['uiName'] = str_replace('XX', $i, $item->attributes['uiName']);
                         $column['description'] = str_replace('XX', $i, $item->attributes['description']);
                         if (isset($item->attributes['allowInSegments'])) {
                             $column['allowInSegments'] = $item->attributes['allowInSegments'];
                         }
                         $columns[$column['id']] = $column;
                     }
                 } else {
                     $column = [];
                     $column['id'] = $item->id;
                     $column['type'] = $item->attributes['type'];
                     $column['group'] = $item->attributes['group'];
                     $column['status'] = $item->attributes['status'];
                     $column['uiName'] = $item->attributes['uiName'];
                     $column['description'] = $item->attributes['description'];
                     if (isset($item->attributes['allowInSegments'])) {
                         $column['allowInSegments'] = $item->attributes['allowInSegments'];
                     }
                     $columns[$column['id']] = $column;
                 }
             }
         }
     }
     $contents = json_encode($columns);
     $path = craft()->analytics_metadata->getDimmetsFilePath();
     $res = IOHelper::writeToFile($path, $contents);
 }
 /**
  * Set translations.
  *
  * @param string $locale
  * @param array  $translations
  *
  * @throws Exception if unable to write to file
  */
 public function set($locale, array $translations)
 {
     // Determine locale's translation destination file
     $file = __DIR__ . '/../translations/' . $locale . '.php';
     // Get current translation
     if ($current = @(include $file)) {
         $translations = array_merge($current, $translations);
     }
     // Prepare php file
     $php = "<?php\r\n\r\nreturn ";
     // Get translations as php
     $php .= var_export($translations, true);
     // End php file
     $php .= ';';
     // Convert double space to tab (as in Craft's own translation files)
     $php = str_replace("  '", "\t'", $php);
     // Save code to file
     if (!IOHelper::writeToFile($file, $php)) {
         // If not, complain
         throw new Exception(Craft::t('Something went wrong while saving your translations'));
     }
 }
Пример #8
0
 /**
  * @inheritDoc IZip::unzip()
  *
  * @param $srcZip
  * @param $destFolder
  *
  * @return bool
  */
 public function unzip($srcZip, $destFolder)
 {
     @ini_set('memory_limit', craft()->config->get('phpMaxMemoryLimit'));
     $zip = new \ZipArchive();
     $zipContents = $zip->open($srcZip, \ZipArchive::CHECKCONS);
     if ($zipContents !== true) {
         Craft::log('Could not open the zip file: ' . $srcZip, LogLevel::Error);
         return false;
     }
     for ($i = 0; $i < $zip->numFiles; $i++) {
         if (!($info = $zip->statIndex($i))) {
             Craft::log('Could not retrieve a file from the zip archive ' . $srcZip, LogLevel::Error);
             return false;
         }
         // normalize directory separators
         $info = IOHelper::normalizePathSeparators($info['name']);
         // found a directory
         if (mb_substr($info, -1) === '/') {
             IOHelper::createFolder($destFolder . '/' . $info);
             continue;
         }
         // Don't extract the OSX __MACOSX directory
         if (mb_substr($info, 0, 9) === '__MACOSX/') {
             continue;
         }
         $contents = $zip->getFromIndex($i);
         if ($contents === false) {
             Craft::log('Could not extract file from zip archive ' . $srcZip, LogLevel::Error);
             return false;
         }
         if (!IOHelper::writeToFile($destFolder . '/' . $info, $contents, true, true)) {
             Craft::log('Could not copy file to ' . $destFolder . '/' . $info . ' while unzipping from ' . $srcZip, LogLevel::Error);
             return false;
         }
     }
     $zip->close();
     return true;
 }
Пример #9
0
 /**
  * Saves application state in persistent storage.
  *
  * @param mixed $state state data (must be serializable).
  */
 public function save($state)
 {
     IOHelper::writeToFile($this->stateFile, serialize($state));
 }
Пример #10
0
 public function actionSendSupportRequest()
 {
     $this->requirePostRequest();
     craft()->config->maxPowerCaptain();
     $success = false;
     $errors = array();
     $zipFile = null;
     $tempFolder = null;
     $getHelpModel = new FeedMe_GetHelpModel();
     $getHelpModel->fromEmail = craft()->request->getPost('fromEmail');
     $getHelpModel->feedIssue = craft()->request->getPost('feedIssue');
     $getHelpModel->message = trim(craft()->request->getPost('message'));
     $getHelpModel->attachLogs = (bool) craft()->request->getPost('attachLogs');
     $getHelpModel->attachSettings = (bool) craft()->request->getPost('attachSettings');
     $getHelpModel->attachFeed = (bool) craft()->request->getPost('attachFeed');
     $getHelpModel->attachFields = (bool) craft()->request->getPost('attachFields');
     $getHelpModel->attachment = UploadedFile::getInstanceByName('attachAdditionalFile');
     if ($getHelpModel->validate()) {
         $plugin = craft()->plugins->getPlugin('feedMe');
         $feed = craft()->feedMe_feeds->getFeedById($getHelpModel->feedIssue);
         // Add some extra info about this install
         $message = $getHelpModel->message . "\n\n" . "------------------------------\n\n" . 'Craft ' . craft()->getEditionName() . ' ' . craft()->getVersion() . '.' . craft()->getBuild() . "\n\n" . 'Feed Me ' . $plugin->getVersion();
         try {
             $zipFile = $this->_createZip();
             $tempFolder = craft()->path->getTempPath() . StringHelper::UUID() . '/';
             if (!IOHelper::folderExists($tempFolder)) {
                 IOHelper::createFolder($tempFolder);
             }
             //
             // Attached just the Feed Me log
             //
             if ($getHelpModel->attachLogs) {
                 if (IOHelper::folderExists(craft()->path->getLogPath())) {
                     $logFolderContents = IOHelper::getFolderContents(craft()->path->getLogPath());
                     foreach ($logFolderContents as $file) {
                         // Just grab the Feed Me log
                         if (IOHelper::fileExists($file) && basename($file) == 'feedme.log') {
                             Zip::add($zipFile, $file, craft()->path->getStoragePath());
                         }
                     }
                 }
             }
             //
             // Backup our feed settings
             //
             if ($getHelpModel->attachSettings) {
                 if (IOHelper::folderExists(craft()->path->getDbBackupPath())) {
                     $backup = craft()->path->getDbBackupPath() . StringHelper::toLowerCase('feedme_' . gmdate('ymd_His') . '.sql');
                     $feedInfo = $this->_prepareSqlFeedSettings($getHelpModel->feedIssue);
                     IOHelper::writeToFile($backup, $feedInfo . PHP_EOL, true, true);
                     Zip::add($zipFile, $backup, craft()->path->getStoragePath());
                 }
             }
             //
             // Save the contents of the feed
             //
             if ($getHelpModel->attachFeed) {
                 $feedData = craft()->feedMe_feed->getRawData($feed->feedUrl);
                 $tempFile = $tempFolder . 'feed.' . StringHelper::toLowerCase($feed->feedType);
                 IOHelper::writeToFile($tempFile, $feedData . PHP_EOL, true, true);
                 if (IOHelper::fileExists($tempFile)) {
                     Zip::add($zipFile, $tempFile, $tempFolder);
                 }
             }
             //
             // Get some information about the fields we're mapping to - handy to know
             //
             if ($getHelpModel->attachFields) {
                 $fieldInfo = array();
                 foreach ($feed->fieldMapping as $feedHandle => $fieldHandle) {
                     $field = craft()->fields->getFieldByHandle($fieldHandle);
                     if ($field) {
                         $fieldInfo[] = $this->_prepareExportField($field);
                     }
                 }
                 // Support PHP <5.4, JSON_PRETTY_PRINT = 128, JSON_NUMERIC_CHECK = 32
                 $json = json_encode($fieldInfo, 128 | 32);
                 $tempFile = $tempFolder . 'fields.json';
                 IOHelper::writeToFile($tempFile, $json . PHP_EOL, true, true);
                 if (IOHelper::fileExists($tempFile)) {
                     Zip::add($zipFile, $tempFile, $tempFolder);
                 }
             }
             //
             // Add in any additional attachments
             //
             if ($getHelpModel->attachment) {
                 $tempFile = $tempFolder . $getHelpModel->attachment->getName();
                 $getHelpModel->attachment->saveAs($tempFile);
                 // Make sure it actually saved.
                 if (IOHelper::fileExists($tempFile)) {
                     Zip::add($zipFile, $tempFile, $tempFolder);
                 }
             }
         } catch (\Exception $e) {
             FeedMePlugin::log('Tried to attach debug logs to a support request and something went horribly wrong: ' . $e->getMessage(), LogLevel::Warning, true);
         }
         $email = new EmailModel();
         $email->fromEmail = $getHelpModel->fromEmail;
         $email->toEmail = "*****@*****.**";
         $email->subject = "Feed Me Support";
         $email->body = $message;
         if ($zipFile) {
             $email->addAttachment($zipFile, 'FeedMeSupportAttachment.zip', 'base64', 'application/zip');
         }
         $result = craft()->email->sendEmail($email);
         if ($result) {
             if ($zipFile) {
                 if (IOHelper::fileExists($zipFile)) {
                     IOHelper::deleteFile($zipFile);
                 }
             }
             if ($tempFolder) {
                 IOHelper::clearFolder($tempFolder);
                 IOHelper::deleteFolder($tempFolder);
             }
             $success = true;
         } else {
             $errors = array('Support' => array('Unable to contact support. Please try again soon.'));
         }
     } else {
         $errors = $getHelpModel->getErrors();
     }
     $this->returnJson(array('success' => $success, 'errors' => $errors));
 }
Пример #11
0
 /**
  * @param $srcZip
  * @param $destFolder
  * @return bool
  */
 public function unzip($srcZip, $destFolder)
 {
     $zip = new \PclZip($srcZip);
     $tempDestFolders = null;
     // check to see if it's a valid archive.
     if (($zipFiles = $zip->extract(PCLZIP_OPT_EXTRACT_AS_STRING)) == false) {
         Craft::log('Tried to unzip ' . $srcZip . ', but PclZip thinks it is not a valid zip archive.', LogLevel::Error);
         return false;
     }
     if (count($zipFiles) == 0) {
         Craft::log($srcZip . ' appears to be an empty zip archive.', LogLevel::Error);
         return false;
     }
     // find out which directories we need to create in the destination.
     foreach ($zipFiles as $zipFile) {
         if (substr($zipFile['filename'], 0, 9) === '__MACOSX/') {
             continue;
         }
         $folderName = IOHelper::getFolderName($zipFile['filename']);
         if ($folderName == './') {
             $tempDestFolders[] = $destFolder . '/';
         } else {
             $tempDestFolders[] = $destFolder . '/' . rtrim(IOHelper::getFolderName($zipFile['filename']), '/');
         }
     }
     $tempDestFolders = array_unique($tempDestFolders);
     $finalDestFolders = array();
     foreach ($tempDestFolders as $tempDestFolder) {
         // Skip over the working directory
         if (rtrim($destFolder, '/') == rtrim($tempDestFolder, '/')) {
             continue;
         }
         // Make sure the current directory is within the working directory
         if (strpos($tempDestFolder, $destFolder) === false) {
             continue;
         }
         $finalDestFolders[] = $tempDestFolder;
     }
     asort($finalDestFolders);
     // Create the destination directories.
     foreach ($finalDestFolders as $finalDestFolder) {
         if (!IOHelper::folderExists($finalDestFolder)) {
             if (!IOHelper::createFolder($finalDestFolder)) {
                 Craft::log('Could not create folder ' . $finalDestFolder . ' while unzipping: ' . $srcZip, LogLevel::Error);
                 return false;
             }
         }
     }
     unset($finalDestFolders);
     // Extract the files from the zip
     foreach ($zipFiles as $zipFile) {
         // folders have already been created.
         if ($zipFile['folder']) {
             continue;
         }
         if (substr($zipFile['filename'], 0, 9) === '__MACOSX/') {
             continue;
         }
         $destFile = $destFolder . '/' . $zipFile['filename'];
         if (!IOHelper::writeToFile($destFile, $zipFile['content'], true, true)) {
             Craft::log('Could not copy the file ' . $destFile . ' while unziping: ' . $srcZip, LogLevel::Error);
             return false;
         }
     }
     return true;
 }
Пример #12
0
 /**
  * @inheritDoc IFieldType::prepValueFromPost()
  *
  * @param mixed $value
  *
  * @return mixed
  */
 public function prepValueFromPost($value)
 {
     $dataFiles = array();
     // Grab data strings
     if (isset($value['data']) && is_array($value['data'])) {
         foreach ($value['data'] as $index => $dataString) {
             if (preg_match('/^data:(?<type>[a-z0-9]+\\/[a-z0-9]+);base64,(?<data>.+)/i', $dataString, $matches)) {
                 $type = $matches['type'];
                 $data = base64_decode($matches['data']);
                 if (!$data) {
                     continue;
                 }
                 if (!empty($value['filenames'][$index])) {
                     $filename = $value['filenames'][$index];
                 } else {
                     $extension = FileHelper::getExtensionByMimeType($type);
                     $filename = 'Uploaded file.' . $extension;
                 }
                 $dataFiles[] = array('filename' => $filename, 'data' => $data);
             }
         }
     }
     // Remove these so they don't interfere.
     if (isset($value['data']) && isset($value['filenames'])) {
         unset($value['data'], $value['filenames']);
     }
     $uploadedFiles = array();
     // See if we have uploaded file(s).
     $contentPostLocation = $this->getContentPostLocation();
     if ($contentPostLocation) {
         $files = UploadedFile::getInstancesByName($contentPostLocation);
         foreach ($files as $file) {
             $uploadedFiles[] = array('filename' => $file->getName(), 'location' => $file->getTempName());
         }
     }
     // See if we have to validate against fileKinds
     $settings = $this->getSettings();
     $allowedExtensions = false;
     if (isset($settings->restrictFiles) && !empty($settings->restrictFiles) && !empty($settings->allowedKinds)) {
         $allowedExtensions = static::_getAllowedExtensions($settings->allowedKinds);
     }
     if (is_array($allowedExtensions)) {
         foreach ($dataFiles as $file) {
             $extension = StringHelper::toLowerCase(IOHelper::getExtension($file['filename']));
             if (!in_array($extension, $allowedExtensions)) {
                 $this->_failedFiles[] = $file['filename'];
             }
         }
         foreach ($uploadedFiles as $file) {
             $extension = StringHelper::toLowerCase(IOHelper::getExtension($file['filename']));
             if (!in_array($extension, $allowedExtensions)) {
                 $this->_failedFiles[] = $file['filename'];
             }
         }
     }
     if (!empty($this->_failedFiles)) {
         return true;
     }
     // If we got here either there are no restrictions or all files are valid so let's turn them into Assets
     // Unless there are no files at all.
     if (empty($value) && empty($dataFiles) && empty($uploadedFiles)) {
         return array();
     }
     if (empty($value)) {
         $value = array();
     }
     $fileIds = array();
     if (!empty($dataFiles) || !empty($uploadedFiles)) {
         $targetFolderId = $this->_determineUploadFolderId($settings);
         foreach ($dataFiles as $file) {
             $tempPath = AssetsHelper::getTempFilePath($file['filename']);
             IOHelper::writeToFile($tempPath, $file['data']);
             $response = craft()->assets->insertFileByLocalPath($tempPath, $file['filename'], $targetFolderId);
             $fileIds[] = $response->getDataItem('fileId');
             IOHelper::deleteFile($tempPath, true);
         }
         foreach ($uploadedFiles as $file) {
             $tempPath = AssetsHelper::getTempFilePath($file['filename']);
             move_uploaded_file($file['location'], $tempPath);
             $response = craft()->assets->insertFileByLocalPath($tempPath, $file['filename'], $targetFolderId);
             $fileIds[] = $response->getDataItem('fileId');
             IOHelper::deleteFile($tempPath, true);
         }
     }
     $fileIds = array_merge($value, $fileIds);
     // Make it look like the actual POST data contained these file IDs as well,
     // so they make it into entry draft/version data
     $this->element->setRawPostContent($this->model->handle, $fileIds);
     return $fileIds;
 }
Пример #13
0
 /**
  * @param $key
  *
  * @return bool
  * @throws Exception|EtException
  */
 private function _setLicenseKey($key)
 {
     // Make sure the key file does not exist first. Et will never overwrite a license key.
     if (($keyFile = IOHelper::fileExists(craft()->path->getLicenseKeyPath())) == false) {
         $keyFile = craft()->path->getLicenseKeyPath();
         if ($this->_isConfigFolderWritable()) {
             preg_match_all("/.{50}/", $key, $matches);
             $formattedKey = '';
             foreach ($matches[0] as $segment) {
                 $formattedKey .= $segment . PHP_EOL;
             }
             return IOHelper::writeToFile($keyFile, $formattedKey);
         }
         throw new EtException('Craft needs to be able to write to your “craft/config” folder and it can’t.', 10001);
     }
     throw new Exception(Craft::t('Cannot overwrite an existing license.key file.'));
 }
 /**
  * Download a file to the target location. The file will be downloaded using the public URL, instead of cURL.
  *
  * @param $path
  * @param $targetFile
  *
  * @return bool
  */
 private function _downloadFile($path, $targetFile)
 {
     $target = $this->getSettings()->urlPrefix . $path;
     $ch = curl_init($target);
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $response = curl_exec($ch);
     IOHelper::writeToFile($targetFile, $response);
     return true;
 }
Пример #15
0
 /**
  * @param        $viewName
  * @param        $createQuery
  * @param string $action
  *
  * @return string
  */
 private function _processView($viewName, $createQuery, $action = 'create')
 {
     $result = PHP_EOL . 'DROP VIEW IF EXISTS ' . craft()->db->quoteTableName($viewName) . ';' . PHP_EOL . PHP_EOL;
     if ($action == 'create') {
         $result .= PHP_EOL . '--' . PHP_EOL . '-- Schema for view `' . $viewName . '`' . PHP_EOL . '--' . PHP_EOL;
         $result .= $createQuery . ';' . PHP_EOL . PHP_EOL;
         IOHelper::writeToFile($this->_filePath, $result, true, true);
     }
     return $result;
 }
Пример #16
0
 /**
  * @param $contents
  * @param $append
  *
  * @return bool
  */
 public function write($contents, $append)
 {
     if (!IOHelper::writeToFile($this->getRealPath(), $contents, false, $append)) {
         return false;
     }
     return true;
 }
Пример #17
0
 /**
  * @param $args
  * @return int
  */
 public function actionCreate($args)
 {
     $pluginHandle = false;
     if (isset($args[1])) {
         // See if this is a plugin
         $plugin = craft()->plugins->getPlugin($args[1]);
         if ($plugin) {
             $name = $args[0];
             $pluginHandle = $args[1];
         } else {
             $name = $args[1];
         }
         if (!preg_match('/^\\w+$/', $name)) {
             echo "Error: The name of the migration must contain letters, digits and/or underscore characters only.\n";
             return 1;
         }
         $fullName = 'm' . gmdate('ymd_His') . '_' . $name;
         $migrationNameDesc = 'mYYMMDD_HHMMSS_migrationName';
     } else {
         $this->usageError('Please provide a name for the new migration.');
         return 1;
     }
     if ($pluginHandle) {
         $this->_validatePlugin($pluginHandle);
         if (!preg_match('/^\\w+$/', $pluginHandle)) {
             echo "Error: The name of the plugin must contain letters, digits and/or underscore characters only.\n";
             return 1;
         }
         $fullName = 'm' . gmdate('ymd_His') . '_' . strtolower($pluginHandle) . '_' . $name;
         $migrationNameDesc = 'mYYMMDD_HHMMSS_pluginHandle_migrationName';
         // The plugin path should always be the plugin's migration directory.
         $path = craft()->path->getMigrationsPath($pluginHandle);
     } else {
         // The plugin path for Craft can vary.
         $path = rtrim(IOHelper::normalizePathSeparators($args[0]), '/') . '/';
     }
     $content = strtr(craft()->migrations->getTemplate(), array('{ClassName}' => $fullName, '{MigrationNameDesc}' => $migrationNameDesc));
     $file = $path . $fullName . '.php';
     if ($this->confirm("Create new migration '{$file}'?")) {
         IOHelper::writeToFile($file, $content);
         echo "New migration created successfully.\n";
     }
 }
 /**
  * @param        $tableName
  * @param        $createQuery
  * @param string $action
  *
  * @return string
  */
 private function _processTable($tableName, $createQuery, $action = 'create')
 {
     $result = PHP_EOL . 'DROP TABLE IF EXISTS ' . craft()->db->quoteTableName($tableName) . ';' . PHP_EOL . PHP_EOL;
     if ($action == 'create') {
         $result .= PHP_EOL . '--' . PHP_EOL . '-- Schema for table `' . $tableName . '`' . PHP_EOL . '--' . PHP_EOL;
         $pattern = '/CONSTRAINT.*|FOREIGN[\\s]+KEY/';
         // constraints to $tableName
         preg_match_all($pattern, $createQuery, $this->_constraints[$tableName]);
         $createQuery = preg_split('/$\\R?^/m', $createQuery);
         $createQuery = preg_replace($pattern, '', $createQuery);
         $removed = false;
         foreach ($createQuery as $key => $statement) {
             // Stupid PHP.
             $temp = trim($createQuery[$key]);
             if (empty($temp)) {
                 unset($createQuery[$key]);
                 $removed = true;
             }
         }
         if ($removed) {
             $createQuery[count($createQuery) - 2] = rtrim($createQuery[count($createQuery) - 2], ',');
         }
         // resort the keys
         $createQuery = array_values($createQuery);
         for ($i = 0; $i < count($createQuery) - 1; $i++) {
             $result .= $createQuery[$i] . PHP_EOL;
         }
         $result .= $createQuery[$i] . ';' . PHP_EOL;
         // Write out what we have so far.
         IOHelper::writeToFile($this->_filePath, $result, true, true);
         // See if we have any data.
         $totalRows = craft()->db->createCommand('SELECT count(*) FROM ' . craft()->db->quoteTableName($tableName) . ';')->queryScalar();
         if ($totalRows == 0) {
             return;
         }
         // Data!
         IOHelper::writeToFile($this->_filePath, PHP_EOL . '--' . PHP_EOL . '-- Data for table `' . $tableName . '`' . PHP_EOL . '--' . PHP_EOL . PHP_EOL, true, true);
         $batchSize = 1000;
         // Going to grab the data in batches.
         $totalBatches = ceil($totalRows / $batchSize);
         for ($counter = 0; $counter < $totalBatches; $counter++) {
             @set_time_limit(240);
             $offset = $batchSize * $counter;
             $rows = craft()->db->createCommand('SELECT * FROM ' . craft()->db->quoteTableName($tableName) . ' LIMIT ' . $offset . ',' . $batchSize . ';')->queryAll();
             if (!empty($rows)) {
                 $attrs = array_map(array(craft()->db, 'quoteColumnName'), array_keys($rows[0]));
                 foreach ($rows as $row) {
                     $insertStatement = 'INSERT INTO ' . craft()->db->quoteTableName($tableName) . ' (' . implode(', ', $attrs) . ') VALUES';
                     // Process row
                     foreach ($row as $columnName => $value) {
                         if ($value === null) {
                             $row[$columnName] = 'NULL';
                         } else {
                             $row[$columnName] = craft()->db->getPdoInstance()->quote($value);
                         }
                     }
                     $insertStatement .= ' (' . implode(', ', $row) . ');';
                     IOHelper::writeToFile($this->_filePath, $insertStatement . PHP_EOL, true, true);
                 }
             }
         }
         IOHelper::writeToFile($this->_filePath, PHP_EOL . PHP_EOL, true, true);
     }
     return $result;
 }
Пример #19
0
 /**
  * Download a file to the target location. The file will be downloaded using the public URL, instead of cURL.
  *
  * @param $path
  * @param $targetFile
  *
  * @return bool
  */
 private function _downloadFile($path, $targetFile)
 {
     $targetUri = $this->_prepareRequestURI($this->getSettings()->container . '/' . $path);
     $response = $this->_doAuthenticatedRequest(static::RACKSPACE_STORAGE_OPERATION, $targetUri);
     IOHelper::writeToFile($targetFile, static::_extractRequestResponse($response));
     return true;
 }
Пример #20
0
 /**
  * Creates cache of assets.
  *
  * @return Void
  */
 protected function createCache()
 {
     $contents = '';
     foreach ($this->assets as $asset) {
         $contents .= $this->minifyAsset($asset) . "\n";
     }
     if (!IOHelper::writeToFile($this->makePathToCacheFilename(), $contents)) {
         return false;
     }
     $this->onCreateCache(new Event($this));
     return true;
 }
Пример #21
0
 /**
  * Get icon path for a given extension
  *
  * @param $ext
  *
  * @return string
  */
 private function _getIconPath($ext)
 {
     $sourceIconPath = craft()->path->getResourcesPath() . 'images/file.svg';
     $extLength = mb_strlen($ext);
     if ($extLength > 5) {
         // Too long; just use the blank file icon
         return $sourceIconPath;
     }
     // See if the icon already exists
     $iconPath = craft()->path->getAssetsIconsPath() . StringHelper::toLowerCase($ext) . '.svg';
     if (IOHelper::fileExists($iconPath)) {
         return $iconPath;
     }
     // Create a new one
     $svgContents = IOHelper::getFileContents($sourceIconPath);
     $textSize = $extLength <= 3 ? '26' : ($extLength == 4 ? '22' : '18');
     $textNode = '<text x="50" y="73" text-anchor="middle" font-family="sans-serif" fill="#8F98A3" ' . 'font-size="' . $textSize . '">' . StringHelper::toUpperCase($ext) . '</text>';
     $svgContents = str_replace('<!-- EXT -->', $textNode, $svgContents);
     IOHelper::writeToFile($iconPath, $svgContents);
     return $iconPath;
 }
Пример #22
0
 /**
  * Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class.
  *
  * @param  string  $key    The key identifying the value to be cached
  * @param  string  $value  The value to be cached
  * @param  integer $expire The number of seconds in which the cached value will expire. 0 means never expire.
  * @return boolean true    If the value is successfully stored into cache, false otherwise
  */
 protected function setValue($key, $value, $expire)
 {
     if (!$this->_gced && mt_rand(0, 1000000) < $this->getGCProbability()) {
         $this->gc();
         $this->_gced = true;
     }
     if ($expire <= 0) {
         $expire = 31536000;
         // 1 year
     }
     $expire += time();
     $cacheFile = $this->getCacheFile($key);
     if ($this->directoryLevel > 0) {
         IOHelper::createFolder(IOHelper::getFolderName($cacheFile), IOHelper::getWritableFolderPermissions());
     }
     if ($this->_originalKey == 'useWriteFileLock') {
         if (IOHelper::writeToFile($cacheFile, $value, true, false, true) !== false) {
             IOHelper::changePermissions($cacheFile, IOHelper::getWritableFilePermissions());
             return IOHelper::touch($cacheFile, $expire);
         } else {
             return false;
         }
     } else {
         if (IOHelper::writeToFile($cacheFile, $value) !== false) {
             IOHelper::changePermissions($cacheFile, IOHelper::getWritableFilePermissions());
             return IOHelper::touch($cacheFile, $expire);
         } else {
             return false;
         }
     }
 }
 /**
  * Saves the image to the target path.
  *
  * @param string  $targetPath
  * @param boolean $autoQuality
  *
  * @throws \Imagine\Exception\RuntimeException
  * @return null
  */
 public function saveAs($targetPath, $autoQuality = false)
 {
     if (IOHelper::getExtension($targetPath) == 'svg') {
         IOHelper::writeToFile($targetPath, $this->_svgContent);
     } else {
         throw new Exception(Craft::t("Manipulated SVG image rasterizing is unreliable. Please see ImagesService::loadImage()"));
     }
     return true;
 }
Пример #24
0
 /**
  * Saves log messages in files.
  *
  * @param array $logs The list of log messages
  *
  * @return null
  */
 protected function processLogs($logs)
 {
     $types = array();
     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;
         $plugin = isset($log[5]) ? StringHelper::toLowerCase($log[5]) : 'craft';
         if (isset($types[$plugin])) {
             $types[$plugin] .= $this->formatLogMessageWithForce($message, $level, $category, $time, $force, $plugin);
         } else {
             $types[$plugin] = $this->formatLogMessageWithForce($message, $level, $category, $time, $force, $plugin);
         }
     }
     foreach ($types as $plugin => $text) {
         $text .= PHP_EOL . '******************************************************************************************************' . PHP_EOL;
         $this->setLogFile($plugin . '.log');
         $logFile = IOHelper::normalizePathSeparators($this->getLogPath() . '/' . $this->getLogFile());
         // Check the config setting first.  Is it set to true?
         if (craft()->config->get('useWriteFileLock') === true) {
             $lock = true;
         } else {
             if (craft()->config->get('useWriteFileLock') === false) {
                 $lock = false;
             } else {
                 if (craft()->cache->get('useWriteFileLock') === 'yes') {
                     $lock = true;
                 } else {
                     $lock = false;
                 }
             }
         }
         $fp = @fopen($logFile, 'a');
         if ($lock) {
             @flock($fp, LOCK_EX);
         }
         if (IOHelper::getFileSize($logFile) > $this->getMaxFileSize() * 1024) {
             $this->rotateFiles();
             if ($lock) {
                 @flock($fp, LOCK_UN);
             }
             @fclose($fp);
             if ($lock) {
                 IOHelper::writeToFile($logFile, $text, false, true, false);
             } else {
                 IOHelper::writeToFile($logFile, $text, false, true, true);
             }
         } else {
             @fwrite($fp, $text);
             if ($lock) {
                 @flock($fp, LOCK_UN);
             }
             @fclose($fp);
         }
     }
 }