本文整理汇总了PHP中Grav\Common\Utils类的典型用法代码示例。如果您正苦于以下问题:PHP Utils类的具体用法?PHP Utils怎么用?PHP Utils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Utils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: checkSecurityToken
protected function checkSecurityToken()
{
/** @var Request $request */
$request = $this->container['request'];
$nonce = $request->get->get('nonce');
return isset($nonce) && Utils::verifyNonce($nonce, 'gantry-admin');
}
示例2: save
/**
* Save a group
*/
public function save()
{
$blueprints = new Blueprints('blueprints://');
$blueprint = $blueprints->get('user/group');
$fields = $blueprint->fields();
self::getGrav()['config']->set("groups.{$this->groupname}", []);
foreach ($fields as $field) {
if ($field['type'] == 'text') {
$value = $field['name'];
if (isset($this->items[$value])) {
self::getGrav()['config']->set("groups.{$this->groupname}.{$value}", $this->items[$value]);
}
}
if ($field['type'] == 'array') {
$value = $field['name'];
$arrayValues = Utils::resolve($this->items, $field['name']);
if ($arrayValues) {
foreach ($arrayValues as $arrayIndex => $arrayValue) {
self::getGrav()['config']->set("groups.{$this->groupname}.{$value}.{$arrayIndex}", $arrayValue);
}
}
}
}
$type = 'groups';
$blueprints = $this->blueprints("config/{$type}");
$obj = new Data(self::getGrav()['config']->get($type), $blueprints);
$file = CompiledYamlFile::instance(self::getGrav()['locator']->findResource("config://{$type}.yaml"));
$obj->file($file);
$obj->save();
}
示例3: init
public function init()
{
$this->shortcode->getHandlers()->add('fa', function (ShortcodeInterface $sc) {
// Load assets if required
if ($this->config->get('plugins.shortcode-core.fontawesome.load', false)) {
$this->shortcode->addAssets('css', $this->config->get('plugins.shortcode-core.fontawesome.url'));
}
// Get shortcode content and parameters
$str = $sc->getContent();
$icon = $sc->getParameter('icon', false);
if (!$icon) {
$icon = $sc->getParameter('fa', trim($sc->getParameterAt(0), '='));
}
if (!Utils::startsWith($icon, 'fa-')) {
$icon = 'fa-' . $icon;
}
$extras = explode(',', $sc->getParameter('extras', ''));
foreach ($extras as $extra) {
if (!Utils::startsWith($extra, 'fa-')) {
$extra = 'fa-' . $extra;
}
$icon .= ' ' . $extra;
}
$output = '<i class="fa ' . $icon . '">' . $str . '</i>';
return $output;
});
}
示例4: setup
/**
* If the admin path matches, initialize the Login plugin configuration and set the admin
* as active.
*/
public function setup()
{
// Autoloader
spl_autoload_register(function ($class) {
if (Utils::startsWith($class, 'Grav\\Plugin\\Admin')) {
require_once __DIR__ . '/classes/' . strtolower(basename(str_replace("\\", "/", $class))) . '.php';
}
});
$route = $this->config->get('plugins.admin.route');
if (!$route) {
return;
}
$this->base = '/' . trim($route, '/');
$this->admin_route = rtrim($this->grav['pages']->base(), '/') . $this->base;
$this->uri = $this->grav['uri'];
// check for existence of a user account
$account_dir = $file_path = $this->grav['locator']->findResource('account://');
$user_check = glob($account_dir . '/*.yaml');
// If no users found, go to register
if ($user_check == false || count((array) $user_check) == 0) {
if (!$this->isAdminPath()) {
$this->grav->redirect($this->admin_route);
}
$this->template = 'register';
}
// Only activate admin if we're inside the admin path.
if ($this->isAdminPath()) {
$this->active = true;
// Set cache based on admin_cache option
if (method_exists($this->grav['cache'], 'setEnabled')) {
$this->grav['cache']->setEnabled($this->config->get('plugins.admin.cache_enabled'));
}
}
}
示例5: get
/**
* Makes a request to the URL by using the preferred method
* @param string $uri URL to call
* @param array $options An array of parameters for both `curl` and `fopen`
* @param callable $callback Either a function or callback in array notation
* @return string The response of the request
*/
public static function get($uri = '', $options = [], $callback = null)
{
if (!self::isCurlAvailable() && !self::isFopenAvailable()) {
throw new \RuntimeException('Could not start an HTTP request. `allow_url_open` is disabled and `cURL` is not available');
}
// disable time limit if possible to help with slow downloads
if (!Utils::isFunctionDisabled('set_time_limit') && !ini_get('safe_mode')) {
set_time_limit(0);
}
$options = array_replace_recursive(self::$defaults, $options);
$method = 'get' . ucfirst(strtolower(self::$method));
self::$callback = $callback;
return static::$method($uri, $options, $callback);
}
示例6: getContents
private function getContents($fn)
{
if (Utils::startswith($fn, 'data:')) {
$path = $this->grav['locator']->findResource('user://data', true);
$fn = ltrim($fn, 'data:');
} else {
$path = $this->grav['page']->path();
}
$path = $path . DS . $fn;
if (file_exists($path)) {
return file_get_contents($path);
}
return null;
}
示例7: get
/**
* Makes a request to the URL by using the preferred method
*
* @param string $uri URL to call
* @param array $options An array of parameters for both `curl` and `fopen`
* @param callable $callback Either a function or callback in array notation
*
* @return string The response of the request
*/
public static function get($uri = '', $options = [], $callback = null)
{
if (!self::isCurlAvailable() && !self::isFopenAvailable()) {
throw new \RuntimeException('Could not start an HTTP request. `allow_url_open` is disabled and `cURL` is not available');
}
// check if this function is available, if so use it to stop any timeouts
try {
if (!Utils::isFunctionDisabled('set_time_limit') && !ini_get('safe_mode') && function_exists('set_time_limit')) {
set_time_limit(0);
}
} catch (\Exception $e) {
}
$options = array_replace_recursive(self::$defaults, $options);
$method = 'get' . ucfirst(strtolower(self::$method));
self::$callback = $callback;
return static::$method($uri, $options, $callback);
}
示例8: filecontent
public function filecontent($path)
{
$path_info = pathinfo($path);
$config = Grav::instance()['config']->get('plugins.file-content');
if (in_array($path_info['extension'], $config['allowed_extensions'])) {
if (Utils::startsWith($path, '/')) {
if ($config['allow_in_grav'] && file_exists(GRAV_ROOT . $path)) {
return file_get_contents(GRAV_ROOT . $path);
} elseif ($config['allow_in_filesystem'] && file_exists($path)) {
return file_get_contents($path);
}
} else {
$page_path = Grav::instance()['page']->path() . '/' . $path;
if ($config['allow_in_page'] && file_exists($page_path)) {
return file_get_contents($page_path);
}
}
}
return $path;
}
示例9: init
public function init()
{
$this->shortcode->getHandlers()->add('ui-animated-text', function (ShortcodeInterface $sc) {
// Add assets
$this->shortcode->addAssets('css', 'plugin://shortcode-ui/css/ui-atext.css');
$this->shortcode->addAssets('js', 'plugin://shortcode-ui/js/ui-atext.js');
$content = $sc->getContent();
$animation = $sc->getParameter('animation', 'rotate-1');
$words = $sc->getParameter('words', 'cool, funky, fresh');
$visible = $sc->getParameter('visible', 1);
if (Utils::contains($content, '%WORDS%')) {
$content = explode('%WORDS%', $content);
} else {
$content = (array) $content;
}
if (intval($visible) > count($words)) {
$visible = 1;
}
$output = $this->twig->processTemplate('partials/ui-atext.html.twig', ['content' => $content, 'words' => explode(',', $words), 'animation' => $animation, 'element' => $sc->getParameter('element', 'h1'), 'wrapper_extra' => Utils::contains($animation, 'type') ? ' waiting' : '', 'visible' => $visible]);
return $output;
});
}
示例10: serve
/**
* @return int|null|void
*/
protected function serve()
{
$this->options = $this->input->getOptions();
$this->gpm = new GPM($this->options['force']);
$this->displayGPMRelease();
$this->data = $this->gpm->getRepository();
$data = $this->filter($this->data);
$climate = new CLImate();
$climate->extend('Grav\\Console\\TerminalObjects\\Table');
if (!$data) {
$this->output->writeln('No data was found in the GPM repository stored locally.');
$this->output->writeln('Please try clearing cache and running the <green>bin/gpm index -f</green> command again');
$this->output->writeln('If this doesn\'t work try tweaking your GPM system settings.');
$this->output->writeln('');
$this->output->writeln('For more help go to:');
$this->output->writeln(' -> <yellow>https://learn.getgrav.org/troubleshooting/common-problems#cannot-connect-to-the-gpm</yellow>');
die;
}
foreach ($data as $type => $packages) {
$this->output->writeln("<green>" . strtoupper($type) . "</green> [ " . count($packages) . " ]");
$packages = $this->sort($packages);
if (!empty($packages)) {
$table = [];
$index = 0;
foreach ($packages as $slug => $package) {
$row = ['Count' => $index++ + 1, 'Name' => "<cyan>" . Utils::truncate($package->name, 20, false, ' ', '...') . "</cyan> ", 'Slug' => $slug, 'Version' => $this->version($package), 'Installed' => $this->installed($package)];
$table[] = $row;
}
$climate->table($table);
}
$this->output->writeln('');
}
$this->output->writeln('You can either get more informations about a package by typing:');
$this->output->writeln(' <green>' . $this->argv . ' info <cyan><package></cyan></green>');
$this->output->writeln('');
$this->output->writeln('Or you can install a package by typing:');
$this->output->writeln(' <green>' . $this->argv . ' install <cyan><package></cyan></green>');
$this->output->writeln('');
}
示例11: get
/**
* Makes a request to the URL by using the preferred method
*
* @param string $uri URL to call
* @param array $options An array of parameters for both `curl` and `fopen`
* @param callable $callback Either a function or callback in array notation
*
* @return string The response of the request
*/
public static function get($uri = '', $options = [], $callback = null)
{
if (!self::isCurlAvailable() && !self::isFopenAvailable()) {
throw new \RuntimeException('Could not start an HTTP request. `allow_url_open` is disabled and `cURL` is not available');
}
// check if this function is available, if so use it to stop any timeouts
try {
if (!Utils::isFunctionDisabled('set_time_limit') && !ini_get('safe_mode') && function_exists('set_time_limit')) {
set_time_limit(0);
}
} catch (\Exception $e) {
}
$config = Grav::instance()['config'];
$overrides = [];
// SSL Verify Peer and Proxy Setting
$settings = ['method' => $config->get('system.gpm.method', self::$method), 'verify_peer' => $config->get('system.gpm.verify_peer', true), 'proxy_url' => $config->get('system.gpm.proxy_url', $config->get('system.proxy_url', false))];
if (!$settings['verify_peer']) {
$overrides = array_replace_recursive([], $overrides, ['curl' => [CURLOPT_SSL_VERIFYPEER => $settings['verify_peer']], 'fopen' => ['ssl' => ['verify_peer' => $settings['verify_peer'], 'verify_peer_name' => $settings['verify_peer']]]]);
}
// Proxy Setting
if ($settings['proxy_url']) {
$proxy = parse_url($settings['proxy_url']);
$fopen_proxy = ($proxy['scheme'] ?: 'http') . '://' . $proxy['host'] . (isset($proxy['port']) ? ':' . $proxy['port'] : '');
$overrides = array_replace_recursive([], $overrides, ['curl' => [CURLOPT_PROXY => $proxy['host'], CURLOPT_PROXYTYPE => 'HTTP'], 'fopen' => ['proxy' => $fopen_proxy, 'request_fulluri' => true]]);
if (isset($proxy['port'])) {
$overrides['curl'][CURLOPT_PROXYPORT] = $proxy['port'];
}
if (isset($proxy['user']) && isset($proxy['pass'])) {
$fopen_auth = $auth = base64_encode($proxy['user'] . ':' . $proxy['pass']);
$overrides['curl'][CURLOPT_PROXYUSERPWD] = $proxy['user'] . ':' . $proxy['pass'];
$overrides['fopen']['header'] = "Proxy-Authorization: Basic {$fopen_auth}";
}
}
$options = array_replace_recursive(self::$defaults, $options, $overrides);
$method = 'get' . ucfirst(strtolower($settings['method']));
self::$callback = $callback;
return static::$method($uri, $options, $callback);
}
示例12: sendActivationEmail
/**
* Handle the email to activate the user account.
*
* @return bool True if the action was performed.
*/
protected function sendActivationEmail($user)
{
if (empty($user->email)) {
throw new \RuntimeException($this->grav['language']->translate('PLUGIN_LOGIN.USER_NEEDS_EMAIL_FIELD'));
}
$token = md5(uniqid(mt_rand(), true));
$expire = time() + 604800;
// next week
$user->activation_token = $token . '::' . $expire;
$user->save();
$param_sep = $this->grav['config']->get('system.param_sep', ':');
$activation_link = $this->grav['base_url_absolute'] . $this->config->get('plugins.login.route_activate') . '/token' . $param_sep . $token . '/username' . $param_sep . $user->username . '/nonce' . $param_sep . Utils::getNonce('user-activation');
$sitename = $this->grav['config']->get('site.title', 'Website');
$subject = $this->grav['language']->translate(['PLUGIN_LOGIN.ACTIVATION_EMAIL_SUBJECT', $sitename]);
$content = $this->grav['language']->translate(['PLUGIN_LOGIN.ACTIVATION_EMAIL_BODY', $user->username, $activation_link, $sitename]);
$to = $user->email;
$sent = LoginUtils::sendEmail($subject, $content, $to);
if ($sent < 1) {
throw new \RuntimeException($this->grav['language']->translate('PLUGIN_LOGIN.EMAIL_SENDING_FAILURE'));
}
return true;
}
示例13: recurse
/**
* Recursive function to load & build page relationships.
*
* @param string $directory
* @param Page|null $parent
* @return Page
* @throws \RuntimeException
* @internal
*/
protected function recurse($directory, Page &$parent = null)
{
$directory = rtrim($directory, DS);
$page = new Page();
/** @var Config $config */
$config = $this->grav['config'];
/** @var Language $language */
$language = $this->grav['language'];
// stuff to do at root page
if ($parent === null) {
// Fire event for memory and time consuming plugins...
if ($config->get('system.pages.events.page')) {
$this->grav->fireEvent('onBuildPagesInitialized');
}
}
$page->path($directory);
if ($parent) {
$page->parent($parent);
}
$page->orderDir($config->get('system.pages.order.dir'));
$page->orderBy($config->get('system.pages.order.by'));
// Add into instances
if (!isset($this->instances[$page->path()])) {
$this->instances[$page->path()] = $page;
if ($parent && $page->path()) {
$this->children[$parent->path()][$page->path()] = array('slug' => $page->slug());
}
} else {
throw new \RuntimeException('Fatal error when creating page instances.');
}
$content_exists = false;
$pages_found = glob($directory . '/*' . CONTENT_EXT);
$page_extensions = $language->getFallbackPageExtensions();
if ($pages_found) {
foreach ($page_extensions as $extension) {
foreach ($pages_found as $found) {
if (preg_match('/^.*\\/[0-9A-Za-z\\-\\_]+(' . $extension . ')$/', $found)) {
$page_found = $found;
$page_extension = $extension;
break 2;
}
}
}
}
if ($parent && !empty($page_found)) {
$file = new \SplFileInfo($page_found);
$page->init($file, $page_extension);
$content_exists = true;
if ($config->get('system.pages.events.page')) {
$this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
}
}
// set current modified of page
$last_modified = $page->modified();
/** @var \DirectoryIterator $file */
foreach (new \FilesystemIterator($directory) as $file) {
$name = $file->getFilename();
// Ignore all hidden files if set.
if ($this->ignore_hidden) {
if ($name && $name[0] == '.') {
continue;
}
}
if ($file->isFile()) {
// Update the last modified if it's newer than already found
if (!in_array($file->getBasename(), $this->ignore_files) && ($modified = $file->getMTime()) > $last_modified) {
$last_modified = $modified;
}
} elseif ($file->isDir() && !in_array($file->getFilename(), $this->ignore_folders)) {
if (!$page->path()) {
$page->path($file->getPath());
}
$path = $directory . DS . $name;
$child = $this->recurse($path, $page);
if (Utils::startsWith($name, '_')) {
$child->routable(false);
}
$this->children[$page->path()][$child->path()] = array('slug' => $child->slug());
if ($config->get('system.pages.events.page')) {
$this->grav->fireEvent('onFolderProcessed', new Event(['page' => $page]));
}
}
}
// Set routability to false if no page found
if (!$content_exists) {
$page->routable(false);
}
// Override the modified and ID so that it takes the latest change into account
$page->modified($last_modified);
$page->id($last_modified . md5($page->filePath()));
// Sort based on Defaults or Page Overridden sort order
//.........这里部分代码省略.........
示例14: download
/**
* Provides the ability to download a file to the browser
*
* @param $file the full path to the file to be downloaded
* @param bool $force_download as opposed to letting browser choose if to download or render
*/
public static function download($file, $force_download = true)
{
if (file_exists($file)) {
// fire download event
self::getGrav()->fireEvent('onBeforeDownload', new Event(['file' => $file]));
$file_parts = pathinfo($file);
$filesize = filesize($file);
// check if this function is available, if so use it to stop any timeouts
if (function_exists('set_time_limit')) {
set_time_limit(0);
}
ignore_user_abort(false);
if ($force_download) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file_parts['basename']);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
} else {
header("Content-Type: " . Utils::getMimeType($file_parts['extension']));
}
header('Content-Length: ' . $filesize);
// 8kb chunks for now
$chunk = 8 * 1024;
$fh = fopen($file, "rb");
if ($fh === false) {
return;
}
// Repeat reading until EOF
while (!feof($fh)) {
echo fread($fh, $chunk);
ob_flush();
// flush output
flush();
}
exit;
}
}
示例15: findPackages
/**
* Searches for a list of Packages in the repository
* @param array $searches An array of either slugs or names
* @return array Array of found Packages
* Format: ['total' => int, 'not_found' => array, <found-slugs>]
*/
public function findPackages($searches = [])
{
$packages = ['total' => 0, 'not_found' => []];
foreach ($searches as $search) {
$repository = '';
// if this is an object, get the search data from the key
if (is_object($search)) {
$search = (array) $search;
$key = key($search);
$repository = $search[$key];
$search = $key;
}
if ($found = $this->findPackage($search)) {
// set override respository if provided
if ($repository) {
$found->override_repository = $repository;
}
if (!isset($packages[$found->package_type])) {
$packages[$found->package_type] = [];
}
$packages[$found->package_type][$found->slug] = $found;
$packages['total']++;
} else {
// make a best guess at the type based on the repo URL
if (Utils::contains($repository, '-theme')) {
$type = 'themes';
} else {
$type = 'plugins';
}
$not_found = new \stdClass();
$not_found->name = Inflector::camelize($search);
$not_found->slug = $search;
$not_found->package_type = $type;
$not_found->install_path = str_replace('%name%', $search, $this->install_paths[$type]);
$not_found->override_repository = $repository;
$packages['not_found'][$search] = $not_found;
}
}
return $packages;
}