/** * doAjax * * @return mixed */ protected function doExecute() { if (!$this->app->get('unidev.image.storage')) { throw new \LogicException('No image storage set in config.'); } $file = $this->input->files->get($this->fieldName); $folder = $this->input->getPath('folder'); $folder = ltrim($folder . '/', '/'); if ($file->getError()) { throw new \RuntimeException('Upload fail: ' . UploadedFileHelper::getUploadMessage($file->getError()), 500); } $id = $this->getImageName($file->getClientFilename()); $temp = $this->getImageTemp($id, File::getExtension($file->getClientFilename())); if (!is_dir(dirname($temp))) { Folder::create(dirname($temp)); } $file->moveTo($temp); $temp = $this->resize($temp); if (!is_file($temp)) { throw new \RuntimeException('Temp file not exists'); } $url = ImageUploader::upload($temp, $this->getImagePath($folder . $id, File::getExtension($temp))); File::delete($temp); $this->addMessage('Upload success.'); return array('url' => $url); }
/** * doExecute * * @return mixed */ protected function doExecute() { $xml = $this->config['dest'] . '/{{extension.name.lower}}.xml'; $content = file_get_contents($xml); $content = str_replace('client="site"', '{{module.client}}', $content); File::write($content, $xml); }
/** * Do this execute. * * @return mixed */ protected function doExecute() { $dest = $this->config['dir.dest']; $migName = $this->config['replace.controller.item.name.cap'] . 'Init'; if (!is_dir($dest . '/Migration')) { return; } // Copy migration $files = Folder::files($dest . '/Migration'); $file = false; // If last migration with same name exists, delete duplicated migration. foreach ($files as $file) { $fileName = pathinfo($file, PATHINFO_BASENAME); if (strpos($file, $migName . '.php') !== false && $fileName != '19700101000000_' . $migName . '.php') { if (is_file($dest . '/Migration/' . '19700101000000_' . $migName . '.php')) { File::delete($dest . '/Migration/' . '19700101000000_' . $migName . '.php'); } return; } } foreach ($files as $file) { if (strpos($file, $migName . '.php') !== false) { break; } } // Migration not exists, return. if (!$file) { return; } $newName = gmdate('YmdHis') . '_' . $migName . '.php'; File::move($file, $dest . '/Migration/' . $newName); $this->io->out('[<info>Action</info>] Rename migration file to: ' . $newName); }
/** * generateEntry * * @param Asset $entry * * @return Page */ public function generateEntry(Asset $entry) { $view = new PageHtmlView(); $layout = File::stripExtension($entry->getPath()); $html = $view->setLayout($layout)->render(); $file = $layout . '.html'; return new Page($file, $html); }
/** * delete * * @param string $path * * @return bool */ public static function delete($path) { if (is_dir($path)) { Folder::delete($path); } elseif (is_file($path)) { File::delete($path); } return true; }
function recursiveCopy($filename, $initialfolder, $targetfolder) { $badfiles = ['vendor', 'node_modules', '.DS_Store', 'sftp-config.json', '.git', '.gitignore', 'build.sh']; foreach (Folder::items($initialfolder . '/' . $filename, false, Folder::PATH_BASENAME) as $item) { if (!in_array($item, $badfiles)) { if (is_dir($initialfolder . '/' . $filename . '/' . $item)) { recursiveCopy($item, $initialfolder . '/' . $filename, $targetfolder . '/' . $filename); } else { File::copy($initialfolder . '/' . $filename . '/' . $item, $targetfolder . '/' . $filename . '/' . $item); } } } }
/** * copyFile * * @param string $src * @param string $dest * @param array $replace * * @return void */ protected function copyFile($src, $dest, $replace = array()) { // Replace dest file name. $dest = strtr($dest, $replace); if (is_file($dest)) { $this->io->out('File exists: ' . $dest); } else { $content = strtr(file_get_contents($src), $replace); if (File::write($dest, $content)) { $this->io->out('File created: ' . $dest); } } }
/** * loadRouting * * @return mixed */ public function loadRouting() { $files = Folder::files(__DIR__ . '/Resources/routing'); $routes = array(); foreach ($files as $file) { $ext = File::getExtension($file); if ($ext != 'yml') { continue; } $routes = array_merge($routes, Yaml::parse(file_get_contents($file))); } return $routes; }
/** * copyFile * * @param string $src * @param string $dest * @param array $replace * * @return void */ protected function copyFile($src, $dest, $replace = array()) { // Replace dest file name. $dest = strtr($dest, $replace); $dest .= '.tpl'; if (is_file($dest)) { $this->io->out('[<comment>File exists</comment>] ' . $dest); } else { $content = strtr(file_get_contents($src), $replace); if (File::write($dest, $content)) { $this->io->out('[<info>File created</info>] ' . $dest); } } }
/** * copyFile * * @param string $src * @param string $dest * @param array $replace * * @return void */ protected function copyFile($src, $dest, $replace = array()) { // Replace dest file name. $dest = SimpleTemplate::render($dest, $replace, $this->tagVariable); if (substr($dest, -4) == '.tpl') { $dest = substr($dest, 0, -4); } if (is_file($dest)) { $this->io->out('[<comment>File exists</comment>] ' . $dest); } else { $content = SimpleTemplate::render(file_get_contents($src), $replace, $this->tagVariable); if (File::write($dest, $content)) { $this->io->out('[<info>File created</info>] ' . $dest); } } }
/** * Execute the controller. * * @return mixed Return executed result. * * @throws \LogicException * @throws \RuntimeException */ public function execute() { $files = $this->input->files; $field = $this->input->get('field', 'file'); $id = $this->input->get('id'); $author = Author::getAuthor($id); $user = User::get(); $blog = Blog::get(); try { if (!Author::isAdmin($blog, $user)) { throw new ValidFailException('You cannot edit this author.'); } $src = $files->getByPath($field . '.tmp_name', null, InputFilter::STRING); $name = $files->getByPath($field . '.name', null, InputFilter::STRING); if (!$src) { throw new \Exception('File not upload'); } $ext = pathinfo($name, PATHINFO_EXTENSION); $uuid = $author->uuid ?: Uuid::v4(); $src = Thumb::createThumb($src); $dest = sprintf('author/%s/%s.%s', sha1($uuid), md5($uuid), $ext); $result = S3Helper::put($src, $dest); File::delete($src); if (!$result) { throw new \Exception('Upload fail.'); } } catch (\Exception $e) { $response = new Response(); $response->setBody(json_encode(['error' => $e->getMessage()])); $response->setMimeType('text/json'); $response->respond(); exit; } $return = new Registry(); $return['filename'] = 'https://windspeaker.s3.amazonaws.com/' . $dest; $return['file'] = 'https://windspeaker.s3.amazonaws.com/' . $dest; $return['uuid'] = $uuid; if ($author->id) { $author->image = $return['filename']; (new DataMapper('authors'))->updateOne($author); } $response = new Response(); $response->setBody((string) $return); $response->setMimeType('text/json'); $response->respond(); exit; }
/** * Execute the controller. * * @return boolean True if controller finished execution, false if the controller did not * finish execution. A controller might return false if some precondition for * the controller to run has not been satisfied. * * @throws \LogicException * @throws \RuntimeException */ public function execute() { // Flip src and dest because we want to convert template. $dest = $this->config->get('dir.dest'); $src = $this->config->get('dir.src'); $this->config->set('dir.dest', $src); $this->config->set('dir.src', $dest); $this->doAction(new Action\ConvertTemplateAction()); // Rename migration if (is_dir($src . '/Migration')) { $file = Folder::files($src . '/Migration')[0]; $time = '19700101000000'; $newFilename = preg_replace('/\\d+(_.+Init\\.php\\.tpl)/', $time . '$1', $file); File::move($file, $newFilename); } return true; }
/** * compress * * @return void */ public function compress() { // Get assets list from Document $list = $this->getStorage(); $list = ArrayHelper::getColumn($list, 'url'); // Build assets hash per page. $name = $this->buildHash($list); // Cache file path. $path = $this->getCachePath($name); $assetPath = WINDWALKER_PUBLIC . '/' . $this->asset->getAssetFolder() . '/' . $path; // Prepare to minify and combine files. if (!is_file($assetPath)) { // Combine data by file list. $data = $this->combineData($list); $data = $this->doCompress($data); File::write($assetPath, $data); } $this->addAsset($path); }
/** * findPaths * * @param string $layout * * @return \SplFileInfo */ public function findPaths($layout = null) { $layout = $layout ?: $this->getLayout(); if (is_file($this->getPath() . '/' . $layout)) { return new \SplFileInfo(realpath($this->getPath() . '/' . $layout)); } $layout = explode('/', $layout); $name = array_pop($layout); $layout = implode('/', $layout); if (is_dir($this->getPath() . '/' . $layout)) { $files = Filesystem::find($this->path . '/' . $layout, $name); /** @var \SplFileInfo $file */ foreach ($files as $file) { if (File::stripExtension($file->getFilename()) == $name) { return $file; } } } return null; }
/** * doExecute * * @return int */ protected function doExecute() { $path = $this->getArgument(0); $package = $this->getOption('p'); $folder = $this->console->get('asset.folder', 'asset'); if ($package = PackageHelper::getPackage($package)) { $path = $package->getDir() . '/Resources/asset/' . $path; } else { $path = WINDWALKER_PUBLIC . '/' . trim($folder, '/') . '/' . $path; } if (is_file($path)) { $files = array(new \SplFileInfo($path)); } elseif (is_dir($path)) { $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::FOLLOW_SYMLINKS)); } else { throw new \InvalidArgumentException('No path'); } /** @var \SplFileInfo $file */ foreach ($files as $file) { $ext = File::getExtension($file->getPathname()); if (StringHelper::endsWith($file->getBasename(), '.min.' . $ext)) { continue; } if ($ext == 'css') { $this->out('[<comment>Compressing</comment>] ' . $file); $data = \Minify_CSS_Compressor::process(file_get_contents($file)); $data = str_replace("\n", ' ', $data); } elseif ($ext == 'js') { $this->out('[<comment>Compressing</comment>] ' . $file); $data = \JSMinPlus::minify(file_get_contents($file)); $data = str_replace("\n", ';', $data); } else { continue; } $newName = $file->getPath() . '/' . File::stripExtension($file->getBasename()) . '.min.' . $ext; file_put_contents($newName, $data); $this->out('[<info>Compressed</info>] ' . $newName); } }
/** * Execute the controller. * * @return mixed Return executed result. * * @throws \LogicException * @throws \RuntimeException */ public function execute() { $files = $this->input->files; $field = $this->input->get('field', 'file'); $user = User::get(); try { $src = $files->getByPath($field . '.tmp_name', null, InputFilter::STRING); $name = $files->getByPath($field . '.name', null, InputFilter::STRING); if (!$src) { throw new \Exception('File not upload'); } $ext = pathinfo($name, PATHINFO_EXTENSION); $src = Thumb::createThumb($src); $dest = sprintf('user/%s/%s.%s', sha1('user-profile-' . $user->id), md5('user-profile-' . $user->id), $ext); $result = S3Helper::put($src, $dest); File::delete($src); if (!$result) { throw new \Exception('Upload fail.'); } } catch (\Exception $e) { $response = new Response(); $response->setBody(json_encode(['error' => $e->getMessage()])); $response->setMimeType('text/json'); $response->respond(); exit; } $return = new Registry(); $return['filename'] = 'https://windspeaker.s3.amazonaws.com/' . $dest; $return['file'] = 'https://windspeaker.s3.amazonaws.com/' . $dest; $user->image = $return['filename']; User::save($user); $response = new Response(); $response->setBody((string) $return); $response->setMimeType('text/json'); $response->respond(); exit; }
/** * loadAllFromPath * * @param string $path * @param string $format * @param string $package */ public static function loadAllFromPath($path, $format, $package = null) { $config = Ioc::getConfig(); $locale = $config['language.locale'] ?: 'en-GB'; $default = $config['language.default'] ?: 'en-GB'; $locale = LanguageNormalize::toLanguageTag($locale); $default = LanguageNormalize::toLanguageTag($default); $localePath = $path . '/' . $locale; $files = array(); if (is_dir($localePath)) { $files = array_merge($files, (array) Folder::files($localePath, false, Folder::PATH_BASENAME)); } $defaultPath = $path . '/' . $default; if (is_dir($defaultPath)) { $files = array_merge($files, (array) Folder::files($defaultPath, false, Folder::PATH_BASENAME)); } foreach ($files as $file) { $ext = File::getExtension($file); if (strcasecmp($ext, $format) !== 0) { continue; } Translator::loadFile(File::stripExtension($file), strtolower($format), $package); } }
/** * createFolder * * @param string $dest * * @return void */ protected function createFolder($dest) { $this->out('<info>Create</info>: ' . $dest); Folder::create($dest); File::write($dest . '/.gitkeep', ''); }
/** * getItem * * @param array $paths * * @return string */ public function getItem($paths) { $path = array_pop($paths); return \Windwalker\Filesystem\File::stripExtension($path); }
/** * dump * * @return void */ public static function dump() { $list = static::getList(); $ids = ArrayHelper::getColumn($list, 'id'); $content = implode(',', $ids); File::write(static::getTempPath(), $content); }
/** * Moves a folder. * * @param string $src The path to the source folder. * @param string $dest The path to the destination folder. * @param bool $override Override files. * * @throws Exception\FilesystemException * @return mixed Error message on false or boolean true on success. * * @since 2.0 */ public static function move($src, $dest, $override = false) { if (!is_dir($src)) { throw new FilesystemException('Cannot find source folder'); } if (is_dir($dest)) { if (!$override) { throw new FilesystemException('Folder already exists'); } foreach (static::items($src, true, static::PATH_RELATIVE) as $item) { if (is_file($src . '/' . $item)) { File::move($src . '/' . $item, $dest . '/' . $item, true); } elseif (is_dir($src . '/' . $item)) { static::create($dest . '/' . $item); } } static::delete($src); return true; } if (!@rename($src, $dest)) { throw new FilesystemException('Rename failed'); } return true; }
/** * Method to test write(). * * @return void * * @covers Windwalker\Filesystem\File::write */ public function testWrite() { File::write(static::$dest . '/folder3/level2/test.txt', 'tmpFile'); $this->assertStringEqualsFile(static::$dest . '/folder3/level2/test.txt', 'tmpFile'); }
/** * quickUpload * * @param string $base64 * @param string $uri * * @return string */ public static function quickUpload($base64, $uri) { $ext = Base64Image::getTypeFromBase64($base64); if (!$ext) { return false; } $temp = WINDWALKER_TEMP . '/unidev/images/temp/' . gmdate('Ymd') . '/' . md5(uniqid(mt_rand(1, 999))) . '.' . $ext; if (!is_dir(dirname($temp))) { Folder::create(dirname($temp)); } Base64Image::toFile($base64, $temp); // Upload to Cloud $url = ImageUploader::upload($temp, $uri); if (is_file($temp)) { File::delete($temp); } return $url; }
/** * Save config to file. * * @return void */ public static function saveConfig() { File::write(static::getPath(), static::getConfig()->toString(static::$type)); }
/** * loadRouting * * @return mixed */ public function loadRouting() { $routes = parent::loadRouting(); foreach (Folder::files(__DIR__ . '/Resources/routing') as $file) { if (File::getExtension($file) == 'yml') { $routes = array_merge($routes, (array) Yaml::parse(file_get_contents($file))); } } // Merge other routes here... $routes = array_merge($routes, WarderHelper::getAdminRouting()); $routes = array_merge($routes, LunaHelper::getAdminRouting()); return $routes; }
/** * onAfterWriteFiles * * @return void */ public function onAfterWriteFiles() { include_once __DIR__ . '/../../vendor/autoload.php'; $base = realpath(__DIR__ . '/../../..'); $items = Folder::files($base, true); $sitemap = new Sitemap(); $root = Ioc::getConfig()->get('site.root'); $sitemap->addItem($root, 1.0); foreach ($items as $item) { if (File::getExtension($item) != 'html') { continue; } $loc = str_replace('\\', '/', substr($item, strlen($base) + 1)); $sitemap->addItem($root . '/' . $loc, 0.8, ChangeFreq::WEEKLY, new \DateTime()); } $xml = $sitemap->toString(); file_put_contents($base . '/sitemap.xml', $xml); }
/** * getRemoteUrl * * @param string $path * * @return string */ public function getRemoteUrl($path) { if (!File::getExtension($path)) { $img = $this->imgur->image($path); return $img->link; } return static::getHost() . '/' . $path; }
/** * Execute this command. * * @return int * * @since 2.0 */ protected function doExecute() { $package = $this->getArgument(0); if (!$package) { throw new WrongArgumentException('Please enter package name.'); } $package = ConsoleHelper::getAllPackagesResolver()->getPackage($package); if (!$package) { throw new \InvalidArgumentException(sprintf('Package: %s not found', $this->getArgument(0))); } $recordClass = $this->getArgument(1); if (!$recordClass) { throw new WrongArgumentException('Please enter record name or class.'); } $recordClass = StringNormalise::toClassNamespace($recordClass); $pkgNamespace = ReflectionHelper::getNamespaceName($package); if (!class_exists($recordClass)) { $recordClass = $pkgNamespace . '\\Record\\' . ucfirst($recordClass) . 'Record'; } $table = null; if (class_exists($recordClass)) { try { /** @var Record $record */ $record = new $recordClass(); $table = $record->getTableName(); } catch (\Exception $e) { // Nothing } } if ($this->getArgument(2)) { $table = $this->getArgument(2); } $columns = Ioc::getDatabase()->getTable($table, true)->getColumnDetails(true); $fields = []; $dataType = Ioc::getDatabase()->getTable($table)->getDataType(); foreach ($columns as $column) { $fields[] = ['name' => $column->Field, 'type' => $dataType::getPhpType(explode('(', $column->Type)[0])]; } // Prepare Trait name $name = end(explode('\\', $recordClass)); $name = str_replace('Record', '', $name); $shortName = ucfirst($name) . 'DataTrait'; $data = ['package_namespace' => $pkgNamespace . '\\Record\\Traits', 'short_name' => $shortName, 'columns' => $fields]; $content = (new Edge(new EdgeStringLoader()))->render($this->getTemplate(), $data); $file = $package->getDir() . '/Record/Traits/' . $shortName . '.php'; if (is_file($file) && !(new BooleanPrompter())->ask('File: <comment>' . $file . '</comment> exists, do you want to override it? [N/y]: ', false)) { throw new \RuntimeException(' Canceled...'); } File::write($file, $content); $this->out()->out('Writing file: <info>' . $file . '</info> success.'); return true; }
/** * getRoute * * @return string */ public function getRoute() { if ($this->name == 'index' || $this->name == 'default') { $route = dirname($this->path); return Path::clean($route == '.' ? null : $route, '/'); } return Path::clean(File::stripExtension($this->path), '/'); }
/** * Method to get property Target * * @return string */ public function getTarget() { if (!$this->target) { $this->target = ltrim($this->getLayout(), '\\/'); $this->target = File::stripExtension($this->target) . '.html'; } return $this->target; }