<?PHP
/*********************************************************************************
 * 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-2005 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/

 /*  This function was only called twice, why is it needed instead of an array()?
function get_field_value($field,$type, $label, $required, $options_dom, $translateOptions=true){
	return array('name'=>$field, 'type'=>$type, 'label'=>get_field_label_value($label), 'required'=>$required, 'options'=>get_field_options($options_dom, $translateOptions));
}*/

/*  This function was only called once and it uses a global variable to get information from
       two calls ago.
function get_field_label_value($label){
	global $module_name;
	return translate($label, $module_name);
}*/

/* Most of this function is repeating work that was done two calls ago
     The rest of it is superfluous
function get_field_options($options_dom, $translateOptions = true){
	global $module_name,$app_list_strings;
	if(empty($options_dom)){
		return array();
	}
	if($translateOptions) {
		$options =  translate($options_dom, $module_name);
	} else {
		$options = $options_dom;
	}
	$options_ret = array();
	foreach($options as $name=>$value){
			$options_ret[] =  array('name'=> $name , 'value'=>$value);
	}
	return $options_ret;
}
*/

function get_field_list(&$value){
	$list = array();
	if(!empty($value->field_defs)){
		foreach($value->field_defs as $var){
			if(isset($var['source']) && $var['source'] != 'db' && (!isset($var['type'])|| $var['type'] != 'relate'))continue;
			$required = 0;
			$options_dom = array();
			$options_ret = array();
			// Apparently the only purpose of this check is to make sure we only return fields
			//   when we've read a record.  Otherwise this function is identical to get_module_field_list
			//if(isset($value->$var['name'])){
				if(isset($value->required_fields) && key_exists($var['name'], $value->required_fields)){
					$required = 1;
				}
				if(isset($var['options'])){
					$options_dom = translate($var['options'], $value->module_dir);
					if(!is_array($options_dom)) $options_dom = array();
					foreach($options_dom as $key=>$oneOption)
						$options_ret[] = get_name_value($key,$oneOption);
				}
				$list[$var['name']] = array('name'=>$var['name'],
											'type'=>$var['type'],
											'label'=>translate($var['vname'], $value->module_dir),
											'required'=>$required,
											'options'=>$options_ret );
			//}
		}
	}
		if($value->module_dir == 'Bugs'){
			require_once('modules/Releases/Release.php');
			$seedRelease = new Release();
			$options = $seedRelease->get_releases(TRUE, "Active");
			$options_ret = array();
			foreach($options as $name=>$value){
				$options_ret[] =  array('name'=> $name , 'value'=>$value);
			}
			if(isset($list['fixed_in_release'])){
				$list['fixed_in_release']['type'] = 'enum';
				$list['fixed_in_release']['options'] = $options_ret;
			}
			if(isset($list['release'])){
				$list['release']['type'] = 'enum';
				$list['release']['options'] = $options_ret;
			}
			if(isset($list['release_name'])){
				$list['release_name']['type'] = 'enum';
				$list['release_name']['options'] = $options_ret;
			}
		}
		if(isset($value->assigned_user_name) && isset($list['assigned_user_id'])) {
			$list['assigned_user_name'] = $list['assigned_user_id'];
			$list['assigned_user_name']['name'] = 'assigned_user_name';
		}






		if(isset($list['modified_user_id'])) {
			$list['modified_by_name'] = $list['modified_user_id'];
			$list['modified_by_name']['name'] = 'modified_by_name';
		}
		if(isset($list['created_by'])) {
			$list['created_by_name'] = $list['created_by'];
			$list['created_by_name']['name'] = 'created_by_name';
		}
	return $list;

}


function get_name_value($field,$value){
	return array('name'=>$field, 'value'=>$value);
}

function get_user_module_list($user){
	global $app_list_strings;
	$app_list_strings = return_app_list_strings_language($current_language);
	$modules = query_module_access_list($user);
	global $modInvisList, $modInvisListActivities;

	foreach($modInvisList as $invis){
		$modules[$invis] = 'read_only';
	}

	if(isset($modules['Calendar']) || $modules['Activities']){
		foreach($modInvisListActivities as $invis){
				$modules[$invis] = $invis;
		}
	}

	return $modules;



}

function check_modules_access($user, $module_name, $action='write'){
	if(!isset($_SESSION['avail_modules'])){
		$_SESSION['avail_modules'] = get_user_module_list($user);
	}
	if(isset($_SESSION['avail_modules'][$module_name])){
		if($action == 'write' && $_SESSION['avail_modules'][$module_name] == 'read_only'){
			if(is_admin($user))return true;
			return false;
		}
		return true;
	}
	return false;

}

