<?php
// $Id$

/**
 * @file
 * Basic SEO rules for the SEO Checker
 */

/**
 * Implements hook_register_seo_rules().
 * @return (array) rules
 */
function basic_seo_rules_register_seo_rules() {
  $rules['alt_attributes'] = array(
    'name' => t('Alt attributes in <img> - tags'),
    'description' => t('Checks if all the <img> tags in the body have an alt attribute.'),
    'threshold type' => 'at_least',
    'default threshold' => 100,
    'callback' => 'basic_seo_rules_alt_attribute',
    'passed feedback' => t('Test passed.'),
    'failed feedback' => t('Test failed, please make sure your images contain an alternative text.'),
  );
  $rules['title_attributes'] = array(
    'name' => t('Title attributes in <a href> - tags'),
    'description' => t('Checks if all the <a href> tags have a title attribute.'),
    'threshold type' => 'at_least',
    'default threshold' => 100,
    'callback' => 'basic_seo_rules_title_attribute',
    'passed feedback' => t('Test passed.'),
    'failed feedback' => t('Test failed, please make sure your links contain a title attribute.'),
  );
  return $rules;
}

/********************************* CALLBACKS *********************************/

/**
 * Implements the alt attribute in <img>-tags check.
 * @return (int) result
 * @param array $form_values
 */
function basic_seo_rules_alt_attribute($form_values) {
  if (!isset($form_values['body'])) {
    // No body field on this node.
    return FALSE;
  }

  if (!preg_match_all('/<img[^>]+>/i', $form_values['body'][$form_values['body']['#language']][0]['value']['#value'], $matches)) {
    return FALSE;
  }
  $total = 0;
  $successful = 0;
  foreach ($matches[0] as $image_tag) {
    if (preg_match('/alt=(\S{3,})/i', $image_tag)) {
      $successful++;
    }
    $total++;
  }
  return 100*$successful/$total;
}

/**
 * Implements the title attribute in <a href>-tags check.
 * @return (int) result
 * @param array $form_values
 */
function basic_seo_rules_title_attribute($form_values) {
  if (!isset($form_values['body'])) {
    // No body field on this node.
    return FALSE;
  }

  if (!preg_match_all('/<a[^>]+href[^>]*>/i', $form_values['body'][$form_values['body']['#language']][0]['value']['#value'], $matches)) {
    return FALSE;
  }

  $total = 0;
  $successful = 0;
  foreach ($matches[0] as $ahref_tag) {
    if (preg_match('/title=(\S{3,})/i', $ahref_tag)) {
      $successful++;
    }
    $total++;
  }
  return 100*$successful/$total;
}
