<?php

/**
 * API service to allow remote searches.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\search
 * @copyright Copyright (c) 2013 - 2014 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * searchApiV1 Class
 *
 * Class to implement the search endpoint.
 */
class searchApiV1 extends flApiService {

	/**
	 * Accept a query term from the caller and return the search results.
	 */
	function queryGet() {

		// Get and verify parameters
		$q = $this->request->getQuery('q', '');
		$page = $this->request->getQuery('page', 0);
		$pageSize = $this->request->getQuery('pageSize', 10);
		$words = $this->request->getQuery('words', 30);
		$searchIn = $this->request->getQuery('searchIn', '');
		$summary = $this->request->getQuery('summary', null);
		if(empty($q) || !preg_match('/^[\w\+ &-]+$/', $q) ||
			!preg_match('/^\d+$/', $words) ||
			!preg_match('/^\d+$/', $page) ||
			!preg_match('/^\d+$/', $pageSize))
			throw new flExceptionBadRequest();

		$fields = @json_decode($this->request->getQuery('fields', ''));
		if(!is_array($fields))
			$fields = array();

		// Run the search
		$search = new flSearch(clearFusionCMS::getDb(), 'cf_search_' . clearFusionCMS::getSite());
		$results = $search->find(
			$q,
			$searchIn,
			true,
			true,
			$this->apiServer->getPermissions(),
			$fields,
			$page * $pageSize,
			$pageSize,
			$this->request->getQuery('matchAll', 0) != 0
		);

		// Build the reply
		$reply = array(
			'totalMatches' => $results->total(),
			'page' => $page,
			'pageSize' => $pageSize,
			'results' => array()
		);
		if(count($results)) {
			foreach($results as $result) {
				if(($helper = cfSearchHelper::getHelper($result['root'])) && ($sum = $helper->getSearchSummary($result['node'], $summary, $words))) {
					$reply['results'][] = array(
						'link' => 'http://' . $this->request->getServerName() . $sum['uri'],
						'title' => $sum['title'],
						'summary' => $sum['summary'],
						'img' => isset($sum['img']) ? $sum['img'] : ''
					);
				}
			}
		}

		// Send reply to requester
		$this->response->setStatusCode(200)
			->setBody(json_encode($reply))
			->sendResponse();
	}
}
