You are here

newsletter_statistics.admin.inc in Newsletter 7.2

Admin page callbacks for the newsletter module.

File

modules/statistics/includes/newsletter_statistics.admin.inc
View source
<?php

/**
 * @file
 * Admin page callbacks for the newsletter module.
 */

/**
 * Menu callback; present newsletter statistics.
 */
function newsletter_statistics_general($form, &$form_state) {
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Options'),
    '#attributes' => array(
      'class' => array(
        'container-inline',
      ),
    ),
  );
  $options['compare'] = t('Compare the selected newsletters');
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'compare',
  );
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );
  $header = array(
    'id' => array(
      'data' => t('ID'),
      'field' => 'nnid',
    ),
    'title' => array(
      'data' => t('Newsletter/List Title'),
      'field' => 'title',
    ),
    'last_sent' => array(
      'data' => t('Last Sent'),
      'field' => 'last_sent',
      'sort' => 'desc',
    ),
    'subscribers_sent' => array(
      'data' => t('E-mails Sent'),
      'field' => 'subscribers_sent',
    ),
    'clicks' => array(
      'data' => t('Total Clicks'),
      'field' => 'clicks',
    ),
    'ctr' => array(
      'data' => t('CTR'),
    ),
    'opened' => array(
      'data' => t('Opened(times)'),
      'field' => 'opens',
    ),
    'open_rate' => array(
      'data' => t('Open Rate'),
    ),
    'send_again' => array(
      'data' => t('To be sent again'),
      'field' => 'send_again',
    ),
  );
  $subquery = db_select('newsletter_newsletter', 's');
  $subquery
    ->fields('s', array(
    'title',
  ));
  $subquery
    ->addExpression('MAX(last_sent)', 'maxts');
  $subquery
    ->groupBy('title');
  $query = db_select('newsletter_newsletter', 't')
    ->extend('PagerDefault')
    ->extend('TableSort');
  $query
    ->fields('t');
  $query
    ->join($subquery, 'grp', 'grp.title = t.title AND grp.maxts = t.last_sent');
  $query
    ->leftjoin('newsletter_list', 'list', 't.title = list.title');
  $query
    ->addField('list', 'send_again', 'send_again');
  $query
    ->condition('t.last_sent', 0, '<>');
  $query
    ->limit(50);
  $query
    ->orderByHeader($header);
  $result = $query
    ->execute();
  $options = array();
  foreach ($result as $row) {
    $send_again_timestamp = strtotime($row->send_again);
    $options[$row->nnid] = array(
      'id' => (int) $row->nnid,
      'title' => check_plain($row->title),
      'last_sent' => format_date($row->last_sent, 'short'),
      'subscribers_sent' => (int) $row->subscribers_sent,
      'clicks' => (int) $row->clicks,
      'ctr' => number_format(@($row->clicks / $row->subscribers_sent) * 100, 2) . '%',
      'opened' => (int) $row->opens,
      'open_rate' => number_format(@($row->opens / $row->subscribers_sent) * 100, 2) . '%',
      'send_again' => is_numeric($send_again_timestamp) ? format_date($send_again_timestamp, 'short') : '-',
    );
  }
  $form['newsletter'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No newsletters sent yet.'),
  );
  $form['pager'] = array(
    '#theme' => 'pager',
  );
  return $form;
}
function newsletter_statistics_general_validate($form, &$form_state) {
  if (!array_filter($form_state['values']['newsletter'])) {
    form_set_error('newsletter', t('Please select newsletters to compare'));
  }
}
function newsletter_statistics_general_submit($form, &$form_state) {
  switch ($form_state['values']['operation']) {
    case 'compare':
      $args['compare'] = '';
      foreach (array_filter($form_state['values']['newsletter']) as $newsletter) {
        $args['compare'] .= $newsletter . ',';
      }
      $args['compare'] = drupal_encode_path(rtrim($args['compare'], ','));
      $form_state['redirect'] = array(
        'admin/config/media/newsletter/stats/graphic',
        array(
          'query' => $args,
        ),
      );
      break;
  }
}

/**
 * Menu callback; present newsletter statistics graphs.
 */
