You are here

function forward_update_1 in Forward 7

Same name and namespace in other branches
  1. 5 forward.install \forward_update_1()
  2. 6 forward.install \forward_update_1()

Add statistics table and populate with data from forward_log

File

./forward.install, line 87
Install, update and uninstall functions for the forward module.

Code

function forward_update_1() {

  // initialize table
  $schema['forward_statistics'] = array(
    'fields' => array(
      'nid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'last_forward_timestamp' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'forward_count' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'clickthrough_count' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'index' => array(
      'last_forward_timestamp',
    ),
    'primary key' => array(
      'nid',
    ),
  );
  $ret = array();
  db_create_table('forward_statistics', $schema['forward_statistics']);
  $id = db_insert('forward_log')
    ->fields(array(
    'nid' => 0,
    'last_forward_timestamp' => 0,
    'forward_count' => 0,
    'clickthrough_count' => 0,
  ))
    ->execute();

  // Build the SELECT query.
  $query = db_select('node', 'n');

  // Add the fields we want.
  $query
    ->addField('n', 'nid');

  // Perform the insert.
  db_insert('mytable')
    ->from($query)
    ->execute();

  // fill table
  $forwards = db_query("SELECT f.nid, f.timestamp, COUNT(f.nid) as forward_count FROM {node} n LEFT JOIN {forward_log} f ON f.nid = n.nid WHERE f.type = :f.type GROUP BY f.nid, f.timestamp", array(
    ':f.type' => 'SENT',
  ));
  foreach ($forwards as $forward) {
    $forward_count = db_query("SELECT COUNT(nid) FROM {forward_log} WHERE nid = :nid AND type = :type", array(
      ':nid' => $forward->nid,
      ':type' => 'SENT',
    ))
      ->fetchField();
    $clickthrough_count = db_query("SELECT COUNT(nid) FROM {forward_log} WHERE nid = :nid AND type = :type", array(
      ':nid' => $forward->nid,
      ':type' => 'REF',
    ))
      ->fetchField();
    db_update('forward_statistics')
      ->fields(array(
      'forward_count' => $forward_count,
      'clickthrough_count' => $clickthrough_count,
      'last_forward_timestamp' => $forward->timestamp,
    ))
      ->condition('nid', $forward->nid)
      ->execute();
  }
  return t('Forward statistics updated.');
}