<?php
/*
 * $RCSfile: MultiLangSearch.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.
 */

/**
 * @package MultiLang
 * @version $Revision: 1.4 $ $Date: 2005/08/23 03:49:46 $
 * @author Alan Harder <alan.harder@sun.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 MultiLang
 * @subpackage Classes
 *
 */
class MultiLangSearch extends GallerySearchInterface_1_0 {

    /**
     * @see GallerySearchInterface_1_0::getSearchModuleInfo()
     */
    function getSearchModuleInfo() {
	global $gallery;
	list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'multilang');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$info = array('name' => $module->translate('MultiLanguage'),
		      'description' => $module->translate('MultiLanguage Captions'));

	list ($ret, $languageCode) = $gallery->getActiveLanguageCode();
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	list ($ret, $defaultLanguage) =
	    GalleryCoreApi::getPluginParameter('module', 'core', 'default.language');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}
	if ($languageCode == $defaultLanguage) {
	    $info['options'] = array();
	    return array(GalleryStatus::success(), $info);
	}

	/* Get name for current language */
	$supportedLanguages = GalleryTranslator::getSupportedLanguages();
	list ($language, $country) = preg_split('/[-_]/', "${languageCode}_");
	if (empty($supportedLanguages[$language][$country]['description'])) {
	    return array(GalleryStatus::success(), array('options' => array()));
	}
	$languageName = $supportedLanguages[$language][$country]['description'];

	$info['options'] = array(
	    'title' => array(
		'description' => $module->translate(
		    array('text' => 'Search titles (%s)', 'arg1' => $languageName)),
		'enabled' => 1),
	    'summary' => array(
		'description' => $module->translate(
		    array('text' => 'Search summaries (%s)', 'arg1' => $languageName)),
		'enabled' => 1),
	    'description' => array(
		'description' => $module->translate(
		    array('text' => 'Search descriptions (%s)', 'arg1' => $languageName)),
		'enabled' => 1));

	return array(GalleryStatus::success(), $info);
    }

    /**
     * @see GallerySearchInterface_1_0::search()
     */
    function search($options, $criteria, $offset=0, $count=-1) {
	global $gallery;
	if (empty($options)) {
	    $data = array('start' => 0, 'end' => 0, 'count' => 0, 'results' => array());
	    return array(GalleryStatus::success(), $data);
	}

	list ($ret, $languageCode) = $gallery->getActiveLanguageCode();
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	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));

	$searchClause = array();
	if (isset($options['title'])) {
	    $searchClause[] = '[MultiLangItemMap::title] LIKE ?';
	}
	if (isset($options['summary'])) {
	    $searchClause[] = '[MultiLangItemMap::summary] LIKE ?';
	}
	if (isset($options['description'])) {
	    $searchClause[] = '[MultiLangItemMap::description] LIKE ?';
	}
	$searchString = implode(' OR ', $searchClause);

	$countQuery = sprintf('
	SELECT
	  COUNT([MultiLangItemMap::itemId])
	FROM
	  [MultiLangItemMap], [GalleryAccessSubscriberMap]
	WHERE
	  [MultiLangItemMap::itemId] = [GalleryAccessSubscriberMap::itemId]
	  AND
	  [GalleryAccessSubscriberMap::accessListId] IN (%s)
	  AND
	  [MultiLangItemMap::language] = ?
	  AND
	  (' . $searchString . ')
	', $aclMarkers);

	$query = sprintf('
	SELECT
	  [MultiLangItemMap::itemId],
	  [MultiLangItemMap::title],
	  [MultiLangItemMap::summary],
	  [MultiLangItemMap::description]
	FROM
	  [MultiLangItemMap], [GalleryAccessSubscriberMap]
	WHERE
	  [MultiLangItemMap::itemId] = [GalleryAccessSubscriberMap::itemId]
	  AND
	  [GalleryAccessSubscriberMap::accessListId] IN (%s)
	  AND
	  [MultiLangItemMap::language] = ?
	  AND
	  (' . $searchString . ')
	ORDER BY
	  [MultiLangItemMap::itemId] DESC
	', $aclMarkers);

	$data = $aclIds;
	$data[] = $languageCode;
	foreach ($searchClause as $tmp) {
	    $data[] = '%' . $criteria . '%';
	}

	/* 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];

	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', 'multilang');
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$label = array($module->translate('Title'),
		       $module->translate('Summary'),
		       $module->translate('Description'));

	$searchResults = array();
	while ($result = $results->nextResult()) {
	    $searchResults[] = array('itemId' => (int)$result[0], 'fields' => array(
		array('key' => $label[0], 'value' => $result[1]),
		array('key' => $label[1], 'value' => $result[2]),
		array('key' => $label[2], 'value' => $result[3])));
	}

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