function get_name_value_list(&$value){
	$list = array();
	if(!empty($value->field_defs)){
		if(isset($value->assigned_user_name)) {
			$list['assigned_user_name'] = get_name_value('assigned_user_name', $value->assigned_user_name);
		}





		if(isset($value->modified_by_name)) {
			$list['modified_by_name'] = get_name_value('modified_by_name', $value->modified_by_name);
		}
		if(isset($value->created_by_name)) {
			$list['created_by_name'] = get_name_value('created_by_name', $value->created_by_name);
		}
		foreach($value->field_defs as $var){
			if(isset($var['source']) && $var['source'] != 'db' && (!isset($var['type'])|| $var['type'] != 'relate'))continue;
			if(isset($value->$var['name'])){
				$list[$var['name']] = get_name_value($var['name'], $value->$var['name']);
			}
		}
	}
	return $list;

}

function array_get_name_value_list($array){
	$list = array();
	foreach($array as $name=>$value){

				$list[$name] = get_name_value($name, $value);
	}
	return $list;

}

function array_get_return_value($array, $module){

	return Array('id'=>$array['id'],
				'module_name'=> $module,
				'name_value_list'=>array_get_name_value_list($array)
				);
}

function get_return_value(&$value, $module){
	global $module_name, $current_user;
	$module_name = $module;
	if($module == 'Users' && $value->id != $current_user->id){
		$value->user_hash = '';
	}
	return Array('id'=>$value->id,
				'module_name'=> $module,
				'name_value_list'=>get_name_value_list($value)
				);
}

/*
function get_module_field_list(&$value){
	$list = array();
	if(!empty($value->field_defs)){
		foreach($value->field_defs as $var){
			$required = 0;
			$options_dom = array();
			$translateOptions = false;

				if(isset($value->required_fields) && key_exists($var['name'], $value->required_fields)){
					$required = 1;
				}
				if(isset($var['options'])){
					$options_dom = $var['options'];
					$translateOptions = true;
				}
				if($value->module_dir == 'Bugs'){
					require_once('modules/Releases/Release.php');
					$seedRelease = new Release();
					$options = $seedRelease->get_releases(TRUE, "Active");
					if($var['name'] == 'fixed_in_release'){
						$var['type'] = 'enum';
						$translateOptions = false;
						foreach($options as $name=>$avalue){
							$options_dom[$avalue] =  $name;
						}
					}
					if($var['name'] == 'release'){
						$var['type'] = 'enum';
						$translateOptions = false;
						foreach($options as $name=>$avalue){
							$options_dom[$avalue] =  $name;
						}
					}
				}
				$list[$var['name']] = array('name'=>$var['name'],
											'type'=>$var['type'],
											'label'=>translate($var['vname'], $value->module_dir),
											'required'=>$required,
											'options'=>get_field_options($options_dom, $translateOptions) );

		}
		}

	return $list;
}
*/

function get_return_module_fields(&$value, $module, &$error){
	global $module_name;
	$module_name = $module;
	return Array('module_name'=>$module,
				//'module_fields'=> get_module_field_list($value),
				'module_fields'=> get_field_list($value),
				'error'=>get_name_value_list($value)
				);
}

function get_return_error_value($error_num, $error_name, $error_description){
	return Array('number'=>$error_num,
				'name'=> $error_name,
				'description'=>	$error_description
				);
}

function filter_field_list(&$field_list, &$select_fields, $module_name){
	$key_value_list = values_to_keys($select_fields);
	if($module_name == 'Contacts'){
		global $invalid_contact_fields;
		if(is_array($invalid_contact_fields)){
		foreach($invalid_contact_fields as $name=>$val){
			if(isset($field_list[$name])){
					unset($field_list[$name]);
			}

		}
		}
	}
	if( is_array($field_list) && !empty($key_value_list) && is_array($key_value_list)){
		while($current_value = current($field_list)){
				if(!key_exists($current_value['name'], $key_value_list)){
					if(isset($field_list[key($field_list)])){
						unset($field_list[key($field_list)]);
					}

				}else{
					next($field_list);
				}
		}
	}

	return $field_list;

}
function filter_return_list(&$output_list, &$select_fields, $module_name){
	$key_value_list = values_to_keys($select_fields);

	for($sug = 0; $sug < sizeof($output_list) ; $sug++){
	$field_list = $output_list[$sug]['field_list'];
	$name_list = $output_list[$sug]['name_value_list'];
	if($module_name == 'Contacts'){
		global $invalid_contact_fields;
		if(is_array($invalid_contact_fields)){
		foreach($invalid_contact_fields as $name=>$val){
			if(isset($field_list[$name])){
						unset($field_list[$name]);
			}
			unset($name_list[$name]);
		}
		}
	}

	if( is_array($name_list) && !empty($key_value_list) && is_array($key_value_list)){
		while($current_value = current($name_list)){
				if(!key_exists($current_value['name'], $key_value_list)){
					if(isset($field_list[key($name_list)])){
						unset($field_list[key($name_list)]);
					}
					unset($name_list[key($name_list)]);

				}else{
					next($name_list);
				}
		}
	}
	}
	return $output_list;

}

