예제 #1
0
파일: Types.php 프로젝트: clee03/metal
 private function findBlueprints($paths)
 {
     $options = ['compare' => 'Filename', 'pattern' => '|\\.yaml$|', 'filters' => ['key' => '|\\.yaml$|'], 'key' => 'SubPathName', 'value' => 'PathName'];
     foreach ((array) $paths as $path) {
         return Folder::all($path, $options);
     }
 }
예제 #2
0
 public static function backup($destination = null, callable $messager = null)
 {
     if (!$destination) {
         $destination = self::getGrav()['locator']->findResource('backup://', true);
         if (!$destination) {
             throw new \RuntimeException('The backup folder is missing.');
         }
         Folder::mkdir($destination);
     }
     $name = self::getGrav()['config']->get('site.title', basename(GRAV_ROOT));
     $inflector = new Inflector();
     if (is_dir($destination)) {
         $date = date('YmdHis', time());
         $filename = trim($inflector->hyphenize($name), '-') . '-' . $date . '.zip';
         $destination = rtrim($destination, DS) . DS . $filename;
     }
     $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => 'Creating new Backup "' . $destination . '"']);
     $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => '']);
     $zip = new \ZipArchive();
     $zip->open($destination, \ZipArchive::CREATE);
     $max_execution_time = ini_set('max_execution_time', 600);
     static::folderToZip(GRAV_ROOT, $zip, strlen(rtrim(GRAV_ROOT, DS) . DS), $messager);
     $messager && $messager(['type' => 'progress', 'percentage' => false, 'complete' => true]);
     $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => '']);
     $messager && $messager(['type' => 'message', 'level' => 'info', 'message' => 'Saving and compressing archive...']);
     $zip->close();
     if ($max_execution_time !== false) {
         ini_set('max_execution_time', $max_execution_time);
     }
     return $destination;
 }
예제 #3
0
 public function scanTemplates($path)
 {
     $options = ['compare' => 'Filename', 'pattern' => '|\\.html\\.twig$|', 'filters' => ['value' => '|\\.html\\.twig$|'], 'value' => 'Filename', 'recursive' => false];
     foreach (Folder::all($path, $options) as $type) {
         $this->register($type);
     }
     if (file_exists($path . 'modular/')) {
         foreach (Folder::all($path . 'modular/', $options) as $type) {
             $this->register('modular/' . $type);
         }
     }
 }
예제 #4
0
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  */
 private function cleanPaths(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('');
     $output->writeln('<magenta>Clearing cache</magenta>');
     $output->writeln('');
     $user_config = USER_DIR . 'config/system.yaml';
     $anything = false;
     if ($input->getOption('all')) {
         $remove_paths = $this->all_remove;
     } elseif ($input->getOption('assets-only')) {
         $remove_paths = $this->assets_remove;
     } elseif ($input->getOption('images-only')) {
         $remove_paths = $this->images_remove;
     } elseif ($input->getOption('cache-only')) {
         $remove_paths = $this->cache_remove;
     } else {
         $remove_paths = $this->standard_remove;
     }
     foreach ($remove_paths as $path) {
         $files = glob(ROOT_DIR . $path . '*');
         foreach ($files as $file) {
             if (is_file($file)) {
                 if (@unlink($file)) {
                     $anything = true;
                 }
             } elseif (is_dir($file)) {
                 if (@Folder::delete($file)) {
                     $anything = true;
                 }
             }
         }
         if ($anything) {
             $output->writeln('<red>Cleared:  </red>' . $path . '*');
         }
     }
     if (file_exists($user_config)) {
         touch($user_config);
         $output->writeln('');
         $output->writeln('<red>Touched: </red>' . $user_config);
         $output->writeln('');
     }
     if (!$anything) {
         $output->writeln('<green>Nothing to clear...</green>');
         $output->writeln('');
     }
 }
 protected function serve()
 {
     $this->options['name'] = $this->input->getArgument('name');
     $this->name['machine'] = $this->generateMachineName($this->options['name']);
     $this->name['camel'] = $this->generateCamelName($this->options['name']);
     $path['src'] = PLUGINS_DIR . 'component-generator/' . self::COMPONENT;
     $path['dest'] = PLUGINS_DIR . $this->name['machine'];
     $path['tmp'] = CACHE_DIR . 'tmp/' . self::COMPONENT;
     $replace = array('/{{ COMPONENT }}/' => lcfirst($this->name['camel']), '/{{ COMPONENT NAME }}/' => $this->options['name'], '/{{ COMPONENT CAMEL NAME }}/' => $this->name['camel'], '/{{ COMPONENT MACHINE NAME }}/' => $this->name['machine']);
     // Copy dir to cache/temp
     Folder::copy($path['src'], $path['tmp']);
     // Recursively rewrite file names and contents of all files
     $this->rewriteRecursive($path['tmp'], array_keys($replace), array_values($replace));
     // Move dir to rest
     Folder::move($path['tmp'], $path['dest']);
     // Success message
 }
