<?php
 if(!defined('sugarEntry'))define('sugarEntry', true);
//łłńń
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2009 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * 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, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/

// the types/methods defined in this file are deprecated -- please see SoapSugarUsers.php, SoapPortalUsers.php, SoapStudio.php, etc.

$server->wsdl->addComplexType(
    'contact_detail',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'email_address' => array('name'=>'email_address','type'=>'xsd:string'),
        'name1' => array('name'=>'name1','type'=>'xsd:string'),
        'name2' => array('name'=>'name2','type'=>'xsd:string'),
        'association' => array('name'=>'association','type'=>'xsd:string'),
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'msi_id' => array('name'=>'id','type'=>'xsd:string'),
        'type' => array('name'=>'type','type'=>'xsd:string'),
    )
);

$server->wsdl->addComplexType(
    'contact_detail_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:contact_detail[]')
    ),
    'tns:contact_detail'
);

$server->wsdl->addComplexType(
    'user_detail',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'email_address' => array('name'=>'email_address','type'=>'xsd:string'),
        'user_name' => array('name'=>'user_name', 'type'=>'xsd:string'),
        'first_name' => array('name'=>'first_name','type'=>'xsd:string'),
        'last_name' => array('name'=>'last_name','type'=>'xsd:string'),
        'department' => array('name'=>'department','type'=>'xsd:string'),
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'title' => array('name'=>'title','type'=>'xsd:string'),
    )
);

$server->wsdl->addComplexType(
    'user_detail_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:user_detail[]')
    ),
    'tns:user_detail'
);


