本文整理汇总了PHP中Drupal\Component\Utility\Crypt类的典型用法代码示例。如果您正苦于以下问题:PHP Crypt类的具体用法?PHP Crypt怎么用?PHP Crypt使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Crypt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: dump
/**
* {@inheritdoc}
*
* The file name for the CSS or JS cache file is generated from the hash of
* the aggregated contents of the files in $data. This forces proxies and
* browsers to download new CSS when the CSS changes.
*/
public function dump($data, $file_extension)
{
// Prefix filename to prevent blocking by firewalls which reject files
// starting with "ad*".
$filename = $file_extension . '_' . Crypt::hashBase64($data) . '.' . $file_extension;
// Create the css/ or js/ path within the files folder.
$path = 'public://' . $file_extension;
$uri = $path . '/' . $filename;
// Create the CSS or JS file.
file_prepare_directory($path, FILE_CREATE_DIRECTORY);
if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
return FALSE;
}
// If CSS/JS gzip compression is enabled and the zlib extension is available
// then create a gzipped version of this file. This file is served
// conditionally to browsers that accept gzip using .htaccess rules.
// It's possible that the rewrite rules in .htaccess aren't working on this
// server, but there's no harm (other than the time spent generating the
// file) in generating the file anyway. Sites on servers where rewrite rules
// aren't working can set css.gzip to FALSE in order to skip
// generating a file that won't be used.
if (extension_loaded('zlib') && \Drupal::config('system.performance')->get($file_extension . '.gzip')) {
if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
return FALSE;
}
}
return $uri;
}
示例2: handleAutocomplete
/**
* Autocomplete the label of an entity.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object that contains the typed tags.
* @param string $target_type
* The ID of the target entity type.
* @param string $selection_handler
* The plugin ID of the entity reference selection handler.
* @param string $selection_settings_key
* The hashed key of the key/value entry that holds the selection handler
* settings.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The matched entity labels as a JSON response.
*
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
* Thrown if the selection settings key is not found in the key/value store
* or if it does not match the stored data.
*/
public function handleAutocomplete(Request $request, $target_type, $selection_handler, $selection_settings_key)
{
$matches = array();
// Get the typed string from the URL, if it exists.
if ($input = $request->query->get('q')) {
$typed_string = Tags::explode($input);
$typed_string = Unicode::strtolower(array_pop($typed_string));
// Selection settings are passed in as a hashed key of a serialized array
// stored in the key/value store.
$selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
if ($selection_settings !== FALSE) {
$selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
if ($selection_settings_hash !== $selection_settings_key) {
// Disallow access when the selection settings hash does not match the
// passed-in key.
throw new AccessDeniedHttpException('Invalid selection settings key.');
}
} else {
// Disallow access when the selection settings key is not found in the
// key/value store.
throw new AccessDeniedHttpException();
}
$matches = $this->matcher->getMatches($target_type, $selection_handler, $selection_settings, $typed_string);
}
return new JsonResponse($matches);
}
示例3: setUp
/**
* {@inheritdoc}
*/
public function setUp()
{
parent::setUp();
$this->key = Crypt::randomBytesBase64(55);
$this->state = $this->getMock('Drupal\\Core\\State\\StateInterface');
$this->privateKey = new PrivateKey($this->state);
}
示例4: handle
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
{
$config = $this->configFactory->get('shield.settings');
$allow_cli = $config->get('allow_cli');
$user = $config->get('user');
$pass = $config->get('pass');
if (empty($user) || PHP_SAPI === 'cli' && $allow_cli) {
// If username is empty, then authentication is disabled,
// or if request is coming from a cli and it is allowed,
// then proceed with response without shield authentication.
return $this->httpKernel->handle($request, $type, $catch);
} else {
if ($request->server->has('PHP_AUTH_USER') && $request->server->has('PHP_AUTH_PW')) {
$input_user = $request->server->get('PHP_AUTH_USER');
$input_pass = $request->server->get('PHP_AUTH_PW');
} elseif ($request->server->has('HTTP_AUTHORIZATION')) {
list($input_user, $input_pass) = explode(':', base64_decode(substr($request->server->get('HTTP_AUTHORIZATION'), 6)), 2);
} elseif ($request->server->has('REDIRECT_HTTP_AUTHORIZATION')) {
list($input_user, $input_pass) = explode(':', base64_decode(substr($request->server->get('REDIRECT_HTTP_AUTHORIZATION'), 6)), 2);
}
if (isset($input_user) && $input_user === $user && Crypt::hashEquals($pass, $input_pass)) {
return $this->httpKernel->handle($request, $type, $catch);
}
}
$response = new Response();
$response->headers->add(['WWW-Authenticate' => 'Basic realm="' . strtr($config->get('print'), ['[user]' => $user, '[pass]' => $pass]) . '"']);
$response->setStatusCode(401);
return $response;
}
示例5: generate
/**
* {@inheritdoc}
*/
public function generate()
{
// Obtain a random string of 32 hex characters.
$hex = bin2hex(Crypt::randomBytes(16));
// The variable names $time_low, $time_mid, $time_hi_and_version,
// $clock_seq_hi_and_reserved, $clock_seq_low, and $node correlate to
// the fields defined in RFC 4122 section 4.1.2.
//
// Use characters 0-11 to generate 32-bit $time_low and 16-bit $time_mid.
$time_low = substr($hex, 0, 8);
$time_mid = substr($hex, 8, 4);
// Use characters 12-15 to generate 16-bit $time_hi_and_version.
// The 4 most significant bits are the version number (0100 == 0x4).
// We simply skip character 12 from $hex, and concatenate the strings.
$time_hi_and_version = '4' . substr($hex, 13, 3);
// Use characters 16-17 to generate 8-bit $clock_seq_hi_and_reserved.
// The 2 most significant bits are set to one and zero respectively.
$clock_seq_hi_and_reserved = base_convert(substr($hex, 16, 2), 16, 10);
$clock_seq_hi_and_reserved &= 0b111111;
$clock_seq_hi_and_reserved |= 0b10000000;
// Use characters 18-19 to generate 8-bit $clock_seq_low.
$clock_seq_low = substr($hex, 18, 2);
// Use characters 20-31 to generate 48-bit $node.
$node = substr($hex, 20);
// Re-combine as a UUID. $clock_seq_hi_and_reserved is still an integer.
$uuid = sprintf('%s-%s-%s-%02x%s-%s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $clock_seq_low, $node);
return $uuid;
}
示例6: testFeed
/**
* Generates a test feed and simulates last-modified and etags.
*
* @param $use_last_modified
* Set TRUE to send a last modified header.
* @param $use_etag
* Set TRUE to send an etag.
* @param Request $request
* Information about the current HTTP request.
*
* @return \Symfony\Component\HttpFoundation\Response
* A feed that forces cache validation.
*/
public function testFeed($use_last_modified, $use_etag, Request $request)
{
$response = new Response();
$last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
$etag = Crypt::hashBase64($last_modified);
$if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
$if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));
// Send appropriate response. We respond with a 304 not modified on either
// etag or on last modified.
if ($use_last_modified) {
$response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
}
if ($use_etag) {
$response->headers->set('ETag', $etag);
}
// Return 304 not modified if either last modified or etag match.
if ($last_modified == $if_modified_since || $etag == $if_none_match) {
$response->setStatusCode(304);
return $response;
}
// The following headers force validation of cache.
$response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
// Read actual feed from file.
$file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
$handle = fopen($file_name, 'r');
$feed = fread($handle, filesize($file_name));
fclose($handle);
$response->setContent($feed);
return $response;
}
示例7: setUp
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->syncDirectory = $this->publicFilesDirectory . '/config_' . Crypt::randomBytesBase64() . '/sync';
$this->settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) array('value' => $this->syncDirectory, 'required' => TRUE);
// Other directories will be created too.
$this->settings['config_directories']['custom'] = (object) array('value' => $this->publicFilesDirectory . '/config_custom', 'required' => TRUE);
parent::setUp();
}
示例8: testGenerateSeedOnGet
/**
* Tests that a new token seed is generated upon first use.
*
* @covers ::get
*/
public function testGenerateSeedOnGet()
{
$key = Crypt::randomBytesBase64();
$this->privateKey->expects($this->any())->method('get')->will($this->returnValue($key));
$this->sessionMetadata->expects($this->once())->method('getCsrfTokenSeed')->will($this->returnValue(NULL));
$this->sessionMetadata->expects($this->once())->method('setCsrfTokenSeed')->with($this->isType('string'));
$this->assertInternalType('string', $this->generator->get());
}
示例9: generateHash
/**
* Generates a unique hash for identification purposes.
*
* @param string $source_path
* Source path of the redirect.
* @param array $source_query
* Source query as an array.
* @param string $language
* Redirect language.
*
* @return string
* Base 64 hash.
*/
public static function generateHash($source_path, array $source_query, $language)
{
$hash = array('source' => Unicode::strtolower($source_path), 'language' => $language);
if (!empty($source_query)) {
$hash['source_query'] = $source_query;
}
redirect_sort_recursive($hash, 'ksort');
return Crypt::hashBase64(serialize($hash));
}
示例10: setUp
/**
* {@inheritdoc}
*/
function setUp()
{
parent::setUp();
$this->key = Crypt::randomBytesBase64(55);
$this->privateKey = $this->getMockBuilder('Drupal\\Core\\PrivateKey')->disableOriginalConstructor()->setMethods(array('get'))->getMock();
$this->privateKey->expects($this->any())->method('get')->will($this->returnValue($this->key));
$settings = array('hash_salt' => $this->randomName());
new Settings($settings);
$this->generator = new CsrfTokenGenerator($this->privateKey);
}
示例11: setUp
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->configDirectory = $this->publicFilesDirectory . '/config_' . Crypt::randomBytesBase64();
$this->settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) array('value' => $this->configDirectory . '/sync', 'required' => TRUE);
// Create the files directory early so we can test the error case.
mkdir($this->publicFilesDirectory);
// Create a file so the directory can not be created.
file_put_contents($this->configDirectory, 'Test');
parent::setUp();
}
示例12: startBackgroundJob
/**
* Starts a background job using a new process.
*
* @param \Drupal\feeds\FeedInterface $feed
* The feed to start the job for.
* @param string $method
* Method to execute on importer; one of 'import' or 'clear'.
*
* @throws Exception $e
*
* @todo Inject these dependencies.
*/
protected function startBackgroundJob(FeedInterface $feed, $method)
{
$cid = 'feeds_feed:' . $feed->id();
$token = Crypt::randomStringHashed(55);
\Drupal::state()->set($cid, array('token' => $token, 'method' => $method));
$client = \Drupal::httpClient();
// Do not wait for a response.
$client->addSubscriber(new AsyncPlugin());
$url = $this->url('feeds.execute', array('feeds_feed' => $feed->id()), array('absolute' => TRUE));
$request = $client->post($url)->addPostFields(array('token' => $token));
$request->send();
}
示例13: form
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state)
{
$form = parent::form($form, $form_state);
$api_key = $this->entity;
$hex = isset($api_key->key) ? $api_key->key : substr(hash('sha256', Crypt::randomBytes(16)), 0, 32);
$form['label'] = array('#type' => 'textfield', '#title' => $this->t('Machine Name'), '#maxlength' => 255, '#default_value' => $api_key->label(), '#description' => $this->t("Machine Name for the API Key."), '#required' => TRUE);
$form['key'] = array('#type' => 'textfield', '#title' => $this->t('API Key'), '#maxlength' => 42, '#default_value' => $hex, '#description' => $this->t("The generated API Key for an user."), '#required' => TRUE);
$form['user_uuid'] = array('#type' => 'select', '#multiple' => FALSE, '#options' => self::get_user(), '#description' => $this->t("Please select the User who gets authenticated with that API Key."), '#default_value' => $api_key->user_uuid);
$form['id'] = array('#type' => 'machine_name', '#default_value' => $api_key->id(), '#machine_name' => array('exists' => '\\Drupal\\api_key_auth\\Entity\\ApiKey::load'), '#disabled' => !$api_key->isNew());
/* You will need additional form elements for your custom properties. */
return $form;
}
示例14: testActionConfiguration
/**
* Tests configuration of advanced actions through administration interface.
*/
function testActionConfiguration()
{
// Create a user with permission to view the actions administration pages.
$user = $this->drupalCreateUser(array('administer actions'));
$this->drupalLogin($user);
// Make a POST request to admin/config/system/actions.
$edit = array();
$edit['action'] = Crypt::hashBase64('action_goto_action');
$this->drupalPostForm('admin/config/system/actions', $edit, t('Create'));
$this->assertResponse(200);
// Make a POST request to the individual action configuration page.
$edit = array();
$action_label = $this->randomMachineName();
$edit['label'] = $action_label;
$edit['id'] = strtolower($action_label);
$edit['url'] = 'admin';
$this->drupalPostForm('admin/config/system/actions/add/' . Crypt::hashBase64('action_goto_action'), $edit, t('Save'));
$this->assertResponse(200);
// Make sure that the new complex action was saved properly.
$this->assertText(t('The action has been successfully saved.'), "Make sure we get a confirmation that we've successfully saved the complex action.");
$this->assertText($action_label, "Make sure the action label appears on the configuration page after we've saved the complex action.");
// Make another POST request to the action edit page.
$this->clickLink(t('Configure'));
preg_match('|admin/config/system/actions/configure/(.+)|', $this->getUrl(), $matches);
$aid = $matches[1];
$edit = array();
$new_action_label = $this->randomMachineName();
$edit['label'] = $new_action_label;
$edit['url'] = 'admin';
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertResponse(200);
// Make sure that the action updated properly.
$this->assertText(t('The action has been successfully saved.'), "Make sure we get a confirmation that we've successfully updated the complex action.");
$this->assertNoText($action_label, "Make sure the old action label does NOT appear on the configuration page after we've updated the complex action.");
$this->assertText($new_action_label, "Make sure the action label appears on the configuration page after we've updated the complex action.");
$this->clickLink(t('Configure'));
$element = $this->xpath('//input[@type="text" and @value="admin"]');
$this->assertTrue(!empty($element), 'Make sure the URL appears when re-editing the action.');
// Make sure that deletions work properly.
$this->drupalGet('admin/config/system/actions');
$this->clickLink(t('Delete'));
$this->assertResponse(200);
$edit = array();
$this->drupalPostForm("admin/config/system/actions/configure/{$aid}/delete", $edit, t('Delete'));
$this->assertResponse(200);
// Make sure that the action was actually deleted.
$this->assertRaw(t('The action %action has been deleted.', array('%action' => $new_action_label)), 'Make sure that we get a delete confirmation message.');
$this->drupalGet('admin/config/system/actions');
$this->assertResponse(200);
$this->assertNoText($new_action_label, "Make sure the action label does not appear on the overview page after we've deleted the action.");
$action = entity_load('action', $aid);
$this->assertFalse($action, 'Make sure the action is gone after being deleted.');
}
示例15: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$settings = $this->settings;
if ($settings['settings_source'] === 'global') {
$config = \Drupal::config('pathologic.settings');
$settings['protocol_style'] = $config->get('protocol_style');
$settings['local_paths'] = $config->get('local_paths');
} else {
$settings = $settings['local_settings'];
}
// @todo Move code from .module file to inside here.
return new FilterProcessResult(_pathologic_filter($text, $settings, Crypt::hashBase64(serialize($settings))));
}