You are here

wordstream.module in WordStream Keyword Tools 6

Same filename and directory in other branches
  1. 7 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, 'https://www.wordstream.com/register-free-keyword-tool');
DEFINE(WORDSTREAM_LINK_WIDGET_GENERATOR, 'http://www.wordstream.com/widget-generator');
DEFINE(WORDTRACKER_ADULT_FILTER_DEFAULT, TRUE);

/**
 * Implementation of hook_menu().
 */
function wordstream_menu() {
  $items = array();
  $items['admin/settings/wordstream'] = array(
    'title' => t('WordStream'),
    'description' => 'Analyze and optimize node content.',
    '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/content/wordstream'] = array(
    'title' => t('Wordstream'),
    '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/content/wordstream/keywords'] = array(
    'title' => t('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;
}

/**
 * Implementation of hook_perm()
 */
function wordstream_perm() {
  return array(
    'admin wordstream',
    'access wordstream reports',
  );
}
function wordstream_util() {
  return 'ok';
}
function wordstream_include_api_class() {

  /*
  include_once(drupal_get_path('module', 'wordstream') . '/lib/class.wordstream.inc');
  $un = variable_get('wordstream_username', '');
  $pw = variable_get('wordstream_password', '');
  $wordstream = new WordStream($un, $pw);

  if (!$_SESSION['wordstream']['sid']) {
    $ret = $wordstream->login();
    list($un, $sid) = explode(':', $ret);
    $_SESSION['wordstream']['sid'] = $sid;
  }
  return $wordstream;
  */
  $files['module_path'] = './' . drupal_get_path('module', 'wordstream') . '/lib/class.wordstream.inc';
  if (module_exists('libraries') && ($p = libraries_get_path('wordstream'))) {
    $files['libraries_path'] = './' . $p . '/class.wordstream.inc';
  }
  foreach ($files as $f) {
    if (file_exists($f)) {
      $file = $f;
      break;
    }
  }
  if (!$file) {
    $msg = t('The WordStream module requires the WordStream API class. ');
    $msg .= l(t('Download the class here.'), 'https://api.wordstream.com/doc/sample_code?doc=wordstream_api.php&label=WordStream%20API%20Sample%20Code', array(
      'attributes' => array(
        'target' => 'alchemy',
      ),
    ));
    $msg .= "<br><br>";
    if ($files['libraries_path']) {
      $msg .= t(' Save the file on your server in a folder named "wordstream" under the libraries directory; %path.', array(
        '%path' => $files['libraries_path'],
      ));
    }
    else {
      $msg .= t(' Save the file on your server in a folder named "lib" under the WordStream module directory; %path.', array(
        '%path' => $files['module_path'],
      ));
    }
    if ($analysis) {
      $analysis['messages'][] = contentanalysis_format_message($msg, 'error');
    }
    else {
      drupal_set_message($msg, 'error');
    }
    return FALSE;
  }
  require_once $file;
  $un = variable_get('wordstream_username', '');
  $pw = variable_get('wordstream_password', '');
  $wordstream = new WordStream($un, $pw);
  if (!$_SESSION['wordstream']['sid']) {
    $ret = $wordstream
      ->login();
    list($un, $sid) = explode(':', $ret);
    $_SESSION['wordstream']['sid'] = $sid;
  }
  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');
  }
  $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 .= 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) {
        $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,
      ),
    ), 'setting');
  }
  return $output;
}

/**
 * Generates main wordstream report form
 * 
 * @param $form_state
 * @param analysis struc $analysis
 * @param bool $ajax
 */
function wordstream_stats_report_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 = $analysis['inputs'];
  $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;
  }
  $_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) {
  $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('kwresearch_adult_filter', 'remove_dubious');
  }

  //print "include_plurals=$include_plurals, adult_filter=$adult_filter";
  if (!$type) {
    $type = 'keywords';
    $params['type'] = 'keywords';
  }
  $last_cache = variable_get('wordstream_last_cache', 0);
  $cachecheck = FALSE;
  if (time - $last_cache > variable_get('wordstream_cache_time', 604800)) {
    $cachecheck = TRUE;
  }
  $sql = '
    SELECT *
    FROM {wordstream_cache}
    WHERE
    keyphrase = "%s" AND
    adult_filter = %d AND
    api_call = "%s"
  ';
  $dbresult = db_fetch_array(db_query($sql, $keywords, $adult_filter, $type));
  if ($dbresult) {
    $dbret = unserialize($dbresult['data']);
    if (!$cachecheck) {
      return $dbret;

      //return array_slice($dbret, 0, $limit);
    }
  }
  $wordstream = wordstream_include_api_class();
  if (!$wordstream) {
    return array();
  }
  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) {
    $sql = '
      INSERT INTO {wordstream_cache}
      (keyphrase, adult_filter, api_call, updated, data)
      VALUES ("%s", %d, "%s", %d,"%s")
    ';

    //dsm(sprintf($sql, $keywords, $adult_filter, $type, time(), serialize($apiret)));
    $query = db_query($sql, $keywords, $adult_filter, $type, time(), serialize($apiret));
  }
  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, time(), serialize($apiret), $keywords, $adult_filter, $type);
  }
  elseif (array_slice($dbret, 0, 10) != array_slice($apiret, 0, 10)) {

    // empty cache, it is out of date
    $sql = '
      DELETE FROM {wordstream_data}
    ';

    //dsm(sprintf($sql));
    $query = db_query($sql);
    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;
}
function theme_wordstream_stats_report($analysis) {
  $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-' . $values['kid'],
    );
  }
  $attr = array(
    'id' => 'kwresearch-result-table-' . check_plain(str_replace(' ', '-', $analysis['inputs']['keyword'])),
    'class' => 'kwresearch-result-table',
  );
  $output = '<div id="kwresearch-result-block-' . check_plain(str_replace(' ', '-', $analysis['inputs']['keyword'])) . '" class="kwresearch-result-block">';
  $output .= theme_table($hdrs, $rows, $attr);
  return $output;
}

/**
 *  Implentation of hook_contentanalysis_analyzers()
 *  register contentanalysisexample with contentanalysis analyzers registry
 */
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', 3549.7),
    // 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;
}
function wordstream_update_kwresearch_searches_ratio() {
  if (time() > variable_get('wordstream_kwresearch_searches_ratio_updated', 0) + 604800) {

    // 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());
  }
}
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;
}
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
wordstream_get_keyword_data Generates keyword search volume data from WordStream
wordstream_include_api_class
wordstream_keyword_stats_report_page Displays keyword stats report
wordstream_kwresearch_format_stats_values
wordstream_kwresearch_get_keyword_stats
wordstream_kwresearch_sources Implentation of hook_contentanalysis_analyzers() register contentanalysisexample with contentanalysis analyzers registry
wordstream_menu Implementation of hook_menu().
wordstream_perm Implementation of hook_perm()
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
wordstream_util