$server->register(
    'create_session',
    array('user_name'=>'xsd:string','password'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

$server->register(
    'end_session',
    array('user_name'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

$server->register(
    'contact_by_email',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'email_address'=>'xsd:string'),
    array('return'=>'tns:contact_detail_array'),
    $NAMESPACE);

$server->register(
    'get_contact_relationships',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'id'=>'xsd:string'),
    array('return'=>'tns:contact_detail_array'),
    $NAMESPACE);

$server->register(
    'user_list',
    array('user_name'=>'xsd:string','password'=>'xsd:string'),
    array('return'=>'tns:user_detail_array'),
    $NAMESPACE);

$server->register(
    'search',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'name'=>'xsd:string'),
    array('return'=>'tns:contact_detail_array'),
    $NAMESPACE);

$server->register(
	'track_email',
    array('user_name'=>'xsd:string','password'=>'xsd:string','parent_id'=>'xsd:string', 'contact_ids'=>'xsd:string', 'date_sent'=>'xsd:date', 'email_subject'=>'xsd:string', 'email_body'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

$server->register(
	'create_contact',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'first_name'=>'xsd:string', 'last_name'=>'xsd:string', 'email_address'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

$server->register(
	'create_lead',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'first_name'=>'xsd:string', 'last_name'=>'xsd:string', 'email_address'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

$server->register(
	'create_account',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'name'=>'xsd:string', 'phone'=>'xsd:string', 'website'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

$server->register(
	'create_opportunity',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'name'=>'xsd:string', 'amount'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);


$server->register(
	'create_case',
    array('user_name'=>'xsd:string','password'=>'xsd:string', 'name'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

/**
 * Create a new session.  This method is required before calling any other functions.
 *
 * @param string $user_name -- the user name for the session
 * @param string $password -- MD5 of user password
 * @return "Success" if the session is created
 * @return "Failed" if the session creation failed.
 */
function create_session($user_name, $password)
{
	if(validate_user($user_name, $password))
	{
		return "Success";
	}

	return "Failed";
}

/**
 * End a session.  This method will end the SOAP session.
 *
 * @param string $user_name -- the user name for the session
 * @return "Success" if the session is destroyed
 * @return "Failed" if the session destruction failed.
 */
function end_session($user_name)
{
	// get around optimizer warning
	$user_name = $user_name;
	return "Success";
}

/**
 * Validate the user session based on user name and password hash.
 *
 * @param string $user_name -- The user name to create a session for
 * @param string $password -- The MD5 sum of the user's password
 * @return true -- If the session is created
 * @return false -- If the session is not created
 */
function validate_user($user_name, $password){
	global $server, $current_user, $sugar_config, $system_config;
	$user = new User();
	$user->user_name = $user_name;
	$system_config = new Administration();
	$system_config->retrieveSettings('system');
	$authController = new AuthenticationController((!empty($sugar_config['authenticationClass'])? $sugar_config['authenticationClass'] : 'SugarAuthenticate'));
	// Check to see if the user name and password are consistent.
	if($user->authenticate_user($password)){
		// we also need to set the current_user.
		$user->retrieve($user->id);
		$current_user = $user;

		return true;
	}else if(function_exists('mcrypt_cbc')){
		$password = decrypt_string($password);
		if($authController->login($user_name, $password) && isset($_SESSION['authenticated_user_id'])){
			$user->retrieve($_SESSION['authenticated_user_id']);
			$current_user = $user;
			return true;
		}
	}else{
		$GLOBALS['log']->fatal("SECURITY: failed attempted login for $user_name using SOAP api");
		$server->setError("Invalid username and/or password");
		return false;
	}

}

/**
 * Internal: When building a response to the plug-in for Microsoft Outlook, find
 * all contacts that match the email address that was provided.
 *
 * @param array by ref $output_list -- The list of matching beans.  New contacts that match
 *   the email address are appended to the $output_list
 * @param string $email_address -- an email address to search for
 * @param Contact $seed_contact -- A template SugarBean.  This is a blank Contact
 * @param ID $msi_id -- Index Count
 */
function add_contacts_matching_email_address(&$output_list, $email_address, &$seed_contact, &$msi_id)
{
    // escape the email address
	$safe_email_address = addslashes($email_address);
	global $current_user;

	// Verify that the user has permission to see Contact list views
	if(!$seed_contact->ACLAccess('ListView'))
	{
		return;
	}

	$contactList = $seed_contact->emailAddress->getBeansByEmailAddress($safe_email_address);
	// create a return array of names and email addresses.
	foreach($contactList as $contact)
	{
		$output_list[] = Array("name1"	=> $contact->first_name,
			"name2" => $contact->last_name,
			"association" => $contact->account_name,
			"type" => 'Contact',
			"id" => $contact->id,
			"msi_id" => $msi_id,
			"email_address" => $contact->email1);

        $accounts = $contact->get_linked_beans('accounts','Account');
		foreach($accounts as $account)
		{
			$output_list[] = get_account_array($account, $msi_id);
		}

        $opps = $contact->get_linked_beans('opportunities','Opportunity');
		foreach($opps as $opp)
		{
			$output_list[] = get_opportunity_array($opp, $msi_id);
		}

        $cases = $contact->get_linked_beans('cases','aCase');
		foreach($cases as $case)
		{
			$output_list[] = get_case_array($case, $msi_id);
		}

		 $bugs = $contact->get_linked_beans('bugs','Bug');
		foreach($bugs as $bug)
		{
			$output_list[] = get_bean_array($bug, $msi_id, 'Bug');
		}

		$projects = $contact->get_linked_beans('project','Project');
		foreach($projects as $project)
		{
			$output_list[] = get_bean_array($project, $msi_id, 'Project');
		}

		$msi_id = $msi_id + 1;
	}
}

/**
 * Internal: Add Leads that match the specified email address to the result array
 *
 * @param Array $output_list -- List of matching detail records
 * @param String $email_address -- Email address
 * @param Bean $seed_lead -- Seed Lead Bean
 * @param int $msi_id -- output array offset.
 */
function add_leads_matching_email_address(&$output_list, $email_address, &$seed_lead, &$msi_id)
{
	$safe_email_address = addslashes($email_address);
	if(!$seed_lead->ACLAccess('ListView')){
		return;
	}

	$leadList = $seed_lead->emailAddress->getBeansByEmailAddress($safe_email_address);

	// create a return array of names and email addresses.
	foreach($leadList as $lead)
	{
		$output_list[] = Array("name1"	=> $lead->first_name,
			"name2" => $lead->last_name,
			"association" => $lead->account_name,
			"type" => 'Lead',
			"id" => $lead->id,
			"msi_id" => $msi_id,
			"email_address" => $lead->email1);

		$msi_id = $msi_id + 1;
	}
}

/**
 * Return a list of modules related to the specifed contact record
 *
 * This function does not require a session be created first.
 *
 * @param string $user_name -- User name to authenticate with
 * @param string $password -- MD5 of the user password
 * @param string $id -- the id of the record
 * @return contact detail array along with associated objects.
 */
function get_contact_relationships($user_name, $password, $id)
{
	if(!validate_user($user_name, $password)){
		return array();
	}

	$seed_contact = new Contact();
	// Verify that the user has permission to see Contact list views
	if(!$seed_contact->ACLAccess('ListView'))
	{
		return;
	}

	$msi_id = 1;
	$seed_contact->retrieve($id);

	$output_list[] = Array("name1"	=> $seed_contact->first_name,
			"name2" => $seed_contact->last_name,
			"association" => $seed_contact->account_name,
			"type" => 'Contact',
			"id" => $seed_contact->id,
			"msi_id" => $msi_id,
			"email_address" => $seed_contact->email1);

        $accounts = $seed_contact->get_linked_beans('accounts','Account');
		foreach($accounts as $account)
		{
			$output_list[] = get_account_array($account, $msi_id);
		}

        $opps = $seed_contact->get_linked_beans('opportunities','Opportunity');
		foreach($opps as $opp)
		{
			$output_list[] = get_opportunity_array($opp, $msi_id);
		}

        $cases = $seed_contact->get_linked_beans('cases','aCase');
		foreach($cases as $case)
		{
			$output_list[] = get_case_array($case, $msi_id);
		}

		 $bugs = $seed_contact->get_linked_beans('bugs','Bug');
		foreach($bugs as $bug)
		{
			$output_list[] = get_bean_array($bug, $msi_id, 'Bug');
		}

		$projects = $seed_contact->get_linked_beans('project','Project');
		foreach($projects as $project)
		{
			$output_list[] = get_bean_array($project, $msi_id, 'Project');
		}
		return $output_list;
}

// Define a global current user
$current_user = null;

/**
 * Return a list of contact and lead detail records based on a single email
 * address or a  list of email addresses separated by '; '.
 *
 * This function does not require a session be created first.
 *
 * @param string $user_name -- User name to authenticate with
 * @param string $password -- MD5 of the user password
 * @param string $email_address -- Single email address or '; ' separated list of email addresses (e.x "test@example.com; test2@example.com"
 * @return contact detail array along with associated objects.
 */
function contact_by_email($user_name, $password, $email_address)
{
	if(!validate_user($user_name, $password)){
		return array();
	}

	$seed_contact = new Contact();
	$seed_lead = new Lead();
	$output_list = Array();
	$email_address_list = explode("; ", $email_address);

	// remove duplicate email addresses
	$non_duplicate_email_address_list = Array();
	foreach( $email_address_list as $single_address)
	{
		// Check to see if the current address is a match of an existing address
		$found_match = false;
		foreach( $non_duplicate_email_address_list as $non_dupe_single)
		{
			if(strtolower($single_address) == $non_dupe_single)
			{
				$found_match = true;
				break;
			}
		}

		if($found_match == false)
		{
			$non_duplicate_email_address_list[] = strtolower($single_address);
		}
	}

	// now copy over the non-duplicated list as the original list.
	$email_address_list =$non_duplicate_email_address_list;

	// Track the msi_id
	$msi_id = 1;

	foreach( $email_address_list as $single_address)
	{
	    // verify that contacts can be listed
		if($seed_contact->ACLAccess('ListView')){
			add_contacts_matching_email_address($output_list, $single_address, $seed_contact, $msi_id);
		}

	    // verify that leads can be listed
		if($seed_lead->ACLAccess('ListView')){
			add_leads_matching_email_address($output_list, $single_address, $seed_lead, $msi_id);
		}
	}

	return $output_list;
}

/**
 * Internal: convert a bean into an array
 *
 * @param Bean $bean -- The bean to convert
 * @param int $msi_id -- Russult array index
 * @return An associated array containing the detail fields.
 */
function get_contact_array($contact, $msi_id = '0'){
	 $contact->emailAddress->handleLegacyRetrieve($contact);
	 return Array("name1"	=> $contact->first_name,
			"name2" => $contact->last_name,
			"association" => $contact->account_name,
			"type" => 'Contact',
			"id" => $contact->id,
			"msi_id" => $msi_id,
			"email_address" => $contact->email1);



}

/**
 * Internal: Convert a user into an array
 *
 * @param User $user -- The user to convert
 * @return An associated array containing the detail fields.
 */
function get_user_list_array($user) {
    return Array('email_address' => $user->email1,
        'user_name' => $user->user_name,
        'first_name' => $user->first_name,
        'last_name' => $user->last_name,
        'department' => $user->department,
        'id' => $user->id,
        'title' => $user->title);
}

/**
 * Get a full user list.
 *
 * This function does not require a session be created first.
 *
 * @param string $user -- user name for validation
 * @param password $password -- MD5 hash of the user password for validation
 * @return User Array -- An array of user detail records
 */
function user_list($user, $password) {
	if(!validate_user($user, $password)){
		return array();
	}

    $seed_user = new User();
    $output_list = Array();
	if(!$seed_user->ACLAccess('ListView')){
		return $output_list;
	}
    $userList = $seed_user->get_full_list();


    foreach($userList as $user) {
        $output_list[] = get_user_list_array($user);
    }

    return $output_list;
}

/**
 * Internal: Search for contacts based on the specified name and where clause.
 * Currently only the name is used.
 *
 * @param string $name -- Name to search for.
 * @param string $where -- Where clause defaults to ''
 * @param int $msi_id -- Response array index
 * @return array -- Resturns a list of contacts that have the provided name.
 */
function contact_by_search($name, $where = '', $msi_id = '0')
{
	$seed_contact = new Contact();
	if($where == ''){
		$where = $seed_contact->build_generic_where_clause($name);
	}
	if(!$seed_contact->ACLAccess('ListView')){
		return array();
	}
	$response = $seed_contact->get_list("last_name, first_name", $where, 0);
	$contactList = $response['list'];

	$output_list = Array();

	// create a return array of names and email addresses.
	foreach($contactList as $contact)
	{
		$output_list[] = get_contact_array($contact, $msi_id);
	}
	return $output_list;
}

/**
 * Internal: convert a bean into an array
 *
 * @param Bean $bean -- The bean to convert
 * @param int $msi_id -- Russult array index
 * @return An associated array containing the detail fields.
 */
function get_lead_array($lead, $msi_id = '0'){
	 $lead->emailAddress->handleLegacyRetrieve($lead);
	 return Array("name1"	=> $lead->first_name,
			"name2" => $lead->last_name,
			"association" => $lead->account_name,
			"type" => 'Lead',
			"id" => $lead->id,
			"msi_id" => $msi_id,
			"email_address" => $lead->email1);
}

function lead_by_search($name, $where = '', $msi_id = '0')
{
	$seed_lead = new Lead();
	if($where == ''){
		$where = $seed_lead->build_generic_where_clause($name);
	}
	if(!$seed_lead->ACLAccess('ListView')){
		return array();
	}
	$response = $seed_lead->get_list("last_name, first_name", $where, 0);
	$lead_list = $response['list'];

	$output_list = Array();

	// create a return array of names and email addresses.
	foreach($lead_list as $lead)
	{
		$output_list[] = get_lead_array($lead, $msi_id);
	}
	return $output_list;
}

/**
 * Internal: convert a bean into an array
 *
 * @param Bean $bean -- The bean to convert
 * @param int $msi_id -- Russult array index
 * @return An associated array containing the detail fields.
 */
function get_account_array($account, $msi_id){
	return Array("name1"	=> '',
			"name2" => $account->name,
			"association" => $account->billing_address_city,
			"type" => 'Account',
			"id" => $account->id,
			"msi_id" => $msi_id,
			"email_address" => $account->email1);
}

function account_by_search($name, $where = '', $msi_id = '0')
{
	$seed_account = new Account();
	if(!$seed_account->ACLAccess('ListView')){
		return array();
	}
	if($where == ''){
		$where = $seed_account->build_generic_where_clause($name);
	}
	$response = $seed_account->get_list("name", $where, 0);
	$accountList = $response['list'];

	$output_list = Array();

	// create a return array of names and email addresses.
	foreach($accountList as $account)
	{
		$output_list[] = get_account_array($account, $msi_id);
	}
	return $output_list;
}

/**
 * Internal: convert a bean into an array
 *
 * @param Bean $bean -- The bean to convert
 * @param int $msi_id -- Russult array index
 * @return An associated array containing the detail fields.
 */
function get_opportunity_array($value, $msi_id = '0'){
		return  Array("name1"	=> '',
			"name2" => $value->name,
			"association" => $value->account_name,
			"type" => 'Opportunity',
			"id" => $value->id,
			"msi_id" => $msi_id,
			"email_address" => '');

}

function opportunity_by_search($name, $where = '', $msi_id = '0')
{
	$seed = new Opportunity();
	if(!$seed->ACLAccess('ListView')){
		return array();
	}
	if($where == ''){
		$where = $seed->build_generic_where_clause($name);
	}
	$response = $seed->get_list("name", $where, 0);
	$list = $response['list'];

	$output_list = Array();

	// create a return array of names and email addresses.
	foreach($list as $value)
	{
		$output_list[] = get_opportunity_array($value, $msi_id);
	}
	return $output_list;
}

/**
 * Internal: convert a bean into an array
 *
 * @param Bean $bean -- The bean to convert
 * @param int $msi_id -- Russult array index
 * @return An associated array containing the detail fields.
 */
function get_bean_array($value, $msi_id, $type){
	return Array("name1" => '',
			"name2" => $value->get_summary_text(),
			"association" => '',
			"type" => $type,
			"id" => $value->id,
			"msi_id" => $msi_id,
			"email_address" => '');

}

/**
 * Internal: convert a bean into an array
 *
 * @param Bean $bean -- The bean to convert
 * @param int $msi_id -- Russult array index
 * @return An associated array containing the detail fields.
 */
function get_case_array($value, $msi_id){
	return Array("name1" => '',
			"name2" => $value->get_summary_text(),
			"association" => $value->account_name,
			"type" => 'Case',
			"id" => $value->id,
			"msi_id" => $msi_id,
			"email_address" => '');

}

function bug_by_search($name, $where = '', $msi_id='0')
{
	$seed = new Bug();
	if(!$seed->ACLAccess('ListView')){
		return array();
	}
	if($where == ''){
		$where = $seed->build_generic_where_clause($name);
	}
	$response = $seed->get_list("name", $where, 0);
	$list = $response['list'];

	$output_list = Array();

	// create a return array of names and email addresses.
	foreach($list as $value)
	{
		$output_list[] = get_bean_array($value, $msi_id, 'Bug');
	}
	return $output_list;
}

function case_by_search($name, $where = '', $msi_id='0')
{
	$seed = new aCase();
	if(!$seed->ACLAccess('ListView')){
		return array();
	}
	if($where == ''){
		$where = $seed->build_generic_where_clause($name);
	}
	$response = $seed->get_list("name", $where, 0);
	$list = $response['list'];

	$output_list = Array();

	// create a return array of names and email addresses.
	foreach($list as $value)
	{
		$output_list[] = get_case_array($value, $msi_id);
	}
	return $output_list;
}

/**
 * Record and email message and associated it with the specified parent bean and contact ids.
 *
 * This function does not require a session be created first.
 *
 * @param string $user_name -- Name of the user to authenticate
 * @param string $password -- MD5 hash of the user password for authentication
 * @param id $parent_id -- [optional] The parent record to link the email to.
 * @param unknown_type $contact_ids
 * @param string $date_sent -- Date/time the email was sent in Visual Basic Date format. (e.g. '7/22/2004 9:36:31 AM')
 * @param string $email_subject -- The subject of the email
 * @param string $email_body -- The body of the email
 * @return "Invalid username and/or password"
 * @return -1 If the authenticated user does not have ACL access to save Email.
 */
function track_email($user_name, $password,$parent_id, $contact_ids, $date_sent, $email_subject, $email_body)
{
	if(!validate_user($user_name, $password)){
		return "Invalid username and/or password";
	}
	global $current_user;

	$GLOBALS['log']->info("In track email: username: $user_name contacts: $contact_ids date_sent: $date_sent");

	// translate date sent from VB format 7/22/2004 9:36:31 AM
	// to yyyy-mm-dd 9:36:31 AM

	$date_sent = ereg_replace("([0-9]*)/([0-9]*)/([0-9]*)( .*$)", "\\3-\\1-\\2\\4", $date_sent);

	require_once('modules/Users/User.php');
	$seed_user = new User();

	$user_id = $seed_user->retrieve_user_id($user_name);
	$seed_user->retrieve($user_id);
	$current_user = $seed_user;
	require_once('modules/Emails/Email.php');

	$email = new Email();
	if(!$email->ACLAccess('Save')){
		return -1;
	}
	$email->description = $email_body;
	$email->name = $email_subject;
	$email->user_id = $user_id;
	$email->assigned_user_id = $user_id;
	$email->assigned_user_name = $user_name;
	$email->date_start = $date_sent;

	// Save one copy of the email message
	$parent_id_list = explode(";", $parent_id);
	$parent_id = explode(':', $parent_id_list[0]);

	// Having a parent object is optional.  If it is set, then associate it.
	if(isset($parent_id[0]) && isset($parent_id[1]))
	{
		$email->parent_type = $parent_id[0];
		$email->parent_id = $parent_id[1];
	}

	$email->save();
	// for each contact, add a link between the contact and the email message
	$id_list = explode(";", $contact_ids);

	foreach( $id_list as $id)
	{
		if(!empty($id))
		$email->set_emails_contact_invitee_relationship($email->id, $id);
	}

	return "Succeeded";
}

function create_contact($user_name,$password, $first_name, $last_name, $email_address)
{
	if(!validate_user($user_name, $password)){
		return 0;
	}

	require_once('modules/Users/User.php');
	$seed_user = new User();
	$user_id = $seed_user->retrieve_user_id($user_name);
	$seed_user->retrieve($user_id);

	require_once('modules/Contacts/Contact.php');
	$contact = new Contact();
	if(!$contact->ACLAccess('Save')){
		return -1;
	}
	$contact->first_name = $first_name;
	$contact->last_name = $last_name;
	$contact->email1 = $email_address;
	$contact->assigned_user_id = $user_id;
	$contact->assigned_user_name = $user_name;



	return $contact->save();
}

function create_lead($user_name,$password, $first_name, $last_name, $email_address)
{
	if(!validate_user($user_name, $password)){
		return 0;
	}

	//todo make the activity body not be html encoded

	require_once('modules/Users/User.php');
	$seed_user = new User();
	$user_id = $seed_user->retrieve_user_id($user_name);

	require_once('modules/Leads/Lead.php');
	$lead = new Lead();
	if(!$lead->ACLAccess('Save')){
		return -1;
	}
	$lead->first_name = $first_name;
	$lead->last_name = $last_name;
	$lead->email1 = $email_address;
	$lead->assigned_user_id = $user_id;
	$lead->assigned_user_name = $user_name;
	return $lead->save();
}

function create_account($user_name,$password, $name, $phone, $website)
{
	if(!validate_user($user_name, $password)){
		return 0;
	}

	//todo make the activity body not be html encoded

	require_once('modules/Users/User.php');
	$seed_user = new User();
	$user_id = $seed_user->retrieve_user_id($user_name);
	$account = new Account();
	if(!$account->ACLAccess('Save')){
		return -1;
	}
	$account->name = $name;
	$account->phone_office = $phone;
	$account->website = $website;
	$account->assigned_user_id = $user_id;
	$account->assigned_user_name = $user_name;
	$account->save();
	return $account->id;

}
function create_case($user_name,$password, $name)
{
	if(!validate_user($user_name, $password)){
		return 0;
	}

	//todo make the activity body not be html encoded

	require_once('modules/Users/User.php');
	$seed_user = new User();
	$user_id = $seed_user->retrieve_user_id($user_name);
	$case = new aCase();
	if(!$case->ACLAccess('Save')){
		return -1;
	}
	$case->assigned_user_id = $user_id;
	$case->assigned_user_name = $user_name;
	$case->name = $name;
	return $case->save();
}

function create_opportunity($user_name,$password, $name, $amount)
{
	if(!validate_user($user_name, $password)){
		return 0;
	}

	require_once('modules/Users/User.php');
	$seed_user = new User();
	$user_id = $seed_user->retrieve_user_id($user_name);
	$opp = new Opportunity();
	if(!$opp->ACLAccess('Save')){
		return -1;
	}
	$opp->name = $name;
	$opp->amount = $amount;
	$opp->assigned_user_id = $user_id;
	$opp->assigned_user_name = $user_name;
	return $opp->save();
}

function search($user_name, $password,$name){
	if(!validate_user($user_name, $password)){
		return array();
	}
    $name_list = explode("; ", $name);
    $list = array();
	foreach( $name_list as $single_name)
	{
	    $list = array_merge($list, contact_by_search($single_name));
	    $list = array_merge($list, lead_by_search($single_name));
	    $list = array_merge($list, account_by_search($single_name));
	    $list = array_merge($list, case_by_search($single_name));
	    $list = array_merge($list, opportunity_by_search($single_name));
	    $list = array_merge($list, bug_by_search($single_name));
    }
	return $list;
}
//DK, more7 gmbh, ca@more7.com ***

$server->wsdl->addComplexType(
    'ecmproduct',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'product_id' => array('name'=>'product_id','type'=>'xsd:string'),
        'product_re' => array('name'=>'product_re', 'type'=>'xsd:string'),
    	'product_name' => array('name'=>'product_name', 'type'=>'xsd:string'),
    	'product_inventory_state' => array('name' => 'product_inventory_state', 'type' => 'xsd:int'),	
    )
);

$server->wsdl->addComplexType(
    'ecmproduct_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmproduct[]')
    ),
    'tns:ecmproduct'
);


//********************************

//DK, more7 gmbh, ca@more7.com ***

$server->register(
	'ecm_add_order_from_shop',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'order' => 'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);



function ecm_add_order_from_shop($user_name, $password, $order, $presta, $user, $a, $b, $c, $d) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	$x = "";
	$x = "S";
	$y = "false";
	
	 

if(!empty($order)) {
		
		$y = "ok";
		

		try {
		 
			$order = unserialize(base64_decode($order));
			
			
			
			//return print_r($order);
			if(!empty($order) && is_array($order)) {
				
 		
		
				if($order['Order-Header']['OrderNumber'] == "ORDERTEST1234")
					return "IDTEST1234";
					
				else {			
					require_once("modules/EcmSales/EcmSale.php");
					$focus=new EcmSale();
		

		
					$template_id="97700b0d-fbe9-e366-4016-4b260f058a47";
	
					$focus->template_id=$template_id;
					$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from ecmdocumenttemplates where id='".$template_id."'"));
					$focus->template_name=$r['name'];
					$focus->setTemplate();
					$focus->number=$focus->generateNumber();
					$focus->document_no=$focus->formatNumber();
					$focus->currency_id="PLN";
					$focus->ecmlanguage="pl_pl";
					$focus->status="s10";
					$focus->type="sales_order";
					$focus->modified_user_id="d09b87cf-efff-2f7c-a859-4ba38402488f";
					$focus->created_by="d09b87cf-efff-2f7c-a859-4ba38402488f";

					$pr=$order['Order-Lines'];
$x = "ok";
					include_once("modules/Accounts/Account.php");
					//$ww=$GLOBALS['db']->query("select count(*) as c from accounts where b2clogin ='".$order['Order-Parties']['Buyer']['Login']."' and deleted='0'");
					$ww=$GLOBALS['db']->query("select count(*) as c from accounts where `id` ='".$order['Order-Parties']['Buyer']['Login']."' and deleted='0'");
					$rr=$GLOBALS['db']->fetchByAssoc($ww);
					$focus->parent_id="getmir";
					$focus->description=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['Buyer']['Description']);
					
					
					// if($rr['c']==0){
						// $account=new Account();
						$account->ownership="getmir";
						// $account->name=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['Buyer']['Name']);
						// $account->b2clogin=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['Buyer']['Login']);
						// $account->billing_address_street=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['Buyer']['StreetAndNumber']);
						// $account->billing_address_postalcode=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['Buyer']['PostalCode']);
						// $account->billing_address_city=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['Buyer']['CityName']);
						// $account->shipping_address_street=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['DeliveryPoint']['StreetAndNumber']);
						// $account->shipping_address_postalcode=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['DeliveryPoint']['PostalCode']);
						// $account->shipping_address_city=iconv("ISO-8859-2","UTF-8",$order['Order-Parties']['DeliveryPoint']['CityName']);
						// $focus->parent_id=create_guid();
						// $GLOBALS['db']->query("insert into accounts set id='".$focus->parent_id."',name='".$account->name."',billing_address_street='".$account->billing_address_street."',billing_address_postalcode='".$account->billing_address_postalcode."',billing_address_city='".$account->billing_address_city."',shipping_address_street='".$account->shipping_address_street."',shipping_address_postalcode='".$account->shipping_address_postalcode."',shipping_address_city='".$account->shipping_address_city."', b2clogin='".$account->b2clogin."'");
					// }
					// else{
					
					
						//$w=$GLOBALS['db']->query("select id from accounts where b2clogin = '".$order['Order-Parties']['Buyer']['Login']."' and deleted='0'");
						$w=$GLOBALS['db']->query("select `id` from `accounts` where `id` = '".$order['Order-Parties']['Buyer']['Login']."' and `deleted`='0'");
						$r=$GLOBALS['db']->fetchByAssoc($w);
						$account=new Account();
						//update account, maybe sth. change
						
						// $GLOBALS['db']->query("update accounts set name='".$account->name."',billing_address_street='".$account->billing_address_street."',billing_address_postalcode='".$account->billing_address_postalcode."',billing_address_city='".$account->billing_address_city."'"."',shipping_address_street='".$account->shipping_address_street."',shipping_address_postalcode='".$account->shipping_address_postalcode."',shipping_address_city='".$account->shipping_address_city."'where id='".$r['id']."'");
						
						// $account->retrieve($r['id']);
						$focus->parent_id=$r['id'];
					//}
					$focus->assigned_user_id="d09b87cf-efff-2f7c-a859-4ba38402488f";
					$focus->register_date=$order['Order-Header']['OrderDate'];
					$focus->delivery_date=$order['Order-Header']['ExpectedDeliveryDate'];
					//$focus->supplier_code=3442;
					$focus->order_no=$order['Order-Header']['OrderNumber'];
					$focus->ecmlanguage="pl_pl";
					$focus->ecmpaymentcondition_id=$order['Order-Parties']['Buyer']['PaymentConditionId'];

					$focus->parent_name=$r["name"];//$account->name;
					$focus->parent_address_street=$a;//$account->shipping_address_street;
					$focus->parent_address_city=$b;//$account->shipping_address_city;
					$focus->parent_address_postalcode=$c;//$account->shipping_address_postalcode;
					$focus->parent_address_country=$d;//$account->shipping_address_country;
 
					$ra=array();
					$total=0;
					
							
					
					if(count($pr)>0){
					foreach($pr as $prod){
						$product_id="";
						//$w=$GLOBALS['db']->query("select id as ecmproduct_id from ecmproducts where code='".$prod['Line']['Line-Item']['CODE']."' and deleted='0' and code NOT LIKE '%_w' and code NOT LIKE '%_z' and code NOT LIKE '%_W' and code NOT LIKE '%_Z'");
						$w=$GLOBALS['db']->query("select `id` as `ecmproduct_id` from `ecmproducts` where `id`='".$prod['Line']['Line-Item']['CODE']."' and `deleted`='0' and `code` NOT LIKE '%_w' and `code` NOT LIKE '%_z' and `code` NOT LIKE '%_W' and `code` NOT LIKE '%_Z'");
						$r=$GLOBALS['db']->fetchByAssoc($w);
						$product_id=$r['ecmproduct_id'];

						$wp=$GLOBALS['db']->query("select * from `ecmproducts` where `id`='".$product_id."'");
						$rppp=$GLOBALS['db']->fetchByAssoc($wp);
						$product_code=$rppp['code'];
						$product_name=$rppp['name'];
						$vat_id=$rppp['vat_id'];
						$vat_name=$rppp['vat_name'];
						$vat_value=$rppp['vat_value'];

						$return_array['id'] = $product_id;
					    $return_array['code'] = $product_code;
					    $return_array['name'] = $product_name;
					    $return_array['quantity'] = $prod['Line']['Line-Item']['OrderedQuantity'];
					    $return_array['price'] = $prod['Line']['Line-Item']['OrderedUnitNetPrice'];
        				$return_array['discount'] = 0;
					    $return_array['total'] = $prod['Line']['Line-Item']['OrderedQuantity']*$prod['Line']['Line-Item']['OrderedUnitNetPrice'];
        				$return_array['unit_id'] = 1;
        				$return_array['unit_name'] = 'szt.';
        				$return_array['vat_id'] = $vat_id;
        				$return_array['vat_name'] = $vat_name;
        				$return_array['vat_value'] = $vat_value;      
        				$return_array['currency_id'] = 'PLN';  
						$return_array['recipient_code'] = $prod['Line']['Line-Item']['BuyerItemCode'];
						$total+=$return_array['quantity']*$return_array['price']*(1+$vat_value/100);
						$ra[]=$return_array; 
					}
					}
					$focus->position_list = $ra;
					$return_id=$focus->save_from_shop($presta, $user);
					$GLOBALS['db']->query("update `ecmsales` set `total`='".$total."' where `id`='".$return_id."'");

					return $return_id;
					
					
					//return print_r(mysql_error()."mm", true);
				
				}
			}
			
		} catch(Exception $e) {}		
		
	}	 
	
	return $y;
	

}


$server->wsdl->addComplexType(
    'ecmorder',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'order_id' => array('name'=>'order_id','type'=>'xsd:string'),
        'order_status' => array('name'=>'order_status', 'type'=>'xsd:string'),
    )
);

$server->wsdl->addComplexType(
    'ecmorders_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmorder[]')
    ),
    'tns:ecmorder'
);

$server->register(
	'ecm_get_orders_states',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'ids' => 'xsd:string[]'),
    array('return'=>'tns:ecmorders_array'),
    $NAMESPACE);

