public function sortRoutes() { if (empty($this->routes)) { if ($files = $this->resolver->getRoutes()) { foreach ($files as $file) { $dir = dirname($file, 2); /** @var Router $router */ $router = (new Injector())->make('Minute\\Routing\\Router'); require_once $file; $routes = $router->getRouteCollection(); /** @var Route $route */ foreach ($routes as $route) { $method = $route->getMethods()[0]; $defaults = $route->getDefaults(); if ($controller = $defaults['controller']) { $parts = explode('@', $controller, 2); list($classPath, $fn) = [$this->utils->unixPath($parts[0]), $parts[1] ?? 'index']; } else { list($classPath, $fn) = [null, 'index']; } $classPath = preg_replace('/\\.php$/', '', $classPath); $path = $this->utils->unixPath(sprintf('%s/Controller/%s.php', $dir, $classPath)); $action = [$this->resolver->getController($classPath), $fn]; $this->routes[] = array_merge($defaults, ['route' => $route, 'controller' => $controller, 'dir' => $dir, 'path' => $path, 'classPath' => $classPath, 'fn' => $fn, 'action' => $action, 'method' => $method]); } } } } return $this->routes; }
public function newController($path, $controller) { $namespace = $this->utils->dosPath($this->utils->dirname($controller)); $class = $this->utils->filename($controller); if ($this->writer->write($path, ['namespace' => $namespace === '.' ? '' : "\\{$namespace}", 'class' => $class])) { require_once $path; } }
public function write($path, $replacements = [], $info = null) { @mkdir($this->utils->dirname($path), 0777, true); if ($result = file_put_contents($path, $this->readData($replacements))) { $this->logger->info(($info ?? "Written file") . ": " . realpath($path)); return $path; } throw new \Error("Cannot write file: {$path}"); }
public function compile(ImportEvent $importEvent) { $results = ['constants' => [], 'handlers' => []]; $wildcards = []; foreach (['constants', 'handlers'] as $type) { $e = $type === 'constants'; foreach (['App', 'Minute'] as $dir) { $prefix = $e ? "{$dir}\\Event\\" : "{$dir}\\EventHandler\\"; $dirs = $this->resolver->find($prefix); if (!empty($dirs)) { $finder = new Finder(); $fix = function ($path, $replacement) use($prefix) { return preg_replace('/\\.php$/', '', preg_replace(sprintf('/^.*%s/i', preg_quote($prefix)), $replacement, $path)); }; $files = $finder->depth('< 3')->files()->in($dirs)->name('*.php')->contains($e ? 'const ' : 'function '); foreach ($files as $file) { $classPath = $this->utils->dosPath((string) $file); $classPath = $fix($classPath, $prefix); $basename = $fix($classPath, ''); if ($reflector = new ReflectionClass($classPath)) { if ($e) { foreach ($reflector->getConstants() as $value => $constant) { $parts = explode('.', $constant); for ($i = 0, $j = count($parts) - 1; $i < $j; $i++) { $wildcard = join('.', array_slice($parts, 0, $i + 1)) . '.*'; $wildcards[$wildcard] = ['name' => sprintf('%s', strtr($wildcard, '.', '_')), 'value' => $wildcard, 'group' => 'Wildcard events']; } $results['constants'][] = ['name' => sprintf('%s in %s', $this->utils->filename($value), $basename), 'value' => $constant, 'group' => $parts[0]]; } } else { foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { if (!preg_match('/^\\_/', $method->name)) { $value = sprintf("%s@%s", $method->class, $method->name); $parts = explode('\\', $classPath); $results['handlers'][] = ['name' => sprintf('%s@%s', $basename, $method->name), 'value' => $value, 'group' => $parts[2] ?? 'App']; } } } } } } } usort($results[$type], function ($a, $b) { return $a['group'] === $b['group'] ? $a['value'] <=> $b['value'] : $a['group'] <=> $b['group']; }); } usort($wildcards, function ($a, $b) { return $a['value'] <=> $b['value']; }); foreach ($wildcards as $wildcard => $event) { $results['constants'][] = $event; } $importEvent->addContent($results); }
public function write() { $pdo = $this->database->getConnection(); $tables = $pdo->select(sprintf("SELECT TABLE_NAME as `table`, COLUMN_NAME as pk FROM information_schema.columns WHERE table_schema = '%s' AND COLUMN_KEY = 'PRI'", $pdo->getDatabaseName())); foreach ($tables as $table) { $name = $table->table; if (!$this->resolver->getModel($name)) { $path = sprintf('%s/app/Model/%s.php', $this->bootLoader->getBaseDir(), ucfirst(Str::camel(Str::singular("{$name}")))); if (!file_exists($path)) { $this->writer->write($path, ['class' => $this->utils->filename($path), 'table' => $table->table, 'pk' => $table->pk], 'Created new model'); } } } }
public function getViewPath($path) { $path = $this->utils->unixPath($path); $path = preg_replace('/\\{.*?\\}/', '', $path); $path = trim($path, '/'); $parts = explode('/', $path); $depth = min(count($parts) - 1, self::MAX_DEPTH); $capitalize = function ($f) { return ucwords(Str::camel($f)); }; $dirname = $depth > 0 ? join('/', array_map($capitalize, array_slice($parts, 0, $depth))) : null; $filename = join('', array_map($capitalize, array_slice($parts, $depth))); //throw new AwsError("hohohoo"); return !empty($dirname) ? sprintf('%s/%s', $dirname, $filename) : $filename; }
/** * @param array $contents - ['san.txt' => '@san.txt', 'string.txt' => 'anything can be here'] * @param string $zipFile * * @return string */ public function create(array $contents = [], string $zipFile = '') { $zip = new ZipArchive(); $file = sprintf('%s/%s.zip', $this->tmpDir->getTempDir('zip'), $this->utils->filename($zipFile) ?: Str::random(6)); $res = $zip->open($file, ZipArchive::CREATE | ZipArchive::OVERWRITE); foreach ($contents as $filename => $data) { if (strpos($data, '@') === 0) { $zip->addFile(substr($data, 1), $filename); } else { $zip->addFromString($filename, preg_replace("/\r\n/", "\n", $data)); } } $zip->close(); return filesize($file) > 0 ? $file : false; }
public function upload() { $app = App::getInstance(); $user_id = SessionManager::getInstance()->getUserID(); if (!empty($_FILES['file']['name'])) { $filename = $_FILES['file']['name']; $file = sprintf("%s/%s", PathUtils::getTmpDir('tmp/uploads'), $filename); $saved = move_uploaded_file($_FILES['file']['tmp_name'], $file); } elseif (!empty($_POST['file']) && !empty($_POST['data'])) { $filename = $_POST['file']; $file = sprintf("%s/%s", PathUtils::getTmpDir('tmp/uploads'), $filename); $data = !empty($_POST['base64']) ? base64_decode($_POST['data']) : $_POST['data']; $saved = file_put_contents($file, $data); } if (!empty($file) & !empty($saved)) { try { $type = PathUtils::getFileType($file); $event = new UploadEvent($user_id, ['file' => $file]); if ($app->dispatch("user_upload_{$type}", $event)) { if ($upload = $event->getURL()) { HttpResponse::getInstance()->display(['url' => $upload], '', true); } } } finally { @unlink($file); } } HttpResponse::getInstance()->displayError("Unable to upload file"); }
public function createItemArray(string $name, string $modelClass, string $localKey, $foreignKey = null) { $alias = $name; $single = sprintf('%sItem', $this->fixName($name)); $multiple = sprintf('%sArray', $this->fixName($name)); $joinKey = !empty($foreignKey) ? sprintf("'%s'", $foreignKey) : 'null'; $theClass = $this->utils->filename($modelClass); $template = <<<EOF Minute.Models.{$multiple} = (function (_super) { __extends({$multiple}, _super); function {$multiple}(parent) { _super.call(this, Minute.Models.{$single}, parent, '{$alias}', '{$theClass}', '{$localKey}', {$joinKey}); } return {$multiple}; }(Minute.Items)); EOF; return $template; }
/** * @param $urls * * @return array|null */ public function proxy($urls) { if (!empty($urls)) { foreach ($urls as $url) { $tmp = PathUtils::getTmpDir('tmp/proxy'); $path = sprintf("%s/%s.%s", $tmp, md5($url), pathinfo($url, PATHINFO_EXTENSION)); if ($file = file_exists($path) ? $path : HttpUtils::downloadFile($url, $path)) { $files[] = ['remote' => $url, 'local' => $file]; } } } return !empty($files) ? $files : null; }
public function index(RouteEx $_route) { $folders = $this->resolver->find('App\\Controller\\Cron'); $controllers = []; foreach ($folders as $folder) { $classes = glob("{$folder}/*.php"); foreach ($classes as $classPath) { $class = sprintf('\\App\\Controller\\Cron\\%s', $this->utils->filename($classPath)); if (class_exists($class)) { if ($reflector = new ReflectionClass($class)) { foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { if (!preg_match('/^\\_/', $method->name)) { $controller = ['type' => ucwords(basename(dirname($classPath, 4))), 'value' => sprintf("%s@%s", $method->class, $method->name), 'name' => sprintf("%s@%s", $this->utils->filename($method->class), $method->name)]; array_push($controllers, $controller); } } } } } } return (new View())->with(new Helper('NyaSelect'))->set('controllers', $controllers); }
public function upload(UploadEvent $event) { set_time_limit(max(100, ini_get('max_execution_time'))); if (!$event->getUrl()) { #some other uploader has already taken care of it? if ($data = $event->getEventData()) { if ($file = @$data['file']) { if (file_exists($file)) { $app = App::getInstance(); $user_id = $event->getUserId(); if ($s3conf = $app->config->getKey('private/api_keys/aws-s3')) { if (!empty($s3conf['access_key']) && !empty($s3conf['secret_key']) && !empty($s3conf['bucket_name'])) { if ($user_id > 0 || !empty($s3conf['anonymous_uploads'])) { try { $s3 = S3Client::factory(array('key' => $s3conf['access_key'], 'secret' => $s3conf['secret_key'], 'region' => @$s3conf['region'] ?: Region::US_EAST_1)); $type = PathUtils::getFileType($file); $file_key = sprintf("users/%s/%s/%d-%s", $user_id > 0 ? $user_id : 'anon', $type, filesize($file), basename($file)); $result = $s3->putObject(array('Bucket' => $s3conf['bucket_name'], 'SourceFile' => $file, 'Key' => $file_key, 'ContentType' => 'text/plain', 'ACL' => 'public-read', 'StorageClass' => 'REDUCED_REDUNDANCY')); if (!empty($result['ObjectURL'])) { $url = $result['ObjectURL']; if (!empty($s3conf['cdn'])) { $event->setUrl(sprintf('http://%s/%s', $s3conf['cdn'], $file_key)); } else { $event->setUrl($url); } } else { throw new UploadError("Error uploading to S3: No url returned"); } } catch (Exception $e) { throw new UploadError("Error uploading to S3: " . $e->getMessage(), $e); } } else { throw new LoginError("You must be logged in to upload.", $user_id); } } else { throw new UploadError("S3 configuration is incomplete.", $s3conf); } } else { throw new UploadError("S3 configuration is empty"); } } else { throw new UploadError("Upload file is missing"); } } else { throw new UploadError("Upload data is empty"); } } } }
protected function compress($regex, $content, $type = 'js', $version, $excludes) { $files = []; $compressed = preg_replace_callback($regex, function ($matches) use(&$files, $type, $excludes) { if (!empty($excludes) && preg_match("~{$excludes}~", basename($matches[1] ?? ''))) { return $matches[0]; } if ($type === 'css' && !preg_match('/rel="stylesheet"/i', $matches[0])) { return $matches[0]; } else { $files[] = $matches[1]; } return ''; }, $content); if (!empty($files)) { MMinifiedDatum::unguard(true); $name = sprintf('%s.%s', md5(json_encode($files)), $type); $count = MMinifiedDatum::where('name', '=', $name)->where('version', '=', $version)->count(); $baseDir = $this->bootLoader->getBaseDir(); if (empty($count)) { set_time_limit(120); $asset = new AssetCollection(array_map(function ($f) use($type, $baseDir) { $file = realpath(sprintf('%s/public/%s', $baseDir, $f)); $minified = preg_match('/\\.min\\./', $file); if ($type === 'css') { $url = preg_replace('#.*/static/#', '/static/', $this->utils->unixPath($file)); $filters = array_merge([new CssImportFilter(), new CssRewriteFilter()], !$minified ? [new CssMinFilter()] : []); } elseif (!$minified) { $filters = [new JSMinFilter()]; } return new FileAsset($file, !empty($filters) ? $filters : [], $baseDir . '/public', !empty($url) ? $url : ''); }, $files)); $asset->setTargetPath(sprintf('/static/cache/%s/', $type)); if (MMinifiedDatum::create(['name' => $name, 'version' => $version, 'content' => $asset->dump(), 'created_at' => Carbon::now()])) { $count = 1; } } } if (!empty($count) && !empty($name)) { $tag = sprintf($type == 'js' ? '<scrip' . 't src="%s"></script>' : '<lin' . 'k href="%s" type="text/css" rel="stylesheet" media="all">', "/static/cache/{$version}/{$name}"); $compressed = $type === 'css' ? preg_replace('#(<style|</head)#ms', "{$tag}\n\\1", $compressed, 1) : preg_replace('#(<script|</head)#ms', "{$tag}\n\\1", $compressed, 1); return $compressed; } return $content; }
protected function normalize(string $path, string $suffix = '') { $info = $this->utils->pathinfo($path); $class = $this->utils->dosPath(sprintf('%s%s%s', $suffix ? trim($suffix, '\\') . '\\' : '', $info['dirname'] !== '.' ? trim($info['dirname'], '\\') . '\\' : '', $info['filename'])); return "\\{$class}"; }
public function downloadCached(string $url) { $path = sprintf('%s/%s.%s', $this->tmpDir->getTempDir('downloads'), md5($url), $this->utils->extension($url)); return file_exists($path) ? $path : $this->download($url, $path); }
public function getMimeType(string $path) { $ext = strtolower($this->pathUtils->extension($path)); return $this->map[$ext] ?? 'application/octet-stream'; }