예제 #6
0
 private function cleanPaths()
 {
     $this->output->writeln('');
     $this->output->writeln('<red>DELETING</red>');
     $anything = false;
     foreach ($this->paths_to_remove as $path) {
         $path = ROOT_DIR . $path;
         if (is_dir($path) && @Folder::delete($path)) {
             $anything = true;
             $this->output->writeln('<red>dir:  </red>' . $path);
         } elseif (is_file($path) && @unlink($path)) {
             $anything = true;
             $this->output->writeln('<red>file: </red>' . $path);
         }
     }
     if (!$anything) {
         $this->output->writeln('');
         $this->output->writeln('<green>Nothing to clean...</green>');
     }
 }
예제 #7
0
 private static function download($package)
 {
     $contents = Response::get($package->zipball_url, []);
     $cache_dir = self::getGrav()['locator']->findResource('cache://', true);
     $cache_dir = $cache_dir . DS . 'tmp/Grav-' . uniqid();
     Folder::mkdir($cache_dir);
     $filename = $package->slug . basename($package->zipball_url);
     file_put_contents($cache_dir . DS . $filename, $contents);
     return $cache_dir . DS . $filename;
 }
예제 #8
0
 /**
  * Helper method to clear all Grav caches
  *
  * @param string $remove standard|all|assets-only|images-only|cache-only
  *
  * @return array
  */
 public static function clearCache($remove = 'standard')
 {
     $locator = Grav::instance()['locator'];
     $output = [];
     $user_config = USER_DIR . 'config/system.yaml';
     switch ($remove) {
         case 'all':
             $remove_paths = self::$all_remove;
             break;
         case 'assets-only':
             $remove_paths = self::$assets_remove;
             break;
         case 'images-only':
             $remove_paths = self::$images_remove;
             break;
         case 'cache-only':
             $remove_paths = self::$cache_remove;
             break;
         case 'tmp-only':
             $remove_paths = self::$tmp_remove;
             break;
         default:
             $remove_paths = self::$standard_remove;
     }
     foreach ($remove_paths as $stream) {
         // Convert stream to a real path
         try {
             $path = $locator->findResource($stream, true, true);
         } catch (\Exception $e) {
             // stream not found..
             continue;
         }
         $anything = false;
         $files = glob($path . '/*');
         if (is_array($files)) {
             foreach ($files as $file) {
                 if (is_file($file)) {
                     if (@unlink($file)) {
                         $anything = true;
                     }
                 } elseif (is_dir($file)) {
                     if (Folder::delete($file)) {
                         $anything = true;
                     }
                 }
             }
         }
         if ($anything) {
             $output[] = '<red>Cleared:  </red>' . $path . '/*';
         }
     }
     $output[] = '';
     if (($remove == 'all' || $remove == 'standard') && file_exists($user_config)) {
         touch($user_config);
         $output[] = '<red>Touched: </red>' . $user_config;
         $output[] = '';
     }
     return $output;
 }
예제 #9
0
 /**
  * Builds pages.
  *
  * @internal
  */
 protected function buildPages()
 {
     $this->sort = array();
     /** @var Config $config */
     $config = $this->grav['config'];
     /** @var UniformResourceLocator $locator */
     $locator = $this->grav['locator'];
     $pagesDir = $locator->findResource('page://');
     if ($config->get('system.cache.enabled')) {
         /** @var Cache $cache */
         $cache = $this->grav['cache'];
         /** @var Taxonomy $taxonomy */
         $taxonomy = $this->grav['taxonomy'];
         // how should we check for last modified? Default is by file
         switch (strtolower($config->get('system.cache.check.method', 'file'))) {
             case 'none':
             case 'off':
                 $last_modified = 0;
                 break;
             case 'folder':
                 $last_modified = Folder::lastModifiedFolder($pagesDir);
                 break;
             default:
                 $last_modified = Folder::lastModifiedFile($pagesDir);
         }
         $page_cache_id = md5(USER_DIR . $last_modified . $config->checksum());
         list($this->instances, $this->routes, $this->children, $taxonomy_map, $this->sort) = $cache->fetch($page_cache_id);
         if (!$this->instances) {
             $this->grav['debugger']->addMessage('Page cache missed, rebuilding pages..');
             $this->recurse($pagesDir);
             $this->buildRoutes();
             // save pages, routes, taxonomy, and sort to cache
             $cache->save($page_cache_id, array($this->instances, $this->routes, $this->children, $taxonomy->taxonomy(), $this->sort));
         } else {
             // If pages was found in cache, set the taxonomy
             $this->grav['debugger']->addMessage('Page cache hit.');
             $taxonomy->taxonomy($taxonomy_map);
         }
     } else {
         $this->recurse($pagesDir);
         $this->buildRoutes();
     }
 }
