You are here

wordstream.module in WordStream Keyword Tools 7

Same filename and directory in other branches
  1. 6 wordstream.module

File

wordstream.module
View source
<?php

/**
 * @file
 * Analyzes node content for search engine optimization recommendations using the Scribe SEO optimizer
 */
DEFINE('WORDSTREAM_LINK_API_ACCOUNT', 'http://www.wordstream.com/keyword-tool-api-drupal');
DEFINE('WORDSTREAM_ADULT_FILTER_DEFAULT', TRUE);
DEFINE('WORDSTREAM_CACHE_TIME', 604800);

/**
* Implements hook_menu().
().
*/
function wordstream_menu() {
  $items = array();
  $items['admin/config/search/wordstream'] = array(
    'title' => 'WordStream',
    'description' => 'Configure WordStream API and options.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'wordstream_admin_settings',
    ),
    'access callback' => 'user_access',
    'access arguments' => array(
      'admin wordstream',
    ),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'wordstream.admin.inc',
  );
  $items['admin/structure/wordstream'] = array(
    'title' => 'WordStream',
    'description' => 'Research keywords using WordStream API.',
    'page callback' => 'wordstream_keyword_stats_report_page',
    'page arguments' => array(
      'keywords',
    ),
    'access callback' => 'user_access',
    'access arguments' => array(
      'access wordstream reports',
    ),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'wordstream.admin.inc',
  );
  $items['admin/structure/wordstream/keywords'] = array(
    'title' => 'Keywords tool',
    'page callback' => 'wordstream_keyword_stats_report_page',
    'page arguments' => array(
      'keywords',
    ),
    'access callback' => 'user_access',
    'access arguments' => array(
      'access wordstream reports',
    ),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'wordstream.admin.inc',
  );
  $items['wordstream/util'] = array(
    'title' => 'WordStream util',
    'page callback' => 'wordstream_util',
    'access callback' => TRUE,
    'access arguments' => array(
      'access wordstream reports',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
* Implements hook_permission()
().
*/
function wordstream_permission() {
  return array(
    'admin wordstream' => array(
      'title' => t('admin wordstream'),
      'description' => t('TODO Add a description for \'admin wordstream\''),
    ),
    'access wordstream reports' => array(
      'title' => t('access wordstream reports'),
      'description' => t('TODO Add a description for \'access wordstream reports\''),
    ),
  );
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function wordstream_util() {
  $r = variable_get('wordstream_adult_filter', WORDSTREAM_ADULT_FILTER_DEFAULT);
  return "x=" . $r;
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function wordstream_include_api_class($username = NULL, $password = NULL) {
  include_once drupal_get_path('module', 'wordstream') . '/class.wordstream.inc';
  $un = $username ? $username : variable_get('wordstream_username', '');
  $pw = $password ? $password : variable_get('wordstream_password', '');
  if ($un && $pw) {
    $wordstream = new WordStream($un, $pw);
    if (!$_SESSION['wordstream']['sid']) {
      $ret = $wordstream
        ->login();
      list($un, $sid) = explode(':', $ret);
      $_SESSION['wordstream']['sid'] = $sid;
    }
  }
  else {

    /*
        drupal_set_message(
     t('The username and password is not set for the WordStream API. !set',
       array(
         '!set' => l(t('Set credentials.'), 'admin/config/wordstream')
       )
    ), 'error');
    */
    return FALSE;
  }
  return $wordstream;
}

/**
 * Displays keyword stats report
 *
 * @param str $keyword
 */
function wordstream_keyword_stats_report_page($type = 'keywords', $keyword = NULL) {
  if (module_exists('kwresearch')) {
    drupal_add_css(drupal_get_path('module', 'kwresearch') . '/kwresearch.css');
    drupal_add_js(drupal_get_path('module', 'kwresearch') . '/kwresearch.js');
  }
  if (isset($_SESSION['wordstream'])) {
    $analysis = $_SESSION['wordstream']['analysis'];
    $_SESSION['wordstream']['analysis'] = '';
  }
  $stats = TRUE;
  if (!$analysis && $keyword) {
    $analysis = array();
    $analysis['inputs']['keyword'] = $keyword;
    $analysis['analysis'] = wordstream_get_keyword_data($keyword, $msgs);
    if (!empty($msgs)) {
      $analysis['messages'] = $msgs;
    }
  }
  if ($analysis) {

    // turn on keyword operations
    $analysis['inputs']['operations'] = TRUE;
  }
  $output = render(drupal_get_form('wordstream_stats_report_form', $analysis));

  //$output = t('Content Analysis.');
  if ($analysis) {
    $output .= '<div id="wordstream-report" style="clear: both;">';
    $output .= '<h3>' . t('Report') . '</h3>';
    $output .= theme_wordstream_stats_report($analysis);
    $output .= '</div>';

    // initialize kw data array for javascript
    if (is_array($analysis['analysis'])) {
      foreach ($analysis['analysis'] as $kw => $v) {
        if (isset($v['term'])) {
          $site_kw[$v['term']] = array(
            'kid' => (int) $v['kid'],
            'priority' => (int) $v['priority'],
            'value' => (int) $v['value'],
            'page_count' => (int) $v['page_count'],
          );
        }
      }
    }
  }
  if (module_exists('kwresearch')) {
    $site_priority_options = kwresearch_get_priority_options();
    drupal_add_js(array(
      'kwresearch' => array(
        'form' => 'admin_keyword_stats',
        'analyze_path' => base_path() . 'admin/content/kwresearch/keyword_report/',
        'keyword_edit_path' => base_path() . 'admin/content/kwresearch/keyword_list/edit/',
        'return_destination' => 'admin/content/kwresearch/keyword_report/' . $keyword,
        'toggle_site_keyword_callback' => base_path() . 'kwresearch/toggle_site_keyword_js',
        'module_path' => base_path() . drupal_get_path('module', 'kwresearch'),
        'enable_site_keyword_tool' => user_access('kwresearch admin site keywords'),
        'site_keywords_data' => $site_kw,
        'site_priority_options' => $site_priority_options,
      ),
    ), array(
      'type' => 'setting',
      'scope' => JS_DEFAULT,
    ));
  }
  return $output;
}

/**
 * Generates main wordstream report form
 *
 * @param $form_state
 * @param analysis struc $analysis
 * @param bool $ajax
 */
function wordstream_stats_report_form($form, $form_state, $analysis, $ajax = FALSE) {
  $form['pre_inputs'] = array(
    '#type' => 'markup',
    '#value' => '<div id="wordstream-form-inputs">',
  );
  $form['wordstream_keyword'] = array(
    '#type' => 'textfield',
    '#title' => t('Keyword'),
    '#default_value' => $analysis && $analysis['inputs']['wordstream_keyword'] ? $analysis['inputs']['wordstream_keyword'] : '',
  );
  $form['wordstream_stats_report_options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Filters'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['wordstream_stats_report_options'] = array_merge($form['wordstream_stats_report_options'], wordstream_stats_report_form_options($analysis));
  $form['post_inputs'] = array(
    '#type' => 'markup',
    '#value' => '</div>',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

/**
 * returns stats report paramter options form fields array
 * @param analysis struc $analysis
 */
function wordstream_stats_report_form_options($analysis = NULL) {
  $defvals = isset($analysis['inputs']) ? $analysis['inputs'] : array();
  $form['wordstream_adult_filter'] = array(
    '#type' => 'checkbox',
    '#title' => t('Adult keyword filter default'),
    '#return_value' => 'on',
    '#default_value' => isset($defvals['wordstream_adult_filter']) ? $defvals['wordstream_adult_filter'] : variable_get('wordstream_adult_filter', WORDSTREAM_ADULT_FILTER_DEFAULT),
  );
  return $form;
}

/**
 * Stats report form submit handler.
 * @param unknown_type $form
 * @param unknown_type $form_state
 */
function wordstream_stats_report_form_submit($form, &$form_state) {

  //echo "setags_extract_tags_submit($form, &$form_state)";

  //print_r($form_state['values']);
  $analysis['inputs'] = $form_state['values'];
  $params = array(
    'type' => 'keywords',
    'adult_filter' => $analysis['inputs']['wordstream_adult_filter'],
  );
  $analysis['analysis'] = wordstream_get_keyword_data($form_state['values']['wordstream_keyword'], $msgs, $params);
  if (!empty($msgs)) {
    $analysis['messages'] = $msgs;
  }
  if ($analysis['analysis']) {
    $_SESSION['wordstream']['analysis'] = $analysis;
  }
  return;
}

/**
 * Generates keyword search volume data from WordStream
 *
 * @param $keywords
 * @param $msgs
 * @param $params
 */
function wordstream_get_keyword_data($keywords, &$msgs, $params) {

  //dsm($params);
  $type = $params['type'] ? $params['type'] : NULL;
  $adult_filter = $params['adult_filter'] ? 1 : 0;

  //$limit = ($params['limit'])?$params['limit']:NULL;
  if (is_null($adult_filter)) {
    $adult_filter = variable_get('adult_filter', WORDSTREAM_ADULT_FILTER_DEFAULT);
  }
  if (!$type) {
    $type = 'keywords';
    $params['type'] = 'keywords';
  }
  $query = db_select('wordstream_cache', 'c')
    ->fields('c')
    ->condition('keyphrase', $keywords)
    ->condition('adult_filter', $adult_filter)
    ->condition('api_call', $type);
  $dbresult = $query
    ->execute()
    ->fetchObject();
  if ($dbresult) {
    $dbret = unserialize($dbresult->data);
    if (time() - $dbresult->updated < variable_get('wordstream_cache_time', WORDSTREAM_CACHE_TIME)) {
      return $dbret;

      //return array_slice($dbret, 0, $limit);
    }
  }
  $wordstream = wordstream_include_api_class();
  if (!$wordstream) {
    return FALSE;
  }
  if ($type == 'keywords') {
    $apiret = $wordstream
      ->getKeywords($keywords);
  }

  //dsm($apiret);
  if (!is_array($apiret)) {
    $errmsg = t('Expected return of type array, but got [@type]', array(
      '@type' => gettype($apiret),
    ));
    $msgs[] = kwresearch_format_message($errmsg, 'error');
    return FALSE;
  }

  // if keywords longer than 255, don't cache
  if (strlen($keywords) > 255) {
    return $apiret;
  }

  //dsm($apiret);
  if (!$dbresult) {
    $query = db_insert('wordstream_cache')
      ->fields(array(
      'keyphrase' => $keywords,
      'adult_filter' => $adult_filter,
      'api_call' => $type,
      'updated' => time(),
      'data' => serialize($apiret),
    ));
    $id = $query
      ->execute();
  }
  elseif (!$dbret) {

    /*
      	$sql = '
      UPDATE {wordstream_cache}
      SET
        time = %d,
        data = "%s"
      WHERE
        keyphrase = "%s" AND
        adult_filter = %d AND
        api_call = "%s"
    ';
    //dsm(sprintf($sql, time(), serialize($apiret), $keywords, $adult_filter, $type));

    $query = db_query($sql, REQUEST_TIME, serialize($apiret), $keywords, $adult_filter, $type);
    */
    $query = db_update('wordstream_cache')
      ->condition('keyphrase', $keywords)
      ->condition('adult_filter', $adult_filter)
      ->condition('api_call', $type)
      ->fields(array(
      'updated' => time(),
      'data' => serialize($apiret),
    ));
    $query
      ->execute();
  }
  elseif (array_slice($dbret, 0, 10) != array_slice($apiret, 0, 10)) {

    // empty cache, it is out of date

    /*
      	$sql = '
      DELETE FROM {wordstream_cache}
    ';
    //dsm(sprintf($sql));

    $query = db_query($sql);
    */
    db_delete('wordstream_cache')
      ->execute();
    drupal_set_message(t('Keyword cache reset.'));
    variable_set('wordstream_last_cache', time());

    // update new data set search ratios

    //scribeseo_update_kwresearch_searches_ratio();
  }
  return $apiret;
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function theme_wordstream_stats_report($analysis) {

  // TODO: Should this theme wordstream_stats_report be declared in hook_theme()?
  $hdrs = array(
    t('Term'),
    t('Frequency'),
  );
  $rows = array();
  foreach ($analysis['analysis'] as $v) {
    $row = array(
      $v[0],
      number_format($v[1]),
    );
    $rows[] = array(
      'data' => $row,
      'id' => 'kid-' . (isset($v['kid']) ? $v['kid'] : 'n'),
    );
  }
  $attr = array(
    'id' => 'kwresearch-result-table-' . check_plain(str_replace(' ', '-', isset($analysis['inputs']['keyword']) ? $analysis['inputs']['keyword'] : '')),
    'class' => array(
      'kwresearch-result-table',
    ),
  );
  $output = '<div id="kwresearch-result-block-' . check_plain(str_replace(' ', '-', isset($analysis['inputs']['keyword']) ? $analysis['inputs']['keyword'] : '')) . '" class="kwresearch-result-block">';
  $vars = array(
    'header' => $hdrs,
    'rows' => $rows,
    'attributes' => $attr,
  );
  $output .= theme('table', $vars);
  return $output;
}

/**
 *  Implentation of hook_contentanalysis_analyzers()
 *  register contentanalysisexample with contentanalysis analyzers registry
 */

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function wordstream_kwresearch_sources() {
  $sources['wordstream'] = array(
    'title' => t('WordStream'),
    'module' => 'wordstream',
    'form_options' => 'wordstream_stats_report_form_options',
    'stats_callback' => 'wordstream_kwresearch_get_keyword_stats',
    'searches_ratio' => variable_get('wordstream_kwresearch_searches_ratio', 256),
    // ratio = total daily searches / count from data
    'stats_report_columns' => array(
      'wordstream_searches' => t('WS count'),
    ),
    'stats_report_values_callback' => 'wordstream_kwresearch_format_stats_values',
  );
  return $sources;
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function wordstream_update_kwresearch_searches_ratio() {
  if (time() > variable_get('wordstream_kwresearch_searches_ratio_updated', 0) + WORDSTREAM_CACHE_TIME) {

    // request ratio from kwresearch server
    $apiret = xmlrpc('http://www.leveltendesign.com/xmlrpc.php', 'l10seoapi.searches_ratio', 'wordstream');

    //dsm($apiret);
    if (is_numeric($apiret) && $apiret > 0) {
      variable_set('wordstream_kwresearch_searches_ratio', (double) $apiret);
    }
    variable_set('wordstream_kwresearch_searches_ratio_updated', time());
  }
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function wordstream_kwresearch_get_keyword_stats($keywords, $params = NULL) {
  $data = wordstream_get_keyword_data($keywords, $msgs, $params);

  //dsm($data);
  $ret = array();
  if (is_array($data)) {
    foreach ($data as $v) {
      $ret[$v[0]] = array(
        'searches' => $v[1],
      );
    }
  }
  return $ret;
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function wordstream_kwresearch_format_stats_values($values, $keyword = '', $type = 'term') {
  switch ($type) {
    case 'wordstream_searches':
      if ($values['wordstream_searches'] > 0) {
        $output = $values['wordstream_searches'] == 'NA' ? 'NA' : number_format($values['wordstream_searches']);
      }
      else {
        $output = $values['wordstream_searches'];
      }
      break;
    default:
      return FALSE;
  }
  return $output;
}

Functions

Namesort descending Description
theme_wordstream_stats_report @todo Please document this function.
wordstream_get_keyword_data Generates keyword search volume data from WordStream
wordstream_include_api_class @todo Please document this function.
wordstream_keyword_stats_report_page Displays keyword stats report
wordstream_kwresearch_format_stats_values @todo Please document this function.
wordstream_kwresearch_get_keyword_stats @todo Please document this function.
wordstream_kwresearch_sources @todo Please document this function.
wordstream_menu Implements hook_menu(). ().
wordstream_permission Implements hook_permission() ().
wordstream_stats_report_form Generates main wordstream report form
wordstream_stats_report_form_options returns stats report paramter options form fields array
wordstream_stats_report_form_submit Stats report form submit handler.
wordstream_update_kwresearch_searches_ratio @todo Please document this function.
wordstream_util @todo Please document this function.