function login_success(){
	global $current_language, $sugar_config, $app_strings, $app_list_strings;
	$current_language = $sugar_config['default_language'];
	$app_strings = return_application_language($current_language);
	$app_list_strings = return_app_list_strings_language($current_language);
}


/*
 *	Given an account_name, either create the account or assign to a contact.
 */
function add_create_account(&$seed)
{
	$account_name = $seed->account_name;
	$account_id = $seed->account_id;
	$assigned_user_id = $seed->assigned_used_id;

	if ((! isset($account_name) || $account_name == ''))
	{
		return;
	}

	if($seed->account_name = '' && isset($seed->account_id)){
		$seed->accounts->delete($seed->id, $seed->account_id);
		return;
	}

    $arr = array();

	// check if it already exists
    $focus = new Account();

    $query = "select id, deleted from {$focus->table_name} WHERE name='". PearDatabase::quote($account_name)."'";
    $result = mysql_query($query) or sugar_die("Error selecting sugarbean: ".mysql_error());

    $row = $seed->db->fetchByAssoc($result, -1, false);

	// we found a row with that id
    if (isset($row['id']) && $row['id'] != -1)
    {
    	// if it exists but was deleted, just remove it entirely
        if ( isset($row['deleted']) && $row['deleted'] == 1)
        {
            $query2 = "delete from {$focus->table_name} WHERE id='". PearDatabase::quote($row['id'])."'";
            $result2 = mysql_query($query2) or sugar_die("Error deleting existing sugarbean: ".mysql_error());
		}
		// else just use this id to link the contact to the account
        else
        {
        	$focus->id = $row['id'];
        }
    }

	// if we didnt find the account, so create it
    if (! isset($focus->id) || $focus->id == '')
    {
    	$focus->name = $account_name;
		if ( isset($assigned_user_id))
		{
           $focus->assigned_user_id = $assigned_user_id;
           $focus->modified_user_id = $assigned_user_id;
		}
        $focus->save();
    }

    if($seed->account_id != $focus->id){
    	if (!isset($seed->users)){
	    	$seed->load_relationship('accounts');
		}
    	$seed->accounts->delete($seed->id, $seed->account_id);
    }

    if(isset($focus->id) && $focus->id != ''){
		$seed->account_id = $focus->id;
	}
}

function check_for_duplicate_contacts(&$seed){
	require_once('modules/Contacts/Contact.php');
	$query = '';
	$baseQuery = 'select id, first_name, last_name, email1, email2  from contacts where deleted!=1 and (';

	if(isset($seed->id)){
		return false;
	}

	if(!empty($seed->first_name) && !empty($seed->first_name)){
		$query = $baseQuery ."  (first_name like '". $seed->first_name . "%' and last_name = '". $seed->last_name ."')";
	}else{
			$query = $baseQuery ."  last_name = '". $seed->last_name ."'";
	}
	if(!empty($seed->email1)){
		if(empty($query)){
		$query = $baseQuery. "  email1='". $seed->email1 . "' or email2 = '". $seed->email1 ."'";
		}else {
			$query .= "or email1='". $seed->email1 . "' or email2 = '". $seed->email1 ."'";
		}
	}

	if(!empty($query)){
		$rows = array();
		global $db;
		$result = $seed->db->query($query.')');
		if(empty($result)){
			return null;
		}
		for($i = 0; $i < $seed->db->getRowCount($result); $i++){
			$rows[$i] = $seed->db->fetchByAssoc($result, $i);
		}
		if(count($rows)> 0){
			return true;
		}
	}
	return false;
}





?>
