1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
<?php

class CustomSearchForm extends SearchForm
{
	
	private $customSearchClasses = array();
	
	private static function add_search_fields($object, $record)
	{
		$object->setField('Title',$record['Title']);
		$object->setField('Content',$record['Content']);
		return $object;
	}
	
	public function addSearchableClasses($classes)
	{
		$map = array();
		foreach($classes as $class) {
			$SNG = singleton($class);
			$map[$class]['Fields'] = $SNG->stat('searchable_fields');
			$map[$class]['Title'] = $SNG->stat('search_heading');
			$map[$class]['Content'] = $SNG->stat('search_content');
		}
		$this->customSearchClasses = $map;
	}
	
	function classesToSearch($classes) {
		$this->classesToSearch = $classes;
	}

	public function searchEngine($keywords, $pageLength = null, $sortBy = "Relevance DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) {
		if(!$pageLength) $pageLength = $this->pageLength;
		$fileFilter = '';	 	
	 	$keywords = addslashes($keywords);
	
		$extraFilters = array('SiteTree' => '', 'File' => '');
 		foreach($this->customSearchClasses as $class => $arr)
 			$extraFilters[$class] = "";
			 	
	 	if($booleanSearch) $boolean = "IN BOOLEAN MODE";
	 	if($extraFilter) {
	 		$extraFilters['SiteTree'] = " AND $extraFilter";
	 		
	 		if($alternativeFileFilter) $extraFilters['File'] = " AND $alternativeFileFilter";
	 		else $extraFilters['File'] = $extraFilters['SiteTree'];
	 		
	 		foreach($this->customSearchClasses as $class => $arr)
	 			$extraFilters[$class] = " AND $extraFilter";

	 	}
	 	
	 	if($this->showInSearchTurnOn)	$extraFilters['SiteTree'] .= " AND showInSearch <> 0";

		$start = isset($_GET['start']) ? (int)$_GET['start'] : 0;
		$limit = $start . ", " . (int) $pageLength;
		
		$notMatch = $invertedMatch ? "NOT " : "";
		if($keywords) {
			$match['SiteTree'] = "MATCH (Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords) AGAINST ('$keywords' $boolean)";
			$match['File'] = "MATCH (Filename, Title, Content) AGAINST ('$keywords' $boolean) AND ClassName = 'File'";
	
			// We make the relevance search by converting a boolean mode search into a normal one
			$relevanceKeywords = str_replace(array('*','+','-'),'',$keywords);
			$relevance['SiteTree'] = "MATCH (Title) AGAINST ('$relevanceKeywords') + MATCH (Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords) AGAINST ('$relevanceKeywords')";
			$relevance['File'] = "MATCH (Filename, Title, Content) AGAINST ('$relevanceKeywords')";
		} else {
			$relevance['SiteTree'] = $relevance['File'] = 1;
			$match['SiteTree'] = $match['File'] = "1 = 1";
		}
		

		if($keywords) {
			foreach($this->customSearchClasses as $class => $arr) {
				$match[$class] = "MATCH (".implode(',',$arr['Fields']).") AGAINST ('$keywords' $boolean)";
				$relevanceKeywords = str_replace(array('*','+','-'),'',$keywords);
				$relevance[$class] = "MATCH (".implode(',',$arr['Fields']).") AGAINST ('$relevanceKeywords')";
			}
		}
		else {
			foreach($arr['Fields'] as $key => $val)
			{ 
				if ($key && !is_int($key)) 
				{ 
					if (!strpos($key,'.') && array_key_exists('filter',$val) && $val['filter'] == 'PartialMatchFilter') 
					{ 
						$fields[] = $key; 
					} 
				} 
			} 
			$match[$class] = "MATCH (".implode(',',$fields).") AGAINST ('$keywords' $boolean)"; 
			$relevanceKeywords = str_replace(array('*','+','-'),'',$keywords); 
			$relevance[$class] = "MATCH (".implode(',',$fields).") AGAINST ('$relevanceKeywords')";		
		}


		// Generate initial queries and base table names
		$baseClasses = array('SiteTree' => '', 'File' => '');
		foreach($this->classesToSearch as $class) {
			$queries[$class] = singleton($class)->extendedSQL($notMatch . $match[$class] . $extraFilters[$class], "");
			$baseClasses[$class] = reset($queries[$class]->from);
		}

		foreach($this->customSearchClasses as $class => $arr) {
			$queries[$class] = singleton($class)->extendedSQL($notMatch . $match[$class] . $extraFilters[$class], "");
			$baseClasses[$class] = reset($queries[$class]->from);
		}		
		
		// Make column selection lists
		$select = array(
			'SiteTree' => array("ClassName","$baseClasses[SiteTree].ID","ParentID","Title","URLSegment","Content","LastEdited","Created","_utf8'' AS Filename", "_utf8'' AS Name", "$relevance[SiteTree] AS Relevance", "CanViewType"),
			'File' => array("ClassName","$baseClasses[File].ID","_utf8'' AS ParentID","Title","_utf8'' AS URLSegment","Content","LastEdited","Created","Filename","Name","$relevance[File] AS Relevance","NULL AS CanViewType"),
		);

		foreach($this->customSearchClasses as $class => $arr) {
			$select[$class] = array(
				"ClassName",
				"$class.ID",
				"NULL AS ParentID",
				$arr['Title'] . " AS Title",
				"NULL AS URLSegment",
				$arr['Content'] . " AS Content",
				"LastEdited",
				"Created",
				"NULL AS Filename",
				"NULL AS Name",
				"$relevance[$class] AS Relevance",
				"NULL AS CanViewType"
			);
		}		

		// Process queries
		foreach($this->classesToSearch as $class) {
			// There's no need to do all that joining
			$queries[$class]->from = array(str_replace('`','',$baseClasses[$class]) => $baseClasses[$class]);
			$queries[$class]->select = $select[$class];
			$queries[$class]->orderby = null;
		}

		foreach($this->customSearchClasses as $class => $arr) {
			$queries[$class]->from = array(str_replace('`','',$baseClasses[$class]) => $baseClasses[$class]);
			$queries[$class]->select = $select[$class];
			$queries[$class]->orderby = null;
		}		

		// Combine queries
		$querySQLs = array();
		$totalCount = 0;
		foreach($queries as $query) {
			$querySQLs[] = $query->sql();
			$totalCount += $query->unlimitedRowCount();
		}
		$fullQuery = implode(" UNION ", $querySQLs) . " ORDER BY $sortBy LIMIT $limit";
		// Get records
		$records = DB::query($fullQuery);

		foreach($records as $record) {
			$o = new $record['ClassName']($record);
			if(!$o instanceof SiteTree)
				$objects[] = self::add_search_fields($o, $record);
			else
				$objects[] = $o;
		}
		if(isset($objects)) $doSet = new DataObjectSet($objects);
		else $doSet = new DataObjectSet();

		$doSet->setPageLimits($start, $pageLength, $totalCount);
		return $doSet;
	}
	

}


?>