function ecm_get_orders_states($user_name, $password, $ids) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	
	if(!empty($ids)) {
		foreach($ids as $id) {
			if(!empty($id)) {
				$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select status from ecmsales where id='".$id."'"));
				$return_array[] = array(
					'order_id' => $id,           //$order->getId();
					'order_status' => $r['status'],       //$order->getStatus();
				);
				
			} 
			
		}
	}

	return $return_array;
	
}
//add mz 2012-05-01
$server->register(
 'ecm_get_product_codes',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'pricebook'=>'xsd:string', 'lang'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

function ecm_get_product_codes($user_name, $password, $pricebook, $lang) {

	if(!validate_user($user_name, $password))
		return 0;

	if((!empty($pricebook)) && (!empty($lang))) {				
		$w=$GLOBALS['db']->query("select distinct p.code as code, p.product_picture as pp from ecmproducts as p inner join ecmproduct_language as e on e.ecmproduct_id=p.id inner join ecmpricebooks_ecmproducts as cp on p.id=cp.ecmproduct_id inner join ecmpricebooks as c on cp.ecmpricebook_id=c.id where c.name like '".$pricebook."' and p.deleted='0' and p.code!='' and p.product_active='1' and p.name!='' and upper(e.language)='".strtoupper($lang)."' and e.long_description!='' order by p.code desc");
		
		while($r=$GLOBALS['db']->fetchByAssoc($w)){
		if(file_exists("modules/EcmProducts/upload/images/big/".$r['pp'])){
				$products_array[]=$r['code'];	
			}
		}
	}

	return empty($products_array) ? "" : base64_encode(serialize($products_array));
	
}

$server->register(
 'ecm_get_products_to_import_by_code',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'codes' => 'xsd:string', 'lang' => 'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

function ecm_get_products_to_import_by_code($user_name, $password, $codes, $lang) {

	if(!validate_user($user_name, $password))
		return 0;
	
	include_once("modules/EcmProducts/xml_template.php");

		
	if(!empty($codes)) {
	
		$codes =unserialize(base64_decode($codes));
		$codes = implode("','", $codes);
		
		$query = "select distinct p.id as id,p.product_picture as pp from ecmproducts as p inner join ecmproduct_language as e on e.ecmproduct_id=p.id WHERE p.deleted='0' and p.code IN ('".$codes."') and p.product_active='1' and p.name!='' and upper(e.language)='".strtoupper($lang)."' and e.long_description!='' order by p.date_modified desc limit 200";

		$w=$GLOBALS['db']->query($query);
		
		while($r=$GLOBALS['db']->fetchByAssoc($w)){
		if(file_exists("modules/EcmProducts/upload/images/big/".$r['pp'])){
				$products_array[]=xml($r['id'],$lang,1);	
			}
		}
	}

	return empty($products_array) ? "" : base64_encode(serialize($products_array));
	
}

//end mz
//********************************
//DK, more7 gmbh, ca@more7.com ***

$server->register(
 'ecm_get_products_to_import_modified_from',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'datetime' => 'xsd:string', 'lang' => 'xsd:string', 'import_srp_price' => 'xsd:int'),
    array('return'=>'xsd:string'),
    $NAMESPACE);

function ecm_get_products_to_import_modified_from($user_name, $password, $datetime, $lang, $import_srp_price = 0,$pricebook="") {


	
	if(!validate_user($user_name, $password))
		return 0;
	include_once("modules/EcmProducts/xml_template.php");

	if(!empty($datetime)) {
		if($import_srp_price)$name="www.e5";
		else $name="leobite".$lang;
		if($pricebook)$name=$pricebook;
		//$w=$GLOBALS['db']->query("select distinct p.id as id,p.product_picture as pp from ecmproducts as p inner join ecmproduct_language as e on e.ecmproduct_id=p.id inner join ecmpricebooks_ecmproducts as cp on p.id=cp.ecmproduct_id inner join ecmpricebooks as c on cp.ecmpricebook_id=c.id where c.name like '".$name."' and p.deleted='0' and p.date_modified>='".$datetime."' and p.code!='' and p.product_active='1' and p.name!='' and upper(e.language)='".strtoupper($lang)."' and e.long_description!='' order by p.date_modified desc limit 200");
				
		$w=$GLOBALS['db']->query("select distinct p.id as id,p.product_picture as pp from ecmproducts as p inner join ecmproduct_language as e on e.ecmproduct_id=p.id inner join ecmpricebooks_ecmproducts as cp on p.id=cp.ecmproduct_id inner join ecmpricebooks as c on cp.ecmpricebook_id=c.id where c.name like '".$name."' and p.deleted='0' and p.date_modified>='".$datetime."' and p.code!='' and p.product_active='1' and p.name!='' and upper(e.language)='".strtoupper($lang)."' and e.long_description!='' order by p.date_modified desc limit 5");
				
		//return "select distinct p.id as id,p.product_picture as pp, p.code as code from ecmproducts as p inner join ecmproduct_language as e on e.ecmproduct_id=p.id inner join ecmpricebooks_ecmproducts as cp on p.id=cp.ecmproduct_id inner join ecmpricebooks as c on cp.ecmpricebook_id=c.id where c.name like '".$name."' and p.deleted='0' and p.date_modified>='".$datetime."' and p.code!='' and p.product_active='1' and p.name!='' and upper(e.language)='".strtoupper($lang)."' and e.long_description!='' order by p.date_modified desc limit 200";
		
		while($r=$GLOBALS['db']->fetchByAssoc($w)){
		if(file_exists("modules/EcmProducts/upload/images/big/".$r['pp'])){
				$products_array[]=xml($r['id'],$lang,$import_srp_price);	
			}

		}
	}

	return empty($products_array) ? "" : base64_encode(serialize($products_array));
	
}

//DK, more7 gmbh, ca@more7.com ***

$server->wsdl->addComplexType(
    'ecmproduct',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'product_id' => array('name'=>'product_id','type'=>'xsd:string'),
        'product_re' => array('name'=>'product_re', 'type'=>'xsd:string'),
    	'product_name' => array('name'=>'product_name', 'type'=>'xsd:string'),
    	'product_inventory_state' => array('name' => 'product_inventory_state', 'type' => 'xsd:int'),	
    )
);

