/**
  * Gets the logger for a specific channel.
  *
  * @param string $channel
  *   The name of the channel. Can be any string, but the general practice is
  *   to use the name of the subsystem calling this.
  *
  * @return \Psr\Log\LoggerInterface
  *   The logger for the given channel.
  *
  * @todo Require the use of injected services:
  *   https://www.drupal.org/node/2733703
  */
 protected function getLogger($channel)
 {
     if (!$this->loggerFactory) {
         $this->loggerFactory = \Drupal::service('logger.factory');
     }
     return $this->loggerFactory->get($channel);
 }
 /**
  * Constructor for MetatagManager.
  *
  * @param MetatagGroupPluginManager $groupPluginManager
  * @param MetatagTagPluginManager $tagPluginManager
  * @param MetatagToken $token
  * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $channelFactory
  */
 public function __construct(MetatagGroupPluginManager $groupPluginManager, MetatagTagPluginManager $tagPluginManager, MetatagToken $token, LoggerChannelFactoryInterface $channelFactory)
 {
     $this->groupPluginManager = $groupPluginManager;
     $this->tagPluginManager = $tagPluginManager;
     $this->tokenService = $token;
     $this->logger = $channelFactory->get('metatag');
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     // Mock a logger.
     $this->logger = $this->prophesize(LoggerInterface::class);
     // Mock the logger service, make it return our mocked logger, and register
     // it in the container.
     $this->loggerFactory = $this->prophesize(LoggerChannelFactoryInterface::class);
     $this->loggerFactory->get('rules')->willReturn($this->logger->reveal());
     $this->container->set('logger.factory', $this->loggerFactory->reveal());
     // Mock a parameter bag.
     $this->parameterBag = $this->prophesize(ParameterBag::class);
     // Mock a request, and set our mocked parameter bag as it attributes
     // property.
     $this->currentRequest = $this->prophesize(Request::class);
     $this->currentRequest->attributes = $this->parameterBag->reveal();
     // Mock the request stack, make it return our mocked request when the
     // current request is requested, and register it in the container.
     $this->requestStack = $this->prophesize(RequestStack::class);
     $this->requestStack->getCurrentRequest()->willReturn($this->currentRequest);
     $this->container->set('request_stack', $this->requestStack->reveal());
     // Mock the current path stack.
     $this->currentPathStack = $this->prophesize(CurrentPathStack::class);
     $this->container->set('path.current', $this->currentPathStack->reveal());
     // Instantiate the redirect action.
     $this->action = $this->actionManager->createInstance('rules_page_redirect');
 }
 /**
  * Constructs a PageRedirect object.
  *
  * @param array $configuration
  *   A configuration array containing information about the plugin instance.
  * @param string $plugin_id
  *   The plugin ID for the plugin instance.
  * @param mixed $plugin_definition
  *   The plugin implementation definition.
  * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
  *   The logger factory service.
  * @param \Drupal\Core\Path\CurrentPathStack $current_path_stack
  *   The current path stack service.
  * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  *   The request stack service.
  */
 public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerChannelFactoryInterface $logger_factory, CurrentPathStack $current_path_stack, RequestStack $request_stack)
 {
     parent::__construct($configuration, $plugin_id, $plugin_definition);
     $this->logger = $logger_factory->get('rules');
     $this->currentPathStack = $current_path_stack;
     $this->request = $request_stack->getCurrentRequest();
 }
 /**
  * Log not-otherwise-specified errors, including HTTP 500.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
  *   The event to process.
  */
 public function onError(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $error = Error::decodeException($exception);
     $this->logger->get('php')->log($error['severity_level'], '%type: @message in %function (line %line of %file).', $error);
     $is_critical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;
     if ($is_critical) {
         error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items, $langcode)
 {
     $view_mode = $this->getSetting('view_mode');
     $elements = array();
     foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
         // Protect ourselves from recursive rendering.
         static $depth = 0;
         $depth++;
         if ($depth > 20) {
             $this->loggerFactory->get('entity')->error('Recursive rendering detected when rendering entity @entity_type @entity_id. Aborting rendering.', array('@entity_type' => $entity->getEntityTypeId(), '@entity_id' => $entity->id()));
             return $elements;
         }
         if ($entity->id()) {
             $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
             $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());
             // Add a resource attribute to set the mapping property's value to the
             // entity's url. Since we don't know what the markup of the entity will
             // be, we shouldn't rely on it for structured data such as RDFa.
             if (!empty($items[$delta]->_attributes)) {
                 $items[$delta]->_attributes += array('resource' => $entity->url());
             }
         } else {
             // This is an "auto_create" item.
             $elements[$delta] = array('#markup' => $entity->label());
         }
         $depth = 0;
     }
     return $elements;
 }