예제 #10
0
 /**
  * Install a package
  *
  * @param Package $package
  * @param bool    $is_update True if it's an update. False if it's an install
  *
  * @return bool
  */
 private function installPackage($package, $is_update = false)
 {
     $type = $package->package_type;
     Installer::install($this->file, $this->destination, ['install_path' => $package->install_path, 'theme' => $type == 'themes', 'is_update' => $is_update]);
     $error_code = Installer::lastErrorCode();
     Folder::delete($this->tmp);
     if ($error_code) {
         $this->output->write("\r");
         // extra white spaces to clear out the buffer properly
         $this->output->writeln("  |- Installing package...    <red>error</red>                             ");
         $this->output->writeln("  |  '- " . Installer::lastErrorMsg());
         return false;
     }
     $message = Installer::getMessage();
     if ($message) {
         $this->output->write("\r");
         // extra white spaces to clear out the buffer properly
         $this->output->writeln("  |- " . $message);
     }
     $this->output->write("\r");
     // extra white spaces to clear out the buffer properly
     $this->output->writeln("  |- Installing package...    <green>ok</green>                             ");
     return true;
 }
예제 #11
0
 /**
  *
  */
 private function pages()
 {
     $this->output->writeln('');
     $this->output->writeln('<comment>Pages Initializing</comment>');
     // get pages files and initialize if no pages exist
     $pages_dir = $this->destination . '/user/pages';
     $pages_files = array_diff(scandir($pages_dir), array('..', '.'));
     if (count($pages_files) == 0) {
         $destination = $this->source . '/user/pages';
         Folder::rcopy($destination, $pages_dir);
         $this->output->writeln('    <cyan>' . $destination . '</cyan> <comment>-></comment> Created');
     }
 }
예제 #12
0
 /**
  * Detects all plugins with a configuration file and returns them with last modification time.
  *
  * @param  string $folder Location to look up from.
  * @return array
  * @internal
  */
 protected function detectRecursive($folder)
 {
     $path = trim(Folder::getRelativePath($folder), '/');
     if (is_dir($folder)) {
         // Find all system and user configuration files.
         $options = ['compare' => 'Filename', 'pattern' => '|\\.yaml$|', 'filters' => ['key' => '|\\.yaml$|', 'value' => function (\RecursiveDirectoryIterator $file) use($path) {
             return ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()];
         }], 'key' => 'SubPathname'];
         $list = Folder::all($folder, $options);
     } else {
         $list = [];
     }
     return [$path => $list];
 }
예제 #13
0
파일: setup.php 프로젝트: madanyu/learn
<?php

/**
 * Multisite setup for sub-directories or path based
 * URLs for subsites.
 *
 * DO NOT EDIT UNLESS YOU KNOW WHAT YOU ARE DOING!
 */
use Grav\Common\Filesystem\Folder;
// Get relative path from Grav root.
$path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : Folder::getRelativePath($_SERVER['REQUEST_URI'], ROOT_DIR);
// Extract name of subsite from path
$name = Folder::shift($path);
$folder = "sites/{$name}";
$prefix = "/{$name}";
if (!$name || !is_dir(ROOT_DIR . "user/{$folder}")) {
    return [];
}
// Prefix all pages with the name of the subsite
$container['pages']->base($prefix);
return ['environment' => $name, 'streams' => ['schemes' => ['user' => ['type' => 'ReadOnlyStream', 'prefixes' => ['' => ["user/{$folder}"]]]]]];
예제 #14
0
 public static function selfupgrade()
 {
     $upgrader = new Upgrader();
     if (!Installer::isGravInstance(GRAV_ROOT)) {
         return false;
     }
     if (is_link(GRAV_ROOT . DS . 'index.php')) {
         Installer::setError(Installer::IS_LINK);
         return false;
     }
     $update = $upgrader->getAssets()['grav-update'];
     $tmp = CACHE_DIR . 'tmp/Grav-' . uniqid();
     $file = self::_downloadSelfupgrade($update, $tmp);
     Installer::install($file, GRAV_ROOT, ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true]);
     $errorCode = Installer::lastErrorCode();
     Folder::delete($tmp);
     if ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)) {
         return false;
     }
     return true;
 }
