<?php

if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOOPS_ROOT_PATH."/class/XCube_Service.class.php";

/**
 * Sample class
 */
class LegacySearchService extends XCube_Service
{
	/**
	 * @param $parameters['uid'] Target user's id
	 * @param $parameters['current_uid'] Current user's id
	 * @param $parameters['maxhit'] Max hit count of each modules. The default value is 5.
	 */
	function doGetItems(&$parameters)
	{
		$ret = array();
		$uid = $parameters['uid'];
		
		$maxhit = isset($parameters['maxhit']) ? intval($parameters['maxhit']) : 5;
		
		$userHandler =& xoops_gethandler('user');
		$currentUser =& $userHandler->get($parameters['current_uid']);
		
		$gpermHandler = & xoops_gethandler( 'groupperm' );
		$groups = is_object($currentUser) ? $currentUser->getGroups() : XOOPS_GROUP_ANONYMOUS;

		//
		// At first, get active module IDs.
		//
		$moduleHandler =& xoops_gethandler('module');
		$criteria =& new CriteriaCompo(new Criteria('hassearch', 1));
		$criteria->add(new Criteria('isactive', 1));
		
		$mids =& array_keys($moduleHandler->getList($criteria));

		//
		// Next, fetch from $mids[], and check read permission.
		// If user can read the module information, execute search.
		//
		$root =& XCube_Root::getSingleton();
		$timezone = $root->mController->getConfig('server_TZ') * 3600;
		
		$i = 0;
		foreach ($mids as $mid) {
			if ($gpermHandler->checkRight('module_read', $mid, $groups)) {
				$module =& $moduleHandler->get($mid);
				$results =& $module->search('', '', $maxhit, 0, $uid);
				
				$ret[$i]['name'] = $module->get('name');
				
				if (is_array($results) && count($results) > 0) {
					foreach ($results as $result) {
						$item = array();
						if (isset($result['image']) && strlen($result['image']) > 0) {
							$item['image'] = XOOPS_URL . '/modules/' . $module->getVar('dirname') . '/' . $result['image'];
						}
						else {
							$item['image'] = XOOPS_URL . '/images/icons/posticon2.gif';
						}
						
						$item['link'] = XOOPS_URL . '/modules/' . $module->getVar('dirname') . '/' . $result['link'];
						$item['title'] = $result['title'];
						
						//
						// TODO If this service will come to web service, we should
						// change format from unixtime to string by timeoffset.
						//
						$item['time'] = isset($result['time']) ? $result['time'] - $timezone : 0;
						
						$ret[$i]['results'][] = $item;
					}
					
					if (count($results) == 5) {
						$link = @sprintf("%s/search.php?action=showallbyuser&mid=%d&uid=%d",
							XOOPS_URL,
							$module->get('mid'),
							$uid
						);
						
						$ret[$i]['showall_link'] =	$link;
					}
				}
				else {
					$ret[$i]['results'] = array();
					$ret[$i]['showall_link'] = "";
				}
			}
		}
		
		return $ret;
	}
}

?>