本文整理汇总了PHP中IOHelper::writeToFile方法的典型用法代码示例。如果您正苦于以下问题:PHP IOHelper::writeToFile方法的具体用法?PHP IOHelper::writeToFile怎么用?PHP IOHelper::writeToFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IOHelper
的用法示例。
在下文中一共展示了IOHelper::writeToFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getRuntimePath
/**
* 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;
}
示例2: downloadImage
/**
* 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;
}
示例3: setUpBeforeClass
/**
* {@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: run
/**
* 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;
}
示例5: saveImage
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;
}
示例6: importMetadata
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);
}
示例7: set
/**
* 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: unzip
/**
* @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: save
/**
* 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: actionSendSupportRequest
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 = "web@sgroup.com.au";
//.........这里部分代码省略.........
示例11: unzip
/**
* @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: prepValueFromPost
/**
* @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: _setLicenseKey
/**
* @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.'));
}
示例14: _downloadFile
/**
* 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: _processView
/**
* @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;
}