Example #7
0
 /**
  * Gets the logger for a specific channel.
  *
  * @param string $channel
  *   The name of the channel.
  *
  * @return \Psr\Log\LoggerInterface
  *   The logger for this channel.
  */
 protected function logger($channel)
 {
     if (!$this->loggerFactory) {
         $this->loggerFactory = $this->container()->get('logger.factory');
     }
     return $this->loggerFactory->get($channel);
 }
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items, $langcode)
 {
     $view_mode = $this->getSetting('view_mode');
     $elements = array();
     foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
         // Due to render caching and delayed calls, the viewElements() method
         // will be called later in the rendering process through a '#pre_render'
         // callback, so we need to generate a counter that takes into account
         // all the relevant information about this field and the referenced
         // entity that is being rendered.
         $recursive_render_id = $items->getFieldDefinition()->getTargetEntityTypeId() . $items->getFieldDefinition()->getTargetBundle() . $items->getName() . $entity->id();
         if (isset(static::$recursiveRenderDepth[$recursive_render_id])) {
             static::$recursiveRenderDepth[$recursive_render_id]++;
         } else {
             static::$recursiveRenderDepth[$recursive_render_id] = 1;
         }
         // Protect ourselves from recursive rendering.
         if (static::$recursiveRenderDepth[$recursive_render_id] > static::RECURSIVE_RENDER_LIMIT) {
             $this->loggerFactory->get('entity')->error('Recursive rendering detected when rendering entity %entity_type: %entity_id, using the %field_name field on the %bundle_name bundle. Aborting rendering.', ['%entity_type' => $entity->getEntityTypeId(), '%entity_id' => $entity->id(), '%field_name' => $items->getName(), '%bundle_name' => $items->getFieldDefinition()->getTargetBundle()]);
             return $elements;
         }
         $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
         $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());
         // Add a resource attribute to set the mapping property's value to the
         // entity's url. Since we don't know what the markup of the entity will
         // be, we shouldn't rely on it for structured data such as RDFa.
         if (!empty($items[$delta]->_attributes) && !$entity->isNew() && $entity->hasLinkTemplate('canonical')) {
             $items[$delta]->_attributes += array('resource' => $entity->toUrl()->toString());
         }
     }
     return $elements;
 }
Example #9
0
 /**
  * {@inheritdoc}
  */
 public function mail($module, $key, $to, $langcode, $params = array(), $reply = NULL, $send = TRUE)
 {
     $site_config = $this->configFactory->get('system.site');
     $site_mail = $site_config->get('mail');
     if (empty($site_mail)) {
         $site_mail = ini_get('sendmail_from');
     }
     // Bundle up the variables into a structured array for altering.
     $message = array('id' => $module . '_' . $key, 'module' => $module, 'key' => $key, 'to' => $to, 'from' => $site_mail, 'reply-to' => $reply, 'langcode' => $langcode, 'params' => $params, 'send' => TRUE, 'subject' => '', 'body' => array());
     // Build the default headers.
     $headers = array('MIME-Version' => '1.0', 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', 'Content-Transfer-Encoding' => '8Bit', 'X-Mailer' => 'Drupal');
     // To prevent email from looking like spam, the addresses in the Sender and
     // Return-Path headers should have a domain authorized to use the
     // originating SMTP server.
     $headers['Sender'] = $headers['Return-Path'] = $site_mail;
     $headers['From'] = $site_config->get('name') . ' <' . $site_mail . '>';
     if ($reply) {
         $headers['Reply-to'] = $reply;
     }
     $message['headers'] = $headers;
     // Build the email (get subject and body, allow additional headers) by
     // invoking hook_mail() on this module. We cannot use
     // moduleHandler()->invoke() as we need to have $message by reference in
     // hook_mail().
     if (function_exists($function = $module . '_mail')) {
         $function($key, $message, $params);
     }
     // Invoke hook_mail_alter() to allow all modules to alter the resulting
     // email.
     $this->moduleHandler->alter('mail', $message);
     // Retrieve the responsible implementation for this message.
     $system = $this->getInstance(array('module' => $module, 'key' => $key));
     // Format the message body.
     $message = $system->format($message);
     // Optionally send email.
     if ($send) {
         // The original caller requested sending. Sending was canceled by one or
         // more hook_mail_alter() implementations. We set 'result' to NULL,
         // because FALSE indicates an error in sending.
         if (empty($message['send'])) {
             $message['result'] = NULL;
         } else {
             // Ensure that subject is plain text. By default translated and
             // formatted strings are prepared for the HTML context and email
             // subjects are plain strings.
             if ($message['subject']) {
                 $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
             }
             $message['result'] = $system->mail($message);
             // Log errors.
             if (!$message['result']) {
                 $this->loggerFactory->get('mail')->error('Error sending email (from %from to %to with reply-to %reply).', array('%from' => $message['from'], '%to' => $message['to'], '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set')));
                 drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
             }
         }
     }
     return $message;
 }
