<?php
/*
 * $RCSfile: GalleryCoreSearch.class,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2005 Bharat Mediratta
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA.
 */
/**
 * @version $Revision: 1.16 $ $Date: 2005/08/23 03:49:02 $
 * @package GalleryCore
 * @author Bharat Mediratta <bharat@menalto.com>
 */

/**
 * Required classes
 */
GalleryCoreApi::relativeRequireOnce('modules/search/classes/GallerySearchInterface_1_0.class');

/**
 * This is an implementation of the search module's SearchInterface_1_0
 *
 * @package GalleryCore
 * @subpackage Classes
 */
class GalleryCoreSearch extends GallerySearchInterface_1_0 {

    /**
     * @see GallerySearchInterface_1_0.getSearchModuleInfo()
     */
    function getSearchModuleInfo() {
	global $gallery;

	list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'core');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$info = array('name' => $module->translate('Gallery Core'),
		      'description' => $module->translate('Gallery Core Module'),
		      'options' => array(
			  'descriptions' => array(
			      'description' => $module->translate('Search descriptions'),
			      'enabled' => 1),
			  'keywords' => array(
			      'description' => $module->translate('Search keywords'),
			      'enabled' => 1),
			  'summaries' => array(
			      'description' => $module->translate('Search summaries'),
			      'enabled' => 1),
			  'titles' => array('description' => $module->translate('Search titles'),
					    'enabled' => 1)));
	    return array(GalleryStatus::success(), $info);
    }

    /**
     * @see GallerySearchInterface_1_0.search()
     */
    function search($options, $criteria, $offset=0, $count=-1) {
	global $gallery;

	$whereList = array();
	$whereData = array();
	$columnNumber = 0;
	foreach (array('descriptions' => '[GalleryItem::description]',
		       'keywords' => '[GalleryItem::keywords]',
		       'summaries' => '[GalleryItem::summary]',
		       'titles' => '[GalleryItem::title]')
		 as $key => $column) {

	    if (isset($options[$key])) {
		$whereList[] = "$column LIKE ?";
		$whereData[] = '%' . $criteria . '%';
		$selectMap[$column] = $columnNumber++;;
		$selectList[] = $column;
	    }
	}

	/* Always select back title and summary */
	foreach (array('[GalleryItem::title]', '[GalleryItem::summary]') as $column) {
	    if (!isset($selectMap[$column])) {
		$selectMap[$column] = $columnNumber++;
		$selectList[] = $column;
	    }
	}

	$storage =& $gallery->getStorage();
	
	list ($ret, $aclIds) = GalleryCoreApi::fetchAccessListIds(
	    'core.view', $gallery->getActiveUserId());
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	if (empty($aclIds)) {
	    return array(GalleryStatus::success(),
			 array('start' => 0, 'end' => '0',
			       'count' => 0, 'results' => array()));
	}
	$aclMarkers = GalleryUtilities::makeMarkers(count($aclIds));

	$countQuery = sprintf('
        SELECT
          COUNT([GalleryItem::id])
        FROM
          [GalleryItem], [GalleryAccessSubscriberMap]
        WHERE
          (' . join(' OR ', $whereList) . ')
          AND
          [GalleryItem::id] = [GalleryAccessSubscriberMap::itemId]
          AND
          [GalleryAccessSubscriberMap::accessListId] IN (%s)
        ', $aclMarkers);

	$query = sprintf('
        SELECT
          [GalleryItem::id],
          [GalleryUser::fullName],
          [GalleryUser::userName],
          [GalleryEntity::modificationTimestamp], ' .
	    join(', ', $selectList) . '
        FROM
          [GalleryItem], [GalleryAccessSubscriberMap], [GalleryEntity], [GalleryUser]
        WHERE
          (' . join(' OR ', $whereList) . ')
          AND
          [GalleryItem::id] = [GalleryAccessSubscriberMap::itemId]
          AND
          [GalleryItem::id] = [GalleryEntity::id]
          AND
          [GalleryUser::id] = [GalleryItem::ownerId]
          AND
          [GalleryAccessSubscriberMap::accessListId] IN (%s)
        ORDER BY
          [GalleryEntity::modificationTimestamp] DESC, [GalleryItem::id] DESC
        ', $aclMarkers);

	$data = $whereData;
	$data = array_merge($data, $aclIds);

	/* Find the total */
	list ($ret, $results) = $gallery->search($countQuery, $data);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	$result = $results->nextResult();
	$numRows = (int)$result[0];

	/* Get the results that we're interested in */
	list ($ret, $results) = $gallery->search(
	    $query, $data, array('limit' => array('offset' => $offset, 'count' => $count)));
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'core');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$text['description'] = $module->translate('Description');
	$text['keywords'] = $module->translate('Keywords');
	$text['summary'] = $module->translate('Summary');
	$text['title'] = $module->translate('Title');
	$text['owner'] = $module->translate('Owner');

	$searchResults = array();
	while ($result = $results->nextResult()) {
	    $fields = array();
	    foreach (array('[GalleryItem::title]' => $text['title'],
			   '[GalleryItem::summary]' => $text['summary'],
			   '[GalleryItem::keywords]' => $text['keywords'],
			   '[GalleryItem::description]' => $text['description'])
		     as $columnName => $fieldText) {
		if (isset($selectMap[$columnName])) {
		    /*
		     * Remember that our field columns start at column index 4
		     * (id, date, full name, username are columns 0-3)
		     */
		    $fields[] = array(
			'key' => $fieldText, 'value' => $result[$selectMap[$columnName]+4]);
		}
	    }

	    $fields[] = array('key' => $text['owner'],
			      'value' => !empty($result[1]) ? $result[1] : $result[2]);
	    $searchResults[] = array('itemId' => (int)$result[0], 'fields' => $fields);
	}

	$data = array('start' => $numRows == 0 ? 0 : $offset+1,
		      'end' => $numRows == 0 ? 0 : $offset + sizeof($searchResults),
		      'count' => $numRows,
		      'results' => $searchResults);
	return array(GalleryStatus::success(), $data);
    }
}
?>
