';
$log->debug("Exiting get_textmanField method ...");
return $form_field;
}
}
/** Function to get textfield for website field
* @param $label -- field label :: Type string
* @param $name -- field name :: Type string
* @returns $form_field -- return field:: Type string
*/
function get_textwebField($label,$name)
{
global $log;
$log->debug("Entering get_textwebField(".$label.",".$name.") method ...");
$form_field='';
$form_field .='
';
$log->debug("Exiting get_textcomboField method ...");
return $form_field;
}
}
/** Function to get date field
* @param $label -- field label :: Type string
* @param $name -- field name :: Type string
* @param $tid -- tabid :: Type integer
* @returns $form_field -- return field:: Type string
*/
function get_textdateField($label,$name,$tid)
{
global $log;
$log->debug("Entering get_textdateField(".$label.",".$name.",".$tid.") method ...");
global $theme;
global $app_strings;
global $current_user;
$ntc_date_format = $app_strings['NTC_DATE_FORMAT'];
$ntc_time_format = $app_strings['NTC_TIME_FORMAT'];
$form_field='';
$default_date_start = date('Y-m-d');
$default_time_start = date('H:i');
$dis_value=getNewDisplayDate();
if($tid == 2)
{
$form_field .='
';
$log->debug("Exiting get_textdurationField method ...");
return $form_field;
}
}
/** Function to get email text field
* @param $module -- module name :: Type name
* @param $id -- entity id :: Type integer
* @returns $hidden -- hidden:: Type string
*/
//Added to get the parents list as hidden for Emails -- 09-11-2005
function getEmailParentsList($module,$id,$focus = false)
{
global $log;
$log->debug("Entering getEmailParentsList(".$module.",".$id.") method ...");
global $adb, $table_prefix;
// If the information is not sent then read it
if($focus === false) {
if($module == 'Contacts') {
$focus = CRMEntity::getInstance('Contacts');
}
if($module == 'Leads') {
$focus = CRMEntity::getInstance('Leads');
}
$focus->retrieve_entity_info($id,$module);
}
$fieldid = 0;
$fieldname = 'email';
if($focus->column_fields['email'] == '' && $focus->column_fields['yahooid'] != '') {
$fieldname = 'yahooid';
}
$res = $adb->pquery("select * from ".$table_prefix."_field where tabid = ? and fieldname= ? and ".$table_prefix."_field.presence in (0,2)", array(getTabid($module), $fieldname));
$fieldid = $adb->query_result($res,0,'fieldid');
$hidden .= '';
$hidden .= '';
$log->debug("Exiting getEmailParentsList method ...");
return $hidden;
}
/** This Function returns the current status of the specified Purchase Order.
* The following is the input parameter for the function
* $po_id --> Purchase Order Id, Type:Integer
*/
function getPoStatus($po_id)
{
global $log;
$log->debug("Entering getPoStatus(".$po_id.") method ...");
global $log;
$log->info("in getPoName ".$po_id);
global $adb, $table_prefix;
$sql = "select postatus from ".$table_prefix."_purchaseorder where purchaseorderid=?";
$result = $adb->pquery($sql, array($po_id));
$po_status = $adb->query_result($result,0,"postatus");
$log->debug("Exiting getPoStatus method ...");
return $po_status;
}
/** This Function adds the specified product quantity to the Product Quantity in Stock in the Warehouse
* The following is the input parameter for the function:
* $productId --> ProductId, Type:Integer
* $qty --> Quantity to be added, Type:Integer
*/
function addToProductStock($productId,$qty)
{
global $log;
$log->debug("Entering addToProductStock(".$productId.",".$qty.") method ...");
global $adb, $table_prefix;
$qtyInStck=getProductQtyInStock($productId);
$updQty=$qtyInStck + $qty;
$sql = "UPDATE ".$table_prefix."_products set qtyinstock=? where productid=?";
$adb->pquery($sql, array($updQty, $productId));
$log->debug("Exiting addToProductStock method ...");
}
/** This Function adds the specified product quantity to the Product Quantity in Demand in the Warehouse
* @param int $productId - ProductId
* @param int $qty - Quantity to be added
*/
function addToProductDemand($productId,$qty)
{
global $log;
$log->debug("Entering addToProductDemand(".$productId.",".$qty.") method ...");
global $adb, $table_prefix;
$qtyInStck=getProductQtyInDemand($productId);
$updQty=$qtyInStck + $qty;
$sql = "UPDATE ".$table_prefix."_products set qtyindemand=? where productid=?";
$adb->pquery($sql, array($updQty, $productId));
$log->debug("Exiting addToProductDemand method ...");
}
/** This Function subtract the specified product quantity to the Product Quantity in Stock in the Warehouse
* @param int $productId - ProductId
* @param int $qty - Quantity to be subtracted
*/
function deductFromProductStock($productId,$qty)
{
global $log;
$log->debug("Entering deductFromProductStock(".$productId.",".$qty.") method ...");
global $adb, $table_prefix;
$qtyInStck=getProductQtyInStock($productId);
$updQty=$qtyInStck - $qty;
$sql = "UPDATE ".$table_prefix."_products set qtyinstock=? where productid=?";
$adb->pquery($sql, array($updQty, $productId));
$log->debug("Exiting deductFromProductStock method ...");
}
/** This Function subtract the specified product quantity to the Product Quantity in Demand in the Warehouse
* @param int $productId - ProductId
* @param int $qty - Quantity to be subtract
*/
function deductFromProductDemand($productId,$qty)
{
global $log;
$log->debug("Entering deductFromProductDemand(".$productId.",".$qty.") method ...");
global $adb, $table_prefix;
$qtyInStck=getProductQtyInDemand($productId);
$updQty=$qtyInStck - $qty;
$sql = "UPDATE ".$table_prefix."_products set qtyindemand=? where productid=?";
$adb->pquery($sql, array($updQty, $productId));
$log->debug("Exiting deductFromProductDemand method ...");
}
/** This Function returns the current product quantity in stock.
* The following is the input parameter for the function:
* $product_id --> ProductId, Type:Integer
*/
function getProductQtyInStock($product_id)
{
global $log;
$log->debug("Entering getProductQtyInStock(".$product_id.") method ...");
global $adb, $table_prefix;
$query1 = "select qtyinstock from ".$table_prefix."_products where productid=?";
$result=$adb->pquery($query1, array($product_id));
$qtyinstck= $adb->query_result($result,0,"qtyinstock");
$log->debug("Exiting getProductQtyInStock method ...");
return $qtyinstck;
}
/** This Function returns the current product quantity in demand.
* @param int $product_id - ProductId
* @return int $qtyInDemand - Quantity in Demand of a product
*/
function getProductQtyInDemand($product_id)
{
global $log;
$log->debug("Entering getProductQtyInDemand(".$product_id.") method ...");
global $adb, $table_prefix;
$query1 = "select qtyindemand from ".$table_prefix."_products where productid=?";
$result = $adb->pquery($query1, array($product_id));
$qtyInDemand = $adb->query_result($result,0,"qtyindemand");
$log->debug("Exiting getProductQtyInDemand method ...");
return $qtyInDemand;
}
// crmv@187823
/**
* Function to get the vte_table name from 'field' vte_table for the input vte_field based on the module
* @param : string $module - current module value
* @param : string $fieldname - vte_fieldname to which we want the vte_tablename
* @return : string $tablename - vte_tablename in which $fieldname is a column, which is retrieved from 'field' vte_table per $module basis
*
* @warning: This function expects the $fieldname parameter to be a COLUMN name, and the match is NOT exact, but with substring match
* Use the next function to have the expected behaviour
*/
function getTableNameForField($module,$fieldname)
{
global $log;
$log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ...");
global $adb, $table_prefix;
$tabid = getTabid($module);
//Asha
if($module == 'Calendar') {
$tabid = array('9','16');
}
$sql = "select tablename from ".$table_prefix."_field where tabid in (". generateQuestionMarks($tabid) .") and ".$table_prefix."_field.presence in (0,2) and columnname like ?";
$res = $adb->pquery($sql, array($tabid, '%'.$fieldname.'%'));
$tablename = '';
if($adb->num_rows($res) > 0)
{
$tablename = $adb->query_result($res,0,'tablename');
}
$log->debug("Exiting getTableNameForField method ...");
return $tablename;
}
/**
* This is what people expect the getTableNameForField function to do, but since it doesn't, here's the proper one!
*/
function getFieldTable($module,$fieldname) {
global $adb, $table_prefix;
$tabid = array(getTabid($module));
if ($module == 'Calendar') {
$tabid = array('9','16');
}
$sql = "select tablename from ".$table_prefix."_field where tabid in (". generateQuestionMarks($tabid) .") and presence in (0,2) and fieldname = ?";
$res = $adb->pquery($sql, array($tabid, $fieldname));
$tablename = '';
if ($adb->num_rows($res) > 0) {
$tablename = $adb->query_result_no_html($res,0,'tablename');
}
return $tablename;
}
/**
* Similar to getFieldTable, but return also the columnname
*/
function getFieldTableAndColumn($module,$fieldname) {
global $adb, $table_prefix;
$tabid = array(getTabid($module));
if ($module == 'Calendar') {
$tabid = array('9','16');
}
$sql = "select tablename, columnname from ".$table_prefix."_field where tabid in (". generateQuestionMarks($tabid) .") and presence in (0,2) and fieldname = ?";
$res = $adb->pquery($sql, array($tabid, $fieldname));
$tablename = '';
if ($adb->num_rows($res) > 0) {
return $adb->fetchByAssoc($res, -1, false);
}
return null;
}
// crmv@187823e
/** Function to get Days and Dates in between the dates specified
*/
function get_days_n_dates($st,$en)
{
global $log;
$log->debug("Entering get_days_n_dates(".$st.",".$en.") method ...");
$stdate_arr=explode("-",$st);
$endate_arr=explode("-",$en);
$dateDiff = mktime(0,0,0,$endate_arr[1],$endate_arr[2],$endate_arr[0]) - mktime(0,0,0,$stdate_arr[1],$stdate_arr[2],$stdate_arr[0]);//to get dates difference
$days = floor($dateDiff/60/60/24)+1; //to calculate no of. days
for($i=0;$i<$days;$i++)
{
$day_date[] = date("Y-m-d",mktime(0,0,0,date("$stdate_arr[1]"),(date("$stdate_arr[2]")+($i)),date("$stdate_arr[0]")));
}
if(!isset($day_date))
$day_date=0;
$nodays_dates=array($days,$day_date);
$log->debug("Exiting get_days_n_dates method ...");
return $nodays_dates; //passing no of days , days in between the days
}//function end
/** Function to get the start and End Dates based upon the period which we give
*/
function start_end_dates($period)
{
global $log;
$log->debug("Entering start_end_dates(".$period.") method ...");
$st_thisweek= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y")));
if($period=="tweek")
{
$st_date= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y")));
$end_date = date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-1),date("Y")));
$st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y")));
if($st_week==0)
{
$start_week=explode("-",$st_thisweek);
$st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]")));
$end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]")));
}
$period_type="week";
$width="360";
}
else if($period=="lweek")
{
$start_week=explode("-",$st_thisweek);
$st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]")));
$end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]")));
$st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y")));
if($st_week==0)
{
$start_week=explode("-",$st_thisweek);
$st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-14),date("$start_week[0]")));
$end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-8),date("$start_week[0]")));
}
$period_type="week";
$width="360";
}
else if($period=="tmon")
{
$period_type="month";
$width="840";
$st_date = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y")));
$end_date = date("Y-m-t");
}
else if($period=="lmon")
{
$st_date=date("Y-m-d",mktime(0,0,0,date("n")-1,date("1"),date("Y")));
$end_date = date("Y-m-d",mktime(0, 0, 1, date("n"), 0,date("Y")));
$period_type="month";
$start_month=date("d",mktime(0,0,0,date("n"),date("j"),date("Y")));
if($start_month==1)
{
$st_date=date("Y-m-d",mktime(0,0,0,date("n")-2,date("1"),date("Y")));
$end_date = date("Y-m-d",mktime(0, 0, 1, date("n")-1, 0,date("Y")));
}
$width="840";
}
else
{
$curr_date=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
$today_date=explode("-",$curr_date);
$lastday_date=date("Y-m-d",mktime(0,0,0,date("$today_date[1]"),date("$today_date[2]")-1,date("$today_date[0]")));
$st_date=$lastday_date;
$end_date=$lastday_date;
$period_type="yday";
$width="250";
}
if($period_type=="yday")
$height="160";
else
$height="250";
$datevalues=array($st_date,$end_date,$period_type,$width,$height);
$log->debug("Exiting start_end_dates method ...");
return $datevalues;
}//function ends
/** Function to get the Graph and vte_table format for a particular date
based upon the period
*/
function Graph_n_table_format($period_type,$date_value)
{
global $log;
$log->debug("Entering Graph_n_table_format(".$period_type.",".$date_value.") method ...");
$date_val=explode("-",$date_value);
if($period_type=="month") //to get the vte_table format dates
{
$table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
$graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
}
else if($period_type=="week")
{
$table_format=date("d/m",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
$graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
}
else if($period_type=="yday")
{
$table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0])));
$graph_format=$table_format;
}
$values=array($graph_format,$table_format);
$log->debug("Exiting Graph_n_table_format method ...");
return $values;
}
/** Function to get image count for a given product
* @param $id -- product id :: Type integer
* @returns count -- count:: Type integer
*/
function getImageCount($id)
{
global $log;
$log->debug("Entering getImageCount(".$id.") method ...");
global $adb, $table_prefix;
$image_lists=array();
$query="select imagename from ".$table_prefix."_products where productid=?";
$result=$adb->pquery($query, array($id));
$imagename=$adb->query_result($result,0,'imagename');
$image_lists=explode("###",$imagename);
$log->debug("Exiting getImageCount method ...");
return count($image_lists);
}
/** Function to get user image for a given user
* @param $id -- user id :: Type integer
* @returns $image_name -- image name:: Type string
*/
function getUserImageName($id)
{
global $log;
$log->debug("Entering getUserImageName(".$id.") method ...");
global $adb, $table_prefix;
$query = "select imagename from ".$table_prefix."_users where id=?";
$result = $adb->pquery($query, array($id));
$image_name = $adb->query_result($result,0,"imagename");
$log->debug("Inside getUserImageName. The image_name is ".$image_name);
$log->debug("Exiting getUserImageName method ...");
return $image_name;
}
/** Function to get all user images for displaying it in listview
* @returns $image_name -- image name:: Type array
*/
function getUserImageNames()
{
global $log;
$log->debug("Entering getUserImageNames() method ...");
global $adb, $table_prefix;
$query = "select imagename from ".$table_prefix."_users where deleted=0";
$result = $adb->pquery($query, array());
$image_name=array();
for($i=0;$i<$adb->num_rows($result);$i++)
{
if($adb->query_result($result,$i,"imagename")!='')
$image_name[] = $adb->query_result($result,$i,"imagename");
}
$log->debug("Inside getUserImageNames.");
if(count($image_name) > 0)
{
$log->debug("Exiting getUserImageNames method ...");
return $image_name;
}
}
/** Function to check whether user has opted for internal mailer
* @returns $int_mailer -- int mailer:: Type boolean
*/
function useInternalMailer() {
// TODO: use db
return 1;
}
/**
* the function is like unescape in javascript
* added by dingjianting on 2006-10-1 for picklist editor
*/
function utf8RawUrlDecode ($source) {
global $default_charset;
$decodedStr = "";
$pos = 0;
$len = strlen ($source);
while ($pos < $len) {
$charAt = substr ($source, $pos, 1);
if ($charAt == '%') {
$pos++;
$charAt = substr ($source, $pos, 1);
if ($charAt == 'u') {
// we got a unicode character
$pos++;
$unicodeHexVal = substr ($source, $pos, 4);
$unicode = hexdec ($unicodeHexVal);
$entity = "". $unicode . ';';
$decodedStr .= utf8_encode ($entity);
$pos += 4;
}
else {
// we have an escaped ascii character
$hexVal = substr ($source, $pos, 2);
$decodedStr .= chr (hexdec ($hexVal));
$pos += 2;
}
} else {
$decodedStr .= $charAt;
$pos++;
}
}
if(strtolower($default_charset) == 'utf-8')
return html_to_utf8($decodedStr);
else
return $decodedStr;
//return html_to_utf8($decodedStr);
}
/**
*simple HTML to UTF-8 conversion:
*/
function html_to_utf8 ($data) {
return preg_replace_callback("/\\&\\#([0-9]{3,10})\\;/", function($matches) {
return _html_to_utf8($matches[1]);
}, $data); //crmv@56443
}
function _html_to_utf8 ($data)
{
if ($data > 127)
{
$i = 5;
while (($i--) > 0)
{
if ($data != ($a = $data % ($p = pow(64, $i))))
{
$ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
for ($i; $i > 0; $i--)
$ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
break;
}
}
}
else
$ret = "$data;";
return $ret;
}
/**
* Function to find the UI type of a field based on the uitype id
*/
function is_uitype($uitype, $reqtype) {
$ui_type_arr = array(
'_date_' => array(5, 6, 23, 70),
'_picklist_' => array(15, 16, 52, 53, 54, 55, 59, 62, 63, 66, 68, 76, 77, 78, 80, 98, 101, 115, 357),
'_users_list_' => array(52),
);
if ($ui_type_arr[$reqtype] != null) {
if (in_array($uitype, $ui_type_arr[$reqtype])) {
return true;
}
}
return false;
}
/**
* Function to escape quotes
* @param $value - String in which single quotes have to be replaced.
* @return Input string with single quotes escaped.
*/
function escape_single_quotes($value) {
if (isset($value)) $value = str_replace("'", "\'", $value);
return $value;
}
/**
* Function to format the input value for SQL like clause.
* @param $str - Input string value to be formatted.
* @param $flag - By default set to 0 (Will look for cases %string%).
* If set to 1 - Will look for cases %string.
* If set to 2 - Will look for cases string%.
* @return String formatted as per the SQL like clause requirement
*/
function formatForSqlLike($str, $flag=0,$is_field=false) {
global $adb;
if (isset($str)) {
if($is_field==false){
$str = str_replace('%', '\%', $str);
$str = str_replace('_', '\_', $str);
if ($flag == 0) {
$str = '%'. $str .'%';
} elseif ($flag == 1) {
$str = '%'. $str;
} elseif ($flag == 2) {
$str = $str .'%';
}
} else {
if ($flag == 0) {
$str = 'concat("%",'. $str .',"%")';
} elseif ($flag == 1) {
$str = 'concat("%",'. $str .')';
} elseif ($flag == 2) {
$str = 'concat('. $str .',"%")';
}
}
}
return $adb->sql_escape_string($str);
}
/**
* Get Current Module (global variable or from request)
*/
function getCurrentModule($perform_set=false) {
global $currentModule,$root_directory;
if(isset($currentModule)) return $currentModule;
// Do some security check and return the module information
if(isset($_REQUEST['module']))
{
$is_module = false;
$module = $_REQUEST['module'];
$dir = @scandir($root_directory."modules");
$temp_arr = Array("CVS","Attic");
$res_arr = @array_intersect($dir,$temp_arr);
if(count($res_arr) == 0 && !preg_match("/[\/.]/",$module)) {
if(@in_array($module,$dir))
$is_module = true;
}
if($is_module) {
if($perform_set) $currentModule = $module;
return $module;
}
}
return null;
}
/**
* Set the language strings.
*/
function setCurrentLanguage($active_module=null) {
global $current_language, $default_language, $app_strings, $app_list_strings, $mod_strings, $currentModule;
if($active_module==null) {
if (!isset($currentModule))
$active_module = getCurrentModule();
else
$active_module = $currentModule;
}
if(VteSession::hasKey('authenticated_user_language') && VteSession::get('authenticated_user_language') != '')
{
$current_language = VteSession::get('authenticated_user_language');
}
else
{
$current_language = $default_language;
}
//set module and application string arrays based upon selected language
if (!isset($app_strings))
$app_strings = return_application_language($current_language);
if (!isset($app_list_strings))
$app_list_strings = return_app_list_strings_language($current_language);
if (!isset($mod_strings) && isset($active_module))
$mod_strings = return_module_language($current_language, $active_module);
}
/** Function used to get all the picklists and their values for a module
@param string $module - Module name to which the list of picklists and their values needed
@return array $fieldlists - Array of picklists and their values
**/
function getAccessPickListValues($module)
{
global $adb, $log;
global $current_user, $table_prefix;
$log->debug("Entering into function getAccessPickListValues($module)");
$id = getTabid($module);
$query = 'select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from '.$table_prefix.'_field where tabid = ? and uitype in (15,16,111,33,55) and '.$table_prefix.'_field.presence in (0,2)';
$result = $adb->pquery($query, array($id));
$roleid = $current_user->roleid;
$subrole = getRoleSubordinates($roleid);
if(count($subrole)> 0)
{
$roleids = $subrole;
array_push($roleids, $roleid);
}
else
{
$roleids = $roleid;
}
$temp_status = Array();
for($i=0;$i < $adb->num_rows($result);$i++)
{
$fieldname = $adb->query_result($result,$i,"fieldname");
$fieldlabel = $adb->query_result($result,$i,"fieldlabel");
$columnname = $adb->query_result($result,$i,"columnname");
$tabid = $adb->query_result($result,$i,"tabid");
$uitype = $adb->query_result($result,$i,"uitype");
if(!in_array($fieldname,array('activitytype','visibility','duration_minutes','recurringtype','hdnTaxType')))
{
$keyvalue = $columnname;
$fieldvalues = Array();
//se la picklist supporta il nuovo metodo
$columns = $adb->database->MetaColumnNames($table_prefix."_$fieldname");
if (!$columns)
continue;
if (in_array('picklist_valueid',$columns) && $fieldname != 'product_lines'){
$order_by = "sortid,$fieldname";
$pick_query="select $fieldname from ".$table_prefix."_$fieldname inner join ".$table_prefix."_role2picklist on ".$table_prefix."_role2picklist.picklistvalueid = ".$table_prefix."_$fieldname.picklist_valueid and roleid = ? ";
$params = array($roleid);
}
//altrimenti uso il vecchio
else {
if (in_array('sortorderid',$columns))
$order_by = "sortorderid,$fieldname";
else
$order_by = $fieldname;
$pick_query="select $fieldname from ".$table_prefix."_$fieldname";
$params = array();
}
$pick_query.=" order by $order_by asc";
$pickListResult = $adb->pquery($pick_query, $params);
$field_count = $adb->num_rows($pickListResult);
if($field_count) {
while($resultrow = $adb->fetch_array_no_html($pickListResult)) {
$fieldvalues[] = $resultrow[$fieldname];
}
}
if($uitype == 111 && $field_count > 0 && ($fieldname == 'taskstatus' || $fieldname == 'eventstatus'))
{
$temp_count =count($temp_status[$keyvalue]);
if($temp_count > 0)
{
for($t=0;$t < $field_count;$t++)
{
$temp_status[$keyvalue][($temp_count+$t)] = $fieldvalues[$t];
}
$fieldvalues = $temp_status[$keyvalue];
}
else
$temp_status[$keyvalue] = $fieldvalues;
}
if($uitype == 33)
$fieldlists[1][$keyvalue] = $fieldvalues;
else if($uitype == 55 && $fieldname == 'salutationtype')
$fieldlists[$keyvalue] = $fieldvalues;
else if($uitype == 16 || $uitype == 15 || $uitype == 111)
$fieldlists[$keyvalue] = $fieldvalues;
}
}
$log->debug("Exit from function getAccessPickListValues($module)");
return $fieldlists;
}
function get_config_status() {
global $default_charset;
if(strtolower($default_charset) == 'utf-8')
$config_status=1;
else
$config_status=0;
return $config_status;
}
//vtc
function sanitizeUploadFileName($fileName, $badFileExtensions) {
$fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename
$fileName = str_replace(':', '', $fileName); // crmv@95157 - remove colons (Windows doesn't like them!)
$fileName = str_replace('/', '', $fileName); // crmv@132704
$fileNameParts = explode(".", $fileName);
$countOfFileNameParts = count($fileNameParts);
$badExtensionFound = false;
for ($i=0;$i<$countOfFileNameParts;++$i) {
$partOfFileName = $fileNameParts[$i];
if(in_array(strtolower($partOfFileName), $badFileExtensions)) {
$badExtensionFound = true;
$fileNameParts[$i] = $partOfFileName . 'file';
}
}
$newFileName = implode(".", $fileNameParts);
if ($badExtensionFound) {
$newFileName .= ".txt";
}
return $newFileName;
}
//vtc e
/** Function to convert a given time string to Minutes */
function ConvertToMinutes($time_string)
{
$interval = explode(' ', $time_string);
$interval_minutes = intval($interval[0]);
$interval_string = strtolower($interval[1]);
if($interval_string == 'hour' || $interval_string == 'hours')
{
$interval_minutes = $interval_minutes * 60;
}
elseif($interval_string == 'day' || $interval_string == 'days')
{
$interval_minutes = $interval_minutes * 1440;
}
return $interval_minutes;
}
/**
* Function to check if a given record exists (not deleted)
* @param integer $recordId - record id
*/
function isRecordExists($recordId) {
global $adb, $table_prefix;
$query = "SELECT crmid FROM ".$table_prefix."_crmentity where crmid=? AND deleted=0";
$result = $adb->pquery($query, array($recordId));
if ($adb->num_rows($result)) {
return true;
}
return false;
}
/** Function to set date values compatible to database (YY_MM_DD)
* @param $value -- value :: Type string
* @returns $insert_date -- insert_date :: Type string
*/
function getValidDBInsertDateValue($value) {
global $log;
$log->debug("Entering getDBInsertDateValue(".$value.") method ...");
global $current_user;
if (strpos($value,"-") !==false)
$separator = "-";
elseif (strpos($value,".") !==false)
$separator = ".";
elseif (strpos($value,"/") !==false)
$separator = "/";
if ($separator){
list($y,$m,$d) = explode($separator,$value);
if ($separator != "-"){
$value = str_replace($separator,"-",$value);
}
if(strlen($y)<4){
$insert_date = getDBInsertDateValue($value);
} else {
$insert_date = $value;
}
}
else
$insert_date = $value;
$log->debug("Exiting getDBInsertDateValue method ...");
return $insert_date;
}
/* Function to get the related tables data
* @param - $module - Primary module name
* @param - $secmodule - Secondary module name
* return Array $rel_array tables and fields to be compared are sent
* */
function getRelationTables($module,$secmodule){
global $adb, $table_prefix;
$primary_obj = CRMEntity::getInstance($module);
$secondary_obj = CRMEntity::getInstance($secmodule);
$ui10_query = $adb->pquery("SELECT ".$table_prefix."_field.tabid AS tabid,".$table_prefix."_field.tablename AS tablename, ".$table_prefix."_field.columnname AS columnname FROM ".$table_prefix."_field INNER JOIN ".$table_prefix."_fieldmodulerel ON ".$table_prefix."_fieldmodulerel.fieldid = ".$table_prefix."_field.fieldid WHERE (".$table_prefix."_fieldmodulerel.module=? AND ".$table_prefix."_fieldmodulerel.relmodule=?) OR (".$table_prefix."_fieldmodulerel.module=? AND ".$table_prefix."_fieldmodulerel.relmodule=?)",array($module,$secmodule,$secmodule,$module));
if($adb->num_rows($ui10_query)>0){
$ui10_tablename = $adb->query_result($ui10_query,0,'tablename');
$ui10_columnname = $adb->query_result($ui10_query,0,'columnname');
$ui10_tabid = $adb->query_result($ui10_query,0,'tabid');
if($primary_obj->table_name == $ui10_tablename){
$reltables = array($ui10_tablename=>array("".$primary_obj->table_index."","$ui10_columnname"));
} else if($secondary_obj->table_name == $ui10_tablename){
$reltables = array($ui10_tablename=>array("$ui10_columnname","".$secondary_obj->table_index.""),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
} else {
if(isset($secondary_obj->tab_name_index[$ui10_tablename])){
$rel_field = $secondary_obj->tab_name_index[$ui10_tablename];
$reltables = array($ui10_tablename=>array("$ui10_columnname","$rel_field"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
} else {
$rel_field = $primary_obj->tab_name_index[$ui10_tablename];
$reltables = array($ui10_tablename=>array("$rel_field","$ui10_columnname"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
}
}
}else {
// crmv@96033
if(method_exists($primary_obj,'setRelationTables')){ // crmv@172864
$reltables = $primary_obj->setRelationTables($secmodule);
} elseif(method_exists($secondary_obj,'setRelationTables')){ // crmv@172864
$reltablesInv = $secondary_obj->setRelationTables($module);
if (is_array($reltablesInv) && count($reltablesInv) == 2) {
// swap the columns
$first = reset($reltablesInv);
$key = key($reltablesInv);
$t = $first[0]; $first[0] = $first[1]; $first[1] = $t;
if (count($first) == 4) {
$t = $first[2]; $first[2] = $first[3]; $first[3] = $t;
}
$reltables = array($key => $first, "".$primary_obj->table_name."" => "".$primary_obj->table_index."");
}
} else {
$reltables = '';
}
// crmv@96033e
}
if(is_array($reltables) && !empty($reltables)){
$rel_array = $reltables;
} else {
//crmv@18829 crmv@38798
$specialMods = array('Documents', 'Calendar');
if (in_array($module, $specialMods)) {
$rel_array = array(
$primary_obj->relation_table => array($primary_obj->relation_table_id, $primary_obj->relation_table_otherid, $primary_obj->relation_table_module, $primary_obj->relation_table_othermodule),
$primary_obj->table_name => $primary_obj->table_index
);
} elseif (in_array($secmodule, $specialMods)) {
$rel_array = array(
$secondary_obj->relation_table => array($secondary_obj->relation_table_otherid, $secondary_obj->relation_table_id, $secondary_obj->relation_table_module, $secondary_obj->relation_table_othermodule),
$primary_obj->table_name => $primary_obj->table_index
);
} elseif (isInventoryModule($module) && isProductModule($secmodule)) { // crmv@64542
$rel_array = array($table_prefix."_inventoryproductrel"=>array('id', "productid"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
} else {
//crmv@18829e crmv@38798e
$rel_array = array($table_prefix."_crmentityrel"=>array("crmid","relcrmid", "module", "relmodule"),"".$primary_obj->table_name."" => "".$primary_obj->table_index."");
}
}
return $rel_array;
}
/**
* This function returns no value but handles the delete functionality of each entity.
* Input Parameter are $module - module name, $return_module - return module name, $focus - module object, $record - entity id, $return_id - return entity id.
*/
function DeleteEntity($module,$return_module,$focus,$record,$return_id) {
global $log,$adb,$table_prefix;
$log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)");
if ($return_module == 'Documents' && !empty($return_id) && $module != 'Messages') { // crmv@41776
$query = 'DELETE FROM '.$table_prefix.'_senotesrel WHERE crmid=? AND notesid=?';
$params = array($record,$return_id);
$adb->pquery($query,$params);
} elseif ($module != $return_module && !empty($return_module) && !empty($return_id)) {
$focus->unlinkRelationship($record, $return_module, $return_id);
} else {
$focus->trash($module, $record);
}
$log->debug("Exiting DeleteEntity method ...");
}
/* Function to install Vtlib Compliant modules
* @param - $packagename - Name of the module
* @param - $packagepath - Complete path to the zip file of the Module
*/
//crmv@27005
function installVtlibModule($packagename, $packagepath, $customized=false) {
global $log;
require_once('vtlib/Vtecrm/Package.php');
require_once('vtlib/Vtecrm/Module.php');
$vtlib_Utils_Log = true;//crmv@208038
$package = new Vtecrm_Package();
if($package->isLanguageType($packagepath)) {
$package = new Vtecrm_Language();
$package->import($packagepath, true);
return;
}
$module = $package->getModuleNameFromZip($packagepath);
// Customization
if($package->isLanguageType()) {
require_once('vtlib/Vtecrm/Language.php');
$languagePack = new Vtecrm_Language();
@$languagePack->import($packagepath, true);
return;
}
// END
$module_exists = false;
$module_dir_exists = false;
if($module == null) {
$log->fatal("$packagename Module zipfile is not valid!");
} else if(Vtecrm_Module::getInstance($module)) {
$log->fatal("$module already exists!");
$module_exists = true;
}
if($module_exists == false) {
$log->debug("$module - Installation starts here");
$package->import($packagepath, true);
$moduleInstance = Vtecrm_Module::getInstance($module);
if (empty($moduleInstance)) {
$log->fatal("$module module installation failed!");
}
}
}
//crmv@27005e
/* Function to update Vtlib Compliant modules
* @param - $module - Name of the module
* @param - $packagepath - Complete path to the zip file of the Module
*/
function updateVtlibModule($module, $packagepath) {
global $log;
require_once('vtlib/Vtecrm/Package.php');
require_once('vtlib/Vtecrm/Module.php');
$vtlib_Utils_Log = true;//crmv@208038
$package = new Vtecrm_Package();
if($module == null) {
$log->fatal("Module name is invalid");
} else {
$moduleInstance = Vtecrm_Module::getInstance($module);
if($moduleInstance) {
$log->debug("$module - Module instance found - Update starts here");
$package->update($moduleInstance, $packagepath);
} else {
$log->fatal("$module doesn't exists!");
}
}
}
/* Function to only initialize the update of Vtlib Compliant modules
* @param - $module - Name of the module
* @param - $packagepath - Complete path to the zip file of the Module
*/
function initUpdateVtlibModule($module, $packagepath) {
global $log;
require_once('vtlib/Vtecrm/Package.php');
require_once('vtlib/Vtecrm/Module.php');
$vtlib_Utils_Log = true;//crmv@208038
$package = new Vtecrm_Package();
if($module == null) {
$log->fatal("Module name is invalid");
} else {
$moduleInstance = Vtecrm_Module::getInstance($module);
if($moduleInstance) {
$log->debug("$module - Module instance found - Init Update starts here");
$package->initUpdate($moduleInstance, $packagepath, true);
} else {
$log->fatal("$module doesn't exists!");
}
}
}
/**
* this function checks if a given column exists in a given table or not
* @param string $columnName - the columnname
* @param string $tableName - the tablename
* @return boolean $status - true if column exists; false otherwise
*/
function columnExists($columnName, $tableName){
global $adb;
$columnNames = array();
$columnNames = $adb->getColumnNames($tableName);
if(in_array($columnName, $columnNames)){
return true;
}else{
return false;
}
}
/* To get modules list for which work flow and field formulas is permitted*/
function com_vtGetModules($adb) {
global $table_prefix;
$sql="select distinct ".$table_prefix."_field.tabid, name
from ".$table_prefix."_field
inner join ".$table_prefix."_tab
on ".$table_prefix."_field.tabid=".$table_prefix."_tab.tabid
where ".$table_prefix."_field.tabid not in(10,15,29) and ".$table_prefix."_tab.presence = 0 and ".$table_prefix."_tab.isentitytype=1";
$it = new SqlResultIterator($adb, $adb->query($sql));
$modules = array();
foreach($it as $row) {
//crmv@131239
$moduleInstance = Vtecrm_Module::getInstance($row->name);
if ($moduleInstance->is_mod_light) continue;
//crmv@131239e
if(isPermitted($row->name,'index') == "yes") {
$modules[$row->name] = getTranslatedString($row->name, $row->name);
}
}
asort($modules);
return $modules;
}
/**
* this function accepts a potential id returns the module name and entity value for the related field
* @param integer $id - the potential id
* @return array $data - the related module name and field value
*/
function getRelatedInfo($id){
global $adb,$table_prefix;
$data = array();
$sql = "select related_to from ".$table_prefix."_potential where potentialid=?";
$result = $adb->pquery($sql, array($id));
if($adb->num_rows($result)>0){
$relID = $adb->query_result($result, 0, "related_to");
$setype = getSalesEntityType($relID); //crmv@171021
$data = array("setype"=>$setype, "relID"=>$relID);
}
return $data;
}
/**
* this function accepts an ID and returns the entity value for that id
* @param integer $id - the crmid of the record
* @return string $data - the entity name for the id
*/
function getRecordInfoFromID($id){
global $adb,$table_prefix;
$data = array();
//crmv@171021
$setype = getSalesEntityType($id);
if (!empty($setype)) {
$data = getEntityName($setype, $id);
}
//crmv@171021e
$data = array_values($data);
$data = $data[0];
return $data;
}
/**
* this function accepts an tabiD and returns the tablename, fieldname and fieldlabel for email field
* @param integer $tabid - the tabid of current module
* @return string $fields - the array of mail field's tablename, fieldname and fieldlabel
*/
function getMailFields($tabid){
global $adb,$table_prefix;
$fields = array();
$result = $adb->pquery("SELECT tablename,fieldlabel,fieldname FROM ".$table_prefix."_field WHERE tabid=? AND uitype IN (13,104)", array($tabid));
if($adb->num_rows($result)>0){
$tablename = $adb->query_result($result, 0, "tablename");
$fieldname = $adb->query_result($result, 0, "fieldname");
$fieldlabel = $adb->query_result($result, 0, "fieldlabel");
$fields = array("tablename"=>$tablename,"fieldname"=>$fieldname,"fieldlabel"=>$fieldlabel);
}
return $fields;
}
/** Function to set the PHP memory limit to the specified value, if the memory limit set in the php.ini is less than the specified value
* @param $newvalue -- Required Memory Limit
*/
function _phpset_memorylimit_MB($newvalue) {
$current = @ini_get('memory_limit');
if(preg_match("/(.*)M/", $current, $matches)) {
// Check if current value is less then new value
if($matches[1] < $newvalue) {
@ini_set('memory_limit', "{$newvalue}M");
}
}
}
/** Function to get the tab meta information for a given id
* @param $tabId -- tab id :: Type integer
* @returns $tabInfo -- array of preference name to preference value :: Type array
*/
function getTabInfo($tabId) {
global $adb,$table_prefix;
$tabInfoResult = $adb->pquery('SELECT prefname, prefvalue FROM '.$table_prefix.'_tab_info WHERE tabid=?', array($tabId));
$tabInfo = array();
for($i=0; $i<$adb->num_rows($tabInfoResult); ++$i) {
$prefName = $adb->query_result($tabInfoResult, $i, 'prefname');
$prefValue = $adb->query_result($tabInfoResult, $i, 'prefvalue');
$tabInfo[$prefName] = $prefValue;
}
return $tabInfo;
}
// crmv@105600
/** Function to return block name
* @param Integer -- $blockid
* @return String - Block Name
*/
function getBlockName($blockid) {
global $adb,$table_prefix;
if(!empty($blockid)){
$cache = RCache::getInstance();
$key = "blocklabels_".$blockid;
$label = $cache->get($key);
if ($label) return $label;
$block_res = $adb->pquery('SELECT blocklabel FROM '.$table_prefix.'_blocks WHERE blockid = ?',array($blockid));
if($adb->num_rows($block_res)){
$blockname = $adb->query_result($block_res,0,'blocklabel');
$cache->set($key, $blockname);
return $blockname;
}
}
return '';
}
// crmv@105600e
/* Function to get the name of the Field which is used for Module Specific Sequence Numbering, if any
* @param module String - Module label
* return Array - Field name and label are returned */
function getModuleSequenceField($module) {
global $adb, $log,$table_prefix;
$log->debug("Entering function getModuleSequenceFieldName ($module)...");
$field = null;
if (!empty($module)) {
// First look at the cached information
$cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
if($cachedModuleFields === false) {
//uitype 4 points to Module Numbering Field
$seqColRes = $adb->pquery("SELECT fieldname, fieldlabel, columnname, tablename FROM ".$table_prefix."_field WHERE uitype=? AND tabid=? and ".$table_prefix."_field.presence in (0,2)", array('4', getTabid($module))); // crmv@199978
if($adb->num_rows($seqColRes) > 0) {
$fieldname = $adb->query_result($seqColRes,0,'fieldname');
$columnname = $adb->query_result($seqColRes,0,'columnname');
$fieldlabel = $adb->query_result($seqColRes,0,'fieldlabel');
$tablename = $adb->query_result($seqColRes,0,'tablename'); // crmv@199978
$field = array();
$field['name'] = $fieldname;
$field['column'] = $columnname;
$field['label'] = $fieldlabel;
$field['table'] = $tablename; // crmv@199978
}
} else {
foreach($cachedModuleFields as $fieldinfo) {
if($fieldinfo['uitype'] == '4') {
$field = array();
$field['name'] = $fieldinfo['fieldname'];
$field['column'] = $fieldinfo['columnname'];
$field['label'] = $fieldinfo['fieldlabel'];
$field['table'] = $fieldinfo['tablename']; // crmv@199978
break;
}
}
}
}
$log->debug("Exiting getModuleSequenceFieldName...");
return $field;
}
/* Function to get the Result of all the field ids allowed for Duplicates merging for specified tab/module (tabid) */
function getFieldsResultForMerge($tabid) {
global $log, $adb,$table_prefix;
$log->debug("Entering getFieldsResultForMerge(".$tabid.") method ...");
$nonmergable_tabids = array(29);
if (in_array($tabid, $nonmergable_tabids)) {
return null;
}
// List of Fields not allowed for Duplicates Merging based on the module (tabid) [tabid to fields mapping]
$nonmergable_field_tab = Array(
4 => array('portal','imagename'),
13 => array('filename','comments'),
);
$nonmergable_displaytypes = Array(4);
$nonmergable_uitypes = Array('70','69','4');
$sql = "SELECT fieldid,typeofdata FROM ".$table_prefix."_field WHERE tabid = ? and ".$table_prefix."_field.presence in (0,2)";
$params = array($tabid);
$where = '';
if (isset($nonmergable_field_tab[$tabid]) && count($nonmergable_field_tab[$tabid]) > 0) {
$where .= " AND fieldname NOT IN (". generateQuestionMarks($nonmergable_field_tab[$tabid]) .")";
array_push($params, $nonmergable_field_tab[$tabid]);
}
if (count($nonmergable_displaytypes) > 0) {
$where .= " AND displaytype NOT IN (". generateQuestionMarks($nonmergable_displaytypes) .")";
array_push($params, $nonmergable_displaytypes);
}
if (count($nonmergable_uitypes) > 0) {
$where .= " AND uitype NOT IN ( ". generateQuestionMarks($nonmergable_uitypes) .")" ;
array_push($params, $nonmergable_uitypes);
}
if (trim($where) != '') {
$sql .= $where;
}
$res = $adb->pquery($sql, $params);
$log->debug("Exiting getFieldsResultForMerge method ...");
return $res;
}
// Update all the data refering to currency $old_cur to $new_cur
function transferCurrency($old_cur, $new_cur) {
// Transfer User currency to new currency
transferUserCurrency($old_cur, $new_cur);
// Transfer Product Currency to new currency
transferProductCurrency($old_cur, $new_cur);
// Transfer PriceBook Currency to new currency
transferPriceBookCurrency($old_cur, $new_cur);
}
// Function to transfer the users with currency $old_cur to $new_cur as currency
function transferUserCurrency($old_cur, $new_cur) {
global $log, $adb, $current_user, $table_prefix; // crmv@42266
$log->debug("Entering function transferUserCurrency...");
$sql = "update ".$table_prefix."_users set currency_id=? where currency_id=?";
$adb->pquery($sql, array($new_cur, $old_cur));
$current_user->retrieve_entity_info($current_user->id,"Users");
$log->debug("Exiting function transferUserCurrency...");
}
// Function to transfer the products with currency $old_cur to $new_cur as currency
function transferProductCurrency($old_cur, $new_cur) {
global $log, $adb,$table_prefix;
$log->debug("Entering function updateProductCurrency...");
$InventoryUtils = InventoryUtils::getInstance(); // crmv@42024
$prod_res = $adb->pquery("select productid from ".$table_prefix."_products where currency_id = ?", array($old_cur));
$numRows = $adb->num_rows($prod_res);
$prod_ids = array();
for($i=0;$i<$numRows;$i++) {
$prod_ids[] = $adb->query_result($prod_res,$i,'productid');
}
if(count($prod_ids) > 0) {
$prod_price_list = $InventoryUtils->getPricesForProducts($new_cur,$prod_ids);
for($i=0;$ipquery($query, $params);
}
}
$log->debug("Exiting function updateProductCurrency...");
}
// Function to transfer the pricebooks with currency $old_cur to $new_cur as currency
// and to update the associated products with list price in $new_cur currency
function transferPriceBookCurrency($old_cur, $new_cur) {
global $log, $adb,$table_prefix;
$log->debug("Entering function updatePriceBookCurrency...");
$pb_res = $adb->pquery("select pricebookid from ".$table_prefix."_pricebook where currency_id = ?", array($old_cur));
$numRows = $adb->num_rows($pb_res);
$pb_ids = array();
for($i=0;$i<$numRows;$i++) {
$pb_ids[] = $adb->query_result($pb_res,$i,'pricebookid');
}
if(count($pb_ids) > 0) {
for($i=0;$iid = $pb_id;
$focus->mode = 'edit';
$focus->retrieve_entity_info($pb_id, "PriceBooks");
$focus->column_fields['currency_id'] = $new_cur;
$focus->save("PriceBooks");
}
}
$log->debug("Exiting function updatePriceBookCurrency...");
}
//functions for asterisk integration start
/**
* this function returns the caller name based on the phone number that is passed to it
* @param $from - the number which is calling
* returns caller information in name(type) format :: for e.g. Mary Smith (Contact)
* if no information is present in database, it returns :: Unknown Caller (Unknown)
*/
function getCallerName($from) {
global $adb;
//information found
$callerInfo = getCallerInfo($from);
if($callerInfo != false){
$callerName = decode_html($callerInfo['name']);
$module = $callerInfo['module'];
$callerModule = " ($module)";
$callerID = $callerInfo['id'];
$caller =$caller."$callerName$callerModule";
}else{
$caller = $caller." ".getTranslatedString('LBL_CREATE_LEAD')." ".getTranslatedString('LBL_CREATE_CONTACT')." ".getTranslatedString('LBL_CREATE_ACCOUNT')."";
}
return $caller;
}
/**
* this function searches for a given number in vte and returns the callerInfo in an array format
* currently the search is made across only leads, accounts and contacts modules
*
* @param $number - the number whose information you want
* @return array in format array(name=>callername, module=>module, id=>id);
*/
function getCallerInfo($number){
global $adb, $log;
if(empty($number)){
return false;
}
$caller = "Unknown Number (Unknown)"; //declare caller as unknown in beginning
$params = array();
$name = array('Contacts', 'Accounts', 'Leads', 'Vendors'); // crmv@100312
foreach ($name as $module) {
if(!vtlib_isModuleActive($module)) continue; // crmv@157736
$focus = CRMEntity::getInstance($module);
$query = $focus->buildSearchQueryForFieldTypes(array(11,1014), $number);
if(empty($query)) return;
$result = $adb->pquery($query, array());
if($adb->num_rows($result) > 0 ){
$callerName = $adb->query_result($result, 0, "name");
$callerID = $adb->query_result($result,0,'id');
$data = array("name"=>$callerName, "module"=>$module, "id"=>$callerID);
return $data;
}
}
return false;
}
/**
* this function returns the tablename and primarykeys for a given module in array format
* @param object $adb - peardatabase type object
* @param string $module - module name for which you want the array
* @return array(tablename1=>primarykey1,.....)
*/
function get_tab_name_index($adb, $module){
global $table_prefix;
$tabid = getTabid($module);
$sql = "select * from ".$table_prefix."_tab_name_index where tabid = ?";
$result = $adb->pquery($sql, array($tabid));
$count = $adb->num_rows($result);
$data = array();
for($i=0; $i<$count; $i++){
$tablename = $adb->query_result($result, $i, "tablename");
$primaryKey = $adb->query_result($result, $i, "primarykey");
$data[$tablename] = $primaryKey;
}
return $data;
}
/**
* this function returns the value of use_asterisk from the database for the current user
* @param string $id - the id of the current user
*/
//crmv@18038 crmv@105600
function get_use_asterisk($id='',$mode='call'){ //crmv@36559
global $adb,$current_user,$table_prefix;
if ($id == '') $id = $current_user->id;
$cache = RCache::getInstance();
$key = "useasterisk_{$id}_{$mode}";
$result = $cache->get($key);
if (!empty($result)) return $result;
if(!vtlib_isModuleActive('PBXManager')){
$result = 'false';
$cache->set($key, $result);
return $result;
}
$sql = "select * from ".$table_prefix."_asteriskextensions where userid = ?";
$res = $adb->pquery($sql, array($id));
if($adb->num_rows($res)>0){
$use_asterisk = $adb->query_result_no_html($res, 0, "use_asterisk");
$asterisk_extension = $adb->query_result_no_html($res, 0, "asterisk_extension");
if ($mode == "incoming"){
//TODO: controllare se ho impostato il server asterisk, altrimenti non ha senso controllare le chiamate in entrata
if ($use_asterisk == 0){
$result = 'false';
} else {
$result = 'true';
}
} else {
if(empty($asterisk_extension)){
$result = 'false';
} else {
$result = 'true';
}
}
}else{
$result = 'false';
}
$cache->set($key, $result);
return $result;
}
//crmv@18038e crmv@105600e
/**
* this function adds a record to the callhistory module
*
* @param string $userExtension - the extension of the current user
* @param string $callfrom - the caller number
* @param string $callto - the called number
* @param string $status - the status of the call (outgoing/incoming/missed)
* @param object $adb - the peardatabase object
*/
function addToCallHistory($userExtension, $callfrom, $callto, $status, $adb, $useCallerInfo){
global $table_prefix;
$sql = "select * from ".$table_prefix."_asteriskextensions where asterisk_extension=?";
$result = $adb->pquery($sql,array($userExtension));
$userID = $adb->query_result($result, 0, "userid");
if(empty($userID)) {
// we have observed call to extension not configured in vte will returns NULL
return;
}
$crmID = $adb->getUniqueID($table_prefix.'_crmentity');
$timeOfCall = date('Y-m-d H:i:s');
// crmv@150773
$params = array($crmID, $userID, $userID, 0, "PBXManager", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0);
$sql = "insert into ".$table_prefix."_crmentity (crmid, smcreatorid, smownerid, modifiedby, setype, createdtime, modifiedtime, viewedtime, status, version, presence, deleted) values (".generateQuestionMarks($params).")";
$adb->pquery($sql, $params);
// crmv@150773e
if(empty($callfrom)){
$callfrom = "Unknown";
}
if(empty($callto)){
$callto = "Unknown";
}
if($status == 'outgoing'){
//call is from user to record
$sql = "select * from ".$table_prefix."_asteriskextensions where asterisk_extension=?";
$result = $adb->pquery($sql, array($callfrom));
if($adb->num_rows($result)>0){
$userid = $adb->query_result($result, 0, "userid");
$callerName = getUserFullName($userid);
}
$receiver = $useCallerInfo;
if(empty($receiver)){
$receiver = "Unknown";
}else{
$receiver = "".$receiver['name']."";
}
}else{
//call is from record to user
$sql = "select * from ".$table_prefix."_asteriskextensions where asterisk_extension=?";
$result = $adb->pquery($sql,array($callto));
if($adb->num_rows($result)>0){
$userid = $adb->query_result($result, 0, "userid");
$receiver = getUserFullName($userid);
}
$callerName = $useCallerInfo;
if(empty($callerName)){
$callerName = "Unknown $callfrom";
}else{
$callerName = "".decode_html($callerName['name'])."";
}
}
$sql = "insert into ".$table_prefix."_pbxmanager (pbxmanagerid,callfrom,callto,timeofcall,status)values (?,?,?,?,?)";
$params = array($crmID, $callerName, $receiver, $timeOfCall, $status);
$adb->pquery($sql, $params);
return $crmID;
}
//functions for asterisk integration end
//crmv@16312
function validateAlphaNumericInput($string){
preg_match('/^[\w _\-]+$/', $string, $matches);
if(count($matches) == 0) {
return false;
}
return true;
}
function validateServerName($string){
preg_match('/^[\w\-\.\\/:]+$/', $string, $matches);
if(count($matches) == 0) {
return false;
}
return true;
}
function validateEmailId($string){
preg_match('/^[a-zA-Z0-9]+([\_\-\.]*[a-zA-Z0-9]+[\_\-]?)*@[a-zA-Z0-9]+([\_\-]?[a-zA-Z0-9]+)*\.+([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)*$/', $string, $matches);
if(count($matches) == 0) {
return false;
}
return true;
}
//crmv@16312 end
//crmv@25610 crmv@50039 crmv@92843
// modifica il valore di una data/ora in accordo con il timezone passato
// il valore deve essere nel formato YYYY-MM-DD HH:II:SS
// the second parameter is obsolete and should not be used anymore
function adjustTimezone($value, $tzoffset = 0, $user_timezone = null, $reverse = false) {
global $default_timezone, $current_user;
if (empty($user_timezone)) {
$user_timezone = $current_user->column_fields['user_timezone'];
}
$value = trim($value);
// skip if empty
if (substr($value, 0, 4) === '0000') return $value; // crmv@163361
if (!empty($value) && !empty($user_timezone) && $user_timezone != $default_timezone) {
// controlla se c'รจ un'ora nella data
if (preg_match('/[0-5]?[0-9]:[0-5]?[0-9]/', $value, $matches)) {
$onlyHour = ($matches[0] == $value);
// add seconds if missing
$times = explode(':', substr($value, 11));
if (count($times) <= 2) $value .= ':00';
// add a fake date
if ($onlyHour) $value = '2010-10-10 '.$value;
// changed to use the value as date reference
$date = DateTime::createFromFormat('Y-m-d H:i:s', $value, new DateTimeZone($reverse ? $user_timezone : $default_timezone));
if ($date !== false) {
$date->setTimezone(new DateTimeZone($reverse ? $default_timezone : $user_timezone));
$value = $date->format('Y-m-d H:i:s');
}
// remove the fake date
if ($onlyHour) $value = substr($value, strpos($value, ' '));
}
}
return $value;
}
//crmv@25610e crmv@50039e crmv@92843e
//crmv@31126
function getValidDBInsertDateTimeValue($value) {
$value = trim($value);
$valueList = explode(' ',$value);
if(count($valueList) == 2) {
$dbDateValue = getValidDBInsertDateValue($valueList[0]);
$dbTimeValue = $valueList[1];
if(!empty($dbTimeValue) && strpos($dbTimeValue, ':') === false) {
$dbTimeValue = $dbTimeValue.':';
}
$timeValueLength = strlen($dbTimeValue);
if(!empty($dbTimeValue) && strrpos($dbTimeValue, ':') == ($timeValueLength-1)) {
$dbTimeValue = $dbTimeValue.'00';
}
try {
$dateTime = new DateTimeField($dbDateValue.' '.$dbTimeValue);
return $dateTime->getDBInsertDateTimeValue();
} catch (Exception $ex) {
return '';
}
} elseif(count($valueList) == 1) {
return getValidDBInsertDateValue($value);
}
}
//crmv@31126e
/*
* Function to set, character set in the header, as given in include/language/*_lang.php
*/
function insert_charset_header()
{
global $app_strings, $default_charset;
$charset = $default_charset;
if(isset($app_strings['LBL_CHARSET']))
{
$charset = $app_strings['LBL_CHARSET'];
}
header('Content-Type: text/html; charset='. $charset);
}