예제 #15
0
 private function getFilesOrderedByModifiedDate($path = '')
 {
     $files = [];
     if (!$path) {
         $path = DATA_DIR . 'comments';
     }
     if (!file_exists($path)) {
         Folder::mkdir($path);
     }
     $dirItr = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS);
     $filterItr = new RecursiveFolderFilterIterator($dirItr);
     $itr = new \RecursiveIteratorIterator($filterItr, \RecursiveIteratorIterator::SELF_FIRST);
     $itrItr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::SELF_FIRST);
     $filesItr = new \RegexIterator($itrItr, '/^.+\\.yaml$/i');
     // Collect files if modified in the last 7 days
     foreach ($filesItr as $filepath => $file) {
         $modifiedDate = $file->getMTime();
         $sevenDaysAgo = time() - 7 * 24 * 60 * 60;
         if ($modifiedDate < $sevenDaysAgo) {
             continue;
         }
         $files[] = (object) array("modifiedDate" => $modifiedDate, "fileName" => $file->getFilename(), "filePath" => $filepath, "data" => Yaml::parse(file_get_contents($filepath)));
     }
     // Traverse folders and recurse
     foreach ($itr as $file) {
         if ($file->isDir()) {
             $this->getFilesOrderedByModifiedDate($file->getPath() . '/' . $file->getFilename());
         }
     }
     // Order files by last modified date
     usort($files, function ($a, $b) {
         return !($a->modifiedDate > $b->modifiedDate);
     });
     return $files;
 }
예제 #16
0
파일: Pages.php 프로젝트: miguelramos/grav
 /**
  * Builds pages.
  *
  * @internal
  */
 protected function buildPages()
 {
     $this->sort = array();
     /** @var Config $config */
     $config = $this->grav['config'];
     if ($config->get('system.cache.enabled')) {
         /** @var Cache $cache */
         $cache = $this->grav['cache'];
         /** @var Taxonomy $taxonomy */
         $taxonomy = $this->grav['taxonomy'];
         $last_modified = 0;
         // how should we check for last modified? Default is by file
         switch (strtolower($config->get('system.cache.check.method', 'file'))) {
             case 'none':
             case 'off':
                 $last_modified = 0;
                 break;
             case 'folder':
                 $last_modified = Folder::lastModifiedFolder(PAGES_DIR);
                 break;
             default:
                 $last_modified = Folder::lastModifiedFile(PAGES_DIR);
         }
         $page_cache_id = md5(USER_DIR . $last_modified);
         list($this->instances, $this->routes, $this->children, $taxonomy_map, $this->sort) = $cache->fetch($page_cache_id);
         if (!$this->instances) {
             $this->recurse();
             $this->buildRoutes();
             // save pages, routes, taxonomy, and sort to cache
             $cache->save($page_cache_id, array($this->instances, $this->routes, $this->children, $taxonomy->taxonomy(), $this->sort));
         } else {
             // If pages was found in cache, set the taxonomy
             $taxonomy->taxonomy($taxonomy_map);
         }
     } else {
         $this->recurse();
         $this->buildRoutes();
     }
 }
