<?php
/**
* keywords.plugin.php
*
* Auto generates meta keywords for the page based on the frequency of words.
* If there are keywords already the nothing is added.
*
* @author Svetoslav Marinov <hide@address.com>
* @version 1.0
* @package keywords
* @todo Remove, append to existing keyword list.
*/
class seofilter_plugin_keywords extends seofilter_plugin {
var $version = 1.0;
/**
* $event can be executed
* PRE, POST, INPUT, OUTPUT Filter
*
* @param constant
* @access public
* @return bool
*/
function execute($event)
{
$keyword_cache_array = array();
static $meta_keyword_tag = "\n<meta name=\"keywords\" content=\"%s\" />";
if ($event == SEOFILTER_EVENT_POST) {
$params = $this->params();
$buffer = $this->content();
$partial_buff = '';
$req_url = empty($_SERVER['REQUEST_URI']) ? '/' : $_SERVER['REQUEST_URI'];
// Remove query params.
if (($pos = strpos($req_url, "?")) !== false) {
$req_url = substr($req_url, 0, $pos);
}
$refresh_cache = 0;
$keyword_str = '';
$cache_file = SEOFILTER_TMP_DIR . 'keywords.cache.php';
if (file_exists($cache_file)) {
$keyword_cache_array = (array) unserialize(seofilter_safe_read($cache_file));
$cache_last_modified = @filemtime($cache_file);
// if the cache file is older than 2 days schedule update.
if (abs(time() - $cache_last_modified) > 172800) {
$refresh_cache = 1;
}
} else {
$refresh_cache = 1;
}
if (array_key_exists($req_url, $keyword_cache_array)) {
$keyword_str = $keyword_cache_array[$req_url];
} else {
$refresh_cache = 1;
// Assumming that the header will fit in 2k
$partial_buff = substr($buffer, 0, 2048);
if (!empty($partial_buff) && !preg_match('#<meta[^>]*keywords#si', $partial_buff)) {
$keywords = seofilter_util::extract_keywords($buffer, 15);
$keyword_str = join(',', $keywords);
}
}
// Are there keywords ? if No we proceed.
if (!empty($keyword_str)) {
$buffer = preg_replace('#(<\s*head[^>]*>)#si', '\\1' . sprintf($meta_keyword_tag, $keyword_str), $buffer);
// inform the main module that the content has been modified
$this->status(SEOFILTER_STATUS_CONTENT_CHANGED);
$this->content($buffer);
}
if ($refresh_cache) {
$keyword_cache_array[$req_url] = $keyword_str;
seofilter_safe_write($cache_file, serialize($keyword_cache_array));
/*
// I have tried to make the updating of the file to be done after the processing but
// it is NOT possible because shutdown function is already executed when we reach seofilter_handler which calls this plugin
$inst = seofilter_get_instance('stdClass');
$inst->listeners = array();
$inst->listeners[] = array(
'seofilter_safe_write', $cache_file, serialize($keyword_cache_array)
);
*/
// Scheduling the cache update after the script is done so the user don't have to wait.
// register_shutdown_function('seofilter_safe_write', $cache_file, serialize($keyword_cache_array));
}
}
return true;
}
}
?>