protected function init() { $settings = Settings::instance(); if (!strlen($settings->profile_id)) { throw new ApplicationException(trans('rainlab.googleanalytics::lang.strings.notconfigured')); } if (!$settings->gapi_key) { throw new ApplicationException(trans('rainlab.googleanalytics::lang.strings.keynotuploaded')); } $client = new Google_Client(); /* * Set caching */ $cache = new Google_Cache_File(temp_path() . '/Google_Client'); $client->setCache($cache); /* * Set assertion credentials */ $auth = json_decode($settings->gapi_key->getContents(), true); $client->setAuthConfig($auth); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); if ($client->isAccessTokenExpired()) { $client->refreshTokenWithAssertion(); } $this->client = $client; $this->service = new Google_Service_Analytics($client); $this->viewId = 'ga:' . $settings->profile_id; }
public function speak($lang = 'en', $text = 'text not provided') { // Create temp path $uxmsTtsTempPath = temp_path(Configs::get('temp_name')); if (!File::isDirectory($uxmsTtsTempPath)) { if (!File::makeDirectory($uxmsTtsTempPath)) { throw new ApplicationException('Unable to create temp directory: ' . $uxmsTtsTempPath); } } // Create storage path $uxmsTtsStoragePath = storage_path() . '/app/' . Configs::get('final_audio_folder_name'); if (!File::isDirectory($uxmsTtsStoragePath)) { if (!File::makeDirectory($uxmsTtsStoragePath)) { throw new ApplicationException('Unable to create storage directory: ' . $uxmsTtsStoragePath); } } // Check if saved audios will be using and if it exists in stor dir if (Configs::get('use_saved_files')) { if (File::exists($uxmsTtsStoragePath . '/' . md5($text) . '.mp3')) { return $this->tts->getAudioElementOrUri(md5($text)); } } // Lets create the speech $this->tts->text($lang, $text)->saveFile(false); // Do not forget to activate puging from settings.. if (Configs::get('purge_temp')) { $this->tts->clearTemp(); } return $this->tts->getAudioElementOrUri(); }
/** * Download remote file and save to temp. * * @param string * @return File * @throws SystemException If file could not be downloaded */ public function fromUrl($url) { $this->source = $url; $fileName = basename(parse_url($url, PHP_URL_PATH)); $localFile = temp_path('images') . '/' . $fileName; $response = Http::get($url, function ($http) use($localFile) { $http->toFile($localFile); }); if ($response->code == 200) { $this->data = $localFile; $this->tempFile = $localFile; } return $this; }
/** * Initialize this singleton. */ protected function init() { $this->pluginManager = PluginManager::instance(); $this->versionManager = VersionManager::instance(); $this->tempDirectory = temp_path(); $this->baseDirectory = base_path(); $this->disableCoreUpdates = Config::get('cms.disableCoreUpdates', false); $this->bindContainerObjects(); /* * Ensure temp directory exists */ if (!File::isDirectory($this->tempDirectory)) { File::makeDirectory($this->tempDirectory, 0777, true); } }
protected function getSystemWarnings() { $warnings = []; $writablePaths = [temp_path(), themes_path(), storage_path(), storage_path('app'), storage_path('logs'), storage_path('framework'), storage_path('cms'), storage_path('cms/cache'), storage_path('cms/twig'), storage_path('cms/combiner')]; $requiredExtensions = ['GD' => extension_loaded('gd'), 'fileinfo' => extension_loaded('fileinfo'), 'Zip' => class_exists('ZipArchive'), 'cURL' => function_exists('curl_init') && defined('CURLOPT_FOLLOWLOCATION'), 'OpenSSL' => function_exists('openssl_random_pseudo_bytes')]; foreach ($writablePaths as $path) { if (!is_writable($path)) { $warnings[] = Lang::get('backend::lang.warnings.permissions', ['name' => '<strong>' . $path . '</strong>']); } } foreach ($requiredExtensions as $extension => $installed) { if (!$installed) { $warnings[] = Lang::get('backend::lang.warnings.extension', ['name' => '<strong>' . $extension . '</strong>']); } } return $warnings; }
/** * Create the report * @return Response */ public function store() { $input = Input::all(); $file = Input::file('file'); $filename = $file->getClientOriginalName(); $file->move(temp_path(), $filename); $filename = str_replace('.ZIP', '.zip', $filename); $unzipSuccess = Unzip(temp_path() . "/{$filename}", temp_path()); $contents = file_get_contents(temp_path() . "/report_generator.json"); $report_info = json_decode($contents, true); $input = array('name' => $report_info['name'], 'author' => $report_info['author'], 'version' => $report_info['version'], 'website' => $report_info['website'], 'modules' => json_encode($report_info['modules']), 'show_calendars' => $report_info['show_calendars']); if ($report_generator = ReportGenerator::where('name', '=', $input['name'])->first()) { $report_generator->update($input); } else { $report_generator = ReportGenerator::create($input); } return Redirect::to("{$this->link_type}/report-generators")->with('success_message', trans('success_messages.report_generator_install')); }
public function import($theme, $data = [], $sessionKey = null) { @set_time_limit(3600); $this->theme = $theme; $this->fill($data); try { $file = $this->uploaded_file()->withDeferred($sessionKey)->first(); if (!$file) { throw new ApplicationException('There is no file attached to import!'); } $themePath = $this->theme->getPath(); $tempPath = temp_path() . '/' . uniqid('oc'); $zipName = uniqid('oc'); $zipPath = temp_path() . '/' . $zipName; File::put($zipPath, $file->getContents()); if (!@mkdir($tempPath)) { throw new ApplicationException('Unable to create directory ' . $tempPath); } Zip::extract($zipPath, $tempPath); // if (File::isFile($tempPath.'/theme.yaml')) { // File::copy($tempPath.'/theme.yaml', $themePath.'/theme.yaml'); // } if (File::isDirectory($tempPath . '/meta')) { $this->copyDirectory($tempPath . '/meta', $themePath . '/meta'); } foreach ($this->folders as $folder) { if (!array_key_exists($folder, $this->getFoldersOptions())) { continue; } $this->copyDirectory($tempPath . '/' . $folder, $themePath . '/' . $folder); } File::deleteDirectory($tempPath); File::delete($zipPath); $file->delete(); } catch (Exception $ex) { if (!empty($tempPath) && File::isDirectory($tempPath)) { File::deleteDirectory($tempPath); } if (!empty($zipPath) && File::isFile($zipPath)) { File::delete($zipPath); } throw $ex; } }
/** * Execute the console command. * * @return mixed */ public function handle() { // get random file name and file extension $path = temp_path(str_random()); $originalExtension = substr(strrchr($this->argument('url'), '.'), 1); // download file and store it $this->info('Downloading the file...' . PHP_EOL); $response = $this->client->get($this->argument('url'), ['verify' => storage_path('app/wildcard_ccu_edu_tw')]); $this->filesystem->put("{$path}.{$originalExtension}", $response->getBody()->getContents()); // extract the file $this->info('Extracting the file...' . PHP_EOL); (new PharData("{$path}.{$originalExtension}"))->decompress(); (new PharData("{$path}.tar"))->extractTo(temp_path()); // delete non-used files $this->info('Deleting non-used the file...' . PHP_EOL); $this->filesystem->delete(["{$path}.{$originalExtension}", "{$path}.tar", temp_path('index.html')]); $this->filesystem->delete($this->filesystem->glob(temp_path('*e.html'))); $this->info('Succeed!'); }
public function getMedia($mediaId) { $query = ['media_id' => $mediaId]; $result = $this->httpGet(static::MEDIA_GET_URL, $query, [], true, false); $contentType = $result->getHeader('Content-Type')[0]; if (strpos($contentType, 'application/json') !== false) { $result = $this->processHttpResult($result); return $this->processWechatApiResult($result); } $contentDisposition = $result->getHeader('Content-disposition')[0]; preg_match('#filename="(.*)"#', $contentDisposition, $matches); $filename = $matches[1]; $tempDir = temp_path(uniqid()); if (!is_dir($tempDir)) { mkdir($tempDir); } $tempPath = $tempDir . '/' . $filename; file_put_contents($tempPath, $result->getBody()); return new File($tempPath); }
protected function init() { $settings = Settings::instance(); if (!strlen($settings->project_name)) { throw new ApplicationException(Lang::get('rainlab.googleanalytics::lang.exceptions.google_api_not_configured')); } if (!$settings->gapi_key) { throw new ApplicationException(Lang::get('rainlab.googleanalytics::lang.exceptions.google_api_key_not_uploaded')); } $tmpDir = temp_path() . '/Google_Client'; $this->client = new Google_Client(); $this->client->setApplicationName($settings->project_name); $this->client->setClassConfig('Google_Cache_File', 'directory', $tmpDir); /* * Set assertion credentials */ $this->client->setAssertionCredentials(new Google_Auth_AssertionCredentials($settings->app_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $settings->gapi_key->getContents())); $this->client->setClientId($settings->client_id); $this->service = new Google_Service_Analytics($this->client); $this->viewId = 'ga:' . $settings->profile_id; }
public function installLanguageFile($file) { $filename = $this->uploadLanguageFile($file); $filename = str_replace('.ZIP', '.zip', $filename); $canonical = str_replace('.zip', '', $filename); $temp_import_path = temp_path() . '/translations_import/' . $canonical . '/'; if (File::exists($temp_import_path)) { File::deleteDirectory($temp_import_path); } $unzipSuccess = Unzip("{$this->temp_path}{$filename}", $temp_import_path); if (!$unzipSuccess) { throw new Exception("The language file {$filename} couldn\\'t be extracted."); } if (!File::exists("{$temp_import_path}language.json")) { throw new Exception('language.json doesn\'t exist in the language file'); } $language_config = json_decode(file_get_contents("{$temp_import_path}/language.json"), true); $language_dir = $this->language_path . $language_config['code']; File::copyDirectory($temp_import_path . 'lang', $language_dir); // Import the translations from file to database $this->translation_manager->importTranslations(); return $language_config; }
public function export($theme, $data = []) { $this->theme = $theme; $this->fill($data); try { $themePath = $this->theme->getPath(); $tempPath = temp_path() . '/' . uniqid('oc'); $zipName = uniqid('oc'); $zipPath = temp_path() . '/' . $zipName; if (!File::makeDirectory($tempPath)) { throw new ApplicationException('Unable to create directory ' . $tempPath); } if (!File::makeDirectory($metaPath = $tempPath . '/meta')) { throw new ApplicationException('Unable to create directory ' . $metaPath); } File::copy($themePath . '/theme.yaml', $tempPath . '/theme.yaml'); File::copyDirectory($themePath . '/meta', $metaPath); foreach ($this->folders as $folder) { if (!array_key_exists($folder, $this->getFoldersOptions())) { continue; } File::copyDirectory($themePath . '/' . $folder, $tempPath . '/' . $folder); } Zip::make($zipPath, $tempPath); File::deleteDirectory($tempPath); } catch (Exception $ex) { if (strlen($tempPath) && File::isDirectory($tempPath)) { File::deleteDirectory($tempPath); } if (strlen($zipPath) && File::isFile($zipPath)) { File::delete($zipPath); } throw $ex; } return $zipName; }
/** * Generate a zip file of the module * @param $module_alias * @return string */ private function generateZip($module_alias) { $zip_file = temp_path() . "/{$module_alias}.zip"; $this->Zip(temp_path() . "/{$module_alias}/", $zip_file, false); File::deleteDirectory(temp_path() . "/{$module_alias}/"); return $zip_file; }
/** * Define the internal working path, override this method to define. */ public function getTempPath() { $path = temp_path() . '/uploads'; if (!FileHelper::isDirectory($path)) { FileHelper::makeDirectory($path, 0777, true, true); } return $path; }
/** * Create the report generator for download * @param $input * @return */ private function getReportGenerator($input) { if (isset($input['id'])) { unset($input['id']); } if (isset($input['created_by'])) { unset($input['created_by']); } if (isset($input['updated_by'])) { unset($input['updated_by']); } if (isset($input['created_at'])) { unset($input['created_at']); } if (isset($input['updated_at'])) { unset($input['updated_at']); } $report_alias = Str::slug($input['name'], '_'); $report_file = temp_path() . "/report_generator.json"; file_put_contents($report_file, json_encode($input)); $zip_file = temp_path() . "/report_{$report_alias}.zip"; Zip(temp_path() . "/report_generator.json", $zip_file, false); return $zip_file; }
/** * Create cache folder if not exists * * @param $ident */ private function checkCacheFolder($ident) { $cacheFolder = temp_path($this->cachePathPrefix . '/'); if (!file_exists($cacheFolder)) { mkdir($cacheFolder); } if (!$ident) { $ident = $this->undefinedFolderName; } $identFolder = temp_path($this->cachePathPrefix . '/' . $ident . '/'); if (!file_exists($identFolder)) { mkdir($identFolder); } }
/** * Converts a data collection to a CSV file. */ protected function processExportData($columns, $results, $options) { /* * Validate */ if (!$results) { throw new ApplicationException('There was no data supplied to export'); } /* * Parse options */ $defaultOptions = ['useOutput' => false, 'fileName' => 'export.csv', 'delimiter' => null, 'enclosure' => null, 'escape' => null]; $options = array_merge($defaultOptions, $options); $columns = $this->exportExtendColumns($columns); /* * Prepare CSV */ $csv = CsvWriter::createFromFileObject(new SplTempFileObject()); if ($options['delimiter'] !== null) { $csv->setDelimiter($options['delimiter']); } if ($options['enclosure'] !== null) { $csv->setEnclosure($options['enclosure']); } if ($options['escape'] !== null) { $csv->setEscape($options['escape']); } /* * Add headers */ $headers = $this->getColumnHeaders($columns); $csv->insertOne($headers); /* * Add records */ foreach ($results as $result) { $data = $this->matchDataToColumns($result, $columns); $csv->insertOne($data); } /* * Output */ if ($options['useOutput']) { $csv->output($options['fileName']); } /* * Save for download */ $csvName = uniqid('oc'); $csvPath = temp_path() . '/' . $csvName; $output = $csv->__toString(); File::put($csvPath, $output); return $csvName; }
/** * Returns the absolute path for a image copy. * * @param $size * * @return string */ protected function getStoragePath($size) { $path = temp_path('public/' . $this->getPartitionDirectory()); if (!FileHelper::isDirectory($path)) { FileHelper::makeDirectory($path, 0777, true, true); } $storagePath = $path . $this->getStorageFilename($size); $this->sourceSet->push($size, $storagePath); return $storagePath; }
/** * Cleans up the temporary files/folders from temporary directory */ public function cleanup() { File::deleteDirectory($this->full_path); File::delete(temp_path() . '/' . $this->filename); }
/** * Clears the temp dir * * @param string $which * @return Tts */ public function clearTemp($which = '*') { $uxmsTtsTempPath = temp_path(Configs::get('temp_name')); try { if ($which == '*') { array_map('unlink', glob($uxmsTtsTempPath . "/{$which}")); } else { array_map('unlink', glob($uxmsTtsTempPath . "/{$which}_*")); } } catch (\Exception $e) { } return $this; }
/** * Download a previously compiled export file. * @return void */ public function download($name, $outputName = null) { if (!preg_match('/^oc[0-9a-z]*$/i', $name)) { throw new ApplicationException('File not found'); } $csvPath = temp_path() . '/' . $name; if (!file_exists($csvPath)) { throw new ApplicationException('File not found'); } $headers = Response::download($csvPath, $outputName)->headers->all(); $result = Response::make(File::get($csvPath), 200, $headers); @unlink($csvPath); return $result; }
/** * Execute the console command. * * @return mixed */ public function handle() { // 確認是否有 api key if (null === $this->apiPublicKey) { $this->error('Invalid VirusTotal api public key.'); return; } if (!$this->filesystem->isFile($file = $this->argument('file'))) { $this->error('File not exists.'); return; } // 取得欲儲存的 Model if (null === ($model = $this->option('model'))) { $model = $this->ask('The Eloquent ORM Model'); } // 取得欲儲存的欄位 if (null === ($column = $this->option('column'))) { $column = $this->ask('The table\'s column to store the result'); } // 取得欲儲存的欄位 if (null === ($index = $this->option('index'))) { $index = $this->ask('The primary key\'s value to specific row'); } // 檢查 Model 是否存在 if (!class_exists($model)) { $this->error('Model not exists.'); return; } $model = (new $model())->find($index); // 檢查該比資料是否存在 if (null === $model) { $this->error('Model not exists'); return; } // 檢查欄位是否存在 if (!Schema::hasColumn($model->getTableName(), $column)) { $this->error('Column not exists.'); return; } // 檢查是否有替代檔名 if (null !== ($fakeName = $this->option('fakeName')) && strlen($fakeName) > 0) { $fakePath = temp_path($fakeName); $this->filesystem->copy($file, $fakePath); $file = $fakePath; } $virusTotal = new File($this->apiPublicKey); $report = $virusTotal->scan($file); $model->{$column} = $report['permalink']; $model->save(); if (isset($fakePath)) { $this->filesystem->delete($fakePath); } $this->info('File scan successfully!'); }
protected function moveAssets() { // 移動 css 檔 $this->filesystem->move(base_path('resources/views/css/ccu.css.php'), cdn_path('css/ccu.min.css')); // 移動 js 檔 $this->filesystem->move(temp_path('vendors.min.js'), cdn_path('js/vendors.min.js')); $this->info('Move assets successfully!'); }
public function testGetDataWithDateAndIdent() { $url = $this->validUrl; $date = '12.1.2016'; $ident = 'test'; // at first time, data should be saved to file $data = $this->model->getData($url, $date, $ident); $this->assertNotEmpty($data); // check if data exists $filename = temp_path($this->cacheIdent . '/test/12.01.2016.txt'); $this->assertFileExists($filename); }
function __construct() { $this->modules_path = app_path() . '/Modules/'; $this->temp_path = temp_path() . '/'; }
protected function cropImage($imageSrcPath, $selectionData, $cropSessionKey, $path) { $originalFileName = basename($path); $path = rtrim(dirname($path), '/') . '/'; $fileName = basename($imageSrcPath); if (strpos($fileName, '..') !== false || strpos($fileName, '/') !== false || strpos($fileName, '\\') !== false) { throw new SystemException('Invalid image file name.'); } $selectionParams = ['x', 'y', 'w', 'h']; foreach ($selectionParams as $paramName) { if (!array_key_exists($paramName, $selectionData)) { throw new SystemException('Invalid selection data.'); } if (!ctype_digit($selectionData[$paramName])) { throw new SystemException('Invalid selection data.'); } } $sessionDirectoryPath = $this->getCropSessionDirPath($cropSessionKey); $fullSessionDirectoryPath = temp_path($sessionDirectoryPath); if (!File::isDirectory($fullSessionDirectoryPath)) { throw new SystemException('The image editing session is not found.'); } /* * Find the image on the disk and resize it */ $imagePath = $fullSessionDirectoryPath . '/' . $fileName; if (!File::isFile($imagePath)) { throw new SystemException('The image is not found on the disk.'); } $extension = pathinfo($originalFileName, PATHINFO_EXTENSION); $targetImageName = basename($originalFileName, '.' . $extension) . '-' . $selectionData['x'] . '-' . $selectionData['y'] . '-' . $selectionData['w'] . '-' . $selectionData['h'] . '-'; $targetImageName .= time(); $targetImageName .= '.' . $extension; $targetTmpPath = $fullSessionDirectoryPath . '/' . $targetImageName; /* * Crop the image, otherwise copy original to target destination. */ if ($selectionData['w'] == 0 || $selectionData['h'] == 0) { File::copy($imagePath, $targetTmpPath); } else { $resizer = Resizer::open($imagePath); $resizer->resample($selectionData['x'], $selectionData['y'], $selectionData['w'], $selectionData['h'], $selectionData['w'], $selectionData['h']); $resizer->save($targetTmpPath, 95); } /* * Upload the cropped file to the Library */ $targetFolder = $path . 'cropped-images'; $targetPath = $targetFolder . '/' . $targetImageName; $library = MediaLibrary::instance(); $library->put($targetPath, file_get_contents($targetTmpPath)); return ['publicUrl' => $library->getPathUrl($targetPath), 'documentType' => MediaLibraryItem::FILE_TYPE_IMAGE, 'itemType' => MediaLibraryItem::TYPE_FILE, 'path' => $targetPath, 'title' => $targetImageName, 'folder' => $targetFolder]; }
protected function cropImage($imageSrcPath, $selectionData, $cropSessionKey, $path) { $originalFileName = basename($path); $path = rtrim(dirname($path), '/') . '/'; $fileName = basename($imageSrcPath); if (strpos($fileName, '..') !== false || strpos($fileName, '/') !== false || strpos($fileName, '\\') !== false) { throw new SystemException('Invalid image file name.'); } $selectionParams = ['x', 'y', 'w', 'h']; foreach ($selectionParams as $paramName) { if (!array_key_exists($paramName, $selectionData)) { throw new SystemException('Invalid selection data.'); } if (!ctype_digit($selectionData[$paramName])) { throw new SystemException('Invalid selection data.'); } } $sessionDirectoryPath = $this->getCropSessionDirPath($cropSessionKey); $fullSessionDirectoryPath = temp_path($sessionDirectoryPath); if (!File::isDirectory($fullSessionDirectoryPath)) { throw new SystemException('The image editing session is not found.'); } // Find the image on the disk and resize it $imagePath = $fullSessionDirectoryPath . '/' . $fileName; if (!File::isFile($imagePath)) { throw new SystemException('The image is not found on the disk.'); } $extension = pathinfo($originalFileName, PATHINFO_EXTENSION); $targetImageName = basename($originalFileName, '.' . $extension) . '-' . $selectionData['x'] . '-' . $selectionData['y'] . '-' . $selectionData['w'] . '-' . $selectionData['h'] . '-'; $targetImageName .= time(); $targetImageName .= '.' . $extension; $targetTmpPath = $fullSessionDirectoryPath . '/' . $targetImageName; if ($selectionData['w'] == 0 || $selectionData['h'] == 0) { // If cropping is not required, copy the oiginal image to the target destination. File::copy($imagePath, $targetTmpPath); } else { $resizer = Resizer::open($imagePath); $resizer->resample($selectionData['x'], $selectionData['y'], $selectionData['w'], $selectionData['h'], $selectionData['w'], $selectionData['h']); $resizer->save($targetTmpPath, 95); } // Upload the cropped file to the Library $targetPath = $path . 'cropped-images/' . $targetImageName; $library = MediaLibrary::instance(); $library->put($targetPath, file_get_contents($targetTmpPath)); return $library->getPathUrl($targetPath); }