예제 #17
0
 /**
  * Handles ajax upload for files.
  * Stores in a flash object the temporary file and deals with potential file errors.
  *
  * @return mixed True if the action was performed.
  */
 public function uploadFiles()
 {
     $post = $_POST;
     $grav = Grav::instance();
     $uri = $grav['uri']->url;
     $config = $grav['config'];
     $session = $grav['session'];
     $settings = $this->data->blueprints()->schema()->getProperty($post['name']);
     $settings = (object) array_merge(['destination' => $config->get('plugins.form.files.destination', 'self@'), 'avoid_overwriting' => $config->get('plugins.form.files.avoid_overwriting', false), 'random_name' => $config->get('plugins.form.files.random_name', false), 'accept' => $config->get('plugins.form.files.accept', ['image/*']), 'limit' => $config->get('plugins.form.files.limit', 10), 'filesize' => $config->get('plugins.form.files.filesize', 5242880)], (array) $settings, ['name' => $post['name']]);
     $upload = $this->normalizeFiles($_FILES['data'], $settings->name);
     // Handle errors and breaks without proceeding further
     if ($upload->file->error != UPLOAD_ERR_OK) {
         // json_response
         return ['status' => 'error', 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true), $upload->file->name, $this->upload_errors[$upload->file->error])];
     } else {
         // Remove the error object to avoid storing it
         unset($upload->file->error);
         // we need to move the file at this stage or else
         // it won't be available upon save later on
         // since php removes it from the upload location
         $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true);
         $tmp_file = $upload->file->tmp_name;
         $tmp = $tmp_dir . '/uploaded-files/' . basename($tmp_file);
         Folder::create(dirname($tmp));
         if (!move_uploaded_file($tmp_file, $tmp)) {
             // json_response
             return ['status' => 'error', 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '', $tmp)];
         }
         $upload->file->tmp_name = $tmp;
     }
     // Handle file size limits
     $settings->filesize *= 1048576;
     // 2^20 [MB in Bytes]
     if ($settings->filesize > 0 && $upload->file->size > $settings->filesize) {
         // json_response
         return ['status' => 'error', 'message' => $grav['language']->translate('PLUGIN_FORM.EXCEEDED_GRAV_FILESIZE_LIMIT')];
     }
     // Handle Accepted file types
     // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
     $accepted = false;
     $errors = [];
     foreach ((array) $settings->accept as $type) {
         // Force acceptance of any file when star notation
         if ($type == '*') {
             $accepted = true;
             break;
         }
         $isMime = strstr($type, '/');
         $find = str_replace('*', '.*', $type);
         $match = preg_match('#' . $find . '$#', $isMime ? $upload->file->type : $upload->file->name);
         if (!$match) {
             $message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension';
             $errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.';
             $accepted |= false;
         } else {
             $accepted |= true;
         }
     }
     if (!$accepted) {
         // json_response
         return ['status' => 'error', 'message' => implode('<br />', $errors)];
     }
     // Retrieve the current session of the uploaded files for the field
     // and initialize it if it doesn't exist
     $sessionField = base64_encode($uri);
     $flash = $session->getFlashObject('files-upload');
     if (!$flash) {
         $flash = [];
     }
     if (!isset($flash[$sessionField])) {
         $flash[$sessionField] = [];
     }
     if (!isset($flash[$sessionField][$upload->field])) {
         $flash[$sessionField][$upload->field] = [];
     }
     // Set destination
     $destination = Folder::getRelativePath(rtrim($settings->destination, '/'));
     $destination = $this->getPagePathFromToken($destination);
     // Create destination if needed
     if (!is_dir($destination)) {
         Folder::mkdir($destination);
     }
     // Generate random name if required
     if ($settings->random_name) {
         $extension = pathinfo($upload->file->name)['extension'];
         $upload->file->name = Utils::generateRandomString(15) . '.' . $extension;
     }
     // Handle conflicting name if needed
     if ($settings->avoid_overwriting) {
         if (file_exists($destination . '/' . $upload->file->name)) {
             $upload->file->name = date('YmdHis') . '-' . $upload->file->name;
         }
     }
     // Prepare object for later save
     $path = $destination . '/' . $upload->file->name;
     $upload->file->path = $path;
     // $upload->file->route = $page ? $path : null;
     // Prepare data to be saved later
     $flash[$sessionField][$upload->field][$path] = (array) $upload->file;
     // Finally store the new uploaded file in the field session
     $session->setFlashObject('files-upload', $flash);
     // json_response
     return ['status' => 'success', 'session' => \json_encode(['sessionField' => base64_encode($uri), 'path' => $upload->file->path, 'field' => $settings->name])];
 }
예제 #18
0
 /**
  * Helper method to clear all Grav caches
  *
  * @param string $remove    standard|all|assets-only|images-only|cache-only
  *
  * @return array
  */
 public static function clearCache($remove = 'standard')
 {
     $locator = self::getGrav()['locator'];
     $output = [];
     $user_config = USER_DIR . 'config/system.yaml';
     switch ($remove) {
         case 'all':
             $remove_paths = self::$all_remove;
             break;
         case 'assets-only':
             $remove_paths = self::$assets_remove;
             break;
         case 'images-only':
             $remove_paths = self::$images_remove;
             break;
         case 'cache-only':
             $remove_paths = self::$cache_remove;
             break;
         default:
             $remove_paths = self::$standard_remove;
     }
     foreach ($remove_paths as $stream) {
         // Convert stream to a real path
         $path = $locator->findResource($stream, true, true);
         // Make sure path exists before proceeding, otherwise we would wipe ROOT_DIR
         if (!$path) {
             throw new \RuntimeException("Stream '{$stream}' not found", 500);
         }
         $anything = false;
         $files = glob($path . '/*');
         if (is_array($files)) {
             foreach ($files as $file) {
                 if (is_file($file)) {
                     if (@unlink($file)) {
                         $anything = true;
                     }
                 } elseif (is_dir($file)) {
                     if (@Folder::delete($file)) {
                         $anything = true;
                     }
                 }
             }
         }
         if ($anything) {
             $output[] = '<red>Cleared:  </red>' . $path . '/*';
         }
     }
     $output[] = '';
     if (($remove == 'all' || $remove == 'standard') && file_exists($user_config)) {
         touch($user_config);
         $output[] = '<red>Touched: </red>' . $user_config;
         $output[] = '';
     }
     return $output;
 }
 /**
  * @param $package
  *
  * @return bool
  */
 private function installPackage($package)
 {
     Installer::install($this->file, $this->destination, ['install_path' => $package->install_path]);
     $errorCode = Installer::lastErrorCode();
     Folder::delete($this->tmp);
     if ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)) {
         $this->output->write("\r");
         // extra white spaces to clear out the buffer properly
         $this->output->writeln("  |- Installing package...    <red>error</red>                             ");
         $this->output->writeln("  |  '- " . Installer::lastErrorMsg());
         return false;
     }
     $this->output->write("\r");
     // extra white spaces to clear out the buffer properly
     $this->output->writeln("  |- Installing package...    <green>ok</green>                             ");
     return true;
 }
