/** * Modify class source * * @param \Includes\Decorator\DataStructure\Graph\Classes $node Current node * * @return void */ protected function writeCallToSourceFile(\Includes\Decorator\DataStructure\Graph\Classes $node) { $path = LC_DIR_CACHE_CLASSES . $node->getPath(); $content = \Includes\Utils\FileManager::read($path); $content .= PHP_EOL . '// Call static constructor' . PHP_EOL; $content .= '\\' . $node->getClass() . '::' . static::STATIC_CONSTRUCTOR_METHOD . '();'; \Includes\Utils\FileManager::write($path, $content); }
/** * Add info to a log file * * @param string $message Error message * @param integer $code Error code * @param string $backtrace Stack trace OPTIONAL * * @return void */ protected static function logInfo($message, $code, $backtrace = null) { if (!isset($backtrace)) { ob_start(); debug_print_backtrace(); $backtrace = ob_get_contents(); ob_end_clean(); } $message = date('[d-M-Y H:i:s]') . ' Error (code: ' . $code . '): ' . $message . PHP_EOL; // Add additional info $parts = array('Server API: ' . PHP_SAPI); if (isset($_SERVER)) { if (isset($_SERVER['REQUEST_METHOD'])) { $parts[] = 'Request method: ' . $_SERVER['REQUEST_METHOD']; } if (isset($_SERVER['REQUEST_URI'])) { $parts[] = 'URI: ' . $_SERVER['REQUEST_URI']; } } $message .= implode(';' . PHP_EOL, $parts) . ';' . PHP_EOL; $message .= 'Backtrace: ' . PHP_EOL . $backtrace . PHP_EOL . PHP_EOL; \Includes\Utils\FileManager::write(static::getLogFile(), $message, FILE_APPEND); }
/** * Get file pointer * This dedicates to greatest developer of all time, Maxim Shamaev. Because getFilename() is not enough for name combining. * * @return resource */ protected function getFilePointer() { if (!isset($this->filePointer)) { $name = $this->getFilename(); $dir = \Includes\Utils\FileManager::getRealPath(LC_DIR_VAR . $this->generator->getOptions()->dir); if (is_writable($dir)) { if (!\Includes\Utils\FileManager::isExists($dir . LC_DS . '.htaccess')) { // Try to create .htaccess file to protect directory $out = <<<OUT Options -Indexes Deny from all OUT; \Includes\Utils\FileManager::write($dir . LC_DS . '.htaccess', $out); } $this->filePath = $dir . LC_DS . $name; $this->filePointer = @fopen($dir . LC_DS . $name, 'ab'); } else { $this->generator->addError(static::t('Directory does not have permissions to write'), static::t('Directory X does not have permissions to write. Please set necessary permissions to directory X.', array('path' => $dir))); } } return $this->filePointer; }
/** * Save hashes for current version * * @return void */ protected function saveHashesForInstalledFiles() { $data = $this->loadHashesForInstalledFiles(); if (is_array($data)) { \Includes\Utils\FileManager::write($this->getCurrentVersionHashesFilePath(), '<?php' . PHP_EOL . '$data = ' . var_export($data, true) . ';'); } }
/** * Save schema to file * * @return void */ protected static function saveFile() { $string = implode(';', static::$schema); \Includes\Utils\FileManager::write(static::getDBSchemaFilePath(), $string); }
/** * Save cell data * * @param string $id Cell id * @param mixed $data Cell data * @param integer $lifeTime Cell TTL OPTIONAL * * @return boolean */ protected function doSave($id, $data, $lifeTime = 0) { $lifeTime = max(0, intval($lifeTime)); if ($lifeTime) { $lifeTime += LC_START_TIME; } $lifeTime = strval($lifeTime); return \Includes\Utils\FileManager::write($this->getPathById($id), $this->header . str_repeat(' ', $this->ttlLength - strlen($lifeTime)) . $lifeTime . serialize($data)); }
/** * Create a main less file for the provided less files collection * * @param array $lessFiles LESS files structures array * * @return string LESS file name */ protected function makeLESSResourcePath($lessFiles) { $filePath = $this->getCacheDir('screen') . $this->getUniqueName($lessFiles) . '.less'; if (!is_file($filePath)) { $content = ''; foreach ($lessFiles as $resource) { $resourcePath = \Includes\Utils\FileManager::makeRelativePath($this->getCacheDir('screen'), $resource['file']); $content .= "\r\n" . '@import "' . str_replace('/', LC_DS, $resourcePath) . '";' . "\r\n"; } \Includes\Utils\FileManager::mkdirRecursive(dirname($filePath)); \Includes\Utils\FileManager::write($filePath, $content); } return $filePath; }
/** * Divide large CSV file into several parts and return list of part files * * @param \SplFileObject $file File object * * @return array */ public function divideCSVFile($file) { $result = array(); $outputFileFormat = basename($file->getRealPath()); $f = fopen($file->getRealPath(), 'rb'); // Part file index $fi = 1; // Row index $i = 0; $ip = 0; // Delta (sum of rows in all previous part files) $delta = 0; $content = ''; $pendingContent = ''; $columns = $this->getKeyColumns(); // Subdirectory of tmp dir to write CSV part files $subDir = time(); while (true) { $fields = fgetcsv($f, 0, ',', '"'); if (false !== $fields && 1 === count($fields) && null === $fields[0]) { // Skip blank lines continue; } if (null === $header) { // Initialize header $this->processHeaderRow(array($fields)); $header = $this->getCSVString($fields); continue; } $save = false; if (false !== $fields) { // Get current row content $currentRow = $this->getCSVString($fields); $isSubrow = true; if (!empty($prevFields)) { // Check if next line is subrow of current $isEmpty = true; foreach ($columns as $column) { $prevKey = $this->getColumnValue($column, $prevFields); $isEmpty = $isEmpty && !(bool) $prevKey; if (!$isEmpty && $prevKey !== $this->getColumnValue($column, $fields)) { $isSubrow = false; break; } } $isSubrow = $isEmpty ? false : $isSubrow; } else { $isSubrow = false; } if (!$isSubrow) { $prevFields = $fields; } // Prepare content if ($isSubrow) { // Current row is a subrow or one of previous rows - add this to $pendingContent $pendingContent .= $currentRow; $ip++; } else { // Current row is a complete row - merge $pendingContent into $content... $content .= $pendingContent; $i += $ip; // ...then initialize $pendingContent with current row value $pendingContent = $currentRow; $ip = 1; } if ($i >= static::MAX_PART_FILE_ROWS && $content) { $save = true; } } if ($save || false === $fields) { $outputFile = LC_DIR_TMP . $subDir . LC_DS . preg_replace('/(\\.csv)$/', sprintf('.part-%02d.csv', $fi++), $outputFileFormat); if (!\Includes\Utils\FileManager::write($outputFile, $header . $content)) { \XLite\Logger::getInstance()->log('Cannot write file ' . $outputFile); $result = array(); break; } $result[] = array('file' => $outputFile, 'delta' => $delta); $delta += $i; $i = 0; $content = ''; } if (false === $fields) { break; } } // while return $result; }
/** * Put prepared code into the files * * @return void */ protected function writeData() { foreach ($this->replacements as $file => $code) { \Includes\Utils\FileManager::write($file = \Includes\Decorator\ADecorator::getCacheClassesDir() . $file, \Includes\Decorator\Utils\Tokenizer::addCodeToClassBody($file, $code)); } }
/** * Put prepared code into the files * * @return void */ protected function writeData() { foreach ($this->replacements as $file => $code) { \Includes\Utils\FileManager::write($file = LC_DIR_CACHE_CLASSES . $file, \Includes\Decorator\Utils\Tokenizer::addCodeToClassBody($file, $code)); } }
/** * Save tracking file * * @param \XLite\Core\CommonCell $data File data * @param string $docType Document type * @param boolean $flush Flag - flush changes or not (OPTIONAL) * * @return void */ protected function saveTrackingFile($data, $docType, $flush = true) { // Save file to temporary location $filePath = LC_DIR_TMP . 't' . strtolower($docType) . $this->getShipment()->getId() . '_' . $data->filename; \Includes\Utils\FileManager::write($filePath, base64_decode($data->image)); $file = $this->getFileByDocType($docType); if (!isset($file)) { $file = new \XLite\Module\XC\CanadaPost\Model\Order\Parcel\Shipment\Tracking\File(); $file->setDocType($docType); \XLite\Core\Database::getEM()->persist($file); $this->addFile($file); } $file->loadFromLocalFile($filePath); $file->setMime($data->mimeType); if ($flush) { \XLite\Core\Database::getEM()->flush(); } }
/** * Add info to a log file * * @param string $message Error message * @param integer $code Error code * @param string $backtrace Stack trace OPTIONAL * * @return void */ protected static function logInfo($message, $code, $backtrace = null) { if (!isset($backtrace) && 'cli' != PHP_SAPI) { ob_start(); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { debug_print_backtrace(); } $backtrace = ob_get_contents(); ob_end_clean(); } $message = date('[d-M-Y H:i:s]') . ' Error (code: ' . $code . '): ' . $message . PHP_EOL; // Add additional info $parts = array('Server API: ' . PHP_SAPI); if (!empty($_SERVER)) { if (isset($_SERVER['REQUEST_METHOD'])) { $parts[] = 'Request method: ' . $_SERVER['REQUEST_METHOD']; } if (isset($_SERVER['REQUEST_URI'])) { $parts[] = 'URI: ' . $_SERVER['REQUEST_URI']; } } $message .= implode(';' . PHP_EOL, $parts) . ';' . PHP_EOL; if ($backtrace && $code != static::ERROR_CLOSED) { $message .= 'Backtrace: ' . PHP_EOL . $backtrace . PHP_EOL . PHP_EOL; } \Includes\Utils\FileManager::write(static::getLogFile($code), $message, FILE_APPEND); }
/** * Correct (if needed) class doc block comment. Works for one element from the queue * * @param \Includes\Decorator\DataStructure\Graph\Classes $node Current node * * @return void */ protected function correctTagsOnElement(\Includes\Decorator\DataStructure\Graph\Classes $node) { $path = LC_DIR_CACHE_CLASSES . $node->getPath(); \Includes\Utils\FileManager::write($path, \Includes\Decorator\Utils\Tokenizer::getSourceCode($path, null, null, null, call_user_func_array(array($node, 'addLinesToDocBlock'), $this->getTagsToAdd($node)), $node->isDecorator() ? 'abstract' : null)); }
/** * Write record * * @param string $string String * * @return void */ protected function writeRecord($string) { if (!isset($this->fileIndex)) { $this->fileIndex = 1; \Includes\Utils\FileManager::write($this->getSitemapPath(), $this->getHead()); } \Includes\Utils\FileManager::write($this->getSitemapPath(), $string, FILE_APPEND); $this->emptyFile = false; if ($this->needSwitch()) { \Includes\Utils\FileManager::write($this->getSitemapPath(), $this->getFooter(), FILE_APPEND); $this->fileIndex++; \Includes\Utils\FileManager::write($this->getSitemapPath(), $this->getHead(), FILE_APPEND); $this->emptyFile = true; } }
/** * Resize icon * * @param integer $width Destination width * @param integer $height Destination height * @param string $path Write path * * @return array */ protected function resizeIcon($width, $height, $path) { $operator = new \XLite\Core\ImageOperator($this); list($newWidth, $newHeight, $result) = $operator->resizeDown($width, $height); return false !== $result && \Includes\Utils\FileManager::write($path, $operator->getImage()) ? array($newWidth, $newHeight) : null; }
/** * Save modules to file * * @param array $modules Modules array * * @return void */ public static function saveModulesToFile(array $modules) { $string = ''; foreach ($modules as $author => $data) { $string .= '[' . $author . ']' . PHP_EOL; foreach ($data as $name => $enabled) { $string .= $name . ' = ' . (bool) $enabled . PHP_EOL; } } if ($string) { \Includes\Utils\FileManager::write(static::getModulesFilePath(), '; <' . '?php /*' . PHP_EOL . $string . '; */ ?' . '>'); } }
/** * Call Get Artifact request * * Reason to Call: * To retrieve a shipping label, a return label, or the paperwork required for shipment pickup or drop-off (manifest). * * More info at: * https://www.canadapost.ca/cpo/mc/business/productsservices/developers/services/shippingmanifest/shipmentartifact.jsf * * @param \XLite\Module\XC\CanadaPost\Model\Base\Link $link Shipment's link object * * @return \XLite\Core\CommonCell */ public function callGetArtifactRequest(\XLite\Module\XC\CanadaPost\Model\Base\Link $link) { $apiHost = $link->getHref(); $result = new \XLite\Core\CommonCell(); try { $request = new \XLite\Core\HTTP\Request($apiHost); $request->requestTimeout = $this->requestTimeout; $request->verb = 'GET'; $request->setHeader('Authorization', 'Basic ' . base64_encode(static::getCanadaPostConfig()->user . ':' . static::getCanadaPostConfig()->password)); $request->setHeader('Accept', 'application/pdf'); $request->setHeader('Accept-language', static::ACCEPT_LANGUAGE_EN); if (static::isOnBehalfOfAMerchant()) { $request->setHeader('Platform-id', $this->getPlatformId()); } $response = $request->sendRequest(); if (isset($response) && $response->code == 200 && strpos($response->headers->ContentType, 'application/pdf') !== false) { // Save valid PDF file to a temporary file $filePath = LC_DIR_TMP . $link->getFileName(); if (\Includes\Utils\FileManager::write($filePath, $response->body)) { $result->filePath = $filePath; } } else { if (!empty($response->body) && strpos($response->headers->ContentType, 'xml') > -1) { // Parse errors $result = $this->parseResponse($response->body); } else { if (isset($response) && $response->code == 202) { $result->errors = array('GAR_202' => 'The requested resource is not yet available. Please try again later.'); } else { // Other errors $result->errors = array('GAR_01' => sprintf('Error while connecting to the Canada Post host (%s) during Get Artifact request', $apiHost)); } } } } catch (\Exception $e) { if (!isset($result->errors)) { $result->errors = array(); } $result->errors += array($e->getCode(), $e->getMessage()); } return $result; }
/** * Execute request (Lookup issuer list) * * @return boolean */ public function doRequest() { if ($this->checkConfiguration()) { $sCacheFile = false; // Used cached issuers? if ($this->bTestMode == true && $this->sCachePath) { $sCacheFile = $this->sCachePath . 'cache_ideal_rb_prof_issuers_'; $bFileCreated = false; if (file_exists($sCacheFile) == false) { $bFileCreated = true; // Attempt to create cache file \Includes\Utils\FileManager::write($sCacheFile, ''); } if (file_exists($sCacheFile) && is_readable($sCacheFile) && is_writable($sCacheFile)) { if ($bFileCreated || filemtime($sCacheFile) > strtotime('-24 Hours')) { // Read data from cache file if ($sData = file_get_contents($sCacheFile)) { return unserialize($sData); } } } else { $sCacheFile = false; } } $sTimestamp = gmdate('Y-m-d\\TH:i:s.000\\Z'); $sCertificateFingerprint = $this->getCertificateFingerprint($this->sPrivateCertificateFile); $sXml = '<DirectoryReq xmlns="http://www.idealdesk.com/ideal/messages/mer-acq/3.3.1" version="3.3.1">'; $sXml .= '<createDateTimestamp>' . $sTimestamp . '</createDateTimestamp>'; $sXml .= '<Merchant>'; $sXml .= '<merchantID>' . $this->sMerchantId . '</merchantID>'; $sXml .= '<subID>' . $this->sSubId . '</subID>'; $sXml .= '</Merchant>'; $sXml .= '</DirectoryReq>'; // Calculate <DigestValue> $sDigestValue = $this->getMessageDigest($sXml); $sXml = '<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">'; $sXml .= '<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></CanonicalizationMethod>'; $sXml .= '<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></SignatureMethod>'; $sXml .= '<Reference URI="">'; $sXml .= '<Transforms>'; $sXml .= '<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform>'; $sXml .= '</Transforms>'; $sXml .= '<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></DigestMethod>'; $sXml .= '<DigestValue>' . $sDigestValue . '</DigestValue>'; $sXml .= '</Reference>'; $sXml .= '</SignedInfo>'; // Calculate <SignatureValue> $sSignatureValue = $this->getSignature($sXml, $this->sPrivateKeyFile, $this->sPrivateKeyPass); $sXml = '<' . '?' . 'xml version="1.0" encoding="UTF-8"' . '?' . '>' . "\n"; $sXml .= '<DirectoryReq xmlns="http://www.idealdesk.com/ideal/messages/mer-acq/3.3.1" version="3.3.1">'; $sXml .= '<createDateTimestamp>' . $sTimestamp . '</createDateTimestamp>'; $sXml .= '<Merchant>'; $sXml .= '<merchantID>' . $this->sMerchantId . '</merchantID>'; $sXml .= '<subID>' . $this->sSubId . '</subID>'; $sXml .= '</Merchant>'; $sXml .= '<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">'; $sXml .= '<SignedInfo>'; $sXml .= '<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></CanonicalizationMethod>'; $sXml .= '<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></SignatureMethod>'; $sXml .= '<Reference URI="">'; $sXml .= '<Transforms>'; $sXml .= '<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform>'; $sXml .= '</Transforms>'; $sXml .= '<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></DigestMethod>'; $sXml .= '<DigestValue>' . $sDigestValue . '</DigestValue>'; $sXml .= '</Reference>'; $sXml .= '</SignedInfo>'; $sXml .= '<SignatureValue>' . $sSignatureValue . '</SignatureValue>'; $sXml .= '<KeyInfo>'; $sXml .= '<KeyName>' . $sCertificateFingerprint . '</KeyName>'; $sXml .= '</KeyInfo>'; $sXml .= '</Signature>'; $sXml .= '</DirectoryReq>'; $sXmlReply = $this->postToHost($this->sAquirerUrl, $sXml); if ($sXmlReply) { if ($this->verifyResponse($sXmlReply, 'DirectoryRes')) { $aIssuerList = array(); while (strpos($sXmlReply, '<issuerID>')) { $sIssuerId = $this->parseFromXml('issuerID', $sXmlReply); $sIssuerName = $this->parseFromXml('issuerName', $sXmlReply); $aIssuerList[$sIssuerId] = $sIssuerName; $sXmlReply = substr($sXmlReply, strpos($sXmlReply, '</Issuer>') + 9); } // Save data in cache? if ($sCacheFile) { file_put_contents($sCacheFile, serialize($aIssuerList)); } return $aIssuerList; } } } return false; }
/** * Compile and save template * * @param string $original Relative file path * @param boolean $force Flag to force compilation OPTIONAL * * @return string */ public function prepare($original, $force = false) { $compiled = $this->compileDir . substr($original, $this->rootDirLength) . '.php'; if (!$this->isTemplateValid($original, $compiled) || $force) { \Includes\Utils\FileManager::write($compiled, $this->parse($original)); touch($compiled, filemtime($original)); } return $compiled; }
/** * Return resource structure from the file cache * * @param string $type File type of resource (js/css) * @param array $resources Resources for caching * @param array $paramsForCache Parameters of file cache (directory structure path to file) * @param string $prepareCacheFileMethod Method of $this object to read one resource entity and do some inner work if it is necessary * * @return array */ protected function getResourceFromCache($type, array $resources, array $paramsForCache, $prepareCacheFileMethod) { $pathToCacheDir = static::getResourceCacheDir($paramsForCache); \Includes\Utils\FileManager::mkdirRecursive($pathToCacheDir); $file = hash('sha256', serialize($resources)) . '.' . $type; $filePath = $pathToCacheDir . $file; if (!\Includes\Utils\FileManager::isFile($filePath)) { foreach ($resources as $resource) { \Includes\Utils\FileManager::write($filePath, $this->{$prepareCacheFileMethod}($resource['file']), FILE_APPEND); } } return array('file' => $filePath, 'url' => \XLite::getInstance()->getShopURL(str_replace(LC_DS, '/', substr($filePath, strlen(LC_DIR_ROOT))), \XLite\Core\Request::getInstance()->isHTTPS())); }
/** * Update payment methods with data received from the marketplace * * @param array List of payment methods received from marketplace * * @return void */ public function updatePaymentMethods($data) { if (!empty($data) && is_array($data)) { $tmpMethods = $this->createQueryBuilder('m')->select('m')->getQuery()->getArrayResult(); if ($tmpMethods) { $methods = array(); // Prepare associative array of existing methods with 'service_name' as a key foreach ($tmpMethods as $m) { $methods[$m['service_name']] = $m; } foreach ($data as $i => $extMethod) { if (!empty($extMethod['service_name'])) { $extMethod['fromMarketplace'] = 1; $extMethod['moduleEnabled'] = 0; $data[$i] = $extMethod; if (isset($methods[$extMethod['service_name']])) { // Method already exists in the database if (!$methods[$extMethod['service_name']]['fromMarketplace']) { $data[$i] = array('service_name' => $extMethod['service_name'], 'countries' => !empty($extMethod['countries']) ? $extMethod['countries'] : array(), 'exCountries' => !empty($extMethod['exCountries']) ? $extMethod['exCountries'] : array(), 'orderby' => !empty($extMethod['orderby']) ? $extMethod['orderby'] : 0); } } } else { // Wrong data row, ignore this unset($data[$i]); } } // Save data as temporary yaml file $yaml = \Symfony\Component\Yaml\Yaml::dump(array('XLite\\Model\\Payment\\Method' => $data)); $yamlFile = LC_DIR_TMP . 'pm.yaml'; \Includes\Utils\FileManager::write(LC_DIR_TMP . 'pm.yaml', $yaml); // Update database from yaml file \XLite\Core\Database::getInstance()->loadFixturesFromYaml($yamlFile); } } }
/** * Save modules to file * * @param array $modules Modules array * * @return integer|boolean */ protected static function saveUnsafeModulesToFile(array $modules) { $path = static::getUnsafeModulesFilePath(); $string = '; <' . '?php /*' . PHP_EOL; $i = 0; foreach ($modules as $author => $names) { $string .= '[' . $author . ']' . PHP_EOL; foreach ($names as $name => $enabled) { $string .= $name . ' = ' . $enabled . PHP_EOL; $i++; } } $string .= '; */ ?' . '>'; return $i ? \Includes\Utils\FileManager::write($path, $string) : false; }
/** * Update shipping methods with data received from the marketplace * * @param array $data List of payment methods received from marketplace * * @return void */ public function updateShippingMethods($data) { if (!empty($data) && is_array($data)) { $tmpMethods = $this->createQueryBuilder('m')->select('m')->getQuery()->getArrayResult(); if ($tmpMethods) { $methods = array(); // Prepare associative array of existing methods with 'processor' as a key foreach ($tmpMethods as $m) { if ('offline' !== $m['processor'] && '' === $m['carrier']) { $methods[$m['processor']] = $m; } } foreach ($data as $i => $extMethod) { if (!empty($extMethod['processor'])) { $extMethod['fromMarketplace'] = 1; $data[$i] = $extMethod; if (isset($methods[$extMethod['processor']])) { // Method already exists in the database if (!$methods[$extMethod['processor']]['fromMarketplace']) { // Method is not from marketplace, do not update unset($data[$i]); } } } else { // Wrong data row, ignore this unset($data[$i]); } } // Save data as temporary yaml file $yaml = \Symfony\Component\Yaml\Yaml::dump(array('XLite\\Model\\Shipping\\Method' => $data)); $yamlFile = LC_DIR_TMP . 'pm.yaml'; \Includes\Utils\FileManager::write(LC_DIR_TMP . 'pm.yaml', $yaml); // Update database from yaml file \XLite\Core\Database::getInstance()->loadFixturesFromYaml($yamlFile); } } }
/** * Save * * @param string $code Code * * @return void */ protected function saveCode($code) { if ("\r\n" != PHP_EOL) { $code = str_replace("\r\n", PHP_EOL, $code); } $code = str_replace(chr(194) . chr(160), ' ', $code); $file = $this->getFileName(); \Includes\Utils\FileManager::write($file, $code); if (\Includes\Utils\FileManager::isFileWriteable($file)) { \XLite\Core\TopMessage::addInfo('Your custom file is successfully saved'); \Includes\Utils\FileManager::deleteFile(str_replace('custom', 'custom.min', $file)); \XLite\Core\Database::getRepo('XLite\\Model\\Config')->createOption(array('name' => $this->getBackupName(), 'value' => $code, 'category' => 'XC\\ThemeTweaker')); \XLite\Core\Config::updateInstance(); $config = \XLite\Core\Config::getInstance()->Performance; if ($config->aggregate_css || $config->aggregate_js) { \Includes\Utils\FileManager::unlinkRecursive(LC_DIR_CACHE_RESOURCES); \XLite\Core\TopMessage::addInfo('Aggregation cache has been cleaned'); } } else { \XLite\Core\TopMessage::addError('The file {{file}} does not exist or is not writable.', array('file' => $file)); } }
/** * Write data from request into a file * * @param \PEAR2\HTTP\Request\Response $response Response to get data * * @return string */ protected function writeDataToFile(\PEAR2\HTTP\Request\Response $response) { if (!\Includes\Utils\FileManager::isDir(LC_DIR_TMP)) { \Includes\Utils\FileManager::mkdir(LC_DIR_TMP); } if (!\Includes\Utils\FileManager::isDirWriteable(LC_DIR_TMP)) { \Includes\ErrorHandler::fireError('Directory "' . LC_DIR_TMP . '" is not writeable'); } $path = \Includes\Utils\FileManager::getUniquePath(LC_DIR_TMP, uniqid() . '.' . \Includes\Utils\PHARManager::getExtension() ?: 'tar'); return isset($response->body) && \Includes\Utils\FileManager::write($path, $response->body) ? $path : null; }
/** * Step completed * * @param string $step Current step * * @return void */ protected static function completeStep($step) { // "Step completed" indicator \Includes\Utils\FileManager::write(static::getCacheStateIndicatorFileName($step), static::getCacheStateIndicatorFileContent()); // Write classes cache if ($root = static::getClassesTree(false)) { \Includes\Utils\FileManager::write(static::getClassesHashPath(), serialize(array_merge($root->findAll(), array($root)))); } // Remove the "rebuilding cache" indicator file static::checkRebuildIndicatorState(); if (static::isSkipRedirectAfterLastStep($step)) { // Do not redirect after last step // (this mode is used when cache builder was launched from LC standalone installation script) static::displayCompleteMessage(); exit; } elseif (!static::isDoOneStepOnly()) { // Perform redirect (needed for multi-step cache generation) \Includes\Utils\Operator::refresh(); } }
/** * Save fixtures to file * * @return void */ protected static function saveFile() { $string = ''; foreach (array_values(array_unique(static::getFixtures())) as $index => $value) { $string .= ++$index . ' = "' . $value . '"' . PHP_EOL; } \Includes\Utils\FileManager::write(static::getFixturesFilePath(), '; <?php /*' . PHP_EOL . $string . '; */ ?>'); }
/** * Write PHP class to the files * * @param \Includes\Decorator\DataStructure\Graph\Classes $node Current class node * @param \Includes\Decorator\DataStructure\Graph\Classes $parent Parent class node * * @return void */ public static function writeClassFile(\Includes\Decorator\DataStructure\Graph\Classes $node, \Includes\Decorator\DataStructure\Graph\Classes $parent = null) { \Includes\Utils\FileManager::write(\Includes\Decorator\ADecorator::getCacheClassesDir() . $node->getPath(), $node->getSource($parent)); }
/** * Write PHP class to the files * * @param \Includes\Decorator\DataStructure\Graph\Classes $node Current class node * @param \Includes\Decorator\DataStructure\Graph\Classes $parent Parent class node * * @return void */ public static function writeClassFile(\Includes\Decorator\DataStructure\Graph\Classes $node, \Includes\Decorator\DataStructure\Graph\Classes $parent = null) { \Includes\Utils\FileManager::write(LC_DIR_CACHE_CLASSES . $node->getPath(), $node->getSource($parent)); }
/** * Get local path for file-based PHP functions * * @return string */ protected function getLocalPath() { $isTempFile = false; if ($this->isURL()) { if (ini_get('allow_url_fopen')) { $path = $this->getPath(); } else { $path = tempnam(LC_DIR_TMP, 'analyse_file'); if (!\Includes\Utils\FileManager::write($path, $this->getBody())) { \XLite\Logger::getInstance()->log('Unable to write data to file \'' . $path . '\'.', LOG_ERR); $path = false; } $isTempFile = true; } } else { $path = $this->getStoragePath(); } return array($path, $isTempFile); }