<?php

/*
Plugin Name: Seo Terms To Tags
Plugin URI: 
Description: 
Version: 0.1
Author: 
Author URI: 
License: 
*/

function extractTerm($referer = null)
{
    if (empty($referer)) {
        if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
            $referer = $_SERVER['HTTP_REFERER'];
        } else {
            return null;
        }
    }

    $url = parse_url(trim($referer));

    if (empty($url['host'])) {
        return null;
    }

    $query = isset($url['query']) ? $url['query'] : (isset($url['fragment']) ? $url['fragment'] : null);

    if (empty($query)) {
        return null;
    }

    parse_str($query, $queryVars);

    $searchEngines = array(
        'google.' => 'q',
        'bing.'   => 'q',
        'mail.ru' => 'q',
        'aol.'    => 'q',
        'ask.'    => 'q',
        'yahoo.'  => 'p',
        'baidu.'  => 'wd',
        'yandex.' => 'text',
    );

    foreach ($searchEngines as $searchEngine => $param) {
        if (stripos($url['host'], $searchEngine) !== false && isset($queryVars[$param])) {
            return $queryVars[$param];
        }
    }

    return null;
}




add_action('wp_head', 'track');

function track()
{
    if (is_single()) {
        $term = extractTerm();
        if ($term) {
            file_put_contents('wp-content/plugins/1.txt', $term . "\n", FILE_APPEND | LOCK_EX);
        }
    }
}