예제 #20
0
파일: form.php 프로젝트: clee03/metal
 private function cleanFilesData($key, $file)
 {
     /** @var Page $page */
     $page = null;
     $blueprint = $this->items['fields'][$key]['files'];
     $cleanFiles[$key] = [];
     if (!isset($blueprint)) {
         return false;
     }
     $cleanFiles = [$key => []];
     foreach ((array) $file['error'] as $index => $error) {
         if ($error == UPLOAD_ERR_OK) {
             $tmp_name = $file['tmp_name'][$index];
             $name = $file['name'][$index];
             $type = $file['type'][$index];
             $destination = Folder::getRelativePath(rtrim($blueprint['destination'], '/'));
             if (!$this->match_in_array($type, $blueprint['accept'])) {
                 throw new \RuntimeException('File "' . $name . '" is not an accepted MIME type.');
             }
             if (Utils::startsWith($destination, '@page:')) {
                 $parts = explode(':', $destination);
                 $route = $parts[1];
                 $page = self::getGrav()['page']->find($route);
                 if (!$page) {
                     throw new \RuntimeException('Unable to upload file to destination. Page route not found.');
                 }
                 $destination = $page->relativePagePath();
             } else {
                 if ($destination == '@self') {
                     $page = self::getGrav()['page'];
                     $destination = $page->relativePagePath();
                 } else {
                     Folder::mkdir($destination);
                 }
             }
             if (move_uploaded_file($tmp_name, "{$destination}/{$name}")) {
                 $path = $page ? self::getGrav()['uri']->convertUrl($page, $page->route() . '/' . $name) : $destination . '/' . $name;
                 $cleanFiles[$key][$path] = ['name' => $file['name'][$index], 'type' => $file['type'][$index], 'size' => $file['size'][$index], 'file' => $destination . '/' . $name, 'route' => $page ? $path : null];
             } else {
                 throw new \RuntimeException('Unable to upload file(s). Error Code: ' . $error);
             }
         }
     }
     return $cleanFiles[$key];
 }
예제 #21
0
파일: Cache.php 프로젝트: nunull/grav
 /**
  * Helper method to clear all Grav caches
  *
  * @param string $remove    standard|all|assets-only|images-only|cache-only
  *
  * @return array
  */
 public static function clearCache($remove = 'standard')
 {
     $output = [];
     $user_config = USER_DIR . 'config/system.yaml';
     switch ($remove) {
         case 'all':
             $remove_paths = self::$all_remove;
             break;
         case 'assets-only':
             $remove_paths = self::$assets_remove;
             break;
         case 'images-only':
             $remove_paths = self::$images_remove;
             break;
         case 'cache-only':
             $remove_paths = self::$cache_remove;
             break;
         default:
             $remove_paths = self::$standard_remove;
     }
     foreach ($remove_paths as $path) {
         $anything = false;
         $files = glob(ROOT_DIR . $path . '*');
         if (is_array($files)) {
             foreach ($files as $file) {
                 if (is_file($file)) {
                     if (@unlink($file)) {
                         $anything = true;
                     }
                 } elseif (is_dir($file)) {
                     if (@Folder::delete($file)) {
                         $anything = true;
                     }
                 }
             }
         }
         if ($anything) {
             $output[] = '<red>Cleared:  </red>' . $path . '*';
         }
     }
     $output[] = '';
     if (($remove == 'all' || $remove == 'standard') && file_exists($user_config)) {
         touch($user_config);
         $output[] = '<red>Touched: </red>' . $user_config;
         $output[] = '';
     }
     return $output;
 }
