You are here

function facebook_tracking_pixel_page_build in Facebook Tracking Pixel 7

Same name and namespace in other branches
  1. 8 facebook_tracking_pixel.module \facebook_tracking_pixel_page_build()

Implements hook_page_build().

File

./facebook_tracking_pixel.module, line 133
facebook_tracking_pixel.module Facebook Tracking Module.

Code

function facebook_tracking_pixel_page_build(&$page) {

  // Assertain which role should see the tracking information.
  global $user;

  // Default to no tracking.
  $trackable = 0;

  // Determin if the user is trackable based on roles assigned.
  $trackable += _facebook_tracking_pixel_roles($user);

  // Only process tracking codes if the user is trackable.
  if ($trackable > 0) {

    // Pull base code IDs from database and build the noscript header includes.
    $basecodes = db_select('facebook_tracking_pixel_base_codes', 'c')
      ->fields('c')
      ->orderBy('weight')
      ->execute()
      ->fetchAllAssoc('base_code_id');

    // Facebook static code.
    $fb_noscript_src = facebook_tracking_pixel_base_code_nojs();

    // Facebook JS code.
    $fb_script_src = facebook_tracking_pixel_base_code_js();

    // Script path.
    $path = variable_get('facebook_tracking_pixel_path', 'public://facebook_tracking_pixel');

    // Process anything that could be stored in the session.
    if (!empty($_SESSION['facebook_tracking_pixel'])) {

      // We use this foreach to step through the session variables for special
      // case codes.
      foreach ($_SESSION['facebook_tracking_pixel'] as $key => $value) {
        switch ($key) {
          case 'registration':
            $userregfile = $path . '/registrationtracking/fb_trk_user_registration.js';
            $page['content']['#attached']['js']['facebook_tracking_pixel_path_user_registration'] = [
              'type' => 'file',
              'group' => JS_THEME,
              'data' => $userregfile,
              'preprocess' => (bool) variable_get('facebook_tracking_pixel_aggregation', FALSE),
            ];

            // Assemble code and pull the FBID from the session variable.
            $fb_base_code_nojs = $fb_noscript_src[0] . $_SESSION['facebook_tracking_pixel']['registration_fbid'] . $fb_noscript_src[1];
            drupal_add_html_head([
              '#type' => 'markup',
              '#markup' => $fb_base_code_nojs,
              '#weight' => 150,
            ], 'facebook_tracking_pixel_path_user_registration');

            // We remove the session variables, we do not want it loading but once.
            unset($_SESSION['facebook_tracking_pixel']['registration']);
            unset($_SESSION['facebook_tracking_pixel']['registration_fbid']);

            // If this is a user registration event we stop processing.
            return;
            break;
          case 'ftpdcaddtocart':
            $ftpdcbasecodeid = variable_get('facebook_tracking_pixel_commerce_tracking_basecode');
            $ftpdcfbid = db_select('facebook_tracking_pixel_base_codes', 'c')
              ->fields('c', [
              'base_code_fbid',
            ])
              ->condition('base_code_id', $ftpdcbasecodeid, '=')
              ->execute()
              ->fetchField();

            // Prepare an array of arguments to do text replacements.
            $argreplace = [
              '@cur' => $value['currency_code'],
              '@id' => $value['content_id'],
              '@quantity' => $value['quantity'],
              '@val' => $value['value'],
            ];

            // This event will require the JS to be inline in the page.
            $reservedevents = facebook_tracking_pixel_events_reserved();
            $ftpdcpurcode = format_string($reservedevents['ftpdcaddtocart']['code'], $argreplace);
            $inlinejs = $fb_script_src[0] . $ftpdcfbid . $fb_script_src[1] . $ftpdcpurcode;

            // JS to load into page header.
            $page['content']['#attached']['js']['facebook_tracking_pixel_path_drupal_commerce_addtocart'] = [
              'type' => 'inline',
              'group' => JS_THEME,
              'data' => $inlinejs,
              'preprocess' => (bool) variable_get('facebook_tracking_pixel_aggregation', FALSE),
            ];

            // Noscript for header.
            $fb_base_code_nojs = $fb_noscript_src[0] . $ftpdcfbid . $fb_noscript_src[1];
            drupal_add_html_head([
              '#type' => 'markup',
              '#markup' => $fb_base_code_nojs,
              '#weight' => 150,
            ], 'facebook_tracking_pixel_path_drupal_commerce_addtocart');

            // Delete session variable.
            unset($_SESSION['facebook_tracking_pixel']['ftpdcaddtocart']);
            break;
          case 'ftpdcinitiatecheckout':
            $ftpdcbasecodeid = variable_get('facebook_tracking_pixel_commerce_tracking_basecode');
            $ftpdcfbid = db_select('facebook_tracking_pixel_base_codes', 'c')
              ->fields('c', [
              'base_code_fbid',
            ])
              ->condition('base_code_id', $ftpdcbasecodeid, '=')
              ->execute()
              ->fetchField();
            $subdir = variable_get('facebook_tracking_pixel_commerce_js_subdir', 'commercetracking');
            $ftpdcfilname = $path . '/' . $subdir . '/' . 'fb_trk_checkoutstart_' . $ftpdcfbid . '.js';

            // JS to load into page header.
            $page['content']['#attached']['js']['facebook_tracking_pixel_path_drupal_commerce_initiatecheckout'] = [
              'type' => 'file',
              'group' => JS_THEME,
              'data' => $ftpdcfilname,
              'preprocess' => (bool) variable_get('facebook_tracking_pixel_aggregation', FALSE),
            ];

            // Noscript for header.
            $fb_base_code_nojs = $fb_noscript_src[0] . $ftpdcfbid . $fb_noscript_src[1];
            drupal_add_html_head([
              '#type' => 'markup',
              '#markup' => $fb_base_code_nojs,
              '#weight' => 150,
            ], 'facebook_tracking_pixel_path_drupal_commerce_initiatecheckout');

            // Delete session variable.
            unset($_SESSION['facebook_tracking_pixel']['ftpdcinitiatecheckout']);
            unset($subdir);
            break;
          case 'ftpdcpurchase':
            $ftpdcbasecodeid = variable_get('facebook_tracking_pixel_commerce_tracking_basecode');
            $ftpdcfbid = db_select('facebook_tracking_pixel_base_codes', 'c')
              ->fields('c', [
              'base_code_fbid',
            ])
              ->condition('base_code_id', $ftpdcbasecodeid, '=')
              ->execute()
              ->fetchField();

            // We have to load the order and retrieve the total and currency
            $order = commerce_order_load($value);
            $wrapper = entity_metadata_wrapper('commerce_order', $order);
            $currency_code = $wrapper->commerce_order_total->currency_code
              ->value();
            $total = $wrapper->commerce_order_total->amount
              ->value();
            $total = sprintf('%.2f', $total / 100);

            // Add the products to the contents parameter, I am using the node ID as the product ID.
            $order_contents = '';
            foreach ($order->commerce_line_items['und'] as $order_line_item) {
              $line_item = commerce_line_item_load($order_line_item['line_item_id']);
              if ($line_item && $line_item->type == 'product') {
                $order_contents .= '{"id":' . $line_item->data['context']['entity']['entity_id'] . ', "quantity":' . $line_item->quantity . '}';
              }
            }

            // Prepare an array of arguments to do text replacements.
            // Add the order contents to the replace array.
            $argreplace = [
              '@contents' => $order_contents,
              '@cur' => $currency_code,
              '@val' => $total,
            ];

            // This event will require the JS to be inline in the page.
            $reservedevents = facebook_tracking_pixel_events_reserved();
            $ftpdcpurcode = format_string($reservedevents['ftpdcpurchase']['code'], $argreplace);
            $inlinejs = $fb_script_src[0] . $ftpdcfbid . $fb_script_src[1] . $ftpdcpurcode;
            $page['content']['#attached']['js']['facebook_tracking_pixel_path_drupal_commerce_purchase'] = [
              'type' => 'inline',
              'group' => JS_THEME,
              'data' => $inlinejs,
              'preprocess' => FALSE,
            ];

            // Noscript for header.
            $fb_base_code_nojs = $fb_noscript_src[0] . $ftpdcfbid . $fb_noscript_src[1];
            drupal_add_html_head([
              '#type' => 'markup',
              '#markup' => $fb_base_code_nojs,
              '#weight' => 150,
            ], 'facebook_tracking_pixel_path_drupal_commerce_purchase');

            // Delete session variable.
            unset($_SESSION['facebook_tracking_pixel']['ftpdcpurchase']);
            break;

          // If an alter hook has been created. Allow it to be displayed.
          default:
            $context = [
              'fb_script_src' => $fb_script_src,
              'fb_noscript_src' => $fb_noscript_src,
            ];
            drupal_alter('facebook_tracking_pixel_event_' . $key, $value, $page, $context);

            // Delete session variable for the custom tracking code.
            unset($_SESSION['facebook_tracking_pixel'][$key]);
            break;
        }
      }
    }

    // Gather the path based tracking codes.
    $trackingpaths = facebook_tracking_pixel_path_codes();

    // If we have tracking codes. Build the page items.
    if (!empty($trackingpaths)) {
      $i = 0;
      foreach ($trackingpaths as $code) {
        $page['content']['#attached']['js']['facebook_tracking_pixel_path_' . $i] = [
          'type' => 'file',
          'group' => JS_THEME,
          'data' => $code['event_js_file'],
          'preprocess' => (bool) variable_get('facebook_tracking_pixel_aggregation', FALSE),
        ];

        // Assemble code.
        if (isset($basecodes[$code['event_base_code_id']])) {
          $fb_base_code_nojs = $fb_noscript_src[0] . $basecodes[$code['event_base_code_id']]->base_code_fbid . $fb_noscript_src[1];
          drupal_add_html_head([
            '#type' => 'markup',
            '#markup' => $fb_base_code_nojs,
            '#weight' => 150 + $i,
          ], 'facebook_tracking_pixel_path_noscript_' . $i);
          $i++;
        }

        // If we have a tracking path with the same base code id, we must drop
        // the base code ID so it is not loaded below. Preventing duplicate codes
        // loading on the same page since the path code will contain the base code
        // JS components.
        if (array_key_exists($code['event_base_code_id'], $basecodes)) {
          unset($basecodes[$code['event_base_code_id']]);
        }
      }
    }

    // Process global tracking codes that are to run on the entire site.
    $i = 0;
    foreach ($basecodes as $id => $values) {
      if ($values->base_code_global == 1) {

        // Our static tracking file.
        $file = $path . '/fb_tkpx.' . $values->base_code_fbid . '.js';

        // Page content with the static tracking file.
        $page['content']['#attached']['js']['facebook_tracking_pixel_' . $i] = [
          'type' => 'file',
          'group' => JS_THEME,
          'data' => $file,
          'preprocess' => (bool) variable_get('facebook_tracking_pixel_aggregation', FALSE),
        ];

        // Assemble noscript code and add it to the head.
        $fb_base_code_nojs = $fb_noscript_src[0] . $values->base_code_fbid . $fb_noscript_src[1];
        drupal_add_html_head([
          '#type' => 'markup',
          '#markup' => $fb_base_code_nojs,
          '#weight' => 200 + $i,
        ], 'facebook_tracking_pixel_noscript_' . $i);
      }
      $i++;
    }
  }
}