<?php
/**
defined('_JEXEC') or die('Restricted access');
// no direct access
defined('_JEXEC') or die('Restricted access');
require_once (JPATH_BASE.DS.'components'.DS.'com_community'.DS.'models'.DS.'models.php');
class CommunityModelSearch extends JCCModel
{
	var $_data = null;
	var $_profile;
	var $_pagination;
	function CommunityModelSearch(){
		parent::JCCModel();
 	 	global $mainframe;
 	 	// Get pagination request variables
 	 	$limit		= ($mainframe->getCfg('list_limit') == 0) ? 5 : $mainframe->getCfg('list_limit');
	    $limitstart = JRequest::getVar('limitstart', 0, 'REQUEST');
 	 	// In case limit has been changed, adjust it
	    $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit',$limit);
 	 	$this->setState('limitstart',$limitstart);
	}	
	function &getFiltered($wheres = array())
	{
		$db			= &$this->getDBO();
		$wheres[] = 'block = 0';
		$query = "SELECT *"
			. ' FROM #__users'
			. ' WHERE ' . implode( ' AND ', $wheres )
			. ' ORDER BY `id` DESC ';
		$db->setQuery( $query );
		if($db->getErrorNum()) {
			JError::raiseError( 500, $db->stderr());
		}
		$result = $db->loadObjectList();
		return $result;
	}
	/**
	 * get pagination data
	 */	 	
	function getPagination()
	{
		return $this->_pagination;
	}	
	/**
	 * Search for people
	 * @param query	string	people's name to seach for	
	 */	 
	function searchPeople($query){
		$db	= &$this->getDBO();
		$filter = array();
		$strict = true;
		$regex = $strict? 
		      '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' : 
		       '/^([*+!.&#$¦\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' ;
		$data = array();
		//select only non empty field
		foreach($query as $key => $value) {
			if(!empty($query[$key]))
			$data[$key]=$value;
		}
		$filterField = array();
		// build where condition
		foreach($data as $key => $value){
			//for username of email
			if($key=='q' && !empty($value)){
				if (preg_match($regex, trim($value), $matches)){ 
					$query = array($matches[1], $matches[2]);
					$cond = $matches[1]."@".$matches[2];
					$filter[] = "`email`=" . $db->Quote($cond);
			    } else {
					$filter[] = "(UCASE(`name`) like UCASE(" . $db->Quote('%'.$value.'%') . ") OR "
								."UCASE(`username`) like UCASE(" . $db->Quote('%'.$value.'%') . ") )";
			    } 
		    }
		    //for others fields
		    // @todo: we need to verify that each field is really searchable
		    if(preg_match('/^field([0-9]+)$/i',trim($key),$matches1)){
		    	if(!is_array($value))
					$filterField[] = "(`field_id`='{$matches1[1]}' AND `value` = '{$value}')";
			}
		}
		$limit = $this->getState('limit');
		$limitstart = $this->getState('limitstart');		
		$finalResult = array();
		if(count($filter)> 0 || count($filterField > 0)){
// 			// get total record count.
// 			$query = "SELECT count(distinct b.`id`) FROM #__community_fields_values a
// 					  right join #__users b on (a.user_id = b.id)";	    			  
// 			$query .= " WHERE b.block = 0 AND ".implode(' AND ',$filter);
// 
// 			$db->setQuery( $query );
// 			$total = $db->loadResult();
// 			
			// Perform the simple search
			$basicResult = null;
			if(!empty($filter) && count($filter)>0){
				$query = "SELECT distinct b.`id` FROM #__community_fields_values a
						  right join #__users b on (a.user_id = b.id)";	    			  
				$query .= " WHERE b.block = 0 AND ".implode(' AND ',$filter);
				$db->setQuery( $query );
				$basicResult = $db->loadResultArray();
				if($db->getErrorNum()) {
					JError::raiseError( 500, $db->stderr());
				}
			}
			if($basicResult == null)
				$basicResult = array();
			// Perform advance search
			$filterResult = null;
			if(!empty($filterField) & count($filterField) > 0){
				foreach($filterField as $f){
					$query = "SELECT distinct b.`id` FROM #__community_fields_values a
							  right join #__users b on (a.user_id = b.id)";	    			  
					$query .= " WHERE b.block = 0 AND ". $f;
					$db->setQuery( $query );
					$result = $db->loadResultArray();
					if($db->getErrorNum()) {
						JError::raiseError( 500, $db->stderr());
					}
					if($filterResult == null)
						$filterResult = $result;
					elseif (!empty($filterResult )){
						// We reduce the result only for intersected userid
						$filterResult = array_intersect($filterResult, $result);
					}
				}
			}
			if($filterResult == null)
				$filterResult = array();
			$finalResult = array_merge($filterResult, $basicResult);
			$total = count($finalResult);
			// Appy pagination
			if (empty($this->_pagination)) {
		 	    jimport('joomla.html.pagination');
		 	    $this->_pagination = new JPagination($total, $limitstart, $limit);
		 	}
		} 				
//         //getting the actual records
// 		$query = "SELECT distinct `user_id`,`username`,`email`,b.`id` FROM #__community_fields_values a
// 				  right join #__users b on (a.user_id = b.id)
// 				  WHERE b.block = 0 AND ".implode(' AND ',$filter);        
// 		$query .= " LIMIT {$limitstart}, {$limit}";
// 		
// 		$id=array();		
// 		if(count($filter)>0){
// 			$db->setQuery( $query );
// 			echo $db->getQuery();
// 				
// 			if($db->getErrorNum()) {
// 				JError::raiseError( 500, $db->stderr());
// 			}
// 			
// 			$rows = $db->loadObjectList();
// 			
// 			//get user profile
// 			foreach($rows as $row){
// 				$id[]=$row->id;
// 			}
// 						
// 			$id = implode(",",$id);
// 		}
		//$finalResult = array('62','63');
		if(empty($finalResult))
			$finalResult = array(0);
		$id = implode(",",$finalResult);
		//print_r($finalResult);
		$where = array("`id` IN (".$id.")");
	    $result = $this->getFiltered($where);
		return $result;
	}
	// @params $field, array with key[fieldcode] = value
	// just use 1 field for now
	function searchByFieldCode($field){
// 					print_r($field);
// 			exit;
		CError::assert($field , '', '!empty', __FILE__ , __LINE__ );
		$db			=& $this->getDBO();
		$keys = array_keys($field);
		$vals = array_values($field);		
		$fieldId = $this->_getFieldIdFromFieldCode($keys[0]);
		$sql = "SELECT `user_id` FROM jos_community_fields_values "
			." WHERE `value`=". $db->Quote($vals[0]) 
			." AND field_id=". $db->Quote($fieldId);
		$db->setQuery($sql);
		$result = $db->loadObjectList();
		// need to return user object
		$users = array();
		foreach($result as $row){
			$users [] =& CFactory::getUser($row->user_id);
		}
		return $users;
	}
	function _getFieldIdFromFieldCode($code)
	{
		CError::assert($code , '', '!empty', __FILE__ , __LINE__ );
		$db	=& $this->getDBO();
		$query	= 'SELECT' . $db->nameQuote( 'id' ) . ' '
				. 'FROM ' . $db->nameQuote( '#__community_fields' ) . ' '
				. 'WHERE ' . $db->nameQuote( 'fieldcode' ) . '=' . $db->Quote( $code );
		$db->setQuery( $query );
		$id		= $db->loadResult();
		CError::assert($id , '', '!empty', __FILE__ , __LINE__ );
		return $id;
	}
	/**
	 * Method to get users list on this site
	 * 	 
	 **/	 	
	function getPeople( $sorted = 'latest')
	{
		jimport('joomla.html.pagination');
		$db	= &$this->getDBO();
		$limit = $this->getState('limit');
		$limitstart = $this->getState('limitstart');
		// getting the actual records count
		$query = "SELECT count(*) FROM #__users as b WHERE b.block = 0 ORDER BY `registerDate` DESC";
		$db->setQuery($query);
		$total = $db->loadResult();
		switch( $sorted )
		{
			case 'online':
				$query	= 'SELECT DISTINCT(a.id) '
						. 'FROM ' . $db->nameQuote( '#__users' ) . ' AS a '
						. 'LEFT JOIN ' . $db->nameQuote( '#__session' ) . ' AS b '
						. 'ON a.id=b.userid '
						. 'WHERE a.block=' . $db->Quote( '0' )
						. 'ORDER BY b.userid DESC';
				break;
			default:
				$query = JString::str_ireplace('count(*)', 'b.id', $query);
				break;
		}
		$query	.= ' LIMIT ' . $limitstart . ',' . $limit;
		$db->setQuery($query);
		$result = $db->loadObjectList();
		$this->_pagination = new JPagination($total, $limitstart, $limit);
		$cusers = array();
		for($i = 0; $i < count($result); $i++)
		{
			//$usr =& CFactory::getUser(	$result[$i]->id );
			$usr =& CFactory::getUser(	$result[$i]->id );
			$cusers[] = $usr;
		}
		return $cusers;
	}
}
sistem search ederken database de yukardaki kodda search e temel olan tablolara ek olarak , jos_contact_details tablosunda "state" "country" satırlarından da arama yapmasını sağlamak için, bu koda nası bi edit yapmak gerekir..
yardımcı olacaklara şimdiden teşekkürler..