예제 #22
0
 /**
  * Uninstalls one or more given package
  *
  * @param  string $path     The slug of the package(s)
  * @param  array  $options     Options to use for uninstalling
  *
  * @return boolean True if everything went fine, False otherwise.
  */
 public static function uninstall($path, $options = [])
 {
     $options = array_merge(self::$options, $options);
     if (!self::isValidDestination($path, $options['exclude_checks'])) {
         return false;
     }
     return Folder::delete($path);
 }
예제 #23
0
파일: Config.php 프로젝트: miguelramos/grav
 /**
  * Build a list of configuration files with their timestamps. Used for loading settings and caching them.
  *
  * @return array
  * @internal
  */
 protected function build()
 {
     // Find all plugins with default configuration options.
     $plugins = array();
     $iterator = new \DirectoryIterator(PLUGINS_DIR);
     /** @var \DirectoryIterator $plugin */
     foreach ($iterator as $plugin) {
         $name = $plugin->getBasename();
         $file = $plugin->getPathname() . DS . $name . YAML_EXT;
         if (!is_file($file)) {
             continue;
         }
         $modified = filemtime($file);
         $plugins["plugins/{$name}"] = $modified;
     }
     // Find all system and user configuration files.
     $options = array('compare' => 'Filename', 'pattern' => '|\\.yaml$|', 'filters' => array('key' => '|\\.yaml$|'), 'key' => 'SubPathname', 'value' => 'MTime');
     $system = Folder::all(SYSTEM_DIR . 'config', $options);
     $user = Folder::all(USER_DIR . 'config', $options);
     return array('system' => $system, 'plugins' => $plugins, 'user' => $user);
 }
예제 #24
0
 /**
  * @return bool
  */
 private function upgrade()
 {
     Installer::install($this->file, GRAV_ROOT, ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true]);
     $errorCode = Installer::lastErrorCode();
     Folder::delete($this->tmp);
     if ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)) {
         $this->output->write("\r");
         // extra white spaces to clear out the buffer properly
         $this->output->writeln("  |- Installing upgrade...    <red>error</red>                             ");
         $this->output->writeln("  |  '- " . Installer::lastErrorMsg());
         return false;
     }
     $this->output->write("\r");
     // extra white spaces to clear out the buffer properly
     $this->output->writeln("  |- Installing upgrade...    <green>ok</green>                             ");
     return true;
 }
예제 #25
0
 /**
  * Detects all plugins with a configuration file and returns last modification time.
  *
  * @param  string $lookup Location to look up from.
  * @param  bool $blueprints
  * @return array
  * @internal
  */
 protected function detectConfig($lookup = SYSTEM_DIR, $blueprints = false)
 {
     $location = $blueprints ? 'blueprintFiles' : 'configFiles';
     $path = trim(Folder::getRelativePath($lookup), '/');
     if (isset($this->{$location}[$path])) {
         return [$path => $this->{$location}[$path]];
     }
     if (is_dir($lookup)) {
         // Find all system and user configuration files.
         $options = ['compare' => 'Filename', 'pattern' => '|\\.yaml$|', 'filters' => ['key' => '|\\.yaml$|', 'value' => function (\RecursiveDirectoryIterator $file) use($path) {
             return ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()];
         }], 'key' => 'SubPathname'];
         $list = Folder::all($lookup, $options);
     } else {
         $list = [];
     }
     $this->{$location}[$path] = $list;
     return [$path => $list];
 }
예제 #26
0
 /**
  * Detects all plugins with a configuration file and returns them with last modification time.
  *
  * @param  string $folder   Location to look up from.
  * @param  string $pattern  Pattern to match the file. Pattern will also be removed from the key.
  * @param  int    $levels   Maximum number of recursive directories.
  * @return array
  * @internal
  */
 protected function detectAll($folder, $pattern, $levels)
 {
     $path = trim(Folder::getRelativePath($folder), '/');
     if (is_dir($folder)) {
         // Find all system and user configuration files.
         $options = ['levels' => $levels, 'compare' => 'Filename', 'pattern' => $pattern, 'filters' => ['pre-key' => $this->base, 'key' => $pattern, 'value' => function (\RecursiveDirectoryIterator $file) use($path) {
             return ["{$path}/{$file->getSubPathname()}" => $file->getMTime()];
         }], 'key' => 'SubPathname'];
         $list = Folder::all($folder, $options);
         ksort($list);
     } else {
         $list = [];
     }
     return $list;
 }
