<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * The contents of this file are subject to the SugarCRM Public License Version
 * 1.1.3 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by SugarCRM" logo and
 *    (ii) the SugarCRM copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) 2004-2006 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/
 
/**
 * quicksearchQuery class, handles AJAX calls from quicksearch.js
 *
 * @copyright  2004-2007 SugarCRM Inc.
 * @license    http://www.sugarcrm.com/crm/products/sugar-professional-eula.html  SugarCRM Professional End User License
 * @since      Class available since Release 4.5.1
 */
class quicksearchQuery {
    /**
     * Internal function to construct where clauses
     */
    function constructWhere(&$query_obj, $table='') {
        if (! empty($table)) {
            $table .= ".";
        }
        $cond_arr = array();
    
        if (! is_array($query_obj['conditions'])) {
            $query_obj['conditions'] = array();
        }
    
        foreach($query_obj['conditions'] as $condition) {
             if($condition['op'] == 'contains') {
                array_push($cond_arr,PearDatabase::quote($table.$condition['name'])." like '%".PearDatabase::quote($condition['value'])."%'");
             }
             if($condition['op'] == 'like_custom') {
                $like = '';
                if(!empty($condition['begin'])) $like .= PearDatabase::quote($condition['begin']);
                $like .= PearDatabase::quote($condition['value']);
                if(!empty($condition['end'])) $like .= PearDatabase::quote($condition['end']);
                array_push($cond_arr,PearDatabase::quote($table.$condition['name'])." like '$like'");
             } else { // starts_with
                array_push($cond_arr,PearDatabase::quote($table.$condition['name'])." like '".PearDatabase::quote($condition['value'])."%'");
             }
        }
        
        if($table == 'users.') {
            array_push($cond_arr,$table."status='Active'");
        }
        
        return implode(" {$query_obj['group']} ",$cond_arr);
    }
    
    /**
     * Query a module for a list of items
     * 
     * @param array $args
     * example for querying Account module with 'a':
     * array ('modules' => array('Accounts'), // module to use
     *        'field_list' => array('name', 'id'), // fields to select
     *        'group' => 'or', // how the conditions should be combined
     *        'conditions' => array(array( // array of where conditions to use
     *                              'name' => 'name', // field 
     *                              'op' => 'like_custom', // operation
     *                              'end' => '%', // end of the query
     *                              'value' => 'a',  // query value
     *                              )
     *                        ),
     *        'order' => 'name', // order by
     *        'limit' => '30', // limit, number of records to return 
     *       )
     * @return array list of elements returned
     */
    function query($args) {
        $json = getJSONobj();
        global $sugar_config;
        global $beanFiles, $beanList;
        
        if($sugar_config['list_max_entries_per_page'] < ($args['limit'] + 1)) // override query limits
            $sugar_config['list_max_entries_per_page'] = ($args['limit'] + 1);
    
        //decode condition parameter values..
        if (is_array($args['conditions'])) {
            foreach($args['conditions'] as $key=>$condition)    {       
                if (!empty($condition['value'])) {
                    $where = $json->decode(utf8_encode($condition['value']));
                    $args['conditions'][$key]['value'] = $where;
                }       
            }
        }
        
        $list_return = array();
        
        foreach($args['modules'] as $module) {
            require_once($beanFiles[$beanList[$module]]);
            $focus = new $beanList[$module];
            
            $query_orderby = '';
            if (!empty($args['order'])) {
                $query_orderby = $args['order'];
            }
            $query_limit = '';
            if (!empty($args['limit'])) {
                $query_limit = $args['limit'];
            }
            $query_where = $this->constructWhere($args, $focus->table_name);
            $list_arr = array();
            if($focus->ACLAccess('ListView', true)) {
                $curlist = $focus->get_list($query_orderby, $query_where, 0, $query_limit, -1, 0);
                $list_return = array_merge($list_return,$curlist['list']);
            }
        }
        
        $app_list_strings = null;
    
        for($i = 0; $i < count($list_return); $i++) {
            $list_arr[$i]= array();
            $list_arr[$i]['fields']= array();
            $list_arr[$i]['module']= $list_return[$i]->object_name;
            
            foreach($args['field_list'] as $field) {
                // handle enums
                if( (isset($list_return[$i]->field_name_map[$field]['type']) && $list_return[$i]->field_name_map[$field]['type'] == 'enum') || 
                    (isset($list_return[$i]->field_name_map[$field]['custom_type']) && $list_return[$i]->field_name_map[$field]['custom_type'] == 'enum')) {
                    
                    // get fields to match enum vals
                    if(empty($app_list_strings)) {
                        if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') $current_language = $_SESSION['authenticated_user_language'];
                        else $current_language = $sugar_config['default_language'];
                        $app_list_strings = return_app_list_strings_language($current_language);
                    }
                    
                    // match enum vals to text vals in language pack for return
                    if(!empty($app_list_strings[$list_return[$i]->field_name_map[$field]['options']])) {
                        $list_return[$i]->$field = $app_list_strings[$list_return[$i]->field_name_map[$field]['options']][$list_return[$i]->$field];
                    }
                }
    
                $list_arr[$i]['fields'][$field] = $list_return[$i]->$field;
            }
        }
        
        return $json->encode($list_arr);
    }
    
    /**
     * Returns the list of users, faster than using query method for Users module
     * 
     * @param array $args arguments used to construct query, see query() for example
     * 
     * @return array list of users returned
     */
    function get_user_array($args) {
        global $json;
        
        //decode condition parameter values..
        if(is_array($args['conditions'])) {
            foreach($args['conditions'] as $key=>$condition) {      
                if (!empty($condition['value'])) {
                    $args['conditions'][$key]['value'] = $json->decode($condition['value']);
                }
            }
        }
        
        $response = array();
        
        if(showFullName()) { // utils.php, if system is configured to show full name
            $user_array = getUserArrayFromFullName($args['conditions'][0]['value']);
        } else {
            $user_array = get_user_array(false, "Active", '', false, $args['conditions'][0]['value']);
        }
        
        foreach($user_array as $id=>$name) {
            array_push($response, array('fields' => array('id' => $id, 'user_name' => $name), 'module' => 'Users'));
        }
    
        return $json->encode($response);
    }
}

$json = getJSONobj();
$data = $json->decode(html_entity_decode($_REQUEST['data']));
$quicksearchQuery = new quicksearchQuery();
 
switch($data['method']) {
    case 'query':
        echo $quicksearchQuery->query($data);
        break;
    case 'get_user_array':
        echo $quicksearchQuery->get_user_array($data);
        break;
}

?>