$server->wsdl->addComplexType(
    'ecmproduct_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmproduct[]')
    ),
    'tns:ecmproduct'
);

$server->register(
	'ecm_get_products_inventory_states',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'ids' => 'xsd:string[]', 'res' => 'xsd:string[]', 'inventory_id' => 'xsd:string'),
    array('return'=>'tns:ecmproduct_array'),
    $NAMESPACE);

function ecm_get_products_inventory_states($user_name, $password, $ids, $res, $inventory_id = null) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	
	if(!empty($ids)) {
		foreach($ids as $id) {
			if(!empty($id)) {
				if($id == 'IDTEST1') {
					$return_array[] = array(
						'product_id' => 'IDTEST1',
						'product_re' => 'RETEST1',
						'product_inventory_state' => !empty($inventory_id) ? 111111 : 111,
					);
				} else {
					if($inventory_id)$invid=" and stock_id='".$inventory_id."'";
					else $invid="";
					$qty=0;
					$w=$GLOBALS['db']->query("select quantity,product_id from ecmstockstates where product_id='".$id."'".$invid);
					while($r=$GLOBALS['db']->fetchByAssoc($w)){
						$qty+=$r['quantity'];
					}
					$return_array[]=array(
						'product_id'=>$r['product_id'],
						'product_re'=>$re,
						'product_inventory_state'=>$qty,
					);
					/**
					 * jesli jest inventory_id to stan produktu na magazynie inventory_id jesli nie ma inventory_id to stan ogolny
					 */
					
					//laduje $product po $id i dodaje parametry do tablicy jesli istnieje
					//przyklad
					/*
					$return_array[] = array(
						'product_id' => '',           //$product->getId();
						'product_re' => '',           //$product->getRe();
						'product_inventory_state' => 0,   //$product->getInventoryState();
					);
					*/
					
				}
			} 
		}
	}

	if(!empty($res)) {
		foreach($res as $re) {
			if(!empty($re)) {
				if($re == 'RETEST2') {
					$return_array[] = array(
						'product_id' => 'IDTEST2',
						'product_re' => 'RETEST2',
						'product_inventory_state' =>  !empty($inventory_id) ? 222222 : 222,
					);
				} else {
					if($inventory_id)$invid=" and stock_id='".$inventory_id."'";
					else $invid="";
					$qty=0;
					$w=$GLOBALS['db']->query("select quantity,product_id from ecmstockstates where product_code like '".strtoupper($re)."'".$invid);
					while($r=$GLOBALS['db']->fetchByAssoc($w)){
						$qty+=$r['quantity'];
					}
					$return_array[]=array(
						'product_id'=>$r['product_id'],
						'product_re'=>$re,
						'product_inventory_state'=>$qty,
					);
					//laduje $product po $re i dodaje parametry do tablicy jesli istnieje
					//przyklad
					/*
					$return_array[] = array(
						'product_id' => '',           //$product->getId();
						'product_re' => '',           //$product->getRe();
						'product_inventory_state' => 0,   //$product->getInventoryState();
					);
					*/
				}
			} 
		}
	}
		
	return $return_array;
	
}