예제 #27
0
파일: gpm.php 프로젝트: emac/emacoo.cn
 public static function selfupgrade()
 {
     $upgrader = new Upgrader();
     if (!Installer::isGravInstance(GRAV_ROOT)) {
         return false;
     }
     if (is_link(GRAV_ROOT . DS . 'index.php')) {
         Installer::setError(Installer::IS_LINK);
         return false;
     }
     if (method_exists($upgrader, 'meetsRequirements') && !$upgrader->meetsRequirements()) {
         $error = [];
         $error[] = '<p>Grav has increased the minimum PHP requirement.<br />';
         $error[] = 'You are currently running PHP <strong>' . PHP_VERSION . '</strong>';
         $error[] = ', but PHP <strong>' . GRAV_PHP_MIN . '</strong> is required.</p>';
         $error[] = '<p><a href="http://getgrav.org/blog/changing-php-requirements-to-5.5" class="button button-small secondary">Additional information</a></p>';
         Installer::setError(implode("\n", $error));
         return false;
     }
     $update = $upgrader->getAssets()['grav-update'];
     $tmp = CACHE_DIR . 'tmp/Grav-' . uniqid();
     $file = self::_downloadSelfupgrade($update, $tmp);
     Installer::install($file, GRAV_ROOT, ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true]);
     $errorCode = Installer::lastErrorCode();
     Folder::delete($tmp);
     if ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)) {
         return false;
     }
     return true;
 }
예제 #28
0
파일: controller.php 프로젝트: clee03/metal
 /**
  * Delete page.
  *
  * @return bool True if the action was performed.
  * @throws \RuntimeException
  */
 protected function taskDelete()
 {
     if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.super'])) {
         return;
     }
     // Only applies to pages.
     if ($this->view != 'pages') {
         return false;
     }
     /** @var Uri $uri */
     $uri = $this->grav['uri'];
     try {
         $page = $this->admin->page();
         if (count($page->translatedLanguages()) > 1) {
             $page->file()->delete();
         } else {
             Folder::delete($page->path());
         }
         $results = Cache::clearCache('standard');
         // Set redirect to either referrer or pages list.
         $redirect = 'pages';
         $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info');
         $this->setRedirect($redirect);
     } catch (\Exception $e) {
         throw new \RuntimeException('Deleting page failed on error: ' . $e->getMessage());
     }
     return true;
 }
예제 #29
0
 /**
  * Moves or copies the page in filesystem.
  *
  * @internal
  */
 protected function doRelocation($reorder)
 {
     if (empty($this->_original)) {
         return;
     }
     // Do reordering.
     if ($reorder && $this->order() != $this->_original->order()) {
         /** @var Pages $pages */
         $pages = self::getGrav()['pages'];
         $parent = $this->parent();
         // Extract visible children from the parent page.
         $list = array();
         /** @var Page $page */
         foreach ($parent->children()->visible() as $page) {
             if ($page->order()) {
                 $list[$page->slug] = $page->path();
             }
         }
         // If page was moved, take it out of the list.
         if ($this->_action == 'move') {
             unset($list[$this->slug()]);
         }
         $list = array_values($list);
         // Then add it back to the new location (if needed).
         if ($this->order()) {
             array_splice($list, min($this->order() - 1, count($list)), 0, array($this->path()));
         }
         // Reorder all moved pages.
         foreach ($list as $order => $path) {
             if ($path == $this->path()) {
                 // Handle current page; we do want to change ordering number, but nothing else.
                 $this->order($order + 1);
             } else {
                 // Handle all the other pages.
                 $page = $pages->get($path);
                 if ($page && $page->exists() && $page->order() != $order + 1) {
                     $page = $page->move($parent);
                     $page->order($order + 1);
                     $page->save(false);
                 }
             }
         }
     }
     if ($this->_action == 'move' && $this->_original->exists()) {
         Folder::move($this->_original->path(), $this->path());
     }
     if ($this->_action == 'copy' && $this->_original->exists()) {
         Folder::copy($this->_original->path(), $this->path());
     }
     if ($this->name() != $this->_original->name()) {
         $path = $this->path();
         if (is_file($path . '/' . $this->_original->name())) {
             rename($path . '/' . $this->_original->name(), $path . '/' . $this->name());
         }
     }
     $this->_action = null;
     $this->_original = null;
 }
예제 #30
0
 /**
  *
  */
 private function symlink()
 {
     $this->output->writeln('');
     $this->output->writeln('<comment>Resetting Symbolic Links</comment>');
     foreach ($this->mappings as $source => $target) {
         if ((int) $source == $source) {
             $source = $target;
         }
         $from = $this->source . $source;
         $to = $this->destination . $target;
         $this->output->writeln('    <cyan>' . $source . '</cyan> <comment>-></comment> ' . $to);
         if (is_dir($to)) {
             @Folder::delete($to);
         } else {
             @unlink($to);
         }
         symlink($from, $to);
     }
 }