public function processQuickAdd(NodeRef $nodeRef, Node &$newNode) { try { $workdir = $this->vendorCacheDirectory; $fileURL = (string) $this->Request->getParameter('FileURL'); if (empty($fileURL)) { $fileURL = (string) $this->Request->getParameter('Url'); } $dataURL = (string) $this->Request->getParameter('DataURL'); if ($fileURL != null && trim($fileURL) !== '') { //process file from URL // $data = $this->HttpRequest->fetchURL($fileURL); // // if($data === FALSE) // throw new Exception("Could not get contents of image file at the specified URL. Please try uploading the image from a local file."); // // $basename = basename($fileURL); // // if(($qpos = strpos($basename,'?')) !== false) // $basename = substr($basename,0,$qpos); // // $uploadTempPath = rtrim($workdir, '/').'/uploads/'.$basename; // // FileSystemUtils::safeFilePutContents($uploadTempPath, $data); $this->getMediaService()->storeMediaFromURL($fileURL, $newNode); } else { if ($dataURL != null && trim($dataURL) !== '') { if (preg_match("/^data:(.*?);base64,(.*)\$/", $dataURL, $m)) { $mimeType = $m[1]; $data = $m[2]; if (empty($data)) { throw new Exception("Could not parse data from base64 encoded DataURL"); } $mimeParts = explode('/', $mimeType); $fname = mt_rand() . '.' . $mimeParts[1]; $newPath = rtrim($workdir, '/') . '/uploads/' . $fname; FileSystemUtils::safeFilePutContents($newPath, base64_decode($data)); $this->getMediaService()->storeMedia($newPath, $newNode); } else { throw new Exception("Invalid base64 encoded DataURL format"); } } else { foreach ($this->Request->getUploadedFiles() as $name => $upload) { if (!$upload->isEmpty()) { $dotPos = strrpos($upload->getName(), '.'); if ($dotPos === FALSE) { throw new Exception("Uploaded file name missing extension!"); } //$uploadBaseName = SlugUtils::createSlug($newNode->Title); //$uploadExtension = strtolower(substr($upload->getName(), $dotPos+1)); //$uploadName = $uploadBaseName.'.'.$uploadExtension; $uploadTempPath = $upload->getTemporaryName(); $newPath = rtrim($workdir, '/') . '/uploads/' . preg_replace('/[\\x80-\\xFF]/', '', $upload->getName()); //MOVE OR COPY UPLOADED FILE TO WORKING PATH if (!$upload->transferTo($newPath)) { throw new Exception('Unable to transfer upload to: ' . $newPath); } $this->getMediaService()->storeMedia($newPath, $newNode); break; //only process 1 uploaded file (for now) } else { throw new Exception("Unsuccessful upload: " . $upload->getHumanError()); } } } } } catch (StorageFacilityException $sfe) { throw new Exception("An error occurred storing the file(s): " . $sfe->getMessage()); } catch (ThumbnailsException $te) { throw new Exception("An error occurred generating the thumbnail(s): " . $te->getMessage()); } catch (Exception $e) { throw new Exception("An error occurred while processing the file(s): " . $e->getMessage()); } }
protected function logLine($message) { FileSystemUtils::safeFilePutContents($this->logFile, '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n", FILE_APPEND); }
protected function storeDeploymentCache($aggregatePath, $cacheArray) { FileSystemUtils::safeFilePutContents($aggregatePath, JSONUtils::encode($cacheArray, true)); }
/** * Performs a write to the filesystem of our data. * * @param string $filename The filename to write to * @param string $value The data to write. * * @return void */ protected function writeFile($filename, $value) { try { FileSystemUtils::safeFilePutContents($filename, serialize($value)); return true; } catch (Exception $e) { return false; } }
/** * Combines all the listed files into a single file at {@link $aggregatePath} * * @param string $md5 The md5 (stored in the aggregate) * @param array $files A list of files to store * @param string $aggregatePath The name of the file to write our aggregate to * * @return array An array with urls as the keys and data as values */ protected function aggregateFiles($md5, array $files, $aggregatePath) { $this->Logger->debug('Rebuilding...'); $file = array("md5" => $md5, $this->subject => array(), "files" => $files); $aggregateContents = "<?php\n\n\$contents = \n" . var_export($file, true) . "\n\n?><?php\n \$" . $this->subject . " = array(\n "; foreach ($files as $filename) { if (!file_exists($filename)) { continue; } $fileContents = file_get_contents($filename); $fileContents = preg_replace('/\\$' . $this->subject . '\\s*\\=\\s*array\\s*\\(/i', '', $fileContents); $fileContents = preg_replace('/\\<\\?php/i', '', $fileContents); $fileContents = preg_replace('/\\)\\;\\s*(\\?\\>)?/', '', $fileContents); $aggregateContents .= $fileContents; // include $filename; //$subject = $this->subject; // if (isset($$subject)) { // foreach ($$subject as $url => $params) // $file[$this->subject][$url] = $params; // } } $aggregateContents .= " ); ?>"; // if (empty(${$this->subject})) // return array(); FileSystemUtils::safeFilePutContents($aggregatePath, $aggregateContents); include $aggregatePath; return ${$this->subject}; }
public function save() { if ($this->lockSystemChanges) { return; } if (!$this->changed) { return; } $xml = new SimpleXMLExtended('<system/>'); $test = $xml->addChild('plugins'); foreach ($this->plugins as $plugin) { $test->addXMLElement($this->SystemXMLConverter->pluginToXML($plugin)); } $test = $xml->addChild('elements'); foreach ($this->elements as $element) { $test->addXMLElement($this->SystemXMLConverter->elementToXML($element)); } $test = $xml->addChild('aspects'); foreach ($this->aspects as $aspect) { $test->addXMLElement($this->SystemXMLConverter->aspectToXML($aspect)); } $test = $xml->addChild('cmsnavitems'); foreach ($this->cmsNavItems as $navItem) { $test->addXMLElement($this->SystemXMLConverter->cmsNavItemToXML($navItem)); } $newContents = $xml->asPrettyXML(); $backup = $this->backupPath . '/system.' . $this->DateFactory->newStorageDate()->format('Y_m_d_His') . '.' . microtime(true) . '.xml'; FileSystemUtils::safeCopy($this->systemXMLFile, $backup); FileSystemUtils::safeFilePutContents($this->systemXMLFile, $newContents); $this->ApplicationContext->clearContextFiles(); $this->changed = false; $this->resetParsed(); }
public function quickAdd() { try { $this->checkNonce(); try { $mediaElementStr = (string) $this->Request->getRequiredParameter('ParentElement'); $mediaElement = $this->ElementService->getBySlug($mediaElementStr); $workdir = $this->vendorCacheDirectory; $fileURL = (string) $this->Request->getParameter('FileURL'); if ($fileURL != null && trim($fileURL) !== '') { //process file from URL $data = $this->HttpRequest->fetchURL($fileURL); if ($data === FALSE) { throw new Exception("Could not get contents of file at the specified URL. Please try uploading the file from a local file."); } $basename = basename($fileURL); if (($qpos = strpos($basename, '?')) !== false) { $basename = substr($basename, 0, $qpos); } $uploadTempPath = rtrim($workdir, '/') . '/uploads/' . $basename; FileSystemUtils::safeFilePutContents($uploadTempPath, $data); $node = $this->FileService->createFileNode($mediaElement, null, $uploadTempPath); } else { foreach ($this->Request->getUploadedFiles() as $name => $upload) { if (!$upload->isEmpty()) { $dotPos = strrpos($upload->getName(), '.'); if ($dotPos === FALSE) { throw new Exception("Uploaded file name missing extension!"); } //$uploadBaseName = SlugUtils::createSlug($newNode->Title); //$uploadExtension = strtolower(substr($upload->getName(), $dotPos+1)); //$uploadName = $uploadBaseName.'.'.$uploadExtension; $uploadTempPath = $upload->getTemporaryName(); $newPath = rtrim($workdir, '/') . '/uploads/' . $upload->getName(); //MOVE OR COPY UPLOADED FILE TO WORKING PATH if (!$upload->transferTo($newPath)) { throw new Exception('Unable to transfer upload to: ' . $newPath); } $node = $this->FileService->createFileNode($mediaElement, null, $newPath); break; //only process 1 uploaded file (for now) } else { throw new Exception("Unsuccessful upload: " . $upload->getHumanError()); } } } } catch (StorageFacilityException $sfe) { throw new Exception("An error occurred storing the media file(s): " . $sfe->getMessage()); } catch (ThumbnailsException $te) { throw new Exception("An error occurred generating the thumbnail(s): " . $te->getMessage()); } catch (HttpRequestServerException $hrse) { throw new Exception("An error occurred while fetching the media file(s): " . $hrse->getCode()); } catch (Exception $e) { throw new Exception("An error occurred while processing the media file(s): " . $e->getMessage()); } // create node $this->getErrors()->throwOnError(); $node = $this->RegulatedNodeService->getByNodeRef($node->getNodeRef(), new NodePartials()); $this->bindToActionDatasource(array($node)); return new View($this->successView()); } catch (ValidationException $e) { $this->bindToActionDatasource(array()); throw $e; } catch (Exception $e) { $this->bindToActionDatasource(array()); $this->errors->addGlobalError($e->getCode(), $e->getMessage())->throwOnError(); } }
/** * Processes an array (or single) of assets. * * @param array $assets Array of asset file names, or a single asset file name * @param string $optionsKey String representation of the options; used to create aggregated file name * @param string $extension File extension, 'js' or 'css' * @param callback $compressCallback Callback to execute to compress the contents of the asset. If null, the * contents won't be compressed. * * @return StorageFacilityFile Aggregated file stored in the aggregate storage facility (with url populated) */ protected function processAsset($asset, $optionsKey, $extension) { $ts = $this->AssetService->getOriginTimestamp($asset); $prefix = ''; $p = basename($asset); $prefix = rtrim($p, '.' . $extension) . '.'; $cacheFileId = '/' . $this->cacheBasePath . '/' . $prefix . md5(serialize(array($asset, $optionsKey, $ts))) . ".v" . $this->DateFactory->newStorageDate($ts)->format(AssetAggregator::DATE_FORMAT) . "." . $extension; if (!$this->AssetService->fileExists($cacheFileId)) { $deployedfile = $this->AssetService->getOriginPath($asset); $contents = @file_get_contents($deployedfile); if ($contents === false) { throw new Exception("Reading contents of file '{$deployedfile}' for asset '{$asset}' failed (empty file contents will cause failure)."); } // strip non-ASCII characters $contents = preg_replace('/[^(\\x20-\\x7F)\\x0A]*/', '', $contents); $tmpFile = $this->vendorCacheDirectory . '/assetCache' . $cacheFileId; if (!is_writable($this->vendorCacheDirectory)) { throw new Exception('Vendor cache directory is not writable: ' . $this->vendorCacheDirectory); } FileSystemUtils::safeFilePutContents($tmpFile, $contents); $this->AssetService->putFile($cacheFileId, $tmpFile, $ts); } $aggregateFile = $this->AssetService->resolveFile($cacheFileId); return $aggregateFile->getURL(); }
/** * Writes the contents to the config file, after first * backing up the current config * * @param string $contents The contents to write to the config file * * @return void */ public function saveContents($contents) { $path = pathinfo($this->configFileLocation); //BACKUP CURRENT config.php $backup = $this->backupPath . '/pluginconfig.' . date('Y_m_d_His') . '.php'; FileSystemUtils::safeCopy($this->configFileLocation, $backup); //OVERWRITE config.php WITH POSTED CONTENTS FileSystemUtils::safeFilePutContents($this->configFileLocation, $contents); $this->VersionService->incrementDeploymentRevision('Saved config.php'); }
public function storeMediaFromURL($url, Node $media, $desiredFilename = null) { $workdir = $this->vendorCacheDirectory; try { $data = $this->HttpRequest->fetchURL($url); } catch (Exception $e) { $data = FALSE; } if ($data === FALSE) { throw new Exception("Could not get contents of file at the specified URL. Please try uploading from a local file."); } if (is_null($desiredFilename)) { $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); $ext = !empty($ext) && strlen($ext) <= 4 ? $ext : $this->getDefaultExtension(); $uploadTempPath = trim($workdir . '/uploads/' . mt_rand() . '.' . $ext); } else { $uploadTempPath = trim($workdir . '/uploads/' . $desiredFilename); } FileSystemUtils::safeFilePutContents($uploadTempPath, $data); $media = $this->storeMedia($uploadTempPath, $media, $desiredFilename); return $media; }
public function export($file, $elements = 'all', $fireEvents = false, $ignoreInTags = false) { if (file_exists($file)) { throw new Exception('Cannot write export file [' . $file . '], file exists'); } if (!$fireEvents) { $this->NodeEvents->disableEvents(); } $this->NodeTagsDAO->setNodeDatabaseTagMergeLimit(-1); $log = ''; if ($elements == 'all') { $elements = $this->ElementService->findAll()->getResults(); } else { $elementSlugs = StringUtils::smartExplode($elements); $elements = array(); foreach ($elementSlugs as $eSlug) { $elements[] = $this->ElementService->getBySlug($eSlug); } } foreach ($elements as $element) { $offset = 0; $nq = new NodeQuery(); $nq->setParameter('Elements.in', $element->getSlug()); $nq->setParameter('Meta.select', 'all'); $nq->setParameter('OutTags.select', 'all'); if (!$ignoreInTags) { $nq->setParameter('InTags.select', 'all'); } $nq->setLimit(1000); $nq->setOffset($offset); $nq->asObjects(); $nq->isRetrieveTotalRecords(true); $nq = $this->NodeService->findAll($nq, true); $nodes = $nq->getResults(); $tCount = $nq->getTotalRecords(); $count = 0; while (count($nodes) > 0) { foreach ($nodes as $node) { FileSystemUtils::safeFilePutContents($file, json_encode($this->NodeMapper->nodeToInputArray($node)) . "\n", FILE_APPEND); ++$count; } $offset += 1000; $nq = new NodeQuery(); $nq->setParameter('Elements.in', $element->getSlug()); $nq->setParameter('Meta.select', 'all'); $nq->setParameter('OutTags.select', 'all'); if (!$ignoreInTags) { $nq->setParameter('InTags.select', 'all'); } $nq->setLimit(1000); $nq->setOffset($offset); $nq->asObjects(); $nodes = $this->NodeService->findAll($nq)->getResults(); } $log .= 'Exported ' . $count . ' of ' . $tCount . ' ' . $element->getSlug() . " nodes.\n"; } if (!$fireEvents) { $this->NodeEvents->enableEvents(); } return $log; }