$server->wsdl->addComplexType(
    'ecmpaymentcondition',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string'),
    	'weight_from' => array('name'=>'weight_from', 'type'=>'xsd:float'),
    	'weight_to' => array('name' => 'weight_to', 'type' => 'xsd:float'),
    	'price' => array('name' => 'price', 'type' => 'xsd:float'),	
    	'currency' => array('name' => 'currency', 'type' => 'xsd:string'),
    	'type' => array('name' => 'type', 'type' => 'xsd:string'),
    )
);

$server->wsdl->addComplexType(
    'ecmpaymentcondition_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmpaymentcondition[]')
    ),
    'tns:ecmpaymentcondition'
);

$server->register(
	'ecm_get_paymentconditions',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'lang' => 'xsd:string'),
    array('return'=>'tns:ecmpaymentcondition_array'),
    $NAMESPACE);

function ecm_get_paymentconditions($user_name, $password, $lang) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	
	if(!empty($lang)) {

		if($lang == 'test') {
			$return_array[] = array(
				'id' => '31231241341',
				'name' => "Za pobraniem 0-2kg",
				'weight_from' => 0.0,
				'weight_to' => 2.0,
				'price' => 10.0,				
				'currency' => 'PLN',
				'type' => 'on_delivery',
			);
			$return_array[] = array(
				'id' => '34524512345',
				'name' => "Za pobraniem 2-5kg",
				'weight_from' => 2.0,
				'weight_to' => 5.0,
				'price' => 14.0,				
				'currency' => 'PLN',
				'type' => 'on_delivery',
			);		
			$return_array[] = array(
				'id' => '5674567467',
				'name' => "Za pobraniem 5-10kg",
				'weight_from' => 5.0,
				'weight_to' => 10.0,
				'price' => 20.0,				
				'currency' => 'PLN',
				'type' => 'on_delivery',
			);		
			$return_array[] = array(
				'id' => '7890987089',
				'name' => "Za pobraniem 10-30kg",
				'weight_from' => 10.0,
				'weight_to' => 30.0,
				'price' => 30.0,				
				'currency' => 'PLN',
				'type' => 'on_delivery',
			);				
		} else {
			$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select id from users where user_name='leobite' and deleted='0'"));
			$w=$GLOBALS['db']->query("select * from ecmpaymentconditions where assigned_user_id='".$r['id']."' and deleted='0'");
			while($r=$GLOBALS['db']->fetchByAssoc($w)){
				if($r['payment_method']==1)$m="on_delivery";
				else $m="cash";
				$return_array[] = array(
				'id' => $r['id'],
				'name' => $r['name'],
				'weight_from' => $r['weight_from'],
				'weight_to' => $r['weight_to'],
				'price' => $r['price'],				
				'currency' => 'PLN',
				'type' => $m,
				);
			}
			
		}
	}
		
	return $return_array;
	
}

//********************************

$server->wsdl->addComplexType(
    'ecmpricebook',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'code' => array('name'=>'code','type'=>'xsd:string'),
        'price' => array('name'=>'price', 'type'=>'xsd:float'),
	 'popular' => array('name'=>'popular', 'type'=>'xsd:int'),
	 'pos' => array('name'=>'pos', 'type'=>'xsd:int'),
    )
);

$server->wsdl->addComplexType(
    'ecmpricebooks_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmpricebook[]')
    ),
    'tns:ecmpricebook'
);
$server->register(
	'ecm_get_prices',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'name' => 'xsd:string'),
    array('return'=>'tns:ecmpricebooks_array'),
    $NAMESPACE);

function ecm_get_prices($user_name, $password, $name) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select id from ecmpricebooks where name like '".$name."' and deleted='0'"));
	$w=$GLOBALS['db']->query("select p.code,e.price,e.popular,p.srp_price,p.vat_value,e.position as position from ecmpricebooks_ecmproducts as e inner join ecmproducts as p on p.id=e.ecmproduct_id and e.deleted='0' and e.ecmpricebook_id='".$r['id']."'");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		if($name=="www.e5" || $name=="TrunkHead")$fp=$r["srp_price"]/(1+$r['vat_value']/100);
		else $fp=$r["price"];
		$return_array[]=array("code"=>$r['code'],"popular"=>$r['popular'],"price"=>$fp,"pos"=>$r['position']);
	}
	return $return_array;

}

//*******************************PRODUCTS image*

$server->wsdl->addComplexType(
    'ecm_get_products_image2',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'zl' => array('name'=>'zl', 'type'=>'xsd:string'),
        'euro' => array('name'=>'euro', 'type'=>'xsd:string')
      
    )
);
 
$server->wsdl->addComplexType(
    'ecmimage_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecm_get_products_image2[]')
    ),
    'tns:ecm_get_products_image2'
);
$server->register(
	'ecm_get_products_image',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'id' => 'xsd:string'),
    array('return'=>'tns:ecmimage_array'),
    $NAMESPACE);

function ecm_get_products_image($user_name, $password, $id) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
 
/*
	$return_array = array();	
	$w=$GLOBALS['db']->query("SELECT `p`.`product_picture` FROM `ecmproducts` `p` WHERE `p`.`id`='".$id."'");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("image"=>$r['product_picture']);
	} */
	 
	/*$return_array = array();	
	$w=$GLOBALS['db']->query("SELECT `p`.`short_description`, `p`.`long_description` FROM `ecmproduct_language` `p` WHERE `p`.`ecmproduct_id`='".$id."' and `p`.`language`='pl'");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array(
		"name_pl"=>$r['short_description'],
		"name_en"=>$r['long_description']
		);
	} */
	
	$return_array = array();	
	$w=$GLOBALS['db']->query("SELECT `p`.`srp_price`, `p`.`srp_price_eur` FROM `ecmproducts` `p` WHERE `p`.`id`='".$id."' AND `p`.`deleted`='0'");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array(
		"zl"=>$r['srp_price'],
		"euro"=>$r['srp_price_eur']
		);
	} 
	
	return $return_array;

}


//*******************************PRODUCTS*


$server->wsdl->addComplexType(
    'ecmproducts',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string'),
        'name_en' => array('name'=>'name_en', 'type'=>'xsd:string'),
        'description' => array('name'=>'description', 'type'=>'xsd:string'),
        'description_en' => array('name'=>'description_en', 'type'=>'xsd:string'),
        'deleted' => array('name'=>'deleted', 'type'=>'xsd:int'),
        'code' => array('name'=>'code', 'type'=>'xsd:string'),
        'manufacturer_id' => array('name'=>'manufacturer_id', 'type'=>'xsd:string'),
        'srp_price' => array('name'=>'srp_price', 'type'=>'xsd:float'),
        'srp_price_eur' => array('name'=>'srp_price_eur', 'type'=>'xsd:float'),
        'pl_vat' => array('name'=>'pl_vat', 'type'=>'xsd:float'),
        'image' => array('name'=>'image', 'type'=>'xsd:string'),
        'popular' => array('name'=>'popular', 'type'=>'xsd:string')
    )
);
 
$server->wsdl->addComplexType(
    'ecmproducts_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmproducts[]')
    ),
    'tns:ecmproducts'
);
$server->register(
	'ecm_get_products2',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'category' => 'xsd:string', 'lang' => 'xsd:int'),
    array('return'=>'tns:ecmproducts_array'),
    $NAMESPACE);

function ecm_get_products2($user_name, $password, $category, $lang, $pricebook, $date = "") {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	if ($lang == 1) $lang = "pl";
	if ($lang == 2) $lang = "en";

	$return_array = array();	
	$w=$GLOBALS['db']->query("SELECT `p`.`id`, `p`.`name`, `l`.`long_description`, 
	`l_en`.`short_description` as `name_en`, `l_en`.`long_description` as `long_description_en`, 
	`pbp`.`deleted`, 
`p`.`code`, `p`.`manufacturer_id`, `p`.`srp_price`, `p`.`srp_price_eur`, 
`v`.`value`, `p`.`product_picture`, `pbp`.`popular` FROM `crm`.`ecmproducts` `p` 
JOIN `crm`.`ecmvats` `v` ON `v`.`id`=`p`.`vat_id` AND `v`.`deleted`='0' 
JOIN `crm`.`ecmpricebooks_ecmproducts` `pbp` ON `pbp`.`ecmproduct_id`=`p`.`id` 
AND `pbp`.`ecmpricebook_id`='".$category."' JOIN `crm`.`ecmproduct_language` `l` 
ON `l`.`ecmproduct_id`=`p`.`id` AND `l`.`language`='pl' 
JOIN `crm`.`ecmproduct_language` `l_en` 
ON `l_en`.`ecmproduct_id`=`p`.`id` AND `l_en`.`language`='en' 
".($date != "" ? "WHERE `p`.`date_modified`>'".$date."'" : ""));
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "name"=>$r['name'],
							  "name_en"=>$r['name_en'],
							  "description"=>$r['long_description'],
							  "description_en"=>$r['long_description_en'],
							  "deleted"=>$r['deleted'],
							  "code"=>$r['code'],
							  "manufacturer_id"=>$r['manufacturer_id'],
							  "srp_price"=>$r['srp_price'],
							  "srp_price_eur"=>$r['srp_price_eur'],
							  "pl_vat"=>$r['value'],
							  "image"=>$r['product_picture'],
							  "popular"=>$r['popular']
							 );
	}
	return $return_array;

}


$server->wsdl->addComplexType(
    'ecmproducts',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string'),
        'name_en' => array('name'=>'name_en', 'type'=>'xsd:string'),
        'description' => array('name'=>'description', 'type'=>'xsd:string'),
        'description_en' => array('name'=>'description_en', 'type'=>'xsd:string'),
        'deleted' => array('name'=>'deleted', 'type'=>'xsd:int'),
        'code' => array('name'=>'code', 'type'=>'xsd:string'),
        'manufacturer_id' => array('name'=>'manufacturer_id', 'type'=>'xsd:string'),
        'srp_price' => array('name'=>'srp_price', 'type'=>'xsd:float'),
        'srp_price_eur' => array('name'=>'srp_price_eur', 'type'=>'xsd:float'),
        'pl_vat' => array('name'=>'pl_vat', 'type'=>'xsd:float'),
        'image' => array('name'=>'image', 'type'=>'xsd:string'),
        'popular' => array('name'=>'popular', 'type'=>'xsd:string')
    )
);
 
$server->wsdl->addComplexType(
    'ecmproducts_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmproducts[]')
    ),
    'tns:ecmproducts'
);
$server->register(
	'ecm_get_products',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'category' => 'xsd:string', 'lang' => 'xsd:int'),
    array('return'=>'tns:ecmproducts_array'),
    $NAMESPACE);

function ecm_get_products($user_name, $password, $category, $lang, $pricebook, $date = "") {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	if ($lang == 1) $lang = "pl";
	if ($lang == 2) $lang = "en";
 
	$return_array = array();	
	$w=$GLOBALS['db']->query("SELECT `p`.`id`, `p`.`name`, `l`.`long_description`, `l_en`.`short_description` as `name_en`, `l_en`.`long_description` as `long_description_en`, `pbp`.`deleted`, `p`.`code`, `p`.`manufacturer_id`, `p`.`srp_price`, `p`.`srp_price_eur`, `v`.`value`, `p`.`product_picture`, `pbp`.`popular` FROM `ecmproducts` `p` JOIN `ecmvats` `v` ON `v`.`id`=`p`.`vat_id` AND `v`.`deleted`='0' JOIN `ecmpricebooks_ecmproducts` `pbp` ON `pbp`.`ecmproduct_id`=`p`.`id` AND `pbp`.`ecmpricebook_id`='".$pricebook."' JOIN `ecmproduct_language` `l` ON `l`.`ecmproduct_id`=`p`.`id` AND `l`.`language`='pl' JOIN `ecmproduct_language` `l_en` ON `l_en`.`ecmproduct_id`=`p`.`id` AND `l_en`.`language`='en' WHERE `p`.`product_category_id`='".$category."'".($date != "" ? " AND `p`.`date_modified`>'".$date."'" : ""));
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "name"=>$r['name'],
							  "name_en"=>$r['name_en'],
							  "description"=>$r['long_description'],
							  "description_en"=>$r['long_description'],
							  "deleted"=>$r['deleted'],
							  "code"=>$r['code'],
							  "manufacturer_id"=>$r['manufacturer_id'],
							  "srp_price"=>$r['srp_price'],
							  "srp_price_eur"=>$r['srp_price_eur'],
							  "pl_vat"=>$r['value'],
							  "image"=>$r['product_picture'],
							  "popular"=>$r['popular']
							 );
	}
	return $return_array;

}

//*******************************ADD SALES*
$server->register(
	'ecm_add_order_from_shop',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'order' => 'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);


function ecm_add_order_from_shop_new($user_name, $password, $order, $presta) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	/*if(!empty($order)) {
		
		try {
			
			$order = unserialize(base64_decode($order));
			//return print_r($order);
			if(!empty($order) && is_array($order)) {
				
				if($order['Order-Header']['OrderNumber'] == "ORDERTEST1234")
					return "IDTEST1234";
				else {					
					require_once("modules/EcmSales/EcmSale.php");
					$focus=new EcmSale();
		
					$template_id="97700b0d-fbe9-e366-4016-4b260f058a47";
	
					$focus->template_id=$template_id;
					$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from ecmdocumenttemplates where id='".$template_id."'"));
					$focus->template_name=$r['name'];
					$focus->setTemplate();
					$focus->number=$focus->generateNumber();
					$focus->document_no=$focus->formatNumber();
					$focus->currency_id="PLN";
					$focus->ecmlanguage="pl_pl";
					$focus->status="s10";
					$focus->type="sales_order";
					$focus->modified_user_id="d09b87cf-efff-2f7c-a859-4ba38402488f";
					$focus->created_by="d09b87cf-efff-2f7c-a859-4ba38402488f";

					$pr=$order['Order-Lines'];
					
					$focus->assigned_user_id="d09b87cf-efff-2f7c-a859-4ba38402488f";
					$focus->register_date=$order['Order-Header']['OrderDate'];
					$focus->delivery_date=$order['Order-Header']['ExpectedDeliveryDate'];
					//$focus->supplier_code=3442;
					$focus->order_no=$order['Order-Header']['OrderNumber'];
					$focus->ecmlanguage="pl_pl";
					$focus->ecmpaymentcondition_id=$order['Order-Parties']['Buyer']['PaymentConditionId'];

					$focus->parent_name=$account->name;
					$focus->parent_address_street=$account->shipping_address_street;
					$focus->parent_address_city=$account->shipping_address_city;
					$focus->parent_address_postalcode=$account->shipping_address_postalcode;
					$focus->parent_address_country=$account->shipping_address_country;

					$ra=array();
					$total=0;
					
					if(count($pr)>0){
					foreach($pr as $prod){
						$product_id="";
						$w=$GLOBALS['db']->query("select id as ecmproduct_id from ecmproducts where code='".$prod['Line']['Line-Item']['CODE']."' and deleted='0' and code NOT LIKE '%_w' and code NOT LIKE '%_z' and code NOT LIKE '%_W' and code NOT LIKE '%_Z'");
						$r=$GLOBALS['db']->fetchByAssoc($w);
						$product_id=$r['ecmproduct_id'];

						$wp=$GLOBALS['db']->query("select * from ecmproducts where id='".$product_id."'");
						$rppp=$GLOBALS['db']->fetchByAssoc($wp);
						$product_code=$rppp['code'];
						$product_name=$rppp['name'];
						$vat_id=$rppp['vat_id'];
						$vat_name=$rppp['vat_name'];
						$vat_value=$rppp['vat_value'];

						$return_array['id'] = $product_id;
					    $return_array['code'] = $product_code;
					    $return_array['name'] = $product_name;
					    $return_array['quantity'] = $prod['Line']['Line-Item']['OrderedQuantity'];
					    $return_array['price'] = $prod['Line']['Line-Item']['OrderedUnitNetPrice'];
        				$return_array['discount'] = 0;
					    $return_array['total'] = $prod['Line']['Line-Item']['OrderedQuantity']*$prod['Line']['Line-Item']['OrderedUnitNetPrice'];
        				$return_array['unit_id'] = 1;
        				$return_array['unit_name'] = 'szt.';
        				$return_array['vat_id'] = $vat_id;
        				$return_array['vat_name'] = $vat_name;
        				$return_array['vat_value'] = $vat_value;      
        				$return_array['currency_id'] = 'PLN';  
						$return_array['recipient_code'] = $prod['Line']['Line-Item']['BuyerItemCode'];
						$total+=$return_array['quantity']*$return_array['price']*(1+$vat_value/100);
						$ra[]=$return_array; 
					}
					}
					$focus->position_list = $ra;
					$return_id=$focus->save_from_shop($presta);
					$GLOBALS['db']->query("update ecmsales set total='".$total."' where id='".$return_id."'");

					return array($return_array, $return_id);
					//return print_r(mysql_error()."mm", true);
				
				}
			}
			
		} catch(Exception $e) {}
		
	}*/
	
	return;
	

}


//*******************************PRICEBOOK PRODUCTS*

$server->wsdl->addComplexType(
    'ecmpricebook_products',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'ecmproduct_id' => array('name'=>'ecmproduct_id', 'type'=>'xsd:string'),
        'price' => array('name'=>'price', 'type'=>'xsd:float'),
        'popular' => array('name'=>'popular', 'type'=>'xsd:int'),
        'deleted' => array('name'=>'deleted', 'type'=>'xsd:int'),
        'vat' => array('name'=>'vat', 'type'=>'xsd:int')
    )
);
 
$server->wsdl->addComplexType(
    'ecmpricebook_products_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmpricebook_products[]')
    ),
    'tns:ecmpricebook_products'
);
$server->register(
	'ecm_get_pricebook_products',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string'),
    array('return'=>'tns:ecmpricebook_products_array'),
    $NAMESPACE);

function ecm_get_pricebook_products($user_name, $password, $pricebook) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	//$w=$GLOBALS['db']->query("SELECT `ecmproduct_id`, `price`, `popular`, `deleted` FROM `ecmpricebooks_ecmproducts` WHERE `ecmpricebook_id`='".$pricebook."'".($date != "" ? " AND `date_modified`>'".$date."'" : ""));
	//$w=$GLOBALS['db']->query("SELECT `ecmproduct_id`, `price`, `popular`, `deleted` FROM `ecmpricebooks_ecmproducts` WHERE `ecmpricebook_id`='".$pricebook."'");
	$w=$GLOBALS['db']->query("SELECT `pp`.`ecmproduct_id`, `pp`.`price`, `pp`.`popular`, `pp`.`deleted`, `p`.`vat_value` FROM 
`crm`.`ecmpricebooks_ecmproducts` `pp`
JOIN `crm`.`ecmproducts` `p` ON `p`.`id`=`pp`.`ecmproduct_id`
WHERE `pp`.`ecmpricebook_id`='".$pricebook."'");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "ecmproduct_id"=>$r['ecmproduct_id'],
							  "price"=>$r['price'],
							  "popular"=>$r['popular'],
							  "deleted"=>$r['deleted'],
							  "vat"=>$r['vat_value']
							 );
	}
	return $return_array;

}

//*******************************PRICEBOOKS*

$server->wsdl->addComplexType(
    'ecmpricebooks',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id', 'type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string')
    )
);
 
$server->wsdl->addComplexType(
    'ecmpricebooks_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmpricebooks[]')
    ),
    'tns:ecmpricebooks'
);
$server->register(
	'ecm_get_pricebooks',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string'),
    array('return'=>'tns:ecmpricebooks_array'),
    $NAMESPACE);

function ecm_get_pricebooks($user_name, $password, $pricebook) {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	//$w=$GLOBALS['db']->query("SELECT `id`, `name` FROM `ecmpricebooks` WHERE `id`='".$pricebook."'");
	$w=$GLOBALS['db']->query("SELECT `id`, `name` FROM `ecmpricebooks`");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "name"=>$r['name']
							 );
	}
	return $return_array;

}
//*******************************CATEGORIES*

$server->wsdl->addComplexType(
    'ecmcategories',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string'),
        'name_en' => array('name'=>'name_en', 'type'=>'xsd:string'),
        'description' => array('name'=>'description', 'type'=>'xsd:string'),
    )
);

$server->wsdl->addComplexType(
    'ecmcategories_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmcategories[]')
    ),
    'tns:ecmcategories'
);
$server->register(
	'ecm_get_categories',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'pricelist' => 'xsd:string'),
    array('return'=>'tns:ecmcategories_array'),
    $NAMESPACE);

function ecm_get_categories($user_name, $password, $pricelist) {

	$GLOBALS['db']->query("INSERT INTO log VALUES ('ńńńńń')");
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	
	//$w = $GLOBALS['db']->query("SELECT `c`.`id`, `c`.`name`, `c`.`name-en`, `c`.`description` FROM `ecmproductcategories` `c` where `c`.`local_transportation`!='0' AND (SELECT count(`p`.`id`) FROM `ecmproducts` `p` JOIN `ecmpricebooks_ecmproducts` `pbp` ON  `pbp`.`ecmpricebook_id`='".$pricelist."' AND `pbp`.`ecmproduct_id`=`p`.`id` WHERE `p`.`product_category_id`=`c`.`id` AND `pbp`.`deleted`='0') > 0 AND `c`.`deleted`='0'");
	//$w = $GLOBALS['db']->query("SET NAMES `latin2`");;
	
	
	$w = $GLOBALS['db']->query("SELECT `c`.`id`, `c`.`name`, `c`.`name_en`, `c`.`description` FROM `ecmproductcategories` `c` where (SELECT count(`p`.`id`) FROM `ecmproducts` `p` JOIN `ecmpricebooks_ecmproducts` `pbp` ON  `pbp`.`ecmpricebook_id`='".$pricelist."' AND `pbp`.`ecmproduct_id`=`p`.`id` WHERE `p`.`product_category_id`=`c`.`id` AND `pbp`.`deleted`='0') > 0 AND `c`.`deleted`='0'");
	while($r = $GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "name"=>$r['name'],
							  "name_en"=>$r['name_en'],
							  "description"=>$r['description']);
	}
	 
		
	return $return_array;

}

//*******************************accounts_shop*


//

//

$server->wsdl->addComplexType(
    'ecmcustomer_add',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'status' => array('name'=>'status','type'=>'xsd:string')
    )
);

$server->wsdl->addComplexType(
    'ecmcustomer_add_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmcategories[]')
    ),
    'tns:ecmcustomer_add'
);
$server->register(
	'ecm_get_customer_add',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'pricelist' => 'xsd:string'),
    array('return'=>'tns:ecmcustomer_add_array'),
    $NAMESPACE);

function ecm_get_customer_add($user_name, $password, $fullname = "", $pricebook = "", $shop_user = "", $email = "", $edit = false, $id = "", $street = "", $company="", $city = "", $code = "", $nip = "", $phone = "") {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	
	if (!$edit) {
	
	 $getID = create_guid();
	$w=$GLOBALS['db']->query("INSERT INTO `accounts` SET `id`='".$getID."', `name`='".$fullname."', `date_entered`='".date("Y-m-d H:i:s")."', `date_modified`='".date("Y-m-d H:i:s")."', `ecmpricebook_id`='".$pricebook."', `shop_user`='".$shop_user."', `email`='".$email."'");

		$return_array[]=array("status"=>$getID);

	} else {
	
	if ($company != "") $fullname = $company;
	
	$w=$GLOBALS['db']->query("UPDATE `accounts` SET `name`='".$fullname."', `shipping_address_postalcode`='".$code."', `shipping_address_street`='".$street."', `shipping_address_city`='".$city."', `billing_address_postalcode`='".$code."', `billing_address_street`='".$street."', `billing_address_city`='".$city."', `vatid`='".$nip."', `phone_office`='".$phone."', `date_modified`='".date("Y-m-d H:i:s")."' WHERE `id`='".$id."'");
	
		$return_array[]=array("status"=>'ok');
		
	}
	return $return_array;

}

//
 
 
//
$server->wsdl->addComplexType(
    'ecmcategories_a',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string'),
        'description' => array('name'=>'description', 'type'=>'xsd:string'),
        'ecmpricebook_id' => array('name'=>'ecmpricebook_id', 'type'=>'xsd:string'),
        'billing_address_street' => array('name'=>'billing_address_street', 'type'=>'xsd:string'),
        'billing_address_postalcode' => array('name'=>'billing_address_postalcode', 'type'=>'xsd:string'),
        'billing_address_city' => array('name'=>'billing_address_city', 'type'=>'xsd:string'),
        'phone_office' => array('name'=>'phone_office', 'type'=>'xsd:string')
    )
);

$server->wsdl->addComplexType(
    'ecmcategories_a_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmcategories[]')
    ),
    'tns:ecmcategories_a'
);
$server->register(
	'ecm_get_categories_a',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'pricelist' => 'xsd:string'),
    array('return'=>'tns:ecmcategories_a_array'),
    $NAMESPACE);

function ecm_get_categories_a($user_name, $password, $date = "") {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}
	
	$return_array = array();	
	
	//$w = $GLOBALS['db']->query("SELECT `c`.`id`, `c`.`name`, `c`.`description` FROM `ecmproductcategories` `c` where `c`.`local_transportation`!='0' AND (SELECT count(`p`.`id`) FROM `ecmproducts` `p` JOIN `ecmpricebooks_ecmproducts` `pbp` ON  `pbp`.`ecmpricebook_id`='".$pricelist."' AND `pbp`.`ecmproduct_id`=`p`.`id` WHERE `p`.`product_category_id`=`c`.`id` AND `pbp`.`deleted`='0') > 0 AND `c`.`deleted`='0'");
	$w=$GLOBALS['db']->query("SELECT `a`.`ecmpricebook_id`, `a`.`shop_user`, `a`.`id`, `a`.`name`, `a`.`deleted`, `a`.`billing_address_street`, `a`.`billing_address_postalcode`, `a`.`billing_address_city`, `a`.`phone_office`, `a`.`vatid`, `a`.`is_vat_free` FROM `accounts` `a` ".($date != "" ? " WHERE `a`.`date_modified`>'".$date."'" : ""));
	while($r = $GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "name"=>$r['name'],
							  "description"=>$r['description'],
							  "ecmpricebook_id"=>$r['ecmpricebook_id'],
							  "billing_address_street"=>$r['billing_address_street'],
							  "billing_address_postalcode"=>$r['billing_address_postalcode'],
							  "billing_address_city"=>$r['billing_address_city'],
							  "phone_office"=>$r['phone_office']
							  );
	}
	return $return_array;

}

//
  
 
//

$server->wsdl->addComplexType(
    'ecmaccounts_shop',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'id' => array('name'=>'id','type'=>'xsd:string'),
        'name' => array('name'=>'name', 'type'=>'xsd:string'),
        'ecmpricebook_id' => array('name'=>'ecmpricebook_id', 'type'=>'xsd:string'),
        'shop_user' => array('name'=>'shop_user', 'type'=>'xsd:string'),
        'deleted' => array('name'=>'deleted', 'type'=>'xsd:int'),
        'billing_address_street' => array('name'=>'billing_address_street', 'type'=>'xsd:string'),
        'billing_address_postalcode' => array('name'=>'billing_address_postalcode', 'type'=>'xsd:string'),
        'billing_address_city' => array('name'=>'billing_address_city', 'type'=>'xsd:string'),
        'phone_office' => array('name'=>'phone_office', 'type'=>'xsd:string'),
        'vatid' => array('name'=>'vatid', 'type'=>'xsd:string'),
        'is_vat_free' => array('name'=>'is_vat_free', 'type'=>'xsd:string')
    )
);
 
$server->wsdl->addComplexType(
    'ecmaccounts_shop_array',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:ecmaccounts_shop[]')
    ),
    'tns:ecmaccounts_shop'
);
$server->register(
	'ecm_get_accounts_shop',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'date' => 'xsd:string', 'lang' => 'xsd:int'),
    array('return'=>'tns:ecmaccounts_shop_array'),
    $NAMESPACE);

function ecm_get_accounts_shop($user_name, $password, $date = "") {
	
	if(!validate_user($user_name, $password)){
		return 0;
	}

	$return_array = array();	
	$w=$GLOBALS['db']->query("SELECT `a`.`ecmpricebook_id`, `a`.`shop_user`, `a`.`id`, `a`.`name`, `a`.`deleted`, `a`.`billing_address_street`, `a`.`billing_address_postalcode`, `a`.`billing_address_city`, `a`.`phone_office`, `a`.`vatid`, `a`.`is_vat_free` FROM `accounts` `a` ".($date != "" ? " WHERE `a`.`date_modified`>'".$date."'" : ""));
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$return_array[]=array("id"=>$r['id'],
							  "ecmpricebook_id"=>$r['ecmpricebook_id'],
							  "shop_user"=>$r['shop_user'],
							  "name"=>$r['name'],
							  "deleted"=>$r['deleted'],
							  "billing_address_street"=>$r['billing_address_street'],
							  "billing_address_postalcode"=>$r['billing_address_postalcode'],
							  "billing_address_city"=>$r['billing_address_city'],
							  "phone_office"=>$r['phone_office'],
							  "vatid"=>$r['vatid'],
							  "is_vat_free"=>$r['is_vat_free']
							 );
	}
	
	return $return_array;

}

/* MobileConnection Functions
MZ 2012-10-05 */ 
$server->register(
	'mobile_login',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string'),
    array('return'=>'xsd:string'),
    $NAMESPACE);
	
function mobile_login($user_name, $password) {	
	if(!validate_user($user_name, $password)){
		return 0;
	}	
	return 1;
}

$server->register(
	'mobile_select',
    array('user_name'=>'xsd:string', 'password'=>'xsd:string', 'fields'=>'xsd:string', 'where'=>'xsd:string', 'orderby'=>'xsd:string', 'limit'=>'xsd:string', 'module'=>'xsd:string' ),
    array('return'=>'xsd:string'),
    $NAMESPACE);
	
function mobile_select($user_name, $password, $fields, $where, $orderby, $limit, $module, $type="") {

	if(!validate_user($user_name, $password)){
		return 'wrong user';
	}
	
	$fields = json_decode(($fields));
	$where = json_decode(($where));
	$limit = json_decode(($limit));
	
	$query = "SELECT ".implode(",",$fields)." FROM ".strtolower($module);
	if (sizeof($where)>0)
		$query.=" WHERE ".implode(" AND ",$where);
	if ($orderby!="")
		$query.=" ORDER BY ".$orderby;
	if (sizeof($limit)==2)
	    $query.=" LIMIT ".implode(",",$limit);
	$query.=";";
	

	if ($type=='debug') return $query;
	if ($type=="count") {
		$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($query));
		return $r['c'];
	}
	
	$w = $GLOBALS['db']->query($query);
	$return_array = array();
	while ($r = $GLOBALS['db']->fetchByAssoc($w)) {
		$r['name'] = str_replace("&quot;","\"", $r['name']);
		$r['name'] = str_replace("&amp","&", $r['name']);
		$return_array[] = $r;
		}
		

	if (sizeof($return_array)==0) return "0";
	return htmlspecialchars_decode(json_encode($return_array), ENT_QUOTES);	
}
?>