function newsletter_statistics_graphic() {
  $path = libraries_get_path('jqplot');
  if (!file_exists($path . '/jquery.jqplot.min.js')) {
    return drupal_set_message(t('jQplot library is not present in your filesystem.
      You need to <a href=@url>download</a> it
      and extract all its files to @path
      folder, so the library is located to
      @path/jquery.jqplot.min.js', array(
      '@url' => 'https://bitbucket.org/cleonello/jqplot/downloads/',
      '@path' => $path,
    )), 'warning');
  }

  // Add css and js files for our charts.
  $iesupport = array(
    '#type' => 'markup',
    '#markup' => '<!--[if lt IE 9]>
      <script language="javascript"
      type="text/javascript" src="' . $path . '/excanvas.js">
      </script><![endif]--> ',
  );
  drupal_add_html_head($iesupport, 'newsletter');
  drupal_add_js($path . '/jquery.jqplot.min.js');
  drupal_add_js($path . '/plugins/jqplot.highlighter.min.js');
  drupal_add_js($path . '/plugins/jqplot.enhancedLegendRenderer.min.js');
  drupal_add_js($path . '/plugins/jqplot.canvasAxisLabelRenderer.min.js');
  drupal_add_js($path . '/plugins/jqplot.dateAxisRenderer.min.js');
  drupal_add_css($path . '/jquery.jqplot.min.css');
  drupal_add_css(drupal_get_path('module', 'newsletter') . '/css/newsletter.admin.css');
  if (isset($_GET['compare'])) {
    $ids = urldecode($_GET['compare']);
    $ids = explode(',', $ids);
    foreach ($ids as $id) {
      $newsletters[] = db_query('SELECT * FROM {newsletter_newsletter}
        WHERE nnid = :id
        AND last_sent <> 0', array(
        ':id' => $id,
      ))
        ->fetchObject();
    }
  }
  else {

    // Compare all the existing newsletters; might be slow
    // @TODO check performance
    $newsletters = db_query('SELECT *
      FROM {newsletter_newsletter}
      WHERE last_sent <> 0')
      ->fetchAll();
  }
  $ctr_vars = array();
  $or_vars = array();
  $smaller_timestamp = REQUEST_TIME;
  foreach ($newsletters as $newsletter) {
    $ctr = @($newsletter->clicks / $newsletter->subscribers_sent) * 100;
    $timestamp_ms = $newsletter->last_sent * 1000;
    @($ctr_vars[$newsletter->title] .= "[{$timestamp_ms}, {$ctr}], ");
    $open_rate = @($newsletter->opens / $newsletter->subscribers_sent) * 100;
    @($or_vars[$newsletter->title] .= "[{$timestamp_ms}, {$open_rate}], ");
    $smaller_timestamp = $newsletter->last_sent < $smaller_timestamp ? $newsletter->last_sent : $smaller_timestamp;
  }
  $first_day = format_date($smaller_timestamp, 'custom', 'Y-m-d');
  if (empty($ctr_vars) && empty($or_vars)) {
    return drupal_set_message(t('No statistics have been gathered yet.'), 'warning');
  }
  $jqplot_js = '(function ($) {$(document).ready(function(){
    $.jqplot.config.enablePlugins = true;';
  $i = 1;
  $cvars = '';
  $ovars = '';
  $labels = '';
  foreach ($ctr_vars as $title => $string) {
    $jqplot_js .= "var l{$i} = [{$string}];\n";
    $cvars .= "l{$i}, ";
    $labels .= "{label:'{$title}'}, ";
    $i++;
  }
  $k = $i;
  foreach ($or_vars as $title => $string) {
    $jqplot_js .= "var l{$k} = [{$string}];\n";
    $ovars .= "l{$k}, ";
    $k++;
  }
  $jqplot_js .= "var first_day = '{$first_day}';";
  $jqplot_js .= "plot1 = \$.jqplot('chart1', [{$cvars}], {";
  $jqplot_js .= 'legend:{show:true, renderer:$.jqplot.EnhancedLegendRenderer},
                  seriesDefaults: {lineWidth:4},';
  $jqplot_js .= "series:[{$labels}],";
  $jqplot_js .= 'seriesColors:[ "#4bb2c5", "#c5b47f", "#EAA228", "#579575",
                    "#839557", "#958c12", "#953579", "#4b5de4",
                    "#d8b83f", "#ff5800", "#0085cc"],
                  highlighter: {bringSeriesToFront: true},
                  axes:{
                    xaxis:{
                      renderer: $.jqplot.DateAxisRenderer,
                      tickOptions:{formatString:"%d %b %y"},
                      min: first_day,
                      label:"Date Sent",
                    },
                    yaxis:{
                      pad:1.0,
                      numberTicks:5,
                      autoscale:false,
                      label:"CTR (%)",
                    }
                  }
                });';
  $jqplot_js .= "plot2 = \$.jqplot('chart2', [{$ovars}], {";
  $jqplot_js .= 'legend:{show:true, renderer:$.jqplot.EnhancedLegendRenderer},
                  seriesDefaults: {lineWidth:4},';
  $jqplot_js .= "series:[{$labels}],";
  $jqplot_js .= 'seriesColors:[ "#4bb2c5", "#c5b47f", "#EAA228", "#579575",
                    "#839557", "#958c12", "#953579", "#4b5de4",
                    "#d8b83f", "#ff5800", "#0085cc"],
                  highlighter: {bringSeriesToFront: true},
                  axes:{
                    xaxis:{
                      renderer: $.jqplot.DateAxisRenderer,
                      tickOptions:{formatString:"%d %b %y"},
                      min: first_day,
                      label:"Date Sent",
                    },
                    yaxis:{
                      pad:1.0,
                      numberTicks:10,
                      autoscale:false,
                      label:"Open Rate (%)"
                    }
                  }
              });
          });})(jQuery);';
  drupal_add_js($jqplot_js, 'inline');
  return '<div id="chart1"></div><div id="chart2"></div>';
}

Functions

Namesort descending Description
newsletter_statistics_general Menu callback; present newsletter statistics.
newsletter_statistics_general_submit
newsletter_statistics_general_validate
newsletter_statistics_graphic Menu callback; present newsletter statistics graphs.