You are here

linkedin_insights_tag.module in LinkedIn Insights Tag 8

Same filename and directory in other branches
  1. 7 linkedin_insights_tag.module

LinkedIn Insights Module..

Adds the required Javascript to all your Drupal pages to allow tracking by the LinkedIn Insights. @author: Sorin Boistean

File

linkedin_insights_tag.module
View source
<?php

/**
 * @file
 * LinkedIn Insights Module..
 *
 * Adds the required Javascript to all your Drupal pages to allow tracking by
 * the LinkedIn Insights.
 * @author: Sorin Boistean
 */
use Drupal\Component\Utility\UrlHelper;

/**
 * Implements hook_page_attachments().
 *
 * Insert JavaScript to the appropriate scope/region of the page.
 */
function linkedin_insights_tag_page_attachments(array &$page) {
  $config = \Drupal::config('linkedin_insights_tag.settings');
  $noscript = $config
    ->get('image_only');

  // Load linkedin_insights_tag library if noscript is not enforced.
  if (empty($noscript)) {
    $roles = $config
      ->get('user_role_roles');
    $user = \Drupal::currentUser();
    $current_user_roles = $user
      ->getRoles();

    // Make sure the visibility user roles are configured.
    if (!empty($roles) && !empty($current_user_roles)) {
      $intersect = array_intersect($roles, $current_user_roles);
      if (!empty($intersect)) {
        $page['#attached']['drupalSettings']['linkedin_insights_tag']['partner_id'] = $config
          ->get('partner_id');
        $page['#attached']['library'][] = 'linkedin_insights_tag/linkedin_insights_tag_variables';
        $page['#attached']['library'][] = 'linkedin_insights_tag/linkedin_insights_tag';
      }
    }
  }
}

/**
 * Implements hook_page_bottom().
 */
function linkedin_insights_tag_page_bottom(array &$page_bottom) {

  // Get config.
  $config = \Drupal::config('linkedin_insights_tag.settings');
  $pid = $config
    ->get('partner_id');

  // If image_only is false, then placement should be in a noscript tag.
  // If image_only is true, do not wrap in a noscript tag.
  $noscript = !$config
    ->get('image_only');
  if (!empty($pid)) {
    $img_src = 'https://dc.ads.linkedin.com/collect/?pid=' . $pid . '&fmt=gif';

    // Validate url.
    if (UrlHelper::isValid($img_src, TRUE)) {

      // Add noscript support.
      $page_bottom[] = [
        'img_tag' => [
          '#type' => 'html_tag',
          '#tag' => 'img',
          '#noscript' => $noscript,
          '#attributes' => [
            'height' => 1,
            'width' => 1,
            'alt' => '',
            'style' => 'display:none',
            'src' => $img_src,
          ],
        ],
      ];
    }
  }
}