Uva Searchengines / protected / controllers / SearchController.php

<?php

class SearchController extends Controller
{
	private $indexPath;

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex() {
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionSearch() {
		Yii::import('application.vendors.*');
		require_once('Zend/Search/Lucene.php');
		$this->indexPath = Yii::getPathOfAlias('application.runtime.searchindex');
		Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
		Zend_Search_Lucene_Analysis_Analyzer::setDefault(
			new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive()
		);
		$stemming = Yii::app()->request->getParam('stemming', 1);
		if ($stemming) {
			require_once 'StandardAnalyzer/Analyzer/Standard/English.php';
			Zend_Search_Lucene_Analysis_Analyzer::setDefault(new StandardAnalyzer_Analyzer_Standard_English());
			$this->indexPath = Yii::getPathOfAlias('application.runtime.searchindexstemming');
		}

		if ($trefwoorden = Yii::app()->request->getParam('query', null)) {
			//            var_dump(Yii::app()->cache->get('results[' . md5($trefwoorden) . ']'));
			//            die();

//			$trefwoorden = preg_replace("/[^a-z \d]/i", " ", $trefwoorden);
			$queryText = trim($trefwoorden);
			if(isset($_GET['date'])){
				$date = intval($_GET['date']);
				$queryText = '(' . $queryText . ') AND date:[' . $date . ' TO ' . $date . ']';
			}
			if (($results = Yii::app()->cache->get('results[' . md5($queryText) . '][' . ($stemming ? 'stemming' : 'nostemming') . ']')) === false) {
				$index = new Zend_Search_Lucene($this->indexPath);
				//            $index->setResultSetLimit(100);
				$hits = $index->find($queryText);
				$results = array();
				foreach ($hits as $hit) {
					$results[] = array(
						'id' => $hit->getDocument()->getFieldValue('id'),
						'score' => $hit->score
					);
				}
				Yii::app()->cache->set('results[' . md5($queryText) . '][' . ($stemming ? 'stemming' : 'nostemming') . ']', $results);
			}
			$query = Zend_Search_Lucene_Search_QueryParser::parse(str_replace('*', '', $trefwoorden), 'UTF-8');

			$from = new Zend_Search_Lucene_Index_Term(1175378400, 'date');
			$to = new Zend_Search_Lucene_Index_Term(1175378400, 'date');

			$latTerm = new Zend_Search_Lucene_Index_Term('[0 TO 1]', 'date');
			$q1 = new Zend_Search_Lucene_Search_Query_Term($latTerm);

//			$subquery = new Zend_Search_Lucene_Search_Query_Range($from, $to, true);
//			$query->addSubquery($q1, true);

			$trefwoorden = strtolower($trefwoorden);
			$trefwoordenArr = explode(' ', trim($trefwoorden));

			$corrects = array();
			foreach ($trefwoordenArr as $trefwoord)
			{
				if (($correct = Yii::app()->cache->get('correct[' . $trefwoord . ']')) === false) {
					$correct = SpellCorrector::correct($trefwoord);
					Yii::app()->cache->set('correct[' . $trefwoord . ']', $correct);
				}
				if ($correct != $trefwoord) {
					$corrects[] = '<strong>' . $correct . '</strong>';
				} else {
					$corrects[] = $correct;
				}
			}
			$correct = implode(' ', $corrects);
			$dataProvider = new CArrayDataProvider($results, array(
				'pagination' => array(
					'pageSize' => 10,
				),
			));

			$timelinedata = $this->setTimeLine($trefwoordenArr);
			$columns = $timelinedata[0];
			$rows = $timelinedata[1];
			$selectedRow = $timelinedata[2];
		}

		$this->render('search', compact('dataProvider', 'results', 'correct', 'trefwoorden', 'query', 'rows', 'columns', 'selectedRow'));

		/*   require_once 'StandardAnalyzer/TokenFilter/EnglishStemmer/PorterStemmer.php';
				$stemmer = new PorterStemmer();
				die($stemmer->stem('cittens'));*/
	}

	private function setTimeLine($words) {
		$rows = array();
		$sql = "
            SELECT
                COUNT(articles_word.word_id) AS count, articles.date AS date
            FROM
                words,
                articles_word,
                articles
            WHERE
                words.id = articles_word.word_id AND articles.id = articles_word.article_id AND words.text = :word
            GROUP BY articles.date
            ";
		$command = Yii::app()->db->createCommand($sql);
		$selectedRow = null;

		foreach ($words as $value)
		{
			//$result is de query, die verderop in de while-loop wordt gebruikt om voor betreffende woorden de counts + date uit de database te vissen.
			$command->bindValue(":word", $value, PDO::PARAM_STR);
			$result = $command->queryAll();

			//loopt door alle resultaten heen van de query, en zet de datum en bijbehorende count in array $test.
			$test = array();
			foreach ($result as $row)
			{
				$test[$row['date']] = $row['count'];
			}

			//Begin- en einddatum grafiek.
			$enddate = "2007-04-30";
			$startdate = "2007-04-01";
			//De datums worden omgezet naar strings, om met elkaar te kunnen vergelijken in de while-conditie hieronder.
			$startdate = (string)$startdate;
			$enddate = (string)$enddate;
			$arr = array();

			//loopt door alle datums heen.
			$i = 0;
			while ($startdate <= $enddate)
			{
				$date = strtotime($startdate);

				//Als een datum niet in de array $test voorkomt (het woord is die dag dus niet gezegd) wordt de count voor die dag op 0 gezet.
				if (!array_key_exists($date, $test)) {
					$count = 0;
				}
				if (array_key_exists($date, $test)) {
					$count = $test[$date];
					//intval is om te voorkomen dat count als een string gelezen wordt; het wordt nu als een getal gezien.
					$count = intval($count);
				}
				//Omdat Google 1 maand erbij telt ('1-4-2007' = 1 mei), wordt er 1 maand vanaf getrokken voordat het in de grafiek gelezen wordt.
				if(isset($_GET['date']) && is_numeric($_GET['date']) && $date == $_GET['date']){
					$selectedRow = $i;
				}
				$date = strtotime('-1 month', $date);
				$date = date('Y, m, d', $date);
				$date = "new Date($date)";
				//datum wordt in $array gezet, met bijbehorende count(s) van woord(en). voor 2 woorden wordt het dus bv: $array[new Date(2007,3,1)] = array(1000, 400)
				if (!isset($rows[$date])) {
					$rows[$date] = array();
				}
				array_push($rows[$date], $count);

				//De startdatum wordt met 1 dag geincrementeerd, net zolang totdat $enddate wordt bereikt.
				$startdate = strtotime('+1 day', strtotime($startdate));
				$startdate = date('Y-m-d', $startdate);
				$i++;
			}
		}
		return array($words, $rows, $selectedRow);
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.