<?php
/*** *** ***
Dev Notes:
Created Jan 24, 2013 by lgaetz - rev. 0 ignore words not used
*** *** ***/

class TAB_Reloaded extends superfecta_base {

    public $description = "Searches The Address Book Reloaded http://sourceforge.net/projects/tab-2/ for appearances of the number and returns the last name and first name, if present, from the contact table.";
    public $version_requirement = "2.11";
    public $source_param = array(
        'tab_server' => array(
            'description' => 'Host address of TAB Reloaded database. (localhost if the database is on the same server as FreePBX)',
            'type' => 'text',
            'default' => 'localhost'
        ),
        'tab_dbase' => array(
            'description' => 'Database name of TAB Reloaded database',
            'type' => 'text',
            'default' => 'tab2'
        ),
		'tab_user' => array(
            'description' => 'Username used to connect to the MySQL database',
            'type' => 'text',
            'default' => 'root'
        ),
        'tab_password' => array(
            'description' => 'Password used to connect to the MySQL database',
            'type' => 'password',
            'default' => 'passw0rd'
        ),
		'tab_digits' => array(
            'description' => 'The number of rightmost digits to check for a match.',
            'type' => 'number',
            'default' => '10'
        ),
		'tab_contact' => array(
            'description' => "Name of the contact table, probably 'contact' with or without a prefix",
            'type' => 'text',
            'default' => 'contact'
        ),
		'tab_properties' => array(
            'description' => "Name of the properties table, probably 'properties' with or without a prefix",
            'type' => 'text',
            'default' => 'properties'
        ),
		
		'Ignore_Keywords' => array(
            'description' => 'If the otherphone table CNAM includes any of the keywords listed here, the otherphone CNAM value will be ignored and the first name last name will be used from the contact table.<br>Seperate keywords with commas.',
            'type' => 'textarea',
            'default' => 'fax, cell, mobile'
        ),
    );


    function get_caller_id($thenumber, $run_param=array()) {
     
		// initialize variables
		$wquery = "";
		$wresult_caller_name = "";
		$wquery_string = "";
		$wquery_result = "";
		$wquery_row = "";
		$caller_id = null;
	 
		//  Field names in the address book tables, these should not change from one TAB install to the next
		$tab_id = "id";			    // name of id field
		$tab_phone1 = "phone1";   	// name of phone1 field in address table
		$tab_phone2 = "phone2";   	// name of phone2 field in address table
		$tab_othernum = "phone";	// name of phone field in otherphone table
		$tab_type = "type";		    // name of type field in otherphone table
		$tab_ln = "lastname";		// name of lastname field in contact table
		$tab_fn = "firstname";		// name of firstname field in contact table

		$this->DebugPrint("Searching The Address Book ... ");
			
		//  trim incoming number to specified filter length
		$thenumber = substr($thenumber, (-1*$run_param['tab_digits']));
	
		// Process ignore words
        $key_words = array();
		$temp_array = explode(',',(isset($run_param['Ignore_Keywords'])?$run_param['Ignore_Keywords']:$source_param['Ignore_Keywords']['default']));
		foreach($temp_array as $val)  {
			$key_words[] = trim($val);
		}

		//  Build regular expression from the modified $thenumber to avoid non-digit characters stored in database
		$wquery = "'[^0-9]*";
		for( $x=0; $x < ((strlen($thenumber))-1); $x++ ) {
			$wquery .=  substr($thenumber,$x,1)."[^0-9]*" ;
		}
		$wquery = $wquery.(substr($thenumber,-1))."([^0-9]+|$)'";

		//  Make a MySQL Connection
		mysql_connect($run_param['tab_server'], $run_param['tab_user'], $run_param['tab_password']) or die(mysql_error());
		mysql_select_db($run_param['tab_dbase']) or die(mysql_error());

		//  Search phone1 and phone2 fields in theaddressbook
		$wquery_string = "SELECT * FROM ".$run_param['tab_contact']." INNER JOIN ".$run_param['tab_properties']." ON ".$run_param['tab_properties'].".id = ".$run_param['tab_contact'].".id WHERE ".$run_param['tab_properties'].".value REGEXP ".$wquery." ORDER BY lastUpdate DESC";
		$wquery_result = mysql_query($wquery_string);

		if (mysql_num_rows($wquery_result)>0)  {
			// If result is found in phone1 or phone2
			$wquery_row = mysql_fetch_array($wquery_result);
			$wresult_caller_name = $wquery_row[$tab_fn]." ".$wquery_row[$tab_ln];
		}
		

		//  Pass result to Superfecta module via $caller_id variable
		if ($wresult_caller_name != "")  {
			$caller_id = trim(strip_tags($wresult_caller_name));
		}       
		
        return($caller_id);
	}
}