<?php

/**
 * 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\content
 * @copyright Copyright (c) 2012 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * contentSearchHelper Class
 *
 * Class to provide support for search to gain access to content.
 *
 * @package clearFusionCMS\module\content
 */
class contentSearchHelper extends cfSearchHelper {

	/**
	 * The content object.
	 *
	 * @var cfContent
	 */
	protected $content;

	/**
	 * Create the helper object.
	 *
	 * @param flDb $db The database object.
	 */
	function __construct($db) {
		parent::__construct($db);
		$this->content = new cfContent($this->db, clearFusionCMS::getSite());
	}

	/**
	 * Get the number of content items.
	 */
	function getContentCount() {
		return $this->db->fetchOne('SELECT COUNT(*) FROM cf_content_' . clearFusionCMS::getSite());
	}

	/**
	 * Reindex the block of items.
	 *
	 * @param int $start The index to start working from.
	 * @param int $items The number of items to index.
	 */
	function reindex($start, $items) {
		// Grab the next block of content and send to search
		$result = $this->db->query('SELECT id FROM cf_content_' . clearFusionCMS::getSite() . " LIMIT $start, $items");
		while($row = $result->fetch()) {
			$page = $this->db->fetchRow('SELECT id,accessperm,issearchable,restype,published,title,subtitle,content,template,summary,meta_title,meta_description,meta_keywords,publishedat FROM cf_content_' . clearFusionCMS::getSite() . ' WHERE id=?', $row['id']);
			if($page['issearchable'] && $page['published']) {

				// Build the path to the doc
				$res = $this->content->getPath($page['id'], array('id'));
				$segs = array('content');
				foreach($res as $d)
					$segs[] = $d['id'];

				// Get custom fields
				$fields = array();
				$fresult = $this->db->query('SELECT placeholder,content FROM cf_customflds_ctnt_' . clearFusionCMS::getSite() . ' LEFT JOIN cf_customflds_templates USING(placeholder) WHERE id=? && template=?', $page['id'], $page['template']);
				while($row = $fresult->fetch())
					$fields[$row['placeholder']] = $row['content'];

				// Build the content
				$content = array_merge(array(
					'title' => $page['title'],
					'subtitle' => $page['subtitle'],
					'content' => $page['restype'] == 'doc' ? $page['content'] : '',
					'summary' => $page['summary'],
					'meta_title' => $page['meta_title'],
					'meta_description' => $page['meta_description'],
					'meta_keywords' => $page['meta_keywords']
				), $fields);

				clearFusionCMS::getEventManager()->notify(new flEvent('system.searchIndex', array(
					'path' => $segs,
					'accessPerm' => $page['accessperm'],
					'publishedAt' => $page['publishedat'],
					'fields' => $content)));
			}
		}
	}

	/**
	 * Get the search summary for the given search path.
	 *
	 * @param string $id The ID of the element to get a summary of.
	 * @param string $order The order to use data to generate the summary or null for the default.
	 * @param int $words The number of words to return in the summary.
	 * @return array The summary data.
	 */
	function getSearchSummary($id, $order = null, $words = 30) {
		if(!($page = $this->content->getNodeData($id, array('id', 'title', 'subtitle', 'summary', 'meta_description', 'content', 'restype'))))
			return false;

		if($page['restype'] != 'doc')
			$page['content'] = '';

		$order = $order === null ? array('summary', 'content', 'meta_description') : explode(',', $order);
		$summary = '';
		foreach($order as $o) {
			if(!empty($page[$o])) {
				$summary = str_replace(array('[', ']'), array('&#91;', '&#93;'), flTextSplitWords::split($page[$o], $words));
				break;
			}
		}

		return array('title' => $page['title'] . (empty($page['subtitle']) ? '' : " - $page[subtitle]"), 'summary' => $summary, 'uri' => $this->content->getPageURI($page['id']));
	}

	/**
	 * Get the URI of the page holding the content.
	 *
	 * @param string $id The ID of the element to get the page URI of.
	 * @param bool $absolute true if an absolute URI should be returned; else false for a relative URI.
	 * @return string The URI of the page or false if not found.
	 */
	function getURI($id, $absolute = true) {
		return $this->content->getPageURI($id, $absolute);
	}
}