Example #10
0
 /**
  * Connect to the Moodle database.
  *
  * @return bool false on failure / mysqli MySQLi object instance on success
  */
 public function connect()
 {
     // Try and connect to the database
     if (NULL === self::$connection) {
         try {
             // Connect to the database.
             $key = $this->getConnectorSettings()->get('database_connection_key');
             self::$connection = Database::getConnection('default', $key);
             // Return the database object.
             return self::$connection;
         } catch (Exception $e) {
             $this->loggerFactory->get('Moodle connection', $this->t('Error connecting to the database: "%error".', array('%error' => $e->getMessage())));
             drupal_set_message($this->t('Error connecting to the database: "%error".', array('%error' => $e->getMessage())));
             return FALSE;
         }
     }
     return self::$connection;
 }
Example #11
0
 /**
  * Get the moodle database connection object.
  *
  * @return \Drupal\Core\Database\Connection
  *   The database connection.
  */
 public function getDatabase()
 {
     // Try and connect to the database
     if (NULL === $this->database) {
         try {
             // Add connection to the Moodle database.
             $database_settings = $this->getDatabaseSettings();
             Database::addConnectionInfo('moodle', 'default', $database_settings);
             // Connect to the database.
             $this->database = Database::getConnection('default', 'moodle');
         } catch (Exception $e) {
             $this->loggerFactory->get('Moodle connection', $this->t('Error connecting to the database: "%error".', array('%error' => $e->getMessage())));
             drupal_set_message($this->t('Error connecting to the database: "%error".', array('%error' => $e->getMessage())));
             return FALSE;
         }
     }
     return $this->database;
 }
Example #12
0
 protected function getQueueUrl()
 {
     if (!isset($this->queueUrl)) {
         $text = t("You have to create a queue before you can get its URL. Use createQueue().");
         $this->logger_factory->get('my_module')->notice($text);
         return FALSE;
     } else {
         return $this->queueUrl;
     }
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function saveFile($uri, $destination, $extensions, AccountProxyInterface $user, $validators = [])
 {
     // Create the file entity.
     $file = $this->fileEntityFromUri($uri, $user);
     // Replace tokens. As the tokens might contain HTML we convert it to plain
     // text.
     $destination = PlainTextOutput::renderFromHtml($this->token->replace($destination));
     // Handle potentialy dangerous extensions.
     $renamed = $this->renameExecutableExtensions($file);
     // The .txt extension may not be in the allowed list of extensions. We have
     // to add it here or else the file upload will fail.
     if ($renamed && !empty($extensions)) {
         $extensions .= ' txt';
         drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()]));
     }
     // Validate the file.
     $errors = $this->validateFile($file, $extensions, $validators);
     if (!empty($errors)) {
         $message = ['error' => ['#markup' => t('The specified file %name could not be uploaded.', ['%name' => $file->getFilename()])], 'item_list' => ['#theme' => 'item_list', '#items' => $errors]];
         drupal_set_message($this->renderer->renderPlain($message), 'error');
         return FALSE;
     }
     // Prepare destination.
     if (!$this->prepareDestination($file, $destination)) {
         drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]), 'error');
         return FALSE;
     }
     // Move uploaded files from PHP's upload_tmp_dir to destination.
     $move_result = file_unmanaged_move($uri, $file->getFileUri());
     if (!$move_result) {
         drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error');
         $this->logger->notice('Upload error. Could not move uploaded file %file to destination %destination.', ['%file' => $file->getFilename(), '%destination' => $file->getFileUri()]);
         return FALSE;
     }
     // Set the permissions on the new file.
     $this->fileSystem->chmod($file->getFileUri());
     // If we made it this far it's safe to record this file in the database.
     $file->save();
     return $file;
 }
 /**
  * Constructs a MenuLinkContentDeleteForm object.
  *
  * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
  *   The entity manager.
  * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
  *   The logger channel factory.
  */
 public function __construct(EntityManagerInterface $entity_manager, LoggerChannelFactoryInterface $logger_factory)
 {
     parent::__construct($entity_manager);
     $this->logger = $logger_factory->get('menu');
 }