From 7309617a2fc17735e70ff5f7f4171971c5053144 Mon Sep 17 00:00:00 2001 From: YuCheng Hu Date: Sat, 21 Aug 2010 19:12:34 +0000 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=88=B0=205.2=20=E5=90=8E?= =?UTF-8?q?=E7=AC=AC=E4=B8=80=E6=AC=A1=20SVN=20=E6=8F=90=E4=BA=A4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit yuchenghu@hawebs.net git-svn-id: https://svn.code.sf.net/p/hawebs/svn@551 a2543c7e-f6e9-4f8a-8bff-1ffc34733512 --- .../trunk/include/utils/CommonUtils.php | 7325 +++++++------ .../trunk/include/utils/DBHealthCheck.php | 205 +- .../trunk/include/utils/DetailViewUtils.php | 3893 +++---- .../trunk/include/utils/EditViewUtils.php | 4142 +++---- oss/vtiger/trunk/include/utils/ExportAjax.php | 102 +- .../trunk/include/utils/ExportRecords.php | 88 +- .../trunk/include/utils/ExportUtils.php | 348 +- .../trunk/include/utils/GetGroupUsers.php | 266 +- .../trunk/include/utils/GetParentGroups.php | 92 +- .../trunk/include/utils/GetUserGroups.php | 206 +- oss/vtiger/trunk/include/utils/GraphUtils.php | 273 +- .../trunk/include/utils/InventoryUtils.php | 2194 ++-- .../trunk/include/utils/ListViewUtils.php | 9121 ++++++++------- .../trunk/include/utils/RecurringType.php | 642 +- .../trunk/include/utils/SearchUtils.php | 2268 ++-- .../trunk/include/utils/UserInfoUtil.php | 8813 +++++++-------- .../trunk/include/utils/VTCacheUtils.php | 506 +- oss/vtiger/trunk/include/utils/VtlibUtils.php | 1159 +- oss/vtiger/trunk/include/utils/encryption.php | 222 +- oss/vtiger/trunk/include/utils/export.php | 684 +- oss/vtiger/trunk/include/utils/utils.php | 9736 ++++++++--------- 21 files changed, 26233 insertions(+), 26052 deletions(-) diff --git a/oss/vtiger/trunk/include/utils/CommonUtils.php b/oss/vtiger/trunk/include/utils/CommonUtils.php index f8845936..4b73b8de 100644 --- a/oss/vtiger/trunk/include/utils/CommonUtils.php +++ b/oss/vtiger/trunk/include/utils/CommonUtils.php @@ -1,3634 +1,3693 @@ -debug("Entering is_admin(".$user->user_name.") method ..."); - - if ($user->is_admin == 'on') - { - $log->debug("Exiting is_admin method ..."); - return true; - } - else - { - $log->debug("Exiting is_admin method ..."); - return false; - } -} - -/** - * THIS FUNCTION IS DEPRECATED AND SHOULD NOT BE USED; USE get_select_options_with_id() - * Create HTML to display select options in a dropdown list. To be used inside - * of a select statement in a form. - * param $option_list - the array of strings to that contains the option list - * param $selected - the string which contains the default value - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_select_options (&$option_list, $selected, $advsearch='false') { - global $log; - $log->debug("Entering get_select_options (".$option_list.",".$selected.",".$advsearch.") method ..."); - $log->debug("Exiting get_select_options method ..."); - return get_select_options_with_id($option_list, $selected, $advsearch); -} - -/** - * Create HTML to display select options in a dropdown list. To be used inside - * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. The values is an array of the datas - * param $option_list - the array of strings to that contains the option list - * param $selected - the string which contains the default value - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_select_options_with_id (&$option_list, $selected_key, $advsearch='false') { - global $log; - $log->debug("Entering get_select_options_with_id (".$option_list.",".$selected_key.",".$advsearch.") method ..."); - $log->debug("Exiting get_select_options_with_id method ..."); - return get_select_options_with_id_separate_key($option_list, $option_list, $selected_key, $advsearch); -} -function get_select_options_with_value (&$option_list, $selected_key, $advsearch='false') { - global $log; - $log->debug("Entering get_select_options_with_id (".$option_list.",".$selected_key.",".$advsearch.") method ..."); - $log->debug("Exiting get_select_options_with_id method ..."); - return get_select_options_with_value_separate_key($option_list, $option_list, $selected_key, $advsearch); -} -/** - * Create HTML to display select options in a dropdown list. To be used inside - * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. - * The values are the display strings. - */ -function get_select_options_array (&$option_list, $selected_key, $advsearch='false') { - global $log; - $log->debug("Entering get_select_options_array (".$option_list.",".$selected_key.",".$advsearch.") method ..."); - $log->debug("Exiting get_select_options_array method ..."); - return get_options_array_seperate_key($option_list, $option_list, $selected_key, $advsearch); -} - -/** - * Create HTML to display select options in a dropdown list. To be used inside - * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. The value is an array of data - * param $label_list - the array of strings to that contains the option list - * param $key_list - the array of strings to that contains the values list - * param $selected - the string which contains the default value - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_options_array_seperate_key (&$label_list, &$key_list, $selected_key, $advsearch='false') { - global $log; - $log->debug("Entering get_options_array_seperate_key (".$label_list.",".$key_list.",".$selected_key.",".$advsearch.") method ..."); - global $app_strings; - if($advsearch=='true') - $select_options = "\n"; - else - $select_options = ""; - - //for setting null selection values to human readable --None-- - $pattern = "/'0?'>".$app_strings['LBL_NONE']."<"; - if (!is_array($selected_key)) $selected_key = array($selected_key); - - //create the type dropdown domain and set the selected value if $opp value already exists - foreach ($key_list as $option_key=>$option_value) { - $selected_string = ''; - // the system is evaluating $selected_key == 0 || '' to true. Be very careful when changing this. Test all cases. - // The vtiger_reported bug was only happening with one of the vtiger_users in the drop down. It was being replaced by none. - if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '') || (in_array($option_key, $selected_key))) - { - $selected_string = 'selected'; - } - - $html_value = $option_key; - - $select_options .= "\n"; - $options[$html_value]=array($label_list[$option_key]=>$selected_string); - } - $select_options = preg_replace($pattern, $replacement, $select_options); - - $log->debug("Exiting get_options_array_seperate_key method ..."); - return $options; -} - -/** - * Create HTML to display select options in a dropdown list. To be used inside - * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. - * The values are the display strings. - */ - -function get_select_options_with_id_separate_key(&$label_list, &$key_list, $selected_key, $advsearch='false') -{ - global $log; - $log->debug("Entering get_select_options_with_id_separate_key(".$label_list.",".$key_list.",".$selected_key.",".$advsearch.") method ..."); - global $app_strings; - if($advsearch=='true') - $select_options = "\n"; - else - $select_options = ""; - - $pattern = "/'0?'>".$app_strings['LBL_NONE']."<"; - if (!is_array($selected_key)) $selected_key = array($selected_key); - - foreach ($key_list as $option_key=>$option_value) { - $selected_string = ''; - if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '') || (in_array($option_key, $selected_key))) - { - $selected_string = 'selected '; - } - - $html_value = $option_key; - - $select_options .= "\n"; - } - $select_options = preg_replace($pattern, $replacement, $select_options); - $log->debug("Exiting get_select_options_with_id_separate_key method ..."); - return $select_options; - -} - -function get_select_options_with_value_separate_key(&$label_list, &$key_list, $selected_key, $advsearch='false') -{ - global $log; - $log->debug("Entering get_select_options_with_id_separate_key(".$label_list.",".$key_list.",".$selected_key.",".$advsearch.") method ..."); - global $app_strings; - if($advsearch=='true') - $select_options = "\n"; - else - $select_options = ""; - - $pattern = "/'0?'>".$app_strings['LBL_NONE']."<"; - if (!is_array($selected_key)) $selected_key = array($selected_key); - - foreach ($key_list as $option_key=>$option_value) { - $selected_string = ''; - if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '') || (in_array($option_key, $selected_key))) - { - $selected_string = 'selected '; - } - - $html_value = $option_key; - - $select_options .= "\n"; - } - $select_options = preg_replace($pattern, $replacement, $select_options); - $log->debug("Exiting get_select_options_with_id_separate_key method ..."); - return $select_options; - -} - -/** - * Converts localized date format string to jscalendar format - * Example: $array = array_csort($array,'town','age',SORT_DESC,'name'); - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function parse_calendardate($local_format) { - global $log; - $log->debug("Entering parse_calendardate(".$local_format.") method ..."); - global $current_user; - if($current_user->date_format == 'dd-mm-yyyy') - { - $dt_popup_fmt = "%d-%m-%Y"; - } - elseif($current_user->date_format == 'mm-dd-yyyy') - { - $dt_popup_fmt = "%m-%d-%Y"; - } - elseif($current_user->date_format == 'yyyy-mm-dd') - { - $dt_popup_fmt = "%Y-%m-%d"; - } - $log->debug("Exiting parse_calendardate method ..."); - return $dt_popup_fmt; -} - -/** - * Decodes the given set of special character - * input values $string - string to be converted, $encode - flag to decode - * returns the decoded value in string fromat - */ - -function from_html($string, $encode=true){ - global $log; - //$log->debug("Entering from_html(".$string.",".$encode.") method ..."); - global $toHtml; - //if($encode && is_string($string))$string = html_entity_decode($string, ENT_QUOTES); - if(is_string($string)){ - if(eregi('(script).*(/script)',$string)) - $string=preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); - //$string = str_replace(array_values($toHtml), array_keys($toHtml), $string); - } - //$log->debug("Exiting from_html method ..."); - return $string; -} - -function fck_from_html($string) -{ - if(is_string($string)){ - if(eregi('(script).*(/script)',$string)) - $string=str_replace('script', '', $string); - } - return $string; -} - -/** - * Function used to decodes the given single quote and double quote only. This function used for popup selection - * @param string $string - string to be converted, $encode - flag to decode - * @return string $string - the decoded value in string fromat where as only single and double quotes will be decoded - */ - -function popup_from_html($string, $encode=true) -{ - global $log; - $log->debug("Entering popup_from_html(".$string.",".$encode.") method ..."); - - $popup_toHtml = array( - '"' => '"', - "'" => ''', - ); - - //if($encode && is_string($string))$string = html_entity_decode($string, ENT_QUOTES); - if($encode && is_string($string)) - { - $string = addslashes(str_replace(array_values($popup_toHtml), array_keys($popup_toHtml), $string)); - } - - $log->debug("Exiting popup_from_html method ..."); - return $string; -} - - -/** To get the Currency of the specified user - * @param $id -- The user Id:: Type integer - * @returns vtiger_currencyid :: Type integer - */ -function fetchCurrency($id) -{ - global $log; - $log->debug("Entering fetchCurrency(".$id.") method ..."); - - // Lookup the information in cache - $currencyinfo = VTCacheUtils::lookupUserCurrenyId($id); - - if($currencyinfo === false) { - global $adb; - $sql = "select currency_id from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($id)); - $currencyid= $adb->query_result($result,0,"currency_id"); - - VTCacheUtils::updateUserCurrencyId($id, $currencyid); - - // Re-look at the cache for consistency - $currencyinfo = VTCacheUtils::lookupUserCurrenyId($id); - } - - $currencyid = $currencyinfo['currencyid']; - $log->debug("Exiting fetchCurrency method ..."); - return $currencyid; -} - -/** Function to get the Currency name from the vtiger_currency_info - * @param $currencyid -- vtiger_currencyid:: Type integer - * @returns $currencyname -- Currency Name:: Type varchar - * - */ -function getCurrencyName($currencyid, $show_symbol=true) -{ - global $log; - $log->debug("Entering getCurrencyName(".$currencyid.") method ..."); - - // Look at cache first - $currencyinfo = VTCacheUtils::lookupCurrencyInfo($currencyid); - - if($currencyinfo === false) { - global $adb; - $sql1 = "select * from vtiger_currency_info where id= ?"; - $result = $adb->pquery($sql1, array($currencyid)); - - $resultinfo = $adb->fetch_array($result); - - // Update cache - VTCacheUtils::updateCurrencyInfo($currencyid, - $resultinfo['currency_name'], $resultinfo['currency_code'], - $resultinfo['currency_symbol'], $resultinfo['conversion_rate'] - ); - - // Re-look at the cache now - $currencyinfo = VTCacheUtils::lookupCurrencyInfo($currencyid); - } - - $currencyname = $currencyinfo['name']; - $curr_symbol = $currencyinfo['symbol']; - - $log->debug("Exiting getCurrencyName method ..."); - if($show_symbol) return getTranslatedCurrencyString($currencyname).' : '.$curr_symbol; - else return $currencyname; - // NOTE: Without symbol the value could be used for filtering/lookup hence avoiding the translation -} - - -/** - * Function to fetch the list of vtiger_groups from group vtiger_table - * Takes no value as input - * returns the query result set object - */ - -function get_group_options() -{ - global $log; - $log->debug("Entering get_group_options() method ..."); - global $adb,$noof_group_rows;; - $sql = "select groupname,groupid from vtiger_groups"; - $result = $adb->pquery($sql, array()); - $noof_group_rows=$adb->num_rows($result); - $log->debug("Exiting get_group_options method ..."); - return $result; -} - -/** - * Function to get the tabid - * Takes the input as $module - module name - * returns the tabid, integer type - */ - -function getTabid($module) -{ - global $log; - $log->debug("Entering getTabid(".$module.") method ..."); - - // Lookup information in cache first - $tabid = VTCacheUtils::lookupTabid($module); - if($tabid === false) { - - if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { - include('tabdata.php'); - $tabid= $tab_info_array[$module]; - - // Update information to cache for re-use - VTCacheUtils::updateTabidInfo($tabid, $module); - - } else { - $log->info("module is ".$module); - global $adb; - $sql = "select tabid from vtiger_tab where name=?"; - $result = $adb->pquery($sql, array($module)); - $tabid= $adb->query_result($result,0,"tabid"); - - // Update information to cache for re-use - VTCacheUtils::updateTabidInfo($tabid, $module); - } - } - - $log->debug("Exiting getTabid method ..."); - return $tabid; - -} - -/** - * Function to get the fieldid - * - * @param Integer $tabid - * @param Boolean $onlyactive - */ -function getFieldid($tabid, $fieldname, $onlyactive = true) { - global $adb; - - // Look up information at cache first - $fieldinfo = VTCacheUtils::lookupFieldInfo($tabid, $fieldname); - if($fieldinfo === false) { - $query = "SELECT fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence - FROM vtiger_field WHERE tabid=? AND fieldname=?"; - $result = $adb->pquery($query, array($tabid, $fieldname)); - - if($adb->num_rows($result)) { - - $resultrow = $adb->fetch_array($result); - - // Update information to cache for re-use - VTCacheUtils::updateFieldInfo( - $tabid, $fieldname,$resultrow['fieldid'], - $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], - $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']); - - $fieldinfo = VTCacheUtils::lookupFieldInfo($tabid, $fieldname); - } - } - - // Get the field id based on required criteria - $fieldid = false; - - if($fieldinfo) { - $fieldid = $fieldinfo['fieldid']; - if($onlyactive && !in_array($fieldinfo['presence'], array('0', '2'))) { - $fieldid = false; - } - } - return $fieldid; -} - -/** - * Function to get the CustomViewName - * Takes the input as $cvid - customviewid - * returns the cvname string fromat - */ - -function getCVname($cvid) -{ - global $log; - $log->debug("Entering getCVname method ..."); - - global $adb; - $sql = "select viewname from vtiger_customview where cvid=?"; - $result = $adb->pquery($sql, array($cvid)); - $cvname = $adb->query_result($result,0,"viewname"); - - $log->debug("Exiting getCVname method ..."); - return $cvname; - -} - - - -/** - * Function to get the ownedby value for the specified module - * Takes the input as $module - module name - * returns the tabid, integer type - */ - -function getTabOwnedBy($module) -{ - global $log; - $log->debug("Entering getTabid(".$module.") method ..."); - - $tabid=getTabid($module); - - if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) - { - include('tabdata.php'); - $tab_ownedby= $tab_ownedby_array[$tabid]; - } - else - { - - $log->info("module is ".$module); - global $adb; - $sql = "select ownedby from vtiger_tab where name=?"; - $result = $adb->pquery($sql, array($module)); - $tab_ownedby= $adb->query_result($result,0,"ownedby"); - } - $log->debug("Exiting getTabid method ..."); - return $tab_ownedby; - -} - - - - -/** - * Function to get the tabid - * Takes the input as $module - module name - * returns the tabid, integer type - */ - -function getSalesEntityType($crmid) -{ - global $log; - $log->debug("Entering getSalesEntityType(".$crmid.") method ..."); - $log->info("in getSalesEntityType ".$crmid); - global $adb; - $sql = "select setype from vtiger_crmentity where crmid=?"; - $result = $adb->pquery($sql, array($crmid)); - $parent_module = $adb->query_result($result,0,"setype"); - $log->debug("Exiting getSalesEntityType method ..."); - return $parent_module; -} - -/** - * Function to get the AccountName when a vtiger_account id is given - * Takes the input as $acount_id - vtiger_account id - * returns the vtiger_account name in string format. - */ - -function getAccountName($account_id) -{ - global $log; - $log->debug("Entering getAccountName(".$account_id.") method ..."); - $log->info("in getAccountName ".$account_id); - - global $adb; - if($account_id != ''){ - $sql = "select accountname from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($account_id)); - $accountname = $adb->query_result($result,0,"accountname"); - } - $log->debug("Exiting getAccountName method ..."); - return $accountname; -} - -/** - * Function to get the ProductName when a product id is given - * Takes the input as $product_id - product id - * returns the product name in string format. - */ - -function getProductName($product_id) -{ - global $log; - $log->debug("Entering getProductName(".$product_id.") method ..."); - - $log->info("in getproductname ".$product_id); - - global $adb; - $sql = "select productname from vtiger_products where productid=?"; - $result = $adb->pquery($sql, array($product_id)); - $productname = $adb->query_result($result,0,"productname"); - $log->debug("Exiting getProductName method ..."); - return $productname; -} - -/** - * Function to get the Potentail Name when a vtiger_potential id is given - * Takes the input as $potential_id - vtiger_potential id - * returns the vtiger_potential name in string format. - */ - -function getPotentialName($potential_id) -{ - global $log; - $log->debug("Entering getPotentialName(".$potential_id.") method ..."); - $log->info("in getPotentialName ".$potential_id); - - global $adb; - $potentialname = ''; - if($potential_id != '') - { - $sql = "select potentialname from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($potential_id)); - $potentialname = $adb->query_result($result,0,"potentialname"); - } - $log->debug("Exiting getPotentialName method ..."); - return $potentialname; -} - -/** - * Function to get the Contact Name when a contact id is given - * Takes the input as $contact_id - contact id - * returns the Contact Name in string format. - */ - -function getContactName($contact_id) -{ - global $log; - $log->debug("Entering getContactName(".$contact_id.") method ..."); - $log->info("in getContactName ".$contact_id); - - global $adb, $current_user; - $contact_name = ''; - if($contact_id != '') - { - $sql = "select * from vtiger_contactdetails where contactid=?"; - $result = $adb->pquery($sql, array($contact_id)); - $firstname = $adb->query_result($result,0,"firstname"); - $lastname = $adb->query_result($result,0,"lastname"); - $contact_name = $lastname; - // Asha: Check added for ticket 4788 - if (getFieldVisibilityPermission("Contacts", $current_user->id,'firstname') == '0') { -// $contact_name .= ' '.$firstname; - $contact_name = $firstname.' '; - } - $contact_name .= $lastname; - - } - $log->debug("Exiting getContactName method ..."); - return $contact_name; -} - -/** - * Function to get the Contact Name when a contact id is given - * Takes the input as $contact_id - contact id - * returns the Contact Name in string format. - */ - -function getLeadName($lead_id) -{ - global $log; - $log->debug("Entering getLeadName(".$lead_id.") method ..."); - $log->info("in getLeadName ".$lead_id); - - global $adb, $current_user; - $lead_name = ''; - if($lead_id != '') - { - $sql = "select * from vtiger_leaddetails where leadid=?"; - $result = $adb->pquery($sql, array($lead_id)); - $firstname = $adb->query_result($result,0,"firstname"); - $lastname = $adb->query_result($result,0,"lastname"); - $lead_name = $lastname; - // Asha: Check added for ticket 4788 - if (getFieldVisibilityPermission("Leads", $current_user->id,'firstname') == '0') { - $lead_name .= ' '.$firstname; - } - } - $log->debug("Exiting getLeadName method ..."); - return $lead_name; -} - -/** - * Function to get the Full Name of a Contact/Lead when a query result and the row count are given - * Takes the input as $result - Query Result, $row_count - Count of the Row, $module - module name - * returns the Contact Name in string format. - */ - -function getFullNameFromQResult($result, $row_count, $module) -{ - global $log, $adb, $current_user; - $log->info("In getFullNameFromQResult(". print_r($result, true) . " - " . $row_count . "-".$module.") method ..."); - - $rowdata = $adb->query_result_rowdata($result,$row_count); - - $name = ''; - if($rowdata != '' && count($rowdata) > 0) - { - $firstname = $rowdata["firstname"]; - $lastname = $rowdata["lastname"]; - $name = $lastname; - // Asha: Check added for ticket 4788 - if (getFieldVisibilityPermission($module, $current_user->id,'firstname') == '0') { - $name .= ' '.$firstname; - } - } - $nam = textlength_check($name); - - return $nam; -} - -/** - * Function to get the Campaign Name when a campaign id is given - * Takes the input as $campaign_id - campaign id - * returns the Campaign Name in string format. - */ - -function getCampaignName($campaign_id) -{ - global $log; - $log->debug("Entering getCampaignName(".$campaign_id.") method ..."); - $log->info("in getCampaignName ".$campaign_id); - - global $adb; - $sql = "select * from vtiger_campaign where campaignid=?"; - $result = $adb->pquery($sql, array($campaign_id)); - $campaign_name = $adb->query_result($result,0,"campaignname"); - $log->debug("Exiting getCampaignName method ..."); - return $campaign_name; -} - - -/** - * Function to get the Vendor Name when a vtiger_vendor id is given - * Takes the input as $vendor_id - vtiger_vendor id - * returns the Vendor Name in string format. - */ - -function getVendorName($vendor_id) -{ - global $log; - $log->debug("Entering getVendorName(".$vendor_id.") method ..."); - $log->info("in getVendorName ".$vendor_id); - global $adb; - $sql = "select * from vtiger_vendor where vendorid=?"; - $result = $adb->pquery($sql, array($vendor_id)); - $vendor_name = $adb->query_result($result,0,"vendorname"); - $log->debug("Exiting getVendorName method ..."); - return $vendor_name; -} - -/** - * Function to get the Quote Name when a vtiger_vendor id is given - * Takes the input as $quote_id - quote id - * returns the Quote Name in string format. - */ - -function getQuoteName($quote_id) -{ - global $log; - $log->debug("Entering getQuoteName(".$quote_id.") method ..."); - $log->info("in getQuoteName ".$quote_id); - global $adb; - if($quote_id != NULL && $quote_id != '') - { - $sql = "select * from vtiger_quotes where quoteid=?"; - $result = $adb->pquery($sql, array($quote_id)); - $quote_name = $adb->query_result($result,0,"subject"); - } - else - { - $log->debug("Quote Id is empty."); - $quote_name = ''; - } - $log->debug("Exiting getQuoteName method ..."); - return $quote_name; -} - -/** - * Function to get the PriceBook Name when a vtiger_pricebook id is given - * Takes the input as $pricebook_id - vtiger_pricebook id - * returns the PriceBook Name in string format. - */ - -function getPriceBookName($pricebookid) -{ - global $log; - $log->debug("Entering getPriceBookName(".$pricebookid.") method ..."); - $log->info("in getPriceBookName ".$pricebookid); - global $adb; - $sql = "select * from vtiger_pricebook where pricebookid=?"; - $result = $adb->pquery($sql, array($pricebookid)); - $pricebook_name = $adb->query_result($result,0,"bookname"); - $log->debug("Exiting getPriceBookName method ..."); - return $pricebook_name; -} - -/** This Function returns the Purchase Order Name. - * The following is the input parameter for the function - * $po_id --> Purchase Order Id, Type:Integer - */ -function getPoName($po_id) -{ - global $log; - $log->debug("Entering getPoName(".$po_id.") method ..."); - $log->info("in getPoName ".$po_id); - global $adb; - $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($sql, array($po_id)); - $po_name = $adb->query_result($result,0,"subject"); - $log->debug("Exiting getPoName method ..."); - return $po_name; -} -/** - * Function to get the Sales Order Name when a vtiger_salesorder id is given - * Takes the input as $salesorder_id - vtiger_salesorder id - * returns the Salesorder Name in string format. - */ - -function getSoName($so_id) -{ - global $log; - $log->debug("Entering getSoName(".$so_id.") method ..."); - $log->info("in getSoName ".$so_id); - global $adb; - $sql = "select * from vtiger_salesorder where salesorderid=?"; - $result = $adb->pquery($sql, array($so_id)); - $so_name = $adb->query_result($result,0,"subject"); - $log->debug("Exiting getSoName method ..."); - return $so_name; -} - -/** - * Function to get the Group Information for a given groupid - * Takes the input $id - group id and $module - module name - * returns the group information in an array format. - */ - -function getGroupName($groupid) -{ - global $adb, $log; - $log->debug("Entering getGroupName(".$groupid.") method ..."); - $group_info = Array(); - $log->info("in getGroupName, entityid is ".$groupid); - if($groupid != '') - { - $sql = "select groupname,groupid from vtiger_groups where groupid = ?"; - $result = $adb->pquery($sql, array($groupid)); - $group_info[] = decode_html($adb->query_result($result,0,"groupname")); - $group_info[] = $adb->query_result($result,0,"groupid"); - } - $log->debug("Exiting getGroupName method ..."); - return $group_info; -} - -/** - * Get the username by giving the user id. This method expects the user id - */ - -function getUserName($userid) -{ - global $adb, $log; - $log->debug("Entering getUserName(".$userid.") method ..."); - $log->info("in getUserName ".$userid); - - if($userid != '') - { - $sql = "select user_name from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($userid)); - $user_name = $adb->query_result($result,0,"user_name"); - } - $log->debug("Exiting getUserName method ..."); - return $user_name; -} - -/** -* Get the user full name by giving the user id. This method expects the user id -* DG 30 Aug 2006 -*/ - -function getUserFullName($userid) -{ - global $log; - $log->debug("Entering getUserFullName(".$userid.") method ..."); - $log->info("in getUserFullName ".$userid); - global $adb; - if($userid != '') - { - $sql = "select first_name, last_name from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($userid)); - $first_name = $adb->query_result($result,0,"first_name"); - $last_name = $adb->query_result($result,0,"last_name"); - $user_name = $first_name." ".$last_name; - } - $log->debug("Exiting getUserFullName method ..."); - return $user_name; -} - -/** Fucntion to get related To name with id */ -function getParentName($parent_id) -{ - global $adb; - if ($parent_id == 0) - return ""; - $sql="select setype from vtiger_crmentity where crmid=?"; - $result=$adb->pquery($sql,array($parent_id)); - //For now i have conditions only for accounts and contacts, if needed can add more - if($adb->query_result($result,'setype') == 'Accounts') - $sql1="select accountname name from vtiger_account where accountid=?"; - else if($adb->query_result($result,'setype') == 'Contacts') - $sql1="select concat( firstname, ' ', lastname ) name from vtiger_contactdetails where contactid=?"; - $result1=$adb->pquery($sql1,array($parent_id)); - $asd=$adb->query_result($result1,'name'); - return $asd; -} - -/** - * Creates and returns database query. To be used for search and other text links. This method expects the module object. - * param $focus - the module object contains the column vtiger_fields - */ - -function getURLstring($focus) -{ - global $log; - $log->debug("Entering getURLstring(".get_class($focus).") method ..."); - $qry = ""; - foreach($focus->column_fields as $fldname=>$val) - { - if(isset($_REQUEST[$fldname]) && $_REQUEST[$fldname] != '') - { - if($qry == '') - $qry = "&".$fldname."=".vtlib_purify($_REQUEST[$fldname]); - else - $qry .="&".$fldname."=".vtlib_purify($_REQUEST[$fldname]); - } - } - if(isset($_REQUEST['current_user_only']) && $_REQUEST['current_user_only'] !='') - { - $qry .="¤t_user_only=".vtlib_purify($_REQUEST['current_user_only']); - } - if(isset($_REQUEST['advanced']) && $_REQUEST['advanced'] =='true') - { - $qry .="&advanced=true"; - } - - if($qry !='') - { - $qry .="&query=true"; - } - $log->debug("Exiting getURLstring method ..."); - return $qry; - -} - -/** This function returns the date in user specified format. - * param $cur_date_val - the default date format - */ - -function getDisplayDate($cur_date_val) -{ - global $log; - $log->debug("Entering getDisplayDate(".$cur_date_val.") method ..."); - global $current_user; - $dat_fmt = $current_user->date_format; - if($dat_fmt == '') - { - $dat_fmt = 'dd-mm-yyyy'; - } - - $date_value = explode(' ',$cur_date_val); - list($y,$m,$d) = split('-',$date_value[0]); - if($dat_fmt == 'dd-mm-yyyy') - { - $display_date = $d.'-'.$m.'-'.$y; - } - elseif($dat_fmt == 'mm-dd-yyyy') - { - - $display_date = $m.'-'.$d.'-'.$y; - } - elseif($dat_fmt == 'yyyy-mm-dd') - { - - $display_date = $y.'-'.$m.'-'.$d; - } - - if($date_value[1] != '') - { - $display_date = $display_date.' '.$date_value[1]; - } - $log->debug("Exiting getDisplayDate method ..."); - return $display_date; - -} - -/** This function returns the date in user specified format. - * Takes no param, receives the date format from current user object - */ - -function getNewDisplayDate() -{ - global $log; - $log->debug("Entering getNewDisplayDate() method ..."); - $log->info("in getNewDisplayDate "); - - global $current_user; - $dat_fmt = $current_user->date_format; - if($dat_fmt == '') - { - $dat_fmt = 'dd-mm-yyyy'; - } - $display_date=''; - if($dat_fmt == 'dd-mm-yyyy') - { - $display_date = date('d-m-Y'); - } - elseif($dat_fmt == 'mm-dd-yyyy') - { - $display_date = date('m-d-Y'); - } - elseif($dat_fmt == 'yyyy-mm-dd') - { - $display_date = date('Y-m-d'); - } - - $log->debug("Exiting getNewDisplayDate method ..."); - return $display_date; -} - -/** This function returns the default vtiger_currency information. - * Takes no param, return type array. - */ - -function getDisplayCurrency() -{ - global $log; - global $adb; - $log->debug("Entering getDisplayCurrency() method ..."); - $curr_array = Array(); - $sql1 = "select * from vtiger_currency_info where currency_status=? and deleted=0"; - $result = $adb->pquery($sql1, array('Active')); - $num_rows=$adb->num_rows($result); - for($i=0; $i<$num_rows;$i++) - { - $curr_id = $adb->query_result($result,$i,"id"); - $curr_name = $adb->query_result($result,$i,"currency_name"); - $curr_symbol = $adb->query_result($result,$i,"currency_symbol"); - $curr_array[$curr_id] = $curr_name.' : '.$curr_symbol; - } - $log->debug("Exiting getDisplayCurrency method ..."); - return $curr_array; -} - -/** This function returns the amount converted to dollar. - * param $amount - amount to be converted. - * param $crate - conversion rate. - */ - -function convertToDollar($amount,$crate){ - global $log; - $log->debug("Entering convertToDollar(".$amount.",".$crate.") method ..."); - $log->debug("Exiting convertToDollar method ..."); - return $amount / $crate; -} - -/** This function returns the amount converted from dollar. - * param $amount - amount to be converted. - * param $crate - conversion rate. - */ -function convertFromDollar($amount,$crate){ - global $log; - $log->debug("Entering convertFromDollar(".$amount.",".$crate.") method ..."); - $log->debug("Exiting convertFromDollar method ..."); - return $amount * $crate; -} - -/** This function returns the amount converted from master currency. - * param $amount - amount to be converted. - * param $crate - conversion rate. - */ -function convertFromMasterCurrency($amount,$crate){ - global $log; - $log->debug("Entering convertFromDollar(".$amount.",".$crate.") method ..."); - $log->debug("Exiting convertFromDollar method ..."); - return $amount * $crate; -} - -/** This function returns the conversion rate and vtiger_currency symbol - * in array format for a given id. - * param $id - vtiger_currency id. - */ - -function getCurrencySymbolandCRate($id) -{ - global $log; - $log->debug("Entering getCurrencySymbolandCRate(".$id.") method ..."); - - // To initialize the currency information in cache - getCurrencyName($id); - - $currencyinfo = VTCacheUtils::lookupCurrencyInfo($id); - - $rate_symbol['rate'] = $currencyinfo['rate']; - $rate_symbol['symbol']= $currencyinfo['symbol']; - - $log->debug("Exiting getCurrencySymbolandCRate method ..."); - return $rate_symbol; -} - -/** This function returns the terms and condition from the database. - * Takes no param and the return type is text. - */ - -function getTermsandConditions() -{ - global $log; - $log->debug("Entering getTermsandConditions() method ..."); - global $adb; - $sql1 = "select * from vtiger_inventory_tandc"; - $result = $adb->pquery($sql1, array()); - $tandc = $adb->query_result($result,0,"tandc"); - $log->debug("Exiting getTermsandConditions method ..."); - return $tandc; -} - -/** - * Create select options in a dropdown list. To be used inside - * a reminder select statement in a vtiger_activity form. - * param $start - start value - * param $end - end value - * param $fldname - vtiger_field name - * param $selvalue - selected value - */ - -function getReminderSelectOption($start,$end,$fldname,$selvalue='') -{ - global $log; - $log->debug("Entering getReminderSelectOption(".$start.",".$end.",".$fldname.",".$selvalue=''.") method ..."); - global $mod_strings; - global $app_strings; - - $def_sel =""; - $OPTION_FLD = ""; - $log->debug("Exiting getReminderSelectOption method ..."); - return $OPTION_FLD; -} - -/** This function returns the List price of a given product in a given price book. - * param $productid - product id. - * param $pbid - vtiger_pricebook id. - */ - -function getListPrice($productid,$pbid) -{ - global $log; - $log->debug("Entering getListPrice(".$productid.",".$pbid.") method ..."); - $log->info("in getListPrice productid ".$productid); - - global $adb; - $query = "select listprice from vtiger_pricebookproductrel where pricebookid=? and productid=?"; - $result = $adb->pquery($query, array($pbid, $productid)); - $lp = $adb->query_result($result,0,'listprice'); - $log->debug("Exiting getListPrice method ..."); - return $lp; -} - -/** This function returns a string with removed new line character, single quote, and back slash double quoute. - * param $str - string to be converted. - */ - -function br2nl($str) { - global $log; - $log->debug("Entering br2nl(".$str.") method ..."); - $str = preg_replace("/(\r\n)/", "\\r\\n", $str); - $str = preg_replace("/'/", " ", $str); - $str = preg_replace("/\"/", " ", $str); - $log->debug("Exiting br2nl method ..."); - return $str; -} - -/** This function returns a text, which escapes the html encode for link tag/ a href tag -*param $text - string/text -*/ - -function make_clickable($text) -{ - global $log; - $log->debug("Entering make_clickable(".$text.") method ..."); - $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text); - // pad it with a space so we can match things at the start of the 1st line. - $ret = ' ' . $text; - - // matches an "xxxx://yyyy" URL at the start of a line, or after a space. - // xxxx can only be alpha characters. - // yyyy is anything up to the first space, newline, comma, double quote or < - $ret = preg_replace("#(^|[\n ])([\w]+?://.*?[^ \"\n\r\t<]*)#is", "\\1\\2", $ret); - - // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing - // Must contain at least 2 dots. xxxx contains either alphanum, or "-" - // zzzz is optional.. will contain everything up to the first space, newline, - // comma, double quote or <. - $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\-]+\.[\w\-.\~]+(?:/[^ \"\t\n\r<]*)?)#is", "\\1\\2", $ret); - - // matches an email@domain type address at the start of a line, or after a space. - // Note: Only the followed chars are valid; alphanums, "-", "_" and or ".". - $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2@\\3", $ret); - - // Remove our padding.. - $ret = substr($ret, 1); - - //remove comma, fullstop at the end of url - $ret = preg_replace("#,\"|\.\"|\)\"|\)\.\"|\.\)\"#", "\"", $ret); - - $log->debug("Exiting make_clickable method ..."); - return($ret); -} -/** - * This function returns the vtiger_blocks and its related information for given module. - * Input Parameter are $module - module name, $disp_view = display view (edit,detail or create),$mode - edit, $col_fields - * column vtiger_fields/ - * This function returns an array - */ - -function getBlocks($module,$disp_view,$mode,$col_fields='',$info_type='') -{ - global $log; - $log->debug("Entering getBlocks(".$module.",".$disp_view.",".$mode.",".$col_fields.",".$info_type.") method ..."); - global $adb,$current_user; - global $mod_strings; - $tabid = getTabid($module); - $block_detail = Array(); - $getBlockinfo = ""; - $query="select blockid,blocklabel,show_title,display_status from vtiger_blocks where tabid=? and $disp_view=0 and visible = 0 order by sequence"; - $result = $adb->pquery($query, array($tabid)); - $noofrows = $adb->num_rows($result); - $prev_header = ""; - $blockid_list = array(); - for($i=0; $i<$noofrows; $i++) - { - $blockid = $adb->query_result($result,$i,"blockid"); - array_push($blockid_list,$blockid); - $block_label[$blockid] = $adb->query_result($result,$i,"blocklabel"); - - $sLabelVal = getTranslatedString($block_label[$blockid], $module); - $aBlockStatus[$sLabelVal] = $adb->query_result($result,$i,"display_status"); - } - if($mode == 'edit') - { - $display_type_check = 'vtiger_field.displaytype = 1'; - }elseif($mode == 'mass_edit') - { - $display_type_check = 'vtiger_field.displaytype = 1 AND vtiger_field.masseditable NOT IN (0,2)'; - }else - { - $display_type_check = 'vtiger_field.displaytype in (1,4)'; - } - - /*if($non_mass_edit_fields!='' && sizeof($non_mass_edit_fields)!=0){ - $mass_edit_query = "AND vtiger_field.fieldname NOT IN (". generateQuestionMarks($non_mass_edit_fields) .")"; - }*/ - - //retreive the vtiger_profileList from database - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - if($disp_view == "detail_view") - { - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users" || $module == "Emails") - { - $sql = "SELECT vtiger_field.* FROM vtiger_field WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND vtiger_field.displaytype IN (1,2,4) and vtiger_field.presence in (0,2) ORDER BY block,sequence"; - $params = array($tabid, $blockid_list); - } - else - { - $profileList = getCurrentUserProfileList(); - $sql = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND vtiger_field.displaytype IN (1,2,4) and vtiger_field.presence in (0,2) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; - $params = array($tabid, $blockid_list, $profileList); - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $sql = fixPostgresQuery( $sql, $log, 0); - } - $result = $adb->pquery($sql, $params); - - // Added to unset the previous record's related listview session values - if(isset($_SESSION['rlvs'])) - unset($_SESSION['rlvs']); - - $getBlockInfo=getDetailBlockInformation($module,$result,$col_fields,$tabid,$block_label); - } - else - { - if ($info_type != '') - { - if($is_admin==true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2]== 0 || $module == 'Users' || $module == "Emails") - { - $sql = "SELECT vtiger_field.* FROM vtiger_field WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND $display_type_check AND info_type = ? and vtiger_field.presence in (0,2) ORDER BY block,sequence"; - $params = array($tabid, $blockid_list, $info_type); - } - else - { - $profileList = getCurrentUserProfileList(); - $sql = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND $display_type_check AND info_type = ? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; - $params = array($tabid, $blockid_list, $info_type, $profileList); - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $sql = fixPostgresQuery( $sql, $log, 0); - } - } - else - { - if($is_admin==true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == 'Users' || $module == "Emails") - { - $sql = "SELECT vtiger_field.* FROM vtiger_field WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list).") AND $display_type_check and vtiger_field.presence in (0,2) ORDER BY block,sequence"; - $params = array($tabid, $blockid_list); - } - else - { - $profileList = getCurrentUserProfileList(); - $sql = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list).") AND $display_type_check AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList).") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; - $params = array($tabid, $blockid_list, $profileList); - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $sql = fixPostgresQuery( $sql, $log, 0); - } - } - $result = $adb->pquery($sql, $params); - $getBlockInfo=getBlockInformation($module,$result,$col_fields,$tabid,$block_label,$mode); - } - $log->debug("Exiting getBlocks method ..."); - if(count($getBlockInfo) > 0) - { - foreach($getBlockInfo as $label=>$contents) - { - if(empty($getBlockInfo[$label])) - { - unset($getBlockInfo[$label]); - } - } - } - $_SESSION['BLOCKINITIALSTATUS'] = $aBlockStatus; - return $getBlockInfo; -} -/** - * This function is used to get the display type. - * Takes the input parameter as $mode - edit (mostly) - * This returns string type value - */ - -function getView($mode) -{ - global $log; - $log->debug("Entering getView(".$mode.") method ..."); - if($mode=="edit") - $disp_view = "edit_view"; - else - $disp_view = "create_view"; - $log->debug("Exiting getView method ..."); - return $disp_view; -} -/** - * This function is used to get the blockid of the customblock for a given module. - * Takes the input parameter as $tabid - module tabid and $label - custom label - * This returns string type value - */ - -function getBlockId($tabid,$label) -{ - global $log; - $log->debug("Entering getBlockId(".$tabid.",".$label.") method ..."); - global $adb; - $blockid = ''; - $query = "select blockid from vtiger_blocks where tabid=? and blocklabel = ?"; - $result = $adb->pquery($query, array($tabid, $label)); - $noofrows = $adb->num_rows($result); - if($noofrows == 1) - { - $blockid = $adb->query_result($result,0,"blockid"); - } - $log->debug("Exiting getBlockId method ..."); - return $blockid; -} - -/** - * This function is used to get the Parent and Child vtiger_tab relation array. - * Takes no parameter and get the data from parent_tabdata.php and vtiger_tabdata.php - * This returns array type value - */ - -function getHeaderArray() -{ - global $log; - $log->debug("Entering getHeaderArray() method ..."); - global $adb; - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - include('parent_tabdata.php'); - include('tabdata.php'); - $noofrows = count($parent_tab_info_array); - foreach($parent_tab_info_array as $parid=>$parval) - { - $subtabs = Array(); - $tablist=$parent_child_tab_rel_array[$parid]; - $noofsubtabs = count($tablist); - - foreach($tablist as $childTabId) - { - $module = array_search($childTabId,$tab_info_array); - - if($is_admin) - { - $subtabs[] = $module; - } - elseif($profileGlobalPermission[2]==0 ||$profileGlobalPermission[1]==0 || $profileTabsPermission[$childTabId]==0) - { - $subtabs[] = $module; - } - } - - $parenttab = getParentTabName($parid); - if($parenttab == 'Settings' && $is_admin) - { - $subtabs[] = 'Settings'; - } - - if($parenttab != 'Settings' ||($parenttab == 'Settings' && $is_admin)) - { - if(!empty($subtabs)) - $relatedtabs[$parenttab] = $subtabs; - } - } - $log->debug("Exiting getHeaderArray method ..."); - return $relatedtabs; -} - -/** - * This function is used to get the Parent Tab name for a given parent vtiger_tab id. - * Takes the input parameter as $parenttabid - Parent vtiger_tab id - * This returns value string type - */ - -function getParentTabName($parenttabid) -{ - global $log; - $log->debug("Entering getParentTabName(".$parenttabid.") method ..."); - global $adb; - if (file_exists('parent_tabdata.php') && (filesize('parent_tabdata.php') != 0)) - { - include('parent_tabdata.php'); - $parent_tabname= $parent_tab_info_array[$parenttabid]; - } - else - { - $sql = "select parenttab_label from vtiger_parenttab where parenttabid=?"; - $result = $adb->pquery($sql, array($parenttabid)); - $parent_tabname= $adb->query_result($result,0,"parenttab_label"); - } - $log->debug("Exiting getParentTabName method ..."); - return $parent_tabname; -} - -/** - * This function is used to get the Parent Tab name for a given module. - * Takes the input parameter as $module - module name - * This returns value string type - */ - - -function getParentTabFromModule($module) -{ - global $log; - $log->debug("Entering getParentTabFromModule(".$module.") method ..."); - global $adb; - if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0) && file_exists('parent_tabdata.php') && (filesize('parent_tabdata.php') != 0)) - { - include('tabdata.php'); - include('parent_tabdata.php'); - $tabid=$tab_info_array[$module]; - foreach($parent_child_tab_rel_array as $parid=>$childArr) - { - if(in_array($tabid,$childArr)) - { - $parent_tabname= $parent_tab_info_array[$parid]; - break; - } - } - $log->debug("Exiting getParentTabFromModule method ..."); - return $parent_tabname; - } - else - { - $sql = "select vtiger_parenttab.* from vtiger_parenttab inner join vtiger_parenttabrel on vtiger_parenttabrel.parenttabid=vtiger_parenttab.parenttabid inner join vtiger_tab on vtiger_tab.tabid=vtiger_parenttabrel.tabid where vtiger_tab.name=?"; - $result = $adb->pquery($sql, array($module)); - $tab = $adb->query_result($result,0,"parenttab_label"); - $log->debug("Exiting getParentTabFromModule method ..."); - return $tab; - } -} - -/** - * This function is used to get the Parent Tab name for a given module. - * Takes no parameter but gets the vtiger_parenttab value from form request - * This returns value string type - */ -function getParentTab() { - global $log, $default_charset; - $log->debug("Entering getParentTab() method ..."); - if(!empty($_REQUEST['parenttab'])) { - $log->debug("Exiting getParentTab method ..."); - return vtlib_purify($_REQUEST['parenttab']); - } else { - $log->debug("Exiting getParentTab method ..."); - return getParentTabFromModule($_REQUEST['module']); - } -} - -/** - * This function is used to get the days in between the current time and the modified time of an entity . - * Takes the input parameter as $id - crmid it will calculate the number of days in between the - * the current time and the modified time from the vtiger_crmentity vtiger_table and return the result as a string. - * The return format is updated day ago <(date when updated)> - */ - -function updateInfo($id) -{ - global $log; - $log->debug("Entering updateInfo(".$id.") method ..."); - - global $adb; - global $app_strings; - $query='select modifiedtime from vtiger_crmentity where crmid = ?'; - $result = $adb->pquery($query, array($id)); - $modifiedtime = $adb->query_result($result,0,'modifiedtime'); - $values=explode(' ',$modifiedtime); - $date_info=explode('-',$values[0]); - $time_info=explode(':',$values[1]); -// $date = $date_info[2].' '.$app_strings[date("M", mktime(0, 0, 0, $date_info[1], $date_info[2],$date_info[0]))].' '.$date_info[0]; - $date = $date_info[0].'年'.date("m", mktime(0, 0, 0, $date_info[1], $date_info[2],$date_info[0])).'月'.$date_info[2].'日'; - $time_modified = mktime($time_info[0], $time_info[1], $time_info[2], $date_info[1], $date_info[2],$date_info[0]); - $time_now = time(); - $days_diff = (int)(($time_now - $time_modified) / (60 * 60 * 24)); - if($days_diff == 0) - $update_info = $app_strings['LBL_UPDATED_TODAY']." (".$date.")"; - elseif($days_diff == 1) - $update_info = $app_strings['LBL_UPDATED']." ".$days_diff." ".$app_strings['LBL_DAY_AGO']." (".$date.")"; - else - $update_info = $app_strings['LBL_UPDATED']." ".$days_diff." ".$app_strings['LBL_DAYS_AGO']." (".$date.")"; - - $log->debug("Exiting updateInfo method ..."); - return $update_info; -} - - -/** - * This function is used to get the Product Images for the given Product . - * It accepts the product id as argument and returns the Images with the script for - * rotating the product Images - */ - -function getProductImages($id) -{ - global $log; - $log->debug("Entering getProductImages(".$id.") method ..."); - global $adb; - $image_lists=array(); - $script_images=array(); - $script = ''; - if($imagename != '') - { - $log->debug("Exiting getProductImages method ..."); - return $script; - } -} - -/** - * This function is used to save the Images . - * It acceps the File lists,modulename,id and the mode as arguments - * It returns the array details of the upload - */ - -function SaveImage($_FILES,$module,$id,$mode) -{ - global $log, $root_directory; - $log->debug("Entering SaveImage(".$_FILES.",".$module.",".$id.",".$mode.") method ..."); - global $adb; - $uploaddir = $root_directory."test/".$module."/" ;//set this to which location you need to give the contact image - $log->info("The Location to Save the Contact Image is ".$uploaddir); - $file_path_name = $_FILES['imagename']['name']; - if (isset($_REQUEST['imagename_hidden'])) { - $file_name = vtlib_purify($_REQUEST['imagename_hidden']); - } else { - //allowed filename like UTF-8 Character - $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name); - } - $image_error="false"; - $saveimage="true"; - if($file_name!="") - { - - $log->debug("Contact Image is given for uploading"); - $image_name_val=file_exist_fn($file_name,0); - - $encode_field_values=""; - $errormessage=""; - - $move_upload_status=move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$image_name_val); - $image_error="false"; - - //if there is an error in the uploading of image - - $filetype= $_FILES['imagename']['type']; - $filesize = $_FILES['imagename']['size']; - - $filetype_array=explode("/",$filetype); - - $file_type_val_image=strtolower($filetype_array[0]); - $file_type_val=strtolower($filetype_array[1]); - $log->info("The File type of the Contact Image is :: ".$file_type_val); - //checking the uploaded image is if an image type or not - if(!$move_upload_status) //if any error during file uploading - { - $log->debug("Error is present in uploading Contact Image."); - $errorCode = $_FILES['imagename']['error']; - if($errorCode == 4) - { - $errorcode="no-image"; - $saveimage="false"; - $image_error="true"; - } - else if($errorCode == 2) - { - $errormessage = 2; - $saveimage="false"; - $image_error="true"; - } - else if($errorCode == 3 ) - { - $errormessage = 3; - $saveimage="false"; - $image_error="true"; - } - } - else - { - $log->debug("Successfully uploaded the Contact Image."); - if($filesize != 0) - { - if (($file_type_val == "jpeg" ) || ($file_type_val == "png") || ($file_type_val == "jpg" ) || ($file_type_val == "pjpeg" ) || ($file_type_val == "x-png") || ($file_type_val == "gif") ) //Checking whether the file is an image or not - { - $saveimage="true"; - $image_error="false"; - } - else - { - $savelogo="false"; - $image_error="true"; - $errormessage = "image"; - } - } - else - { - $savelogo="false"; - $image_error="true"; - $errormessage = "invalid"; - } - - } - } - else //if image is not given - { - $log->debug("Contact Image is not given for uploading."); - if($mode=="edit" && $image_error=="false" ) - { - if($module='contact') - $image_name_val=getContactImageName($id); - elseif($module='user') - $image_name_val=getUserImageName($id); - $saveimage="true"; - } - else - { - $image_name_val=""; - } - } - $return_value=array('imagename'=>$image_name_val, - 'imageerror'=>$image_error, - 'errormessage'=>$errormessage, - 'saveimage'=>$saveimage, - 'mode'=>$mode); - $log->debug("Exiting SaveImage method ..."); - return $return_value; -} - - /** - * This function is used to generate file name if more than one image with same name is added to a given Product. - * Param $filename - product file name - * Param $exist - number time the file name is repeated. - */ - -function file_exist_fn($filename,$exist) -{ - global $log; - $log->debug("Entering file_exist_fn(".$filename.",".$exist.") method ..."); - global $uploaddir; - - if(!isset($exist)) - { - $exist=0; - } - $filename_path=$uploaddir.$filename; - if (file_exists($filename_path)) //Checking if the file name already exists in the directory - { - if($exist!=0) - { - $previous=$exist-1; - $next=$exist+1; - $explode_name=explode("_",$filename); - $implode_array=array(); - for($j=0;$jdebug("Exiting file_exist_fn method ..."); - return $testfilename; - } - } - else - { - $log->debug("Exiting file_exist_fn method ..."); - return $filename; - } -} - -/** - * This function is used get the User Count. - * It returns the array which has the total vtiger_users ,admin vtiger_users,and the non admin vtiger_users - */ - -function UserCount() -{ - global $log; - $log->debug("Entering UserCount() method ..."); - global $adb; - $result=$adb->pquery("select * from vtiger_users where deleted =0", array()); - $user_count=$adb->num_rows($result); - $result=$adb->pquery("select * from vtiger_users where deleted =0 AND is_admin != 'on'", array()); - $nonadmin_count = $adb->num_rows($result); - $admin_count = $user_count-$nonadmin_count; - $count=array('user'=>$user_count,'admin'=>$admin_count,'nonadmin'=>$nonadmin_count); - $log->debug("Exiting UserCount method ..."); - return $count; -} - -/** - * This function is used to create folders recursively. - * Param $dir - directory name - * Param $mode - directory access mode - * Param $recursive - create directory recursive, default true - */ - -function mkdirs($dir, $mode = 0777, $recursive = true) -{ - global $log; - $log->debug("Entering mkdirs(".$dir.",".$mode.",".$recursive.") method ..."); - if( is_null($dir) || $dir === "" ){ - $log->debug("Exiting mkdirs method ..."); - return FALSE; - } - if( is_dir($dir) || $dir === "/" ){ - $log->debug("Exiting mkdirs method ..."); - return TRUE; - } - if( mkdirs(dirname($dir), $mode, $recursive) ){ - $log->debug("Exiting mkdirs method ..."); - return mkdir($dir, $mode); - } - $log->debug("Exiting mkdirs method ..."); - return FALSE; -} - -/** - * This function is used to set the Object values from the REQUEST values. - * @param object reference $focus - reference of the object - */ -function setObjectValuesFromRequest($focus) -{ - global $log; - $log->debug("Entering setObjectValuesFromRequest(".get_class($focus).") method ..."); - global $current_user; - $currencyid=fetchCurrency($current_user->id); - $rate_symbol = getCurrencySymbolandCRate($currencyid); - $rate = $rate_symbol['rate']; - if(isset($_REQUEST['record'])) - { - $focus->id = $_REQUEST['record']; - } - if(isset($_REQUEST['mode'])) - { - $focus->mode = $_REQUEST['mode']; - } - foreach($focus->column_fields as $fieldname => $val) - { - if(isset($_REQUEST[$fieldname])) - { - if(is_array($_REQUEST[$fieldname])) - $value = $_REQUEST[$fieldname]; - else - $value = trim($_REQUEST[$fieldname]); - $focus->column_fields[$fieldname] = $value; - } - } - $log->debug("Exiting setObjectValuesFromRequest method ..."); -} - - /** - * Function to write the tabid and name to a flat file vtiger_tabdata.txt so that the data - * is obtained from the file instead of repeated queries - * returns null - */ - -function create_tab_data_file() -{ - global $log; - $log->debug("Entering create_tab_data_file() method ..."); - $log->info("creating vtiger_tabdata file"); - global $adb; - //$sql = "select * from vtiger_tab"; - // vtlib customization: Disabling the tab item based on presence - $sql = "select * from vtiger_tab where presence in (0,2)"; - // END - - $result = $adb->pquery($sql, array()); - $num_rows=$adb->num_rows($result); - $result_array=Array(); - $seq_array=Array(); - $ownedby_array=Array(); - - for($i=0;$i<$num_rows;$i++) - { - $tabid=$adb->query_result($result,$i,'tabid'); - $tabname=$adb->query_result($result,$i,'name'); - $presence=$adb->query_result($result,$i,'presence'); - $ownedby=$adb->query_result($result,$i,'ownedby'); - $result_array[$tabname]=$tabid; - $seq_array[$tabid]=$presence; - $ownedby_array[$tabid]=$ownedby; - - } - - //Constructing the actionname=>actionid array - $actionid_array=Array(); - $sql1="select * from vtiger_actionmapping"; - $result1=$adb->pquery($sql1, array()); - $num_seq1=$adb->num_rows($result1); - for($i=0;$i<$num_seq1;$i++) - { - $actionname=$adb->query_result($result1,$i,'actionname'); - $actionid=$adb->query_result($result1,$i,'actionid'); - $actionid_array[$actionname]=$actionid; - } - - //Constructing the actionid=>actionname array with securitycheck=0 - $actionname_array=Array(); - $sql2="select * from vtiger_actionmapping where securitycheck=0"; - $result2=$adb->pquery($sql2, array()); - $num_seq2=$adb->num_rows($result2); - for($i=0;$i<$num_seq2;$i++) - { - $actionname=$adb->query_result($result2,$i,'actionname'); - $actionid=$adb->query_result($result2,$i,'actionid'); - $actionname_array[$actionid]=$actionname; - } - - $filename = 'tabdata.php'; - - -if (file_exists($filename)) { - - if (is_writable($filename)) - { - - if (!$handle = fopen($filename, 'w+')) { - echo "Cannot open file ($filename)"; - exit; - } - require_once('modules/Users/CreateUserPrivilegeFile.php'); - $newbuf=''; - $newbuf .=""; - fputs($handle, $newbuf); - fclose($handle); - - } - else - { - echo "The file $filename is not writable"; - } - -} -else -{ - echo "The file $filename does not exist"; - $log->debug("Exiting create_tab_data_file method ..."); - return; -} -} - - - /** - * Function to write the vtiger_parenttabid and name to a flat file parent_tabdata.txt so that the data - * is obtained from the file instead of repeated queries - * returns null - */ - -function create_parenttab_data_file() -{ - global $log; - $log->debug("Entering create_parenttab_data_file() method ..."); - $log->info("creating parent_tabdata file"); - global $adb; - $sql = "select parenttabid,parenttab_label from vtiger_parenttab where visible=0 order by sequence"; - $result = $adb->pquery($sql, array()); - $num_rows=$adb->num_rows($result); - $result_array=Array(); - for($i=0;$i<$num_rows;$i++) - { - $parenttabid=$adb->query_result($result,$i,'parenttabid'); - $parenttab_label=$adb->query_result($result,$i,'parenttab_label'); - $result_array[$parenttabid]=$parenttab_label; - - } - - $filename = 'parent_tabdata.php'; - - - if (file_exists($filename)) { - - if (is_writable($filename)) - { - - if (!$handle = fopen($filename, 'w+')) - { - echo "Cannot open file ($filename)"; - exit; - } - require_once('modules/Users/CreateUserPrivilegeFile.php'); - $newbuf=''; - $newbuf .="$parvalue) - { - $childArray=Array(); - //$sql = "select * from vtiger_parenttabrel where parenttabid=? order by sequence"; - // vtlib customization: Disabling the tab item based on presence - $sql = "select * from vtiger_parenttabrel where parenttabid=? - and tabid in (select tabid from vtiger_tab where presence in (0,2)) order by sequence"; - // END - $result = $adb->pquery($sql, array($parid)); - $num_rows=$adb->num_rows($result); - $result_array=Array(); - for($i=0;$i<$num_rows;$i++) - { - $tabid=$adb->query_result($result,$i,'tabid'); - $childArray[]=$tabid; - } - $parChildTabRelArray[$parid]=$childArray; - - } - $newbuf .= "\n"; - $newbuf .= "\$parent_child_tab_rel_array=".constructTwoDimensionalValueArray($parChildTabRelArray).";\n"; - $newbuf .="\n"; - $newbuf .="\n"; - $newbuf .="\n"; - $newbuf .= "?>"; - fputs($handle, $newbuf); - fclose($handle); - - } - else - { - echo "The file $filename is not writable"; - } - - } - else - { - echo "The file $filename does not exist"; - $log->debug("Exiting create_parenttab_data_file method ..."); - return; - } -} - -/** - * This function is used to get the all the modules that have Quick Create Feature. - * Returns Tab Name and Tablabel. - */ - -function getQuickCreateModules() -{ - global $log; - $log->debug("Entering getQuickCreateModules() method ..."); - global $adb; - global $mod_strings; - - // vtlib customization: Ignore disabled modules. - //$qc_query = "select distinct vtiger_tab.tablabel,vtiger_tab.name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where quickcreate=0 order by vtiger_tab.tablabel"; - $qc_query = "select distinct vtiger_tab.tablabel,vtiger_tab.name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where quickcreate=0 and vtiger_tab.presence != 1 order by vtiger_tab.tablabel"; - // END - - $result = $adb->pquery($qc_query, array()); - $noofrows = $adb->num_rows($result); - $return_qcmodule = Array(); - for($i = 0; $i < $noofrows; $i++) - { - $tablabel = $adb->query_result($result,$i,'tablabel'); - - $tabname = $adb->query_result($result,$i,'name'); - $tablabel = getTranslatedString("SINGLE_$tabname", $tabname); - if(isPermitted($tabname,'EditView','') == 'yes') - { - $return_qcmodule[] = $tablabel; - $return_qcmodule[] = $tabname; - } - } - if(sizeof($return_qcmodule >0)) - { - $return_qcmodule = array_chunk($return_qcmodule,2); - } - - $log->debug("Exiting getQuickCreateModules method ..."); - return $return_qcmodule; -} - -/** - * This function is used to get the Quick create form vtiger_field parameters for a given module. - * Param $module - module name - * returns the value in array format - */ - - -function QuickCreate($module) -{ - global $log; - $log->debug("Entering QuickCreate(".$module.") method ..."); - global $adb; - global $current_user; - global $mod_strings; - - $tabid = getTabid($module); - - //Adding Security Check - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) - { - $quickcreate_query = "select * from vtiger_field where quickcreate in (0,2) and tabid = ? and vtiger_field.presence in (0,2) and displaytype != 2 order by quickcreatesequence"; - $params = array($tabid); - } - else - { - $profileList = getCurrentUserProfileList(); - $quickcreate_query = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND quickcreate in (0,2) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) and displaytype != 2 GROUP BY vtiger_field.fieldid ORDER BY quickcreatesequence"; - $params = array($tabid, $profileList); - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $quickcreate_query = fixPostgresQuery( $quickcreate_query, $log, 0); - } - $category = getParentTab(); - $result = $adb->pquery($quickcreate_query, $params); - $noofrows = $adb->num_rows($result); - $fieldName_array = Array(); - for($i=0; $i<$noofrows; $i++) - { - $fieldtablename = $adb->query_result($result,$i,'tablename'); - $uitype = $adb->query_result($result,$i,"uitype"); - $fieldname = $adb->query_result($result,$i,"fieldname"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $maxlength = $adb->query_result($result,$i,"maximumlength"); - $generatedtype = $adb->query_result($result,$i,"generatedtype"); - $typeofdata = $adb->query_result($result,$i,"typeofdata"); - - //to get validationdata - $fldLabel_array = Array(); - $fldLabel_array[getTranslatedString($fieldlabel)] = $typeofdata; - $fieldName_array[$fieldname] = $fldLabel_array; - $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,$module,'',$typeofdata); - $qcreate_arr[]=$custfld; - } - for ($i=0,$j=0;$i $key1,1 => $key2); - } - $form_data['form'] = $return_data; - $form_data['data'] = $fieldName_array; - $log->debug("Exiting QuickCreate method ...".print_r($form_data,true)); - return $form_data; -} - -/** Function to send the Notification mail to the assigned to owner about the entity creation or updation - * @param string $module -- module name - * @param object $focus -- reference of the object -**/ -function sendNotificationToOwner($module,$focus) -{ - global $log,$app_strings; - $log->debug("Entering sendNotificationToOwner(".$module.",".get_class($focus).") method ..."); - require_once("modules/Emails/mail.php"); - global $current_user; - - $ownername = getUserName($focus->column_fields['assigned_user_id']); - $ownermailid = getUserEmailId('id',$focus->column_fields['assigned_user_id']); - $recseqnumber = ''; - - if($module == 'Contacts') - { - $objectname = $focus->column_fields['lastname'].' '.$focus->column_fields['firstname']; - $recseqnumber=$focus->column_fields['contact_no']; - $mod_name = 'Contact'; - $object_column_fields = array( - 'lastname'=>'Last Name', - 'firstname'=>'First Name', - 'leadsource'=>'Lead Source', - 'department'=>'Department', - 'description'=>'Description', - ); - } - if($module == 'Accounts') - { - $objectname = $focus->column_fields['accountname']; - $recseqnumber=$focus->column_fields['account_no']; - $mod_name = 'Account'; - $object_column_fields = array( - 'accountname'=>'Account Name', - 'rating'=>'Rating', - 'industry'=>'Industry', - 'accounttype'=>'Account Type', - 'description'=>'Description', - ); - } - if($module == 'Potentials') - { - $objectname = $focus->column_fields['potentialname']; - $recseqnumber=$focus->column_fields['potential_no']; - $mod_name = 'Potential'; - $object_column_fields = array( - 'potentialname'=>'Potential Name', - 'amount'=>'Amount', - 'closingdate'=>'Expected Close Date', - 'opportunity_type'=>'Type', - 'description'=>'Description', - ); - } - - if($module == "Accounts" || $module == "Potentials" || $module == "Contacts") - { - $description = $app_strings['MSG_DEAR'].' '.$ownername.',

'; - - if(!empty($recseqnumber)) $recseqnumber = "[$recseqnumber]"; - - if($focus->mode == 'edit') - { - $subject = $app_strings['MSG_REGARDING'].' '.$mod_name.' '.$app_strings['MSG_UPDATION']." $recseqnumber ".$objectname; - $description .= $app_strings['MSG_THE'].' '.$mod_name.' '.$app_strings['MSG_HAS_BEEN_UPDATED'].'.'; - } - else - { - $subject = $app_strings['MSG_REGARDING'].' '.$mod_name.' '.$app_strings['MSG_ASSIGNMENT']." $recseqnumber ".$objectname; - $description .= $app_strings['MSG_THE'].' '.$mod_name.' '.$app_strings['MSG_HAS_BEEN_ASSIGNED_TO_YOU'].'.'; - } - $description .= '
'.$app_strings['MSG_THE'].' '.$mod_name.' '.$app_strings['MSG_DETAILS_ARE'].':

'; - $description .= $mod_name.' '.$app_strings['MSG_ID'].' '.''.$focus->id.'
'; - foreach($object_column_fields as $fieldname => $fieldlabel) - { - //Get the translated string - $temp_label = isset($app_strings[$fieldlabel])?$app_strings[$fieldlabel]:(isset($mod_strings[$fieldlabel])?$mod_strings[$fieldlabel]:$fieldlabel); - - $description .= $temp_label.' : '.$focus->column_fields[$fieldname].'
'; - } - - $description .= '

'.$app_strings['MSG_THANK_YOU'].',
'.$current_user->user_name.'.
'; - $status = send_mail($module,$ownermailid,$current_user->user_name,'',$subject,$description); - - $log->debug("Exiting sendNotificationToOwner method ..."); - return $status; - } -} - -//Function to send notification to the users of a group -function sendNotificationToGroups($groupid,$crmid,$module) -{ - global $adb,$app_strings,$current_user; - $returnEntity=Array(); - $returnEntity=getEntityName($module,Array($crmid)); - $mycrmid=$groupid; - require_once('include/utils/GetGroupUsers.php'); - $getGroupObj=new GetGroupUsers(); - $getGroupObj->getAllUsersInGroup($mycrmid); - $userIds=$getGroupObj->group_users; - if (count($userIds) > 0) { - $groupqry="select email1,id,user_name from vtiger_users WHERE status='Active' AND id in(". generateQuestionMarks($userIds) .")"; - $groupqry_res=$adb->pquery($groupqry, array($userIds)); - for($z=0;$z < $adb->num_rows($groupqry_res);$z++) - { - //handle the mail send to vtiger_users - $emailadd = $adb->query_result($groupqry_res,$z,'email1'); - $curr_userid = $adb->query_result($groupqry_res,$z,'id'); - $tosender=$adb->query_result($groupqry_res,$z,'user_name'); - $pmodule = 'Users'; - $description = $app_strings['MSG_DEAR']." ".$tosender.",
".$returnEntity[$crmid]." ".$app_strings['MSG_HAS_BEEN_CREATED_FOR']." ".$module."

".$app_strings['MSG_THANKS'].",
".$app_strings['MSG_VTIGERTEAM']; - require_once('modules/Emails/mail.php'); - $mail_status = send_mail('Emails',$emailadd,$current_user->user_name,'','Record created-vTiger Team',$description,'','','all',$focus->id); - $all_to_emailids []= $emailadd; - $mail_status_str .= $emailadd."=".$mail_status."&&&"; - } - } -} - - -function getUserslist($setdefval=true) -{ - global $log,$current_user,$module,$adb,$assigned_user_id; - $log->debug("Entering getUserslist() method ..."); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - - if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); - } - else - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id),$current_user->id); - } - foreach($users_combo as $userid=>$value) - { - - foreach($value as $username=>$selected) - { - if ($setdefval == false) { - $change_owner .= ""; - } else { - $change_owner .= ""; - } - } - } - - $log->debug("Exiting getUserslist method ..."); - return $change_owner; -} - - -function getGroupslist() -{ - global $log,$adb,$module,$current_user; - $log->debug("Entering getGroupslist() method ..."); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - - //Commented to avoid security check for groups - if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) - { - $result=get_current_user_access_groups($module); - } - else - { - $result = get_group_options(); - } - - if($result) $nameArray = $adb->fetch_array($result); - if(!empty($nameArray)) - { - if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) - { - $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); - } - else - { - $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id), $current_user->id); - } - } - if(count($groups_combo) > 0) { - foreach($groups_combo as $groupid=>$value) - { - foreach($value as $groupname=>$selected) - { - $change_groups_owner .= ""; - } - } - } - $log->debug("Exiting getGroupslist method ..."); - return $change_groups_owner; -} - - -/** - * Function to Check for Security whether the Buttons are permitted in List/Edit/Detail View of all Modules - * @param string $module -- module name - * Returns an array with permission as Yes or No -**/ -function Button_Check($module) -{ - global $log; - $log->debug("Entering Button_Check(".$module.") method ..."); - $permit_arr = array ('EditView' => '', - 'index' => '', - 'Import' => '', - 'Export' => '', - 'Merge' => '', - 'DuplicatesHandling' => '' ); - - foreach($permit_arr as $action => $perr){ - $tempPer=isPermitted($module,$action,''); - $permit_arr[$action] = $tempPer; - } - $permit_arr["Calendar"] = isPermitted("Calendar","index",''); - $permit_arr["moduleSettings"] = isModuleSettingPermitted($module); - $log->debug("Exiting Button_Check method ..."); - return $permit_arr; - -} - -/** - * Function to Check whether the User is allowed to delete a particular record from listview of each module using - * mass delete button. - * @param string $module -- module name - * @param array $ids_list -- Record id - * Returns the Record Names of each module that is not permitted to delete -**/ -function getEntityName($module, $ids_list) -{ - global $adb; - global $log; - $log->debug("Entering getEntityName(".$module.") method ..."); - - if($module != '') - { - $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?"; - $result = $adb->pquery($query, array($module)); - $fieldsname = $adb->query_result($result,0,'fieldname'); - $tablename = $adb->query_result($result,0,'tablename'); - $entityidfield = $adb->query_result($result,0,'entityidfield'); - if(!(strpos($fieldsname,',') === false)) - { - $fieldlists = explode(',',$fieldsname); - $fieldsname = "concat("; - $fieldsname = $fieldsname.implode(",' ',",$fieldlists); - $fieldsname = $fieldsname.")"; - } - if (count($ids_list) <= 0) { - return array(); - } - - $query1 = "select $fieldsname as entityname from $tablename where $entityidfield in (". generateQuestionMarks($ids_list) .")"; - $params1 = array($ids_list); - $result = $adb->pquery($query1, $params1); - $numrows = $adb->num_rows($result); - $account_name = array(); - for ($i = 0; $i < $numrows; $i++) - { - $entity_id = $ids_list[$i]; - $entity_info[$entity_id] = $adb->query_result($result,$i,'entityname'); - } - return $entity_info; - } - $log->debug("Exiting getEntityName method ..."); -} - -/**Function to get all permitted modules for a user with their parent -*/ - -function getAllParenttabmoduleslist() -{ - global $adb; - global $current_user; - $resultant_array = Array(); - - //$query = 'select name,tablabel,parenttab_label,vtiger_tab.tabid from vtiger_parenttabrel inner join vtiger_tab on vtiger_parenttabrel.tabid = vtiger_tab.tabid inner join vtiger_parenttab on vtiger_parenttabrel.parenttabid = vtiger_parenttab.parenttabid and vtiger_tab.presence order by vtiger_parenttab.sequence, vtiger_parenttabrel.sequence'; - - // vtlib customization: Disabling the tab item based on presence - $query = 'select name,tablabel,parenttab_label,vtiger_tab.tabid from vtiger_parenttabrel inner join vtiger_tab on vtiger_parenttabrel.tabid = vtiger_tab.tabid inner join vtiger_parenttab on vtiger_parenttabrel.parenttabid = vtiger_parenttab.parenttabid and vtiger_tab.presence in (0,2) order by vtiger_parenttab.sequence, vtiger_parenttabrel.sequence'; - // END - - $result = $adb->pquery($query, array()); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - for($i=0;$i<$adb->num_rows($result);$i++) - { - $parenttabname = $adb->query_result($result,$i,'parenttab_label'); - $modulename = $adb->query_result($result,$i,'name'); - $tablabel = $adb->query_result($result,$i,'tablabel'); - $tabid = $adb->query_result($result,$i,'tabid'); - if($is_admin){ - $resultant_array[$parenttabname][] = Array($modulename,$tablabel); - } - elseif($profileGlobalPermission[2]==0 || $profileGlobalPermission[1]==0 || $profileTabsPermission[$tabid]==0) { - $resultant_array[$parenttabname][] = Array($modulename,$tablabel); - } - } - - if($is_admin){ - $resultant_array['Settings'][] = Array('Settings','Settings'); - $resultant_array['Settings'][] = Array('Settings',getTranslatedString('VTLIB_LBL_MODULE_MANAGER', 'Settings'), 'ModuleManager'); - } - return $resultant_array; -} - -/** - * This function is used to decide the File Storage Path in where we will upload the file in the server. - * return string $filepath - filepath inwhere the file should be stored in the server will be return -*/ -function decideFilePath() -{ - global $log, $adb; - $log->debug("Entering into decideFilePath() method ..."); - - $filepath = 'storage/'; - - $year = date('Y'); - $month = date('F'); - $day = date('j'); - $week = ''; - - if(!is_dir($filepath.$year)) - { - //create new folder - mkdir($filepath.$year); - } - - if(!is_dir($filepath.$year."/".$month)) - { - //create new folder - mkdir($filepath."$year/$month"); - } - - if($day > 0 && $day <= 7) - $week = 'week1'; - elseif($day > 7 && $day <= 14) - $week = 'week2'; - elseif($day > 14 && $day <= 21) - $week = 'week3'; - elseif($day > 21 && $day <= 28 ) - $week = 'week4'; - else - $week = 'week5'; - - if(!is_dir($filepath.$year."/".$month."/".$week)) - { - //create new folder - mkdir($filepath."$year/$month/$week"); - } - - $filepath = $filepath.$year."/".$month."/".$week."/"; - - $log->debug("Year=$year & Month=$month & week=$week && filepath=\"$filepath\""); - $log->debug("Exiting from decideFilePath() method ..."); - - return $filepath; -} - -/** - * This function is used to get the Path in where we store the vtiger_files based on the module. - * @param string $module - module name - * return string $storage_path - path inwhere the file will be uploaded (also where it was stored) will be return based on the module -*/ -function getModuleFileStoragePath($module) -{ - global $log; - $log->debug("Entering into getModuleFileStoragePath($module) method ..."); - - $storage_path = "test/"; - - if($module == 'Products') - { - $storage_path .= 'product/'; - } - if($module == 'Contacts') - { - $storage_path .= 'contact/'; - } - - $log->debug("Exiting from getModuleFileStoragePath($module) method. return storage_path = \"$storage_path\""); - return $storage_path; -} - -/** - * This function is used to check whether the attached file is a image file or not - * @param string $file_details - vtiger_files array which contains all the uploaded file details - * return string $save_image - true or false. if the image can be uploaded then true will return otherwise false. -*/ -function validateImageFile($file_details) -{ - global $adb, $log,$app_strings; - $log->debug("Entering into validateImageFile($file_details) method."); - - $savefile = 'true'; - $file_type_details = explode("/",$file_details['type']); - $filetype = $file_type_details['1']; - - if(!empty($filetype)) $filetype = strtolower($filetype); - if (($filetype == "jpeg" ) || ($filetype == "png") || ($filetype == "jpg" ) || ($filetype == "pjpeg" ) || ($filetype == "x-png") || ($filetype == "gif") || ($filetype == 'bmp') ) - { - $saveimage = 'true'; - } - else - { - $saveimage = 'false'; - $_SESSION['image_type_error'] .= "
  ".$file_details[name]."".$app_strings['MSG_IS_NOT_UPLOADED']; - $log->debug("Invalid Image type == $filetype"); - } - - $log->debug("Exiting from validateImageFile($file_details) method. return saveimage=$saveimage"); - return $saveimage; -} - -/** - * This function is used to get the Email Template Details like subject and content for particular template. - * @param integer $templateid - Template Id for an Email Template - * return array $returndata - Returns Subject, Body of Template of the the particular email template. -*/ - -function getTemplateDetails($templateid) -{ - global $adb,$log; - $log->debug("Entering into getTemplateDetails($templateid) method ..."); - $returndata = Array(); - $result = $adb->pquery("select * from vtiger_emailtemplates where templateid=?", array($templateid)); - $returndata[] = $templateid; - $returndata[] = $adb->query_result($result,0,'body'); - $returndata[] = $adb->query_result($result,0,'subject'); - $log->debug("Exiting from getTemplateDetails($templateid) method ..."); - return $returndata; -} -/** - * This function is used to merge the Template Details with the email description - * @param string $description -body of the mail(ie template) - * @param integer $tid - Id of the entity - * @param string $parent_type - module of the entity - * return string $description - Returns description, merged with the input template. -*/ - -function getMergedDescription($description,$id,$parent_type) -{ - global $adb,$log; - $log->debug("Entering getMergedDescription ..."); - $token_data_pair = explode('$',$description); - $fields = Array(); - for($i=1;$i < count($token_data_pair);$i+=2) - { - - $module = explode('-',$token_data_pair[$i]); - $fields[$module[0]][] = $module[1]; - - } - //replace the tokens with the values for the selected parent - switch($parent_type) - { - case 'Accounts': - if(is_array($fields["accounts"])) - { - $columnfields = implode(',',$fields["accounts"]); - $query = "select $columnfields from vtiger_account inner join vtiger_accountscf where vtiger_account.accountid =? and vtiger_accountscf.accountid =?"; - $result = $adb->pquery($query, array($id,$id)); - foreach($fields["accounts"] as $columnname) - { - $token_data = '$accounts-'.$columnname.'$'; - $description = str_replace($token_data,$adb->query_result($result,0,$columnname),$description); - } - } - break; - case 'Contacts': - if(is_array($fields["contacts"])) - { - //Checking for salutation type and checking the table column to be queried - $key = array_search('salutationtype',$fields["contacts"]); - if(isset($key) && $key !='') - { - $fields["contacts"][$key]='salutation'; - } - - $columnfields = implode(',',$fields["contacts"]); - $query = "select $columnfields from vtiger_contactdetails inner join vtiger_contactscf inner join vtiger_customerdetails on vtiger_customerdetails.customerid=vtiger_contactdetails.contactid and vtiger_customerdetails.customerid=vtiger_contactscf.contactid where vtiger_contactdetails.contactid=?"; - $result = $adb->pquery($query, array($id,$id)); - foreach($fields["contacts"] as $columnname) - { - $token_data = '$contacts-'.$columnname.'$'; - $token_value = $adb->query_result($result,0,$columnname); - // Fix for #5417 - if($columnname == 'salutation') $token_value = getTranslatedString($token_value, 'Contacts'); - $description = str_replace($token_data,$token_value,$description); - } - } - break; - case 'Leads': - if(is_array($fields["leads"])) - { - //Checking for salutation type and checking the table column to be queried - $key = array_search('salutationtype',$fields["leads"]); - if(isset($key) && $key !='') - { - $fields["leads"][$key]='salutation'; - } - $columnfields = implode(',',$fields["leads"]); - $query = "select $columnfields from vtiger_leaddetails inner join vtiger_leadscf where vtiger_leaddetails.leadid=? and vtiger_leadscf.leadid=?"; - $result = $adb->pquery($query, array($id,$id)); - foreach($fields["leads"] as $columnname) - { - $token_data = '$leads-'.$columnname.'$'; - $token_value = $adb->query_result($result,0,$columnname); - // Fix for #5417 - if($columnname == 'salutation') $token_value = getTranslatedString($token_value, 'Leads'); - $description = str_replace($token_data,$token_value,$description); - } - } - break; - case 'Users': - if(is_array($fields["users"])) - { - $columnfields = implode(',',$fields["users"]); - $query = "select $columnfields from vtiger_users where id=?"; - $result = $adb->pquery($query, array($id)); - foreach($fields["users"] as $columnname) - { - $token_data = '$users-'.$columnname.'$'; - $description = str_replace($token_data,$adb->query_result($result,0,$columnname),$description); - } - } - break; - } - - $description = getMergedDescriptionCustomVars($fields, $description);//Puneeth : Added for custom date & time fields - $log->debug("Exiting from getMergedDescription ..."); - return $description; -} - -/* Function to merge the custom date & time fields in email templates */ -function getMergedDescriptionCustomVars($fields, $description) { - foreach($fields['custom'] as $columnname) - { - $token_data = '$custom-'.$columnname.'$'; - $token_value = ''; - switch($columnname) { - case 'currentdate': $token_value = date("F j, Y"); break; - case 'currenttime': $token_value = date("G:i:s T"); break; - } - $description = str_replace($token_data, $token_value, $description); - } - return $description; -} -//End : Custom date & time fields - -/** Function used to retrieve a single field value from database - * @param string $tablename - tablename from which we will retrieve the field value - * @param string $fieldname - fieldname to which we want to get the value from database - * @param string $idname - idname which is the name of the entity id in the table like, inoviceid, quoteid, etc., - * @param int $id - entity id - * return string $fieldval - field value of the needed fieldname from database will be returned - */ -function getSingleFieldValue($tablename, $fieldname, $idname, $id) -{ - global $log, $adb; - $log->debug("Entering into function getSingleFieldValue($tablename, $fieldname, $idname, $id)"); - - $fieldval = $adb->query_result($adb->pquery("select $fieldname from $tablename where $idname = ?", array($id)),0,$fieldname); - - $log->debug("Exit from function getSingleFieldValue. return value ==> \"$fieldval\""); - - return $fieldval; -} - -/** Function used to retrieve the announcements from database - * The function accepts no argument and returns the announcements - * return string $announcement - List of announments for the CRM users - */ - -function get_announcements() -{ - global $adb; - $sql=" select * from vtiger_announcement inner join vtiger_users on vtiger_announcement.creatorid=vtiger_users.id"; - $sql.=" AND vtiger_users.is_admin='on' AND vtiger_users.status='Active' AND vtiger_users.deleted = 0"; - $result=$adb->pquery($sql, array()); - for($i=0;$i<$adb->num_rows($result);$i++) - { - $announce = getUserName($adb->query_result($result,$i,'creatorid')).' : '.$adb->query_result($result,$i,'announcement').' '; - if($adb->query_result($result,$i,'announcement')!='') - $announcement.=$announce; - } - return $announcement; -} - -/** Function used to retrieve the rate converted into dollar tobe saved into database - * The function accepts the price in the current currency - * return integer $conv_price - - */ - function getConvertedPrice($price) - { - global $current_user; - $currencyid=fetchCurrency($current_user->id); - $rate_symbol = getCurrencySymbolandCRate($currencyid); - $conv_price = convertToDollar($price,$rate_symbol['rate']); - return $conv_price; - } - - -/** Function used to get the converted amount from dollar which will be showed to the user - * @param float $price - amount in dollor which we want to convert to the user configured amount - * @return float $conv_price - amount in user configured currency - */ -function getConvertedPriceFromDollar($price) -{ - global $current_user; - $currencyid=fetchCurrency($current_user->id); - $rate_symbol = getCurrencySymbolandCRate($currencyid); - $conv_price = convertFromDollar($price,$rate_symbol['rate']); - return $conv_price; -} - - -/** - * Function to get recurring info depending on the recurring type - * return $recurObj - Object of class RecurringType - */ - -function getrecurringObjValue() -{ - $recurring_data = array(); - if(isset($_REQUEST['recurringtype']) && $_REQUEST['recurringtype'] != null && $_REQUEST['recurringtype'] != '--None--' ) - { - if(isset($_REQUEST['date_start']) && $_REQUEST['date_start'] != null) - { - $recurring_data['startdate'] = $_REQUEST['date_start']; - } - if(isset($_REQUEST['due_date']) && $_REQUEST['due_date'] != null) - { - $recurring_data['enddate'] = $_REQUEST['due_date']; - } - $recurring_data['type'] = $_REQUEST['recurringtype']; - if($_REQUEST['recurringtype'] == 'Weekly') - { - if(isset($_REQUEST['sun_flag']) && $_REQUEST['sun_flag'] != null) - $recurring_data['sun_flag'] = true; - if(isset($_REQUEST['mon_flag']) && $_REQUEST['mon_flag'] != null) - $recurring_data['mon_flag'] = true; - if(isset($_REQUEST['tue_flag']) && $_REQUEST['tue_flag'] != null) - $recurring_data['tue_flag'] = true; - if(isset($_REQUEST['wed_flag']) && $_REQUEST['wed_flag'] != null) - $recurring_data['wed_flag'] = true; - if(isset($_REQUEST['thu_flag']) && $_REQUEST['thu_flag'] != null) - $recurring_data['thu_flag'] = true; - if(isset($_REQUEST['fri_flag']) && $_REQUEST['fri_flag'] != null) - $recurring_data['fri_flag'] = true; - if(isset($_REQUEST['sat_flag']) && $_REQUEST['sat_flag'] != null) - $recurring_data['sat_flag'] = true; - } - elseif($_REQUEST['recurringtype'] == 'Monthly') - { - if(isset($_REQUEST['repeatMonth']) && $_REQUEST['repeatMonth'] != null) - $recurring_data['repeatmonth_type'] = $_REQUEST['repeatMonth']; - if($recurring_data['repeatmonth_type'] == 'date') - { - if(isset($_REQUEST['repeatMonth_date']) && $_REQUEST['repeatMonth_date'] != null) - $recurring_data['repeatmonth_date'] = $_REQUEST['repeatMonth_date']; - else - $recurring_data['repeatmonth_date'] = 1; - } - elseif($recurring_data['repeatmonth_type'] == 'day') - { - $recurring_data['repeatmonth_daytype'] = $_REQUEST['repeatMonth_daytype']; - switch($_REQUEST['repeatMonth_day']) - { - case 0 : - $recurring_data['sun_flag'] = true; - break; - case 1 : - $recurring_data['mon_flag'] = true; - break; - case 2 : - $recurring_data['tue_flag'] = true; - break; - case 3 : - $recurring_data['wed_flag'] = true; - break; - case 4 : - $recurring_data['thu_flag'] = true; - break; - case 5 : - $recurring_data['fri_flag'] = true; - break; - case 6 : - $recurring_data['sat_flag'] = true; - break; - } - } - } - if(isset($_REQUEST['repeat_frequency']) && $_REQUEST['repeat_frequency'] != null) - $recurring_data['repeat_frequency'] = $_REQUEST['repeat_frequency']; - $recurObj = new RecurringType($recurring_data); - return $recurObj; - } - -} - -/** Function used to get the translated string to the input string - * @param string $str - input string which we want to translate - * @return string $str - translated string, if the translated string is available then the translated string other wise original string will be returned - */ -function getTranslatedString($str,$module='') -{ - global $app_strings, $mod_strings, $log,$current_language; - $temp_mod_strings = ($module != '' )?return_module_language($current_language,$module):$mod_strings; - $trans_str = ($temp_mod_strings[$str] != '')?$temp_mod_strings[$str]:(($app_strings[$str] != '')?$app_strings[$str]:$str); - $log->debug("function getTranslatedString($str) - translated to ($trans_str)"); - return $trans_str; -} - -/** - * Get translated currency name string. - * @param String $str - input currency name - * @return String $str - translated currency name - */ -function getTranslatedCurrencyString($str) { - global $app_currency_strings; - if(isset($app_currency_strings) && isset($app_currency_strings[$str])) { - return $app_currency_strings[$str]; - } - return $str; -} - -/** function used to get the list of importable fields - * @param string $module - module name - * @return array $fieldslist - array with list of fieldnames and the corresponding translated fieldlabels. The return array will be in the format of [fieldname]=>[fieldlabel] where as the fieldlabel will be translated - */ -function getImportFieldsList($module) -{ - global $adb, $log; - $log->debug("Entering into function getImportFieldsList($module)"); - - $tabid = getTabid($module); - - //Here we can add special cases for module basis, ie., if we want the fields of display type 3, we can add - $displaytype = " displaytype=1 and vtiger_field.presence in (0,2) "; - - $fieldnames = ""; - //For module basis we can add the list of fields for Import mapping - if($module == "Leads" || $module == "Contacts") - { - $fieldnames = " fieldname='salutationtype' "; - } - - //Form the where condition based on tabid , displaytype and extra fields - $where = " WHERE tabid=? and ( $displaytype "; - $params = array($tabid); - if($fieldnames != "") - { - $where .= " or $fieldnames "; - } - $where .= ")"; - - //Get the list of fields and form as array with [fieldname] => [fieldlabel] - $query = "SELECT fieldname, fieldlabel FROM vtiger_field $where"; - $result = $adb->pquery($query, $params); - for($i=0;$i<$adb->num_rows($result);$i++) - { - $fieldname = $adb->query_result($result,$i,'fieldname'); - $fieldlabel = $adb->query_result($result,$i,'fieldlabel'); - $fieldslist[$fieldname] = getTranslatedString($fieldlabel, $module); - } - - $log->debug("Exit from function getImportFieldsList($module)"); - - return $fieldslist; -} -/** Function to get all the comments for a troubleticket - * @param int $ticketid -- troubleticket id - * return all the comments as a sequencial string which are related to this ticket -**/ -function getTicketComments($ticketid) -{ - global $log; - $log->debug("Entering getTicketComments(".$ticketid.") method ..."); - global $adb; - - $commentlist = ''; - $sql = "select * from vtiger_ticketcomments where ticketid=?"; - $result = $adb->pquery($sql, array($ticketid)); - for($i=0;$i<$adb->num_rows($result);$i++) - { - $comment = $adb->query_result($result,$i,'comments'); - if($comment != '') - { - $commentlist .= '

'.$comment; - } - } - if($commentlist != '') - $commentlist = '

The comments are : '.$commentlist; - - $log->debug("Exiting getTicketComments method ..."); - return $commentlist; -} - -function getTicketDetails($id,$whole_date) -{ - global $adb,$mod_strings; - if($whole_date['mode'] == 'edit') - { - $reply = $mod_strings["replied"]; - $temp = "Re : "; - } - else - { - $reply = $mod_strings["created"]; - $temp = " "; - } - - $desc = $mod_strings['Ticket ID'] .' : '.$id.'
Ticket Title : '. $temp .' '.$whole_date['sub']; - $desc .= "

".$mod_strings['Hi']." ". $whole_date['parent_name'].",

".$mod_strings['LBL_PORTAL_BODY_MAILINFO']." ".$reply." ".$mod_strings['LBL_DETAIL']."
"; - $desc .= "
".$mod_strings['Status']." : ".$whole_date['status']; - $desc .= "
".$mod_strings['Category']." : ".$whole_date['category']; - $desc .= "
".$mod_strings['Severity']." : ".$whole_date['severity']; - $desc .= "
".$mod_strings['Priority']." : ".$whole_date['priority']; - $desc .= "

".$mod_strings['Description']." :
".$whole_date['description']; - $desc .= "

".$mod_strings['Solution']." :
".$whole_date['solution']; - $desc .= getTicketComments($id); - - $sql = "SELECT * FROM vtiger_ticketcf WHERE ticketid = ?"; - $result = $adb->pquery($sql, array($id)); - $cffields = $adb->getFieldsArray($result); - foreach ($cffields as $cfOneField) - { - if ($cfOneField != 'ticketid') - { - $cfData = $adb->query_result($result,0,$cfOneField); - $sql = "SELECT fieldlabel FROM vtiger_field WHERE columnname = ? and vtiger_field.presence in (0,2)"; - $cfLabel = $adb->query_result($adb->pquery($sql,array($cfOneField)),0,'fieldlabel'); - $desc .= '

'.$cfLabel.' :
'.$cfData; - } - } - // end of contribution - $desc .= '


'; - $desc .= '
'.$mod_strings["LBL_REGARDS"].',
'.$mod_strings["LBL_TEAM"].'.
'; - return $desc; - -} - -function getPortalInfo_Ticket($id,$title,$contactname,$portal_url) -{ - global $mod_strings; - $bodydetails =$mod_strings['Dear']." ".$contactname.",

"; - $bodydetails .= $mod_strings['reply'].' '.$title.''.$mod_strings['customer_portal']; - $bodydetails .= $mod_strings["link"].'
'; - $bodydetails .= $portal_url; - $bodydetails .= '

'.$mod_strings["Thanks"].'

'.$mod_strings["Support_team"]; - return $bodydetails; -} - -/** - * This function is used to get a random password. - * @return a random password with alpha numeric chanreters of length 8 - */ -function makeRandomPassword() -{ - global $log; - $log->debug("Entering makeRandomPassword() method ..."); - $salt = "abcdefghijklmnopqrstuvwxyz0123456789"; - srand((double)microtime()*1000000); - $i = 0; - while ($i <= 7) - { - $num = rand() % 33; - $tmp = substr($salt, $num, 1); - $pass = $pass . $tmp; - $i++; - } - $log->debug("Exiting makeRandomPassword method ..."); - return $pass; -} - -//added to get mail info for portal user -//type argument included when when addin customizable tempalte for sending portal login details -function getmail_contents_portalUser($request_array,$password,$type='') -{ - global $mod_strings ,$adb; - - $subject = $mod_strings['Customer Portal Login Details']; - - //here id is hardcoded with 5. it is for support start notification in vtiger_notificationscheduler - - $query='select vtiger_emailtemplates.subject,vtiger_emailtemplates.body from vtiger_notificationscheduler inner join vtiger_emailtemplates on vtiger_emailtemplates.templateid=vtiger_notificationscheduler.notificationbody where schedulednotificationid=5'; - - $result = $adb->pquery($query, array()); - $body=$adb->query_result($result,0,'body'); - $contents=$body; - $contents = str_replace('$contact_name$',$request_array['first_name']." ".$request_array['last_name'],$contents); - $contents = str_replace('$login_name$',$request_array['email'],$contents); - $contents = str_replace('$password$',$password,$contents); - $contents = str_replace('$URL$',$request_array['portal_url'],$contents); - $contents = str_replace('$support_team$',$mod_strings['Support Team'],$contents); - $contents = str_replace('$logo$','',$contents); - - if($type == "LoginDetails") - { - $temp=$contents; - $value["subject"]=$adb->query_result($result,0,'subject'); - $value["body"]=$temp; - return $value; - } - - return $contents; - -} - -/** - * Function to get the UItype for a field. - * Takes the input as $module - module name,and columnname of the field - * returns the uitype, integer type - */ -function getUItype($module,$columnname) -{ - global $log; - $log->debug("Entering getUItype(".$module.") method ..."); - //To find tabid for this module - $tabid=getTabid($module); - global $adb; - $sql = "select uitype from vtiger_field where tabid=? and columnname=?"; - $result = $adb->pquery($sql, array($tabid, $columnname)); - $uitype = $adb->query_result($result,0,"uitype"); - $log->debug("Exiting getUItype method ..."); - return $uitype; - -} - -// This function looks like not used anymore. May have to be removed -function is_emailId($entity_id) -{ - global $log,$adb; - $log->debug("Entering is_EmailId(".$entity_id.") method"); - - $module = getSalesEntityType($entity_id); - if($module == 'Contacts') - { - $sql = "select email,yahooid from vtiger_contactdetails inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid where contactid = ?"; - $result = $adb->pquery($sql, array($entity_id)); - $email1 = $adb->query_result($result,0,"email"); - $email2 = $adb->query_result($result,0,"yahooid"); - if($email1 != "" || $email2 != "") { - $check_mailids = "true"; - } else { - $check_mailids = "false"; - } - } - elseif($module == 'Leads') - { - $sql = "select email,yahooid from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_leaddetails.leadid where leadid = ?"; - $result = $adb->pquery($sql, array($entity_id)); - $email1 = $adb->query_result($result,0,"email"); - $email2 = $adb->query_result($result,0,"yahooid"); - if($email1 != "" || $email2 != "") { - $check_mailids = "true"; - } else { - $check_mailids = "false"; - } - } - $log->debug("Exiting is_EmailId() method ..."); - return $check_mailids; -} - -/** - * This function is used to get cvid of default "all" view for any module. - * @return a cvid of a module - */ -function getCvIdOfAll($module) -{ - global $adb,$log; - $log->debug("Entering getCvIdOfAll($module)"); - $qry_res = $adb->pquery("select cvid from vtiger_customview where viewname='All' and entitytype=?", array($module)); - $cvid = $adb->query_result($qry_res,0,"cvid"); - $log->debug("Exiting getCvIdOfAll($module)"); - return $cvid; - - -} - -/** gives the option to display the tagclouds or not for the current user - ** @param $id -- user id:: Type integer - ** @returns true or false in $tag_cloud_view - ** Added to provide User based Tagcloud - **/ - -function getTagCloudView($id=""){ - global $log; - global $adb; - $log->debug("Entering in function getTagCloudView($id)"); - if($id == ''){ - $tag_cloud_status =1; - }else{ - $query = "select visible from vtiger_homestuff where userid=? and stufftype='Tag Cloud'"; - $tag_cloud_status = $adb->query_result($adb->pquery($query, array($id)),0,'visible'); - } - - if($tag_cloud_status == 0){ - $tag_cloud_view='true'; - }else{ - $tag_cloud_view='false'; - } - - $log->debug("Exiting from function getTagCloudView($id)"); - return $tag_cloud_view; -} - -/** Stores the option in database to display the tagclouds or not for the current user - ** @param $id -- user id:: Type integer - ** Added to provide User based Tagcloud - **/ -function SaveTagCloudView($id="") -{ - global $log; - global $adb; - $log->debug("Entering in function SaveTagCloudView($id)"); - $tag_cloud_status=$_REQUEST['tagcloudview']; - - if($tag_cloud_status == "true"){ - $tag_cloud_view = 0; - }else{ - $tag_cloud_view = 1; - } - - if($id == ''){ - $tag_cloud_view =1; - }else{ - $query = "update vtiger_homestuff set visible = ? where userid=? and stufftype='Tag Cloud'"; - $adb->pquery($query, array($tag_cloud_view,$id)); - } - - $log->debug("Exiting from function SaveTagCloudView($id)"); -} - -/** function used to change the Type of Data for advanced filters in custom view and Reports - ** @param string $table_name - tablename value from field table - ** @param string $column_nametable_name - columnname value from field table - ** @param string $type_of_data - current type of data of the field. It is to return the same TypeofData - ** if the field is not matched with the $new_field_details array. - ** return string $type_of_data - If the string matched with the $new_field_details array then the Changed - ** typeofdata will return, else the same typeofdata will return. - ** - ** EXAMPLE: If you have a field entry like this: - ** - ** fieldlabel | typeofdata | tablename | columnname | - ** -------------------+------------+----------------------+------------------+ - ** Potential Name | I~O | vtiger_quotes | potentialid | - ** - ** Then put an entry in $new_field_details like this: - ** - ** "vtiger_quotes:potentialid"=>"V", - ** - ** Now in customview and report's advance filter this field's criteria will be show like string. - ** - **/ -function ChangeTypeOfData_Filter($table_name,$column_name,$type_of_data) -{ - global $adb,$log; - //$log->debug("Entering function ChangeTypeOfData_Filter($table_name,$column_name,$type_of_data)"); - $field=$table_name.":".$column_name; - //Add the field details in this array if you want to change the advance filter field details - - $new_field_details = Array( - - //Contacts Related Fields - "vtiger_contactdetails:accountid"=>"V", - "vtiger_contactsubdetails:birthday"=>"D", - "vtiger_contactdetails:email"=>"V", - "vtiger_contactdetails:yahooid"=>"V", - - //Potential Related Fields - "vtiger_potential:campaignid"=>"V", - - //Account Related Fields - "vtiger_account:parentid"=>"V", - "vtiger_account:email1"=>"V", - "vtiger_account:email2"=>"V", - - //Lead Related Fields - "vtiger_leaddetails:email"=>"V", - "vtiger_leaddetails:yahooid"=>"V", - - //Documents Related Fields - "vtiger_senotesrel:crmid"=>"V", - - //Calendar Related Fields - "vtiger_seactivityrel:crmid"=>"V", - "vtiger_seactivityrel:contactid"=>"V", - "vtiger_recurringevents:recurringtype"=>"V", - - //HelpDesk Related Fields - "vtiger_troubletickets:parent_id"=>"V", - "vtiger_troubletickets:product_id"=>"V", - - //Product Related Fields - "vtiger_products:discontinued"=>"C", - "vtiger_products:vendor_id"=>"V", - "vtiger_products:handler"=>"V", - "vtiger_products:parentid"=>"V", - - //Faq Related Fields - "vtiger_faq:product_id"=>"V", - - //Vendor Related Fields - "vtiger_vendor:email"=>"V", - - //Quotes Related Fields - "vtiger_quotes:potentialid"=>"V", - "vtiger_quotes:inventorymanager"=>"V", - "vtiger_quotes:accountid"=>"V", - - //Purchase Order Related Fields - "vtiger_purchaseorder:vendorid"=>"V", - "vtiger_purchaseorder:contactid"=>"V", - - //SalesOrder Related Fields - "vtiger_salesorder:potentialid"=>"V", - "vtiger_salesorder:quoteid"=>"V", - "vtiger_salesorder:contactid"=>"V", - "vtiger_salesorder:accountid"=>"V", - - //Invoice Related Fields - "vtiger_invoice:salesorderid"=>"V", - "vtiger_invoice:contactid"=>"V", - "vtiger_invoice:accountid"=>"V", - - //Campaign Related Fields - "vtiger_campaign:product_id"=>"V", - - //Related List Entries(For Report Module) - "vtiger_activityproductrel:activityid"=>"V", - "vtiger_activityproductrel:productid"=>"V", - - "vtiger_campaigncontrel:campaignid"=>"V", - "vtiger_campaigncontrel:contactid"=>"V", - - "vtiger_campaignleadrel:campaignid"=>"V", - "vtiger_campaignleadrel:leadid"=>"V", - - "vtiger_cntactivityrel:contactid"=>"V", - "vtiger_cntactivityrel:activityid"=>"V", - - "vtiger_contpotentialrel:contactid"=>"V", - "vtiger_contpotentialrel:potentialid"=>"V", - - "vtiger_crmentitynotesrel:crmid"=>"V", - "vtiger_crmentitynotesrel:notesid"=>"V", - - "vtiger_leadacctrel:leadid"=>"V", - "vtiger_leadacctrel:accountid"=>"V", - - "vtiger_leadcontrel:leadid"=>"V", - "vtiger_leadcontrel:contactid"=>"V", - - "vtiger_leadpotrel:leadid"=>"V", - "vtiger_leadpotrel:potentialid"=>"V", - - "vtiger_pricebookproductrel:pricebookid"=>"V", - "vtiger_pricebookproductrel:productid"=>"V", - - "vtiger_seactivityrel:crmid"=>"V", - "vtiger_seactivityrel:activityid"=>"V", - - "vtiger_senotesrel:crmid"=>"V", - "vtiger_senotesrel:notesid"=>"V", - - "vtiger_seproductsrel:crmid"=>"V", - "vtiger_seproductsrel:productid"=>"V", - - "vtiger_seticketsrel:crmid"=>"V", - "vtiger_seticketsrel:ticketid"=>"V", - - "vtiger_vendorcontactrel:vendorid"=>"V", - "vtiger_vendorcontactrel:contactid"=>"V", - - "vtiger_pricebook:currency_id"=>"V", - ); - - //If the Fields details does not match with the array, then we return the same typeofdata - if(isset($new_field_details[$field])) - { - $type_of_data = $new_field_details[$field]; - } - //$log->debug("Exiting function with the typeofdata: $type_of_data "); - return $type_of_data; -} - - -/** Returns the URL for Basic and Advance Search - ** Added to fix the issue 4600 - **/ -function getBasic_Advance_SearchURL() -{ - - $url = ''; - if($_REQUEST['searchtype'] == 'BasicSearch') - { - $url .= (isset($_REQUEST['query']))?'&query='.vtlib_purify($_REQUEST['query']):''; - $url .= (isset($_REQUEST['search_field']))?'&search_field='.vtlib_purify($_REQUEST['search_field']):''; - $url .= (isset($_REQUEST['search_text']))?'&search_text='.to_html(vtlib_purify($_REQUEST['search_text'])):''; - $url .= (isset($_REQUEST['searchtype']))?'&searchtype='.vtlib_purify($_REQUEST['searchtype']):''; - $url .= (isset($_REQUEST['type']))?'&type='.vtlib_purify($_REQUEST['type']):''; - } - if ($_REQUEST['searchtype'] == 'advance') - { - $url .= (isset($_REQUEST['query']))?'&query='.vtlib_purify($_REQUEST['query']):''; - $count=$_REQUEST['search_cnt']; - for($i=0;$i<$count;$i++) - { - $url .= (isset($_REQUEST['Fields'.$i]))?'&Fields'.$i.'='.stripslashes(str_replace("'","",vtlib_purify($_REQUEST['Fields'.$i]))):''; - $url .= (isset($_REQUEST['Condition'.$i]))?'&Condition'.$i.'='.vtlib_purify($_REQUEST['Condition'.$i]):''; - $url .= (isset($_REQUEST['Srch_value'.$i]))?'&Srch_value'.$i.'='.to_html(vtlib_purify($_REQUEST['Srch_value'.$i])):''; - } - $url .= (isset($_REQUEST['searchtype']))?'&searchtype='.vtlib_purify($_REQUEST['searchtype']):''; - $url .= (isset($_REQUEST['search_cnt']))?'&search_cnt='.vtlib_purify($_REQUEST['search_cnt']):''; - $url .= (isset($_REQUEST['matchtype']))?'&matchtype='.vtlib_purify($_REQUEST['matchtype']):''; - } - return $url; - -} - -/** Clear the Smarty cache files(in Smarty/smarty_c) - ** This function will called after migration. - **/ -function clear_smarty_cache($path=null) { - - global $root_directory; - if($path == null) { - $path=$root_directory.'Smarty/templates_c/'; - } - $mydir = @opendir($path); - while(false !== ($file = readdir($mydir))) { - if($file != "." && $file != ".." && $file != ".svn") { - //chmod($path.$file, 0777); - if(is_dir($path.$file)) { - chdir('.'); - clear_smarty_cache($path.$file.'/'); - //rmdir($path.$file) or DIE("couldn't delete $path$file
"); // No need to delete the directories. - } - else { - // Delete only files ending with .tpl.php - if(strripos($file, '.tpl.php') == (strlen($file)-strlen('.tpl.php'))) { - unlink($path.$file) or DIE("couldn't delete $path$file
"); - } - } - } - } - @closedir($mydir); -} - -/** Get Smarty compiled file for the specified template filename. - ** @param $template_file Template filename for which the compiled file has to be returned. - ** @return Compiled file for the specified template file. - **/ -function get_smarty_compiled_file($template_file, $path=null) { - - global $root_directory; - if($path == null) { - $path=$root_directory.'Smarty/templates_c/'; - } - $mydir = @opendir($path); - $compiled_file = null; - while(false !== ($file = readdir($mydir)) && $compiled_file == null) { - if($file != "." && $file != ".." && $file != ".svn") { - //chmod($path.$file, 0777); - if(is_dir($path.$file)) { - chdir('.'); - $compiled_file = get_smarty_compiled_file($template_file, $path.$file.'/'); - //rmdir($path.$file) or DIE("couldn't delete $path$file
"); // No need to delete the directories. - } - else { - // Check if the file name matches the required template fiel name - if(strripos($file, $template_file.'.php') == (strlen($file)-strlen($template_file.'.php'))) { - $compiled_file = $path.$file; - } - } - } - } - @closedir($mydir); - return $compiled_file; -} - -/** Function to carry out all the necessary actions after migration */ -function perform_post_migration_activities() { - //After applying all the DB Changes,Here we clear the Smarty cache files - clear_smarty_cache(); - //Writing tab data in flat file - create_tab_data_file(); - create_parenttab_data_file(); -} - -/** Function To create Email template variables dynamically -- Pavani */ -function getEmailTemplateVariables(){ - global $adb; - $modules_list = array('Accounts', 'Contacts', 'Leads', 'Users'); - $module_cf_table = array('Accounts' => 'vtiger_accountscf', - 'Contacts' => 'vtiger_contactscf', - 'Leads' => 'vtiger_leadscf'); - foreach($modules_list as $index=>$module){ - if($module == 'Calendar') { - $focus = new Activity(); - } else { - $focus = new $module(); - } - $tabname = $focus->table_name; - $default_fields = $focus->emailTemplate_defaultFields; - // Set the default email template fields for the given module - if ($default_fields != null) { - foreach($default_fields as $index=>$field){ - if($field=='support_start_date' || $field=='support_end_date'){ - $tabname='vtiger_customerdetails'; - } - $sql="select fieldlabel from vtiger_field where tablename=? and columnname=? and vtiger_field.presence in (0,2)"; - $result=$adb->pquery($sql,array($tabname,$field)); - $norows = $adb->num_rows($result); - if($norows > 0){ - $option=array(getTranslatedString($module).': '.getTranslatedString($adb->query_result($result,'fieldlabel')),"$".strtolower($module)."-".$field."$"); - $allFields[] = $option; - } - } - } - // Set the custom fields of a given module for Email templates - $custFields=getCustomFieldArray($module); - foreach($custFields as $val=>$key){ - $sql="select fieldlabel from vtiger_field where tablename=? and columnname=? and uitype!=56 and vtiger_field.presence in (0,2)"; - $result=$adb->pquery($sql,array($module_cf_table[$module],$val)); - $norows = $adb->num_rows($result); - if($norows > 0){ - if($adb->query_result($result,'fieldlabel') != '' and $adb->query_result($result,'fieldlabel') !=NULL){ - $option=array(getTranslatedString($module).': '.getTranslatedString($adb->query_result($result,'fieldlabel')),"$".strtolower($module)."-".$val."$"); - $allFields[] = $option; - } - } - } - //} - $allOptions[] = $allFields; - $allFields=""; - } - $option=array('Current Date','$custom-currentdate$'); - $allFields[] = $option; - $option=array('Current Time','$custom-currenttime$'); - $allFields[] = $option; - $allOptions[] = $allFields; - return $allOptions; -} - -/** Function to get picklist values for the given field that are accessible for the given role. - * @ param $tablename picklist fieldname. - * It gets the picklist values for the given fieldname - * $fldVal = Array(0=>value,1=>value1,-------------,n=>valuen) - * @return Array of picklist values accessible by the user. - */ -function getPickListValues($tablename,$roleid) -{ - global $adb; - $query = "select $tablename from vtiger_$tablename inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$tablename.picklist_valueid where roleid=? and picklistid in (select picklistid from vtiger_picklist) order by sortid"; - $result = $adb->pquery($query, array($roleid)); - $fldVal = Array(); - while($row = $adb->fetch_array($result)) - { - $fldVal []= $row[$tablename]; - } - return $fldVal; -} - -/** Function to check the file access is made within web root directory. */ -function checkFileAccess($filepath) { - global $root_directory; - // Set the base directory to compare with - $use_root_directory = $root_directory; - if(empty($use_root_directory)) { - $use_root_directory = realpath(dirname(__FILE__).'/../../.'); - } - - $realfilepath = realpath($filepath); - - /** Replace all \\ with \ first */ - $realfilepath = str_replace('\\\\', '\\', $realfilepath); - $rootdirpath = str_replace('\\\\', '\\', $use_root_directory); - - /** Replace all \ with / now */ - $realfilepath = str_replace('\\', '/', $realfilepath); - $rootdirpath = str_replace('\\', '/', $rootdirpath); - - if(stripos($realfilepath, $rootdirpath) !== 0) { - die("Sorry! Attempt to access restricted file."); - } -} - -/** Function to get the ActivityType for the given entity id - * @param entityid : Type Integer - * return the activity type for the given id - */ -function getActivityType($id) -{ - global $adb; - $quer = "select activitytype from vtiger_activity where activityid=?"; - $res = $adb->pquery($quer, array($id)); - $acti_type = $adb->query_result($res,0,"activitytype"); - return $acti_type; -} - -/** Function to get owner name either user or group */ -function getOwnerName($id) -{ - global $adb, $log; - $log->debug("Entering getOwnerName(".$id.") method ..."); - $log->info("in getOwnerName ".$id); - - if($id != '') { - $sql = "select user_name from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($id)); - $ownername = $adb->query_result($result,0,"user_name"); - } - if($ownername == '') { - $sql = "select groupname from vtiger_groups where groupid=?"; - $result = $adb->pquery($sql, array($id)); - $ownername = $adb->query_result($result,0,"groupname"); - } - $log->debug("Exiting getOwnerName method ..."); - return $ownername; -} - -/** - * This function is used to get the blockid of the settings block for a given label. - * @param $label - settings label - * @return string type value - */ -function getSettingsBlockId($label) { - global $log, $adb; - $log->debug("Entering getSettingsBlockId(".$label.") method ..."); - - $blockid = ''; - $query = "select blockid from vtiger_settings_blocks where label = ?"; - $result = $adb->pquery($query, array($label)); - $noofrows = $adb->num_rows($result); - if($noofrows == 1) { - $blockid = $adb->query_result($result,0,"blockid"); - } - $log->debug("Exiting getSettingsBlockId method ..."); - return $blockid; -} - -// Function to check if the logged in user is admin -// and if the module is an entity module -// and the module has a Settings.php file within it -function isModuleSettingPermitted($module){ - if (file_exists("modules/$module/Settings.php") && - isPermitted('Settings','index','') == 'yes') { - - return 'yes'; - } - return 'no'; -} - -/** - * this function returns the entity field name for a given module; for e.g. for Contacts module it return concat(lastname, ' ', firstname) - * @param string $module - the module name - * @return string $fieldsname - the entity field name for the module - */ -function getEntityField($module){ - global $adb; - $data = array(); - if(!empty($module)){ - $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?"; - $result = $adb->pquery($query, array($module)); - $fieldsname = $adb->query_result($result,0,'fieldname'); - $tablename = $adb->query_result($result,0,'tablename'); - $entityidfield = $adb->query_result($result,0,'entityidfield'); - if(!(strpos($fieldsname,',') === false)){ - $fieldlists = explode(',',$fieldsname); - $fieldsname = "concat("; - $fieldsname = $fieldsname.implode(",' ',",$fieldlists); - $fieldsname = $fieldsname.")"; - } - } - $data = array("tablename"=>$tablename, "fieldname"=>$fieldsname); - return $data; -} - -// vtiger cache utility -require_once('include/utils/VTCacheUtils.php'); - -// vtlib customization: Extended vtiger CRM utlitiy functions -require_once('include/utils/VtlibUtils.php'); -// END - -function vt_suppressHTMLTags($string){ - return preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); -} +debug("Entering is_admin(".$user->user_name.") method ..."); + + if ($user->is_admin == 'on') + { + $log->debug("Exiting is_admin method ..."); + return true; + } + else + { + $log->debug("Exiting is_admin method ..."); + return false; + } +} + +/** + * THIS FUNCTION IS DEPRECATED AND SHOULD NOT BE USED; USE get_select_options_with_id() + * Create HTML to display select options in a dropdown list. To be used inside + * of a select statement in a form. + * param $option_list - the array of strings to that contains the option list + * param $selected - the string which contains the default value + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_select_options (&$option_list, $selected, $advsearch='false') { + global $log; + $log->debug("Entering get_select_options (".$option_list.",".$selected.",".$advsearch.") method ..."); + $log->debug("Exiting get_select_options method ..."); + return get_select_options_with_id($option_list, $selected, $advsearch); +} + +/** + * Create HTML to display select options in a dropdown list. To be used inside + * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. The values is an array of the datas + * param $option_list - the array of strings to that contains the option list + * param $selected - the string which contains the default value + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_select_options_with_id (&$option_list, $selected_key, $advsearch='false') { + global $log; + $log->debug("Entering get_select_options_with_id (".$option_list.",".$selected_key.",".$advsearch.") method ..."); + $log->debug("Exiting get_select_options_with_id method ..."); + return get_select_options_with_id_separate_key($option_list, $option_list, $selected_key, $advsearch); +} +function get_select_options_with_value (&$option_list, $selected_key, $advsearch='false') { + global $log; + $log->debug("Entering get_select_options_with_id (".$option_list.",".$selected_key.",".$advsearch.") method ..."); + $log->debug("Exiting get_select_options_with_id method ..."); + return get_select_options_with_value_separate_key($option_list, $option_list, $selected_key, $advsearch); +} +/** + * Create HTML to display select options in a dropdown list. To be used inside + * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. + * The values are the display strings. + */ +function get_select_options_array (&$option_list, $selected_key, $advsearch='false') { + global $log; + $log->debug("Entering get_select_options_array (".$option_list.",".$selected_key.",".$advsearch.") method ..."); + $log->debug("Exiting get_select_options_array method ..."); + return get_options_array_seperate_key($option_list, $option_list, $selected_key, $advsearch); +} + +/** + * Create HTML to display select options in a dropdown list. To be used inside + * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. The value is an array of data + * param $label_list - the array of strings to that contains the option list + * param $key_list - the array of strings to that contains the values list + * param $selected - the string which contains the default value + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_options_array_seperate_key (&$label_list, &$key_list, $selected_key, $advsearch='false') { + global $log; + $log->debug("Entering get_options_array_seperate_key (".$label_list.",".$key_list.",".$selected_key.",".$advsearch.") method ..."); + global $app_strings; + if($advsearch=='true') + $select_options = "\n"; + else + $select_options = ""; + + //for setting null selection values to human readable --None-- + $pattern = "/'0?'>".$app_strings['LBL_NONE']."<"; + if (!is_array($selected_key)) $selected_key = array($selected_key); + + //create the type dropdown domain and set the selected value if $opp value already exists + foreach ($key_list as $option_key=>$option_value) { + $selected_string = ''; + // the system is evaluating $selected_key == 0 || '' to true. Be very careful when changing this. Test all cases. + // The vtiger_reported bug was only happening with one of the vtiger_users in the drop down. It was being replaced by none. + if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '') || (in_array($option_key, $selected_key))) + { + $selected_string = 'selected'; + } + + $html_value = $option_key; + + $select_options .= "\n"; + $options[$html_value]=array($label_list[$option_key]=>$selected_string); + } + $select_options = preg_replace($pattern, $replacement, $select_options); + + $log->debug("Exiting get_options_array_seperate_key method ..."); + return $options; +} + +/** + * Create HTML to display select options in a dropdown list. To be used inside + * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. + * The values are the display strings. + */ + +function get_select_options_with_id_separate_key(&$label_list, &$key_list, $selected_key, $advsearch='false') +{ + global $log; + $log->debug("Entering get_select_options_with_id_separate_key(".$label_list.",".$key_list.",".$selected_key.",".$advsearch.") method ..."); + global $app_strings; + if($advsearch=='true') + $select_options = "\n"; + else + $select_options = ""; + + $pattern = "/'0?'>".$app_strings['LBL_NONE']."<"; + if (!is_array($selected_key)) $selected_key = array($selected_key); + + foreach ($key_list as $option_key=>$option_value) { + $selected_string = ''; + if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '') || (in_array($option_key, $selected_key))) + { + $selected_string = 'selected '; + } + + $html_value = $option_key; + + $select_options .= "\n"; + } + $select_options = preg_replace($pattern, $replacement, $select_options); + $log->debug("Exiting get_select_options_with_id_separate_key method ..."); + return $select_options; + +} + +function get_select_options_with_value_separate_key(&$label_list, &$key_list, $selected_key, $advsearch='false') +{ + global $log; + $log->debug("Entering get_select_options_with_id_separate_key(".$label_list.",".$key_list.",".$selected_key.",".$advsearch.") method ..."); + global $app_strings; + if($advsearch=='true') + $select_options = "\n"; + else + $select_options = ""; + + $pattern = "/'0?'>".$app_strings['LBL_NONE']."<"; + if (!is_array($selected_key)) $selected_key = array($selected_key); + + foreach ($key_list as $option_key=>$option_value) { + $selected_string = ''; + if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '') || (in_array($option_key, $selected_key))) + { + $selected_string = 'selected '; + } + + $html_value = $option_key; + + $select_options .= "\n"; + } + $select_options = preg_replace($pattern, $replacement, $select_options); + $log->debug("Exiting get_select_options_with_id_separate_key method ..."); + return $select_options; + +} + +/** + * Converts localized date format string to jscalendar format + * Example: $array = array_csort($array,'town','age',SORT_DESC,'name'); + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function parse_calendardate($local_format) { + global $log; + $log->debug("Entering parse_calendardate(".$local_format.") method ..."); + global $current_user; + if($current_user->date_format == 'dd-mm-yyyy') + { + $dt_popup_fmt = "%d-%m-%Y"; + } + elseif($current_user->date_format == 'mm-dd-yyyy') + { + $dt_popup_fmt = "%m-%d-%Y"; + } + elseif($current_user->date_format == 'yyyy-mm-dd') + { + $dt_popup_fmt = "%Y-%m-%d"; + } + $log->debug("Exiting parse_calendardate method ..."); + return $dt_popup_fmt; +} + +/** + * Decodes the given set of special character + * input values $string - string to be converted, $encode - flag to decode + * returns the decoded value in string fromat + */ + +function from_html($string, $encode=true){ + global $log; + //$log->debug("Entering from_html(".$string.",".$encode.") method ..."); + global $toHtml; + //if($encode && is_string($string))$string = html_entity_decode($string, ENT_QUOTES); + if(is_string($string)){ + if(preg_match('/(script).*(\/script)/i',$string)) + $string=preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); + //$string = str_replace(array_values($toHtml), array_keys($toHtml), $string); + } + //$log->debug("Exiting from_html method ..."); + return $string; +} + +function fck_from_html($string) +{ + if(is_string($string)){ + if(preg_match('/(script).*(\/script)/i',$string)) + $string=str_replace('script', '', $string); + } + return $string; +} + +/** + * Function used to decodes the given single quote and double quote only. This function used for popup selection + * @param string $string - string to be converted, $encode - flag to decode + * @return string $string - the decoded value in string fromat where as only single and double quotes will be decoded + */ + +function popup_from_html($string, $encode=true) +{ + global $log; + $log->debug("Entering popup_from_html(".$string.",".$encode.") method ..."); + + $popup_toHtml = array( + '"' => '"', + "'" => ''', + ); + + //if($encode && is_string($string))$string = html_entity_decode($string, ENT_QUOTES); + if($encode && is_string($string)) + { + $string = addslashes(str_replace(array_values($popup_toHtml), array_keys($popup_toHtml), $string)); + } + + $log->debug("Exiting popup_from_html method ..."); + return $string; +} + + +/** To get the Currency of the specified user + * @param $id -- The user Id:: Type integer + * @returns vtiger_currencyid :: Type integer + */ +function fetchCurrency($id) +{ + global $log; + $log->debug("Entering fetchCurrency(".$id.") method ..."); + + // Lookup the information in cache + $currencyinfo = VTCacheUtils::lookupUserCurrenyId($id); + + if($currencyinfo === false) { + global $adb; + $sql = "select currency_id from vtiger_users where id=?"; + $result = $adb->pquery($sql, array($id)); + $currencyid= $adb->query_result($result,0,"currency_id"); + + VTCacheUtils::updateUserCurrencyId($id, $currencyid); + + // Re-look at the cache for consistency + $currencyinfo = VTCacheUtils::lookupUserCurrenyId($id); + } + + $currencyid = $currencyinfo['currencyid']; + $log->debug("Exiting fetchCurrency method ..."); + return $currencyid; +} + +/** Function to get the Currency name from the vtiger_currency_info + * @param $currencyid -- vtiger_currencyid:: Type integer + * @returns $currencyname -- Currency Name:: Type varchar + * + */ +function getCurrencyName($currencyid, $show_symbol=true) +{ + global $log; + $log->debug("Entering getCurrencyName(".$currencyid.") method ..."); + + // Look at cache first + $currencyinfo = VTCacheUtils::lookupCurrencyInfo($currencyid); + + if($currencyinfo === false) { + global $adb; + $sql1 = "select * from vtiger_currency_info where id= ?"; + $result = $adb->pquery($sql1, array($currencyid)); + + $resultinfo = $adb->fetch_array($result); + + // Update cache + VTCacheUtils::updateCurrencyInfo($currencyid, + $resultinfo['currency_name'], $resultinfo['currency_code'], + $resultinfo['currency_symbol'], $resultinfo['conversion_rate'] + ); + + // Re-look at the cache now + $currencyinfo = VTCacheUtils::lookupCurrencyInfo($currencyid); + } + + $currencyname = $currencyinfo['name']; + $curr_symbol = $currencyinfo['symbol']; + + $log->debug("Exiting getCurrencyName method ..."); + if($show_symbol) return getTranslatedCurrencyString($currencyname).' : '.$curr_symbol; + else return $currencyname; + // NOTE: Without symbol the value could be used for filtering/lookup hence avoiding the translation +} + + +/** + * Function to fetch the list of vtiger_groups from group vtiger_table + * Takes no value as input + * returns the query result set object + */ + +function get_group_options() +{ + global $log; + $log->debug("Entering get_group_options() method ..."); + global $adb,$noof_group_rows;; + $sql = "select groupname,groupid from vtiger_groups"; + $result = $adb->pquery($sql, array()); + $noof_group_rows=$adb->num_rows($result); + $log->debug("Exiting get_group_options method ..."); + return $result; +} + +/** + * Function to get the tabid + * Takes the input as $module - module name + * returns the tabid, integer type + */ + +function getTabid($module) +{ + global $log; + $log->debug("Entering getTabid(".$module.") method ..."); + + // Lookup information in cache first + $tabid = VTCacheUtils::lookupTabid($module); + if($tabid === false) { + + if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { + include('tabdata.php'); + $tabid= $tab_info_array[$module]; + + // Update information to cache for re-use + VTCacheUtils::updateTabidInfo($tabid, $module); + + } else { + $log->info("module is ".$module); + global $adb; + $sql = "select tabid from vtiger_tab where name=?"; + $result = $adb->pquery($sql, array($module)); + $tabid= $adb->query_result($result,0,"tabid"); + + // Update information to cache for re-use + VTCacheUtils::updateTabidInfo($tabid, $module); + } + } + + $log->debug("Exiting getTabid method ..."); + return $tabid; + +} + +/** + * Function to get the fieldid + * + * @param Integer $tabid + * @param Boolean $onlyactive + */ +function getFieldid($tabid, $fieldname, $onlyactive = true) { + global $adb; + + // Look up information at cache first + $fieldinfo = VTCacheUtils::lookupFieldInfo($tabid, $fieldname); + if($fieldinfo === false) { + $query = "SELECT fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence + FROM vtiger_field WHERE tabid=? AND fieldname=?"; + $result = $adb->pquery($query, array($tabid, $fieldname)); + + if($adb->num_rows($result)) { + + $resultrow = $adb->fetch_array($result); + + // Update information to cache for re-use + VTCacheUtils::updateFieldInfo( + $tabid, $fieldname,$resultrow['fieldid'], + $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], + $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']); + + $fieldinfo = VTCacheUtils::lookupFieldInfo($tabid, $fieldname); + } + } + + // Get the field id based on required criteria + $fieldid = false; + + if($fieldinfo) { + $fieldid = $fieldinfo['fieldid']; + if($onlyactive && !in_array($fieldinfo['presence'], array('0', '2'))) { + $fieldid = false; + } + } + return $fieldid; +} + +/** + * Function to get the CustomViewName + * Takes the input as $cvid - customviewid + * returns the cvname string fromat + */ + +function getCVname($cvid) +{ + global $log; + $log->debug("Entering getCVname method ..."); + + global $adb; + $sql = "select viewname from vtiger_customview where cvid=?"; + $result = $adb->pquery($sql, array($cvid)); + $cvname = $adb->query_result($result,0,"viewname"); + + $log->debug("Exiting getCVname method ..."); + return $cvname; + +} + + + +/** + * Function to get the ownedby value for the specified module + * Takes the input as $module - module name + * returns the tabid, integer type + */ + +function getTabOwnedBy($module) +{ + global $log; + $log->debug("Entering getTabid(".$module.") method ..."); + + $tabid=getTabid($module); + + if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) + { + include('tabdata.php'); + $tab_ownedby= $tab_ownedby_array[$tabid]; + } + else + { + + $log->info("module is ".$module); + global $adb; + $sql = "select ownedby from vtiger_tab where name=?"; + $result = $adb->pquery($sql, array($module)); + $tab_ownedby= $adb->query_result($result,0,"ownedby"); + } + $log->debug("Exiting getTabid method ..."); + return $tab_ownedby; + +} + + + + +/** + * Function to get the tabid + * Takes the input as $module - module name + * returns the tabid, integer type + */ + +function getSalesEntityType($crmid) +{ + global $log; + $log->debug("Entering getSalesEntityType(".$crmid.") method ..."); + $log->info("in getSalesEntityType ".$crmid); + global $adb; + $sql = "select setype from vtiger_crmentity where crmid=?"; + $result = $adb->pquery($sql, array($crmid)); + $parent_module = $adb->query_result($result,0,"setype"); + $log->debug("Exiting getSalesEntityType method ..."); + return $parent_module; +} + +/** + * Function to get the AccountName when a vtiger_account id is given + * Takes the input as $acount_id - vtiger_account id + * returns the vtiger_account name in string format. + */ + +function getAccountName($account_id) +{ + global $log; + $log->debug("Entering getAccountName(".$account_id.") method ..."); + $log->info("in getAccountName ".$account_id); + + global $adb; + if($account_id != ''){ + $sql = "select accountname from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($account_id)); + $accountname = $adb->query_result($result,0,"accountname"); + } + $log->debug("Exiting getAccountName method ..."); + return $accountname; +} + +/** + * Function to get the ProductName when a product id is given + * Takes the input as $product_id - product id + * returns the product name in string format. + */ + +function getProductName($product_id) +{ + global $log; + $log->debug("Entering getProductName(".$product_id.") method ..."); + + $log->info("in getproductname ".$product_id); + + global $adb; + $sql = "select productname from vtiger_products where productid=?"; + $result = $adb->pquery($sql, array($product_id)); + $productname = $adb->query_result($result,0,"productname"); + $log->debug("Exiting getProductName method ..."); + return $productname; +} + +/** + * Function to get the Potentail Name when a vtiger_potential id is given + * Takes the input as $potential_id - vtiger_potential id + * returns the vtiger_potential name in string format. + */ + +function getPotentialName($potential_id) +{ + global $log; + $log->debug("Entering getPotentialName(".$potential_id.") method ..."); + $log->info("in getPotentialName ".$potential_id); + + global $adb; + $potentialname = ''; + if($potential_id != '') + { + $sql = "select potentialname from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($potential_id)); + $potentialname = $adb->query_result($result,0,"potentialname"); + } + $log->debug("Exiting getPotentialName method ..."); + return $potentialname; +} + +/** + * Function to get the Contact Name when a contact id is given + * Takes the input as $contact_id - contact id + * returns the Contact Name in string format. + */ + +function getContactName($contact_id) +{ + global $log; + $log->debug("Entering getContactName(".$contact_id.") method ..."); + $log->info("in getContactName ".$contact_id); + + global $adb, $current_user; + $contact_name = ''; + if($contact_id != '') + { + $sql = "select * from vtiger_contactdetails where contactid=?"; + $result = $adb->pquery($sql, array($contact_id)); + $firstname = $adb->query_result($result,0,"firstname"); + $lastname = $adb->query_result($result,0,"lastname"); + $contact_name = $lastname; + // Asha: Check added for ticket 4788 + if (getFieldVisibilityPermission("Contacts", $current_user->id,'firstname') == '0') { + $contact_name .= ' '.$firstname; + } + } + $log->debug("Exiting getContactName method ..."); + return $contact_name; +} + +/** + * Function to get the Contact Name when a contact id is given + * Takes the input as $contact_id - contact id + * returns the Contact Name in string format. + */ + +function getLeadName($lead_id) +{ + global $log; + $log->debug("Entering getLeadName(".$lead_id.") method ..."); + $log->info("in getLeadName ".$lead_id); + + global $adb, $current_user; + $lead_name = ''; + if($lead_id != '') + { + $sql = "select * from vtiger_leaddetails where leadid=?"; + $result = $adb->pquery($sql, array($lead_id)); + $firstname = $adb->query_result($result,0,"firstname"); + $lastname = $adb->query_result($result,0,"lastname"); + $lead_name = $lastname; + // Asha: Check added for ticket 4788 + if (getFieldVisibilityPermission("Leads", $current_user->id,'firstname') == '0') { + $lead_name .= ' '.$firstname; + } + } + $log->debug("Exiting getLeadName method ..."); + return $lead_name; +} + +/** + * Function to get the Full Name of a Contact/Lead when a query result and the row count are given + * Takes the input as $result - Query Result, $row_count - Count of the Row, $module - module name + * returns the Contact Name in string format. + */ + +function getFullNameFromQResult($result, $row_count, $module) +{ + global $log, $adb, $current_user; + $log->info("In getFullNameFromQResult(". print_r($result, true) . " - " . $row_count . "-".$module.") method ..."); + + $rowdata = $adb->query_result_rowdata($result,$row_count); + + $name = ''; + if($rowdata != '' && count($rowdata) > 0) + { + $firstname = $rowdata["firstname"]; + $lastname = $rowdata["lastname"]; + $name = $lastname; + // Asha: Check added for ticket 4788 + if (getFieldVisibilityPermission($module, $current_user->id,'firstname') == '0') { + $name .= ' '.$firstname; + } + } + $nam = textlength_check($name); + + return $nam; +} + +/** + * Function to get the Campaign Name when a campaign id is given + * Takes the input as $campaign_id - campaign id + * returns the Campaign Name in string format. + */ + +function getCampaignName($campaign_id) +{ + global $log; + $log->debug("Entering getCampaignName(".$campaign_id.") method ..."); + $log->info("in getCampaignName ".$campaign_id); + + global $adb; + $sql = "select * from vtiger_campaign where campaignid=?"; + $result = $adb->pquery($sql, array($campaign_id)); + $campaign_name = $adb->query_result($result,0,"campaignname"); + $log->debug("Exiting getCampaignName method ..."); + return $campaign_name; +} + + +/** + * Function to get the Vendor Name when a vtiger_vendor id is given + * Takes the input as $vendor_id - vtiger_vendor id + * returns the Vendor Name in string format. + */ + +function getVendorName($vendor_id) +{ + global $log; + $log->debug("Entering getVendorName(".$vendor_id.") method ..."); + $log->info("in getVendorName ".$vendor_id); + global $adb; + $sql = "select * from vtiger_vendor where vendorid=?"; + $result = $adb->pquery($sql, array($vendor_id)); + $vendor_name = $adb->query_result($result,0,"vendorname"); + $log->debug("Exiting getVendorName method ..."); + return $vendor_name; +} + +/** + * Function to get the Quote Name when a vtiger_vendor id is given + * Takes the input as $quote_id - quote id + * returns the Quote Name in string format. + */ + +function getQuoteName($quote_id) +{ + global $log; + $log->debug("Entering getQuoteName(".$quote_id.") method ..."); + $log->info("in getQuoteName ".$quote_id); + global $adb; + if($quote_id != NULL && $quote_id != '') + { + $sql = "select * from vtiger_quotes where quoteid=?"; + $result = $adb->pquery($sql, array($quote_id)); + $quote_name = $adb->query_result($result,0,"subject"); + } + else + { + $log->debug("Quote Id is empty."); + $quote_name = ''; + } + $log->debug("Exiting getQuoteName method ..."); + return $quote_name; +} + +/** + * Function to get the PriceBook Name when a vtiger_pricebook id is given + * Takes the input as $pricebook_id - vtiger_pricebook id + * returns the PriceBook Name in string format. + */ + +function getPriceBookName($pricebookid) +{ + global $log; + $log->debug("Entering getPriceBookName(".$pricebookid.") method ..."); + $log->info("in getPriceBookName ".$pricebookid); + global $adb; + $sql = "select * from vtiger_pricebook where pricebookid=?"; + $result = $adb->pquery($sql, array($pricebookid)); + $pricebook_name = $adb->query_result($result,0,"bookname"); + $log->debug("Exiting getPriceBookName method ..."); + return $pricebook_name; +} + +/** This Function returns the Purchase Order Name. + * The following is the input parameter for the function + * $po_id --> Purchase Order Id, Type:Integer + */ +function getPoName($po_id) +{ + global $log; + $log->debug("Entering getPoName(".$po_id.") method ..."); + $log->info("in getPoName ".$po_id); + global $adb; + $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($sql, array($po_id)); + $po_name = $adb->query_result($result,0,"subject"); + $log->debug("Exiting getPoName method ..."); + return $po_name; +} +/** + * Function to get the Sales Order Name when a vtiger_salesorder id is given + * Takes the input as $salesorder_id - vtiger_salesorder id + * returns the Salesorder Name in string format. + */ + +function getSoName($so_id) +{ + global $log; + $log->debug("Entering getSoName(".$so_id.") method ..."); + $log->info("in getSoName ".$so_id); + global $adb; + $sql = "select * from vtiger_salesorder where salesorderid=?"; + $result = $adb->pquery($sql, array($so_id)); + $so_name = $adb->query_result($result,0,"subject"); + $log->debug("Exiting getSoName method ..."); + return $so_name; +} + +/** + * Function to get the Group Information for a given groupid + * Takes the input $id - group id and $module - module name + * returns the group information in an array format. + */ + +function getGroupName($groupid) +{ + global $adb, $log; + $log->debug("Entering getGroupName(".$groupid.") method ..."); + $group_info = Array(); + $log->info("in getGroupName, entityid is ".$groupid); + if($groupid != '') + { + $sql = "select groupname,groupid from vtiger_groups where groupid = ?"; + $result = $adb->pquery($sql, array($groupid)); + $group_info[] = decode_html($adb->query_result($result,0,"groupname")); + $group_info[] = $adb->query_result($result,0,"groupid"); + } + $log->debug("Exiting getGroupName method ..."); + return $group_info; +} + +/** + * Get the username by giving the user id. This method expects the user id + */ + +function getUserName($userid) +{ + global $adb, $log; + $log->debug("Entering getUserName(".$userid.") method ..."); + $log->info("in getUserName ".$userid); + + if($userid != '') + { + $sql = "select user_name from vtiger_users where id=?"; + $result = $adb->pquery($sql, array($userid)); + $user_name = $adb->query_result($result,0,"user_name"); + } + $log->debug("Exiting getUserName method ..."); + return $user_name; +} + +/** +* Get the user full name by giving the user id. This method expects the user id +* DG 30 Aug 2006 +*/ + +function getUserFullName($userid) +{ + global $log; + $log->debug("Entering getUserFullName(".$userid.") method ..."); + $log->info("in getUserFullName ".$userid); + global $adb; + if($userid != '') + { + $sql = "select first_name, last_name from vtiger_users where id=?"; + $result = $adb->pquery($sql, array($userid)); + $first_name = $adb->query_result($result,0,"first_name"); + $last_name = $adb->query_result($result,0,"last_name"); + $user_name = $first_name." ".$last_name; + } + $log->debug("Exiting getUserFullName method ..."); + return $user_name; +} + +/** Fucntion to get related To name with id */ +function getParentName($parent_id) +{ + global $adb; + if ($parent_id == 0) + return ""; + $sql="select setype from vtiger_crmentity where crmid=?"; + $result=$adb->pquery($sql,array($parent_id)); + //For now i have conditions only for accounts and contacts, if needed can add more + if($adb->query_result($result,'setype') == 'Accounts') + $sql1="select accountname name from vtiger_account where accountid=?"; + else if($adb->query_result($result,'setype') == 'Contacts') + $sql1="select concat( firstname, ' ', lastname ) name from vtiger_contactdetails where contactid=?"; + $result1=$adb->pquery($sql1,array($parent_id)); + $asd=$adb->query_result($result1,'name'); + return $asd; +} + +/** + * Creates and returns database query. To be used for search and other text links. This method expects the module object. + * param $focus - the module object contains the column vtiger_fields + */ + +function getURLstring($focus) +{ + global $log; + $log->debug("Entering getURLstring(".get_class($focus).") method ..."); + $qry = ""; + foreach($focus->column_fields as $fldname=>$val) + { + if(isset($_REQUEST[$fldname]) && $_REQUEST[$fldname] != '') + { + if($qry == '') + $qry = "&".$fldname."=".vtlib_purify($_REQUEST[$fldname]); + else + $qry .="&".$fldname."=".vtlib_purify($_REQUEST[$fldname]); + } + } + if(isset($_REQUEST['current_user_only']) && $_REQUEST['current_user_only'] !='') + { + $qry .="¤t_user_only=".vtlib_purify($_REQUEST['current_user_only']); + } + if(isset($_REQUEST['advanced']) && $_REQUEST['advanced'] =='true') + { + $qry .="&advanced=true"; + } + + if($qry !='') + { + $qry .="&query=true"; + } + $log->debug("Exiting getURLstring method ..."); + return $qry; + +} + +/** This function returns the date in user specified format. + * param $cur_date_val - the default date format + */ + +function getDisplayDate($cur_date_val) +{ + global $log; + $log->debug("Entering getDisplayDate(".$cur_date_val.") method ..."); + global $current_user; + $dat_fmt = $current_user->date_format; + if($dat_fmt == '') + { + $dat_fmt = 'dd-mm-yyyy'; + } + + $date_value = explode(' ',$cur_date_val); + list($y,$m,$d) = explode('-',$date_value[0]); + if($dat_fmt == 'dd-mm-yyyy') + { + $display_date = $d.'-'.$m.'-'.$y; + } + elseif($dat_fmt == 'mm-dd-yyyy') + { + + $display_date = $m.'-'.$d.'-'.$y; + } + elseif($dat_fmt == 'yyyy-mm-dd') + { + + $display_date = $y.'-'.$m.'-'.$d; + } + + if($date_value[1] != '') + { + $display_date = $display_date.' '.$date_value[1]; + } + $log->debug("Exiting getDisplayDate method ..."); + return $display_date; + +} + +/** + * This function returns the date in user specified format. + * limitation is that mm-dd-yyyy and dd-mm-yyyy will be considered same by this API. + * As in the date value is on mm-dd-yyyy and user date format is dd-mm-yyyy then the mm-dd-yyyy + * value will be return as the API will be considered as considered as in same format. + * this due to the fact that this API tries to consider the where given date is in user date + * format. we need a better gauge for this case. + * @global Users $current_user + * @param Date $cur_date_val the date which should a changed to user date format. + * @return Date + */ +function getValidDisplayDate($cur_date_val) { + global $current_user; + $dat_fmt = $current_user->date_format; + if($dat_fmt == '') { + $dat_fmt = 'dd-mm-yyyy'; + } + $date_value = explode(' ',$cur_date_val); + list($y,$m,$d) = explode('-',$date_value[0]); + list($fy, $fm, $fd) = explode('-', $dat_fmt); + if((strlen($fy) == 4 && strlen($y) == 4) || (strlen($fd) == 4 && strlen($d) == 4)) { + return $cur_date_val; + } + return getDisplayDate($cur_date_val); +} + +/** This function returns the date in user specified format. + * Takes no param, receives the date format from current user object + */ + +function getNewDisplayDate() +{ + global $log; + $log->debug("Entering getNewDisplayDate() method ..."); + $log->info("in getNewDisplayDate "); + + global $current_user; + $dat_fmt = $current_user->date_format; + if($dat_fmt == '') + { + $dat_fmt = 'dd-mm-yyyy'; + } + $display_date=''; + if($dat_fmt == 'dd-mm-yyyy') + { + $display_date = date('d-m-Y'); + } + elseif($dat_fmt == 'mm-dd-yyyy') + { + $display_date = date('m-d-Y'); + } + elseif($dat_fmt == 'yyyy-mm-dd') + { + $display_date = date('Y-m-d'); + } + + $log->debug("Exiting getNewDisplayDate method ..."); + return $display_date; +} + +/** This function returns the default vtiger_currency information. + * Takes no param, return type array. + */ + +function getDisplayCurrency() +{ + global $log; + global $adb; + $log->debug("Entering getDisplayCurrency() method ..."); + $curr_array = Array(); + $sql1 = "select * from vtiger_currency_info where currency_status=? and deleted=0"; + $result = $adb->pquery($sql1, array('Active')); + $num_rows=$adb->num_rows($result); + for($i=0; $i<$num_rows;$i++) + { + $curr_id = $adb->query_result($result,$i,"id"); + $curr_name = $adb->query_result($result,$i,"currency_name"); + $curr_symbol = $adb->query_result($result,$i,"currency_symbol"); + $curr_array[$curr_id] = $curr_name.' : '.$curr_symbol; + } + $log->debug("Exiting getDisplayCurrency method ..."); + return $curr_array; +} + +/** This function returns the amount converted to dollar. + * param $amount - amount to be converted. + * param $crate - conversion rate. + */ + +function convertToDollar($amount,$crate){ + global $log; + $log->debug("Entering convertToDollar(".$amount.",".$crate.") method ..."); + $log->debug("Exiting convertToDollar method ..."); + return $amount / $crate; +} + +/** This function returns the amount converted from dollar. + * param $amount - amount to be converted. + * param $crate - conversion rate. + */ +function convertFromDollar($amount,$crate){ + global $log; + $log->debug("Entering convertFromDollar(".$amount.",".$crate.") method ..."); + $log->debug("Exiting convertFromDollar method ..."); + return $amount * $crate; +} + +/** This function returns the amount converted from master currency. + * param $amount - amount to be converted. + * param $crate - conversion rate. + */ +function convertFromMasterCurrency($amount,$crate){ + global $log; + $log->debug("Entering convertFromDollar(".$amount.",".$crate.") method ..."); + $log->debug("Exiting convertFromDollar method ..."); + return $amount * $crate; +} + +/** This function returns the conversion rate and vtiger_currency symbol + * in array format for a given id. + * param $id - vtiger_currency id. + */ + +function getCurrencySymbolandCRate($id) +{ + global $log; + $log->debug("Entering getCurrencySymbolandCRate(".$id.") method ..."); + + // To initialize the currency information in cache + getCurrencyName($id); + + $currencyinfo = VTCacheUtils::lookupCurrencyInfo($id); + + $rate_symbol['rate'] = $currencyinfo['rate']; + $rate_symbol['symbol']= $currencyinfo['symbol']; + + $log->debug("Exiting getCurrencySymbolandCRate method ..."); + return $rate_symbol; +} + +/** This function returns the terms and condition from the database. + * Takes no param and the return type is text. + */ + +function getTermsandConditions() +{ + global $log; + $log->debug("Entering getTermsandConditions() method ..."); + global $adb; + $sql1 = "select * from vtiger_inventory_tandc"; + $result = $adb->pquery($sql1, array()); + $tandc = $adb->query_result($result,0,"tandc"); + $log->debug("Exiting getTermsandConditions method ..."); + return $tandc; +} + +/** + * Create select options in a dropdown list. To be used inside + * a reminder select statement in a vtiger_activity form. + * param $start - start value + * param $end - end value + * param $fldname - vtiger_field name + * param $selvalue - selected value + */ + +function getReminderSelectOption($start,$end,$fldname,$selvalue='') +{ + global $log; + $log->debug("Entering getReminderSelectOption(".$start.",".$end.",".$fldname.",".$selvalue=''.") method ..."); + global $mod_strings; + global $app_strings; + + $def_sel =""; + $OPTION_FLD = ""; + $log->debug("Exiting getReminderSelectOption method ..."); + return $OPTION_FLD; +} + +/** This function returns the List price of a given product in a given price book. + * param $productid - product id. + * param $pbid - vtiger_pricebook id. + */ + +function getListPrice($productid,$pbid) +{ + global $log; + $log->debug("Entering getListPrice(".$productid.",".$pbid.") method ..."); + $log->info("in getListPrice productid ".$productid); + + global $adb; + $query = "select listprice from vtiger_pricebookproductrel where pricebookid=? and productid=?"; + $result = $adb->pquery($query, array($pbid, $productid)); + $lp = $adb->query_result($result,0,'listprice'); + $log->debug("Exiting getListPrice method ..."); + return $lp; +} + +/** This function returns a string with removed new line character, single quote, and back slash double quoute. + * param $str - string to be converted. + */ + +function br2nl($str) { + global $log; + $log->debug("Entering br2nl(".$str.") method ..."); + $str = preg_replace("/(\r\n)/", "\\r\\n", $str); + $str = preg_replace("/'/", " ", $str); + $str = preg_replace("/\"/", " ", $str); + $log->debug("Exiting br2nl method ..."); + return $str; +} + +/** This function returns a text, which escapes the html encode for link tag/ a href tag +*param $text - string/text +*/ + +function make_clickable($text) +{ + global $log; + $log->debug("Entering make_clickable(".$text.") method ..."); + $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text); + // pad it with a space so we can match things at the start of the 1st line. + $ret = ' ' . $text; + + // matches an "xxxx://yyyy" URL at the start of a line, or after a space. + // xxxx can only be alpha characters. + // yyyy is anything up to the first space, newline, comma, double quote or < + $ret = preg_replace("#(^|[\n ])([\w]+?://.*?[^ \"\n\r\t<]*)#is", "\\1\\2", $ret); + + // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing + // Must contain at least 2 dots. xxxx contains either alphanum, or "-" + // zzzz is optional.. will contain everything up to the first space, newline, + // comma, double quote or <. + $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\-]+\.[\w\-.\~]+(?:/[^ \"\t\n\r<]*)?)#is", "\\1\\2", $ret); + + // matches an email@domain type address at the start of a line, or after a space. + // Note: Only the followed chars are valid; alphanums, "-", "_" and or ".". + $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2@\\3", $ret); + + // Remove our padding.. + $ret = substr($ret, 1); + + //remove comma, fullstop at the end of url + $ret = preg_replace("#,\"|\.\"|\)\"|\)\.\"|\.\)\"#", "\"", $ret); + + $log->debug("Exiting make_clickable method ..."); + return($ret); +} +/** + * This function returns the vtiger_blocks and its related information for given module. + * Input Parameter are $module - module name, $disp_view = display view (edit,detail or create),$mode - edit, $col_fields - * column vtiger_fields/ + * This function returns an array + */ + +function getBlocks($module,$disp_view,$mode,$col_fields='',$info_type='') +{ + global $log; + $log->debug("Entering getBlocks(".$module.",".$disp_view.",".$mode.",".$col_fields.",".$info_type.") method ..."); + global $adb,$current_user; + global $mod_strings; + $tabid = getTabid($module); + $block_detail = Array(); + $getBlockinfo = ""; + $query="select blockid,blocklabel,show_title,display_status from vtiger_blocks where tabid=? and $disp_view=0 and visible = 0 order by sequence"; + $result = $adb->pquery($query, array($tabid)); + $noofrows = $adb->num_rows($result); + $prev_header = ""; + $blockid_list = array(); + for($i=0; $i<$noofrows; $i++) + { + $blockid = $adb->query_result($result,$i,"blockid"); + array_push($blockid_list,$blockid); + $block_label[$blockid] = $adb->query_result($result,$i,"blocklabel"); + + $sLabelVal = getTranslatedString($block_label[$blockid], $module); + $aBlockStatus[$sLabelVal] = $adb->query_result($result,$i,"display_status"); + } + if($mode == 'edit') + { + $display_type_check = 'vtiger_field.displaytype = 1'; + }elseif($mode == 'mass_edit') + { + $display_type_check = 'vtiger_field.displaytype = 1 AND vtiger_field.masseditable NOT IN (0,2)'; + }else + { + $display_type_check = 'vtiger_field.displaytype in (1,4)'; + } + + /*if($non_mass_edit_fields!='' && sizeof($non_mass_edit_fields)!=0){ + $mass_edit_query = "AND vtiger_field.fieldname NOT IN (". generateQuestionMarks($non_mass_edit_fields) .")"; + }*/ + + //retreive the vtiger_profileList from database + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + if($disp_view == "detail_view") + { + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users" || $module == "Emails") + { + $sql = "SELECT vtiger_field.* FROM vtiger_field WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND vtiger_field.displaytype IN (1,2,4) and vtiger_field.presence in (0,2) ORDER BY block,sequence"; + $params = array($tabid, $blockid_list); + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND vtiger_field.displaytype IN (1,2,4) and vtiger_field.presence in (0,2) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; + $params = array($tabid, $blockid_list, $profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $sql = fixPostgresQuery( $sql, $log, 0); + } + $result = $adb->pquery($sql, $params); + + // Added to unset the previous record's related listview session values + if(isset($_SESSION['rlvs'])) + unset($_SESSION['rlvs']); + + $getBlockInfo=getDetailBlockInformation($module,$result,$col_fields,$tabid,$block_label); + } + else + { + if ($info_type != '') + { + if($is_admin==true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2]== 0 || $module == 'Users' || $module == "Emails") + { + $sql = "SELECT vtiger_field.* FROM vtiger_field WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND $display_type_check AND info_type = ? and vtiger_field.presence in (0,2) ORDER BY block,sequence"; + $params = array($tabid, $blockid_list, $info_type); + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list) .") AND $display_type_check AND info_type = ? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; + $params = array($tabid, $blockid_list, $info_type, $profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $sql = fixPostgresQuery( $sql, $log, 0); + } + } + else + { + if($is_admin==true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == 'Users' || $module == "Emails") + { + $sql = "SELECT vtiger_field.* FROM vtiger_field WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list).") AND $display_type_check and vtiger_field.presence in (0,2) ORDER BY block,sequence"; + $params = array($tabid, $blockid_list); + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_field.block IN (". generateQuestionMarks($blockid_list).") AND $display_type_check AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList).") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; + $params = array($tabid, $blockid_list, $profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $sql = fixPostgresQuery( $sql, $log, 0); + } + } + $result = $adb->pquery($sql, $params); + $getBlockInfo=getBlockInformation($module,$result,$col_fields,$tabid,$block_label,$mode); + } + $log->debug("Exiting getBlocks method ..."); + if(count($getBlockInfo) > 0) + { + foreach($getBlockInfo as $label=>$contents) + { + if(empty($getBlockInfo[$label])) + { + unset($getBlockInfo[$label]); + } + } + } + $_SESSION['BLOCKINITIALSTATUS'] = $aBlockStatus; + return $getBlockInfo; +} +/** + * This function is used to get the display type. + * Takes the input parameter as $mode - edit (mostly) + * This returns string type value + */ + +function getView($mode) +{ + global $log; + $log->debug("Entering getView(".$mode.") method ..."); + if($mode=="edit") + $disp_view = "edit_view"; + else + $disp_view = "create_view"; + $log->debug("Exiting getView method ..."); + return $disp_view; +} +/** + * This function is used to get the blockid of the customblock for a given module. + * Takes the input parameter as $tabid - module tabid and $label - custom label + * This returns string type value + */ + +function getBlockId($tabid,$label) +{ + global $log; + $log->debug("Entering getBlockId(".$tabid.",".$label.") method ..."); + global $adb; + $blockid = ''; + $query = "select blockid from vtiger_blocks where tabid=? and blocklabel = ?"; + $result = $adb->pquery($query, array($tabid, $label)); + $noofrows = $adb->num_rows($result); + if($noofrows == 1) + { + $blockid = $adb->query_result($result,0,"blockid"); + } + $log->debug("Exiting getBlockId method ..."); + return $blockid; +} + +/** + * This function is used to get the Parent and Child vtiger_tab relation array. + * Takes no parameter and get the data from parent_tabdata.php and vtiger_tabdata.php + * This returns array type value + */ + +function getHeaderArray() +{ + global $log; + $log->debug("Entering getHeaderArray() method ..."); + global $adb; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + include('parent_tabdata.php'); + include('tabdata.php'); + $noofrows = count($parent_tab_info_array); + foreach($parent_tab_info_array as $parid=>$parval) + { + $subtabs = Array(); + $tablist=$parent_child_tab_rel_array[$parid]; + $noofsubtabs = count($tablist); + + foreach($tablist as $childTabId) + { + $module = array_search($childTabId,$tab_info_array); + + if($is_admin) + { + $subtabs[] = $module; + } + elseif($profileGlobalPermission[2]==0 ||$profileGlobalPermission[1]==0 || $profileTabsPermission[$childTabId]==0) + { + $subtabs[] = $module; + } + } + + $parenttab = getParentTabName($parid); + if($parenttab == 'Settings' && $is_admin) + { + $subtabs[] = 'Settings'; + } + + if($parenttab != 'Settings' ||($parenttab == 'Settings' && $is_admin)) + { + if(!empty($subtabs)) + $relatedtabs[$parenttab] = $subtabs; + } + } + $log->debug("Exiting getHeaderArray method ..."); + return $relatedtabs; +} + +/** + * This function is used to get the Parent Tab name for a given parent vtiger_tab id. + * Takes the input parameter as $parenttabid - Parent vtiger_tab id + * This returns value string type + */ + +function getParentTabName($parenttabid) +{ + global $log; + $log->debug("Entering getParentTabName(".$parenttabid.") method ..."); + global $adb; + if (file_exists('parent_tabdata.php') && (filesize('parent_tabdata.php') != 0)) + { + include('parent_tabdata.php'); + $parent_tabname= $parent_tab_info_array[$parenttabid]; + } + else + { + $sql = "select parenttab_label from vtiger_parenttab where parenttabid=?"; + $result = $adb->pquery($sql, array($parenttabid)); + $parent_tabname= $adb->query_result($result,0,"parenttab_label"); + } + $log->debug("Exiting getParentTabName method ..."); + return $parent_tabname; +} + +/** + * This function is used to get the Parent Tab name for a given module. + * Takes the input parameter as $module - module name + * This returns value string type + */ + + +function getParentTabFromModule($module) +{ + global $log; + $log->debug("Entering getParentTabFromModule(".$module.") method ..."); + global $adb; + if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0) && file_exists('parent_tabdata.php') && (filesize('parent_tabdata.php') != 0)) + { + include('tabdata.php'); + include('parent_tabdata.php'); + $tabid=$tab_info_array[$module]; + foreach($parent_child_tab_rel_array as $parid=>$childArr) + { + if(in_array($tabid,$childArr)) + { + $parent_tabname= $parent_tab_info_array[$parid]; + break; + } + } + $log->debug("Exiting getParentTabFromModule method ..."); + return $parent_tabname; + } + else + { + $sql = "select vtiger_parenttab.* from vtiger_parenttab inner join vtiger_parenttabrel on vtiger_parenttabrel.parenttabid=vtiger_parenttab.parenttabid inner join vtiger_tab on vtiger_tab.tabid=vtiger_parenttabrel.tabid where vtiger_tab.name=?"; + $result = $adb->pquery($sql, array($module)); + $tab = $adb->query_result($result,0,"parenttab_label"); + $log->debug("Exiting getParentTabFromModule method ..."); + return $tab; + } +} + +/** + * This function is used to get the Parent Tab name for a given module. + * Takes no parameter but gets the vtiger_parenttab value from form request + * This returns value string type + */ +function getParentTab() { + global $log, $default_charset; + $log->debug("Entering getParentTab() method ..."); + if(!empty($_REQUEST['parenttab'])) { + $log->debug("Exiting getParentTab method ..."); + return vtlib_purify($_REQUEST['parenttab']); + } else { + $log->debug("Exiting getParentTab method ..."); + return getParentTabFromModule($_REQUEST['module']); + } +} + +/** + * This function is used to get the days in between the current time and the modified time of an entity . + * Takes the input parameter as $id - crmid it will calculate the number of days in between the + * the current time and the modified time from the vtiger_crmentity vtiger_table and return the result as a string. + * The return format is updated day ago <(date when updated)> + */ + +function updateInfo($id) +{ + global $log; + $log->debug("Entering updateInfo(".$id.") method ..."); + + global $adb; + global $app_strings; + $query='select modifiedtime from vtiger_crmentity where crmid = ?'; + $result = $adb->pquery($query, array($id)); + $modifiedtime = $adb->query_result($result,0,'modifiedtime'); + $values=explode(' ',$modifiedtime); + $date_info=explode('-',$values[0]); + $time_info=explode(':',$values[1]); + $date = $date_info[2].' '.$app_strings[date("M", mktime(0, 0, 0, $date_info[1], $date_info[2],$date_info[0]))].' '.$date_info[0]; + $time_modified = mktime($time_info[0], $time_info[1], $time_info[2], $date_info[1], $date_info[2],$date_info[0]); + $time_now = time(); + $days_diff = (int)(($time_now - $time_modified) / (60 * 60 * 24)); + if($days_diff == 0) + $update_info = $app_strings['LBL_UPDATED_TODAY']." (".$date.")"; + elseif($days_diff == 1) + $update_info = $app_strings['LBL_UPDATED']." ".$days_diff." ".$app_strings['LBL_DAY_AGO']." (".$date.")"; + else + $update_info = $app_strings['LBL_UPDATED']." ".$days_diff." ".$app_strings['LBL_DAYS_AGO']." (".$date.")"; + + $log->debug("Exiting updateInfo method ..."); + return $update_info; +} + + +/** + * This function is used to get the Product Images for the given Product . + * It accepts the product id as argument and returns the Images with the script for + * rotating the product Images + */ + +function getProductImages($id) +{ + global $log; + $log->debug("Entering getProductImages(".$id.") method ..."); + global $adb; + $image_lists=array(); + $script_images=array(); + $script = ''; + if($imagename != '') + { + $log->debug("Exiting getProductImages method ..."); + return $script; + } +} + +/** + * This function is used to save the Images . + * It acceps the File lists,modulename,id and the mode as arguments + * It returns the array details of the upload + */ + +function SaveImage($_FILES,$module,$id,$mode) +{ + global $log, $root_directory; + $log->debug("Entering SaveImage(".$_FILES.",".$module.",".$id.",".$mode.") method ..."); + global $adb; + $uploaddir = $root_directory."test/".$module."/" ;//set this to which location you need to give the contact image + $log->info("The Location to Save the Contact Image is ".$uploaddir); + $file_path_name = $_FILES['imagename']['name']; + if (isset($_REQUEST['imagename_hidden'])) { + $file_name = vtlib_purify($_REQUEST['imagename_hidden']); + } else { + //allowed filename like UTF-8 Character + $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name); + } + $image_error="false"; + $saveimage="true"; + if($file_name!="") + { + + $log->debug("Contact Image is given for uploading"); + $image_name_val=file_exist_fn($file_name,0); + + $encode_field_values=""; + $errormessage=""; + + $move_upload_status=move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$image_name_val); + $image_error="false"; + + //if there is an error in the uploading of image + + $filetype= $_FILES['imagename']['type']; + $filesize = $_FILES['imagename']['size']; + + $filetype_array=explode("/",$filetype); + + $file_type_val_image=strtolower($filetype_array[0]); + $file_type_val=strtolower($filetype_array[1]); + $log->info("The File type of the Contact Image is :: ".$file_type_val); + //checking the uploaded image is if an image type or not + if(!$move_upload_status) //if any error during file uploading + { + $log->debug("Error is present in uploading Contact Image."); + $errorCode = $_FILES['imagename']['error']; + if($errorCode == 4) + { + $errorcode="no-image"; + $saveimage="false"; + $image_error="true"; + } + else if($errorCode == 2) + { + $errormessage = 2; + $saveimage="false"; + $image_error="true"; + } + else if($errorCode == 3 ) + { + $errormessage = 3; + $saveimage="false"; + $image_error="true"; + } + } + else + { + $log->debug("Successfully uploaded the Contact Image."); + if($filesize != 0) + { + if (($file_type_val == "jpeg" ) || ($file_type_val == "png") || ($file_type_val == "jpg" ) || ($file_type_val == "pjpeg" ) || ($file_type_val == "x-png") || ($file_type_val == "gif") ) //Checking whether the file is an image or not + { + $saveimage="true"; + $image_error="false"; + } + else + { + $savelogo="false"; + $image_error="true"; + $errormessage = "image"; + } + } + else + { + $savelogo="false"; + $image_error="true"; + $errormessage = "invalid"; + } + + } + } + else //if image is not given + { + $log->debug("Contact Image is not given for uploading."); + if($mode=="edit" && $image_error=="false" ) + { + if($module='contact') + $image_name_val=getContactImageName($id); + elseif($module='user') + $image_name_val=getUserImageName($id); + $saveimage="true"; + } + else + { + $image_name_val=""; + } + } + $return_value=array('imagename'=>$image_name_val, + 'imageerror'=>$image_error, + 'errormessage'=>$errormessage, + 'saveimage'=>$saveimage, + 'mode'=>$mode); + $log->debug("Exiting SaveImage method ..."); + return $return_value; +} + + /** + * This function is used to generate file name if more than one image with same name is added to a given Product. + * Param $filename - product file name + * Param $exist - number time the file name is repeated. + */ + +function file_exist_fn($filename,$exist) +{ + global $log; + $log->debug("Entering file_exist_fn(".$filename.",".$exist.") method ..."); + global $uploaddir; + + if(!isset($exist)) + { + $exist=0; + } + $filename_path=$uploaddir.$filename; + if (file_exists($filename_path)) //Checking if the file name already exists in the directory + { + if($exist!=0) + { + $previous=$exist-1; + $next=$exist+1; + $explode_name=explode("_",$filename); + $implode_array=array(); + for($j=0;$jdebug("Exiting file_exist_fn method ..."); + return $testfilename; + } + } + else + { + $log->debug("Exiting file_exist_fn method ..."); + return $filename; + } +} + +/** + * This function is used get the User Count. + * It returns the array which has the total vtiger_users ,admin vtiger_users,and the non admin vtiger_users + */ + +function UserCount() +{ + global $log; + $log->debug("Entering UserCount() method ..."); + global $adb; + $result=$adb->pquery("select * from vtiger_users where deleted =0", array()); + $user_count=$adb->num_rows($result); + $result=$adb->pquery("select * from vtiger_users where deleted =0 AND is_admin != 'on'", array()); + $nonadmin_count = $adb->num_rows($result); + $admin_count = $user_count-$nonadmin_count; + $count=array('user'=>$user_count,'admin'=>$admin_count,'nonadmin'=>$nonadmin_count); + $log->debug("Exiting UserCount method ..."); + return $count; +} + +/** + * This function is used to create folders recursively. + * Param $dir - directory name + * Param $mode - directory access mode + * Param $recursive - create directory recursive, default true + */ + +function mkdirs($dir, $mode = 0777, $recursive = true) +{ + global $log; + $log->debug("Entering mkdirs(".$dir.",".$mode.",".$recursive.") method ..."); + if( is_null($dir) || $dir === "" ){ + $log->debug("Exiting mkdirs method ..."); + return FALSE; + } + if( is_dir($dir) || $dir === "/" ){ + $log->debug("Exiting mkdirs method ..."); + return TRUE; + } + if( mkdirs(dirname($dir), $mode, $recursive) ){ + $log->debug("Exiting mkdirs method ..."); + return mkdir($dir, $mode); + } + $log->debug("Exiting mkdirs method ..."); + return FALSE; +} + +/** + * This function is used to set the Object values from the REQUEST values. + * @param object reference $focus - reference of the object + */ +function setObjectValuesFromRequest($focus) +{ + global $log; + $log->debug("Entering setObjectValuesFromRequest(".get_class($focus).") method ..."); + global $current_user; + $currencyid=fetchCurrency($current_user->id); + $rate_symbol = getCurrencySymbolandCRate($currencyid); + $rate = $rate_symbol['rate']; + if(isset($_REQUEST['record'])) + { + $focus->id = $_REQUEST['record']; + } + if(isset($_REQUEST['mode'])) + { + $focus->mode = $_REQUEST['mode']; + } + foreach($focus->column_fields as $fieldname => $val) + { + if(isset($_REQUEST[$fieldname])) + { + if(is_array($_REQUEST[$fieldname])) + $value = $_REQUEST[$fieldname]; + else + $value = trim($_REQUEST[$fieldname]); + $focus->column_fields[$fieldname] = $value; + } + } + $log->debug("Exiting setObjectValuesFromRequest method ..."); +} + + /** + * Function to write the tabid and name to a flat file vtiger_tabdata.txt so that the data + * is obtained from the file instead of repeated queries + * returns null + */ + +function create_tab_data_file() +{ + global $log; + $log->debug("Entering create_tab_data_file() method ..."); + $log->info("creating vtiger_tabdata file"); + global $adb; + //$sql = "select * from vtiger_tab"; + // vtlib customization: Disabling the tab item based on presence + $sql = "select * from vtiger_tab where presence in (0,2)"; + // END + + $result = $adb->pquery($sql, array()); + $num_rows=$adb->num_rows($result); + $result_array=Array(); + $seq_array=Array(); + $ownedby_array=Array(); + + for($i=0;$i<$num_rows;$i++) + { + $tabid=$adb->query_result($result,$i,'tabid'); + $tabname=$adb->query_result($result,$i,'name'); + $presence=$adb->query_result($result,$i,'presence'); + $ownedby=$adb->query_result($result,$i,'ownedby'); + $result_array[$tabname]=$tabid; + $seq_array[$tabid]=$presence; + $ownedby_array[$tabid]=$ownedby; + + } + + //Constructing the actionname=>actionid array + $actionid_array=Array(); + $sql1="select * from vtiger_actionmapping"; + $result1=$adb->pquery($sql1, array()); + $num_seq1=$adb->num_rows($result1); + for($i=0;$i<$num_seq1;$i++) + { + $actionname=$adb->query_result($result1,$i,'actionname'); + $actionid=$adb->query_result($result1,$i,'actionid'); + $actionid_array[$actionname]=$actionid; + } + + //Constructing the actionid=>actionname array with securitycheck=0 + $actionname_array=Array(); + $sql2="select * from vtiger_actionmapping where securitycheck=0"; + $result2=$adb->pquery($sql2, array()); + $num_seq2=$adb->num_rows($result2); + for($i=0;$i<$num_seq2;$i++) + { + $actionname=$adb->query_result($result2,$i,'actionname'); + $actionid=$adb->query_result($result2,$i,'actionid'); + $actionname_array[$actionid]=$actionname; + } + + $filename = 'tabdata.php'; + + +if (file_exists($filename)) { + + if (is_writable($filename)) + { + + if (!$handle = fopen($filename, 'w+')) { + echo "Cannot open file ($filename)"; + exit; + } + require_once('modules/Users/CreateUserPrivilegeFile.php'); + $newbuf=''; + $newbuf .=""; + fputs($handle, $newbuf); + fclose($handle); + + } + else + { + echo "The file $filename is not writable"; + } + +} +else +{ + echo "The file $filename does not exist"; + $log->debug("Exiting create_tab_data_file method ..."); + return; +} +} + + + /** + * Function to write the vtiger_parenttabid and name to a flat file parent_tabdata.txt so that the data + * is obtained from the file instead of repeated queries + * returns null + */ + +function create_parenttab_data_file() +{ + global $log; + $log->debug("Entering create_parenttab_data_file() method ..."); + $log->info("creating parent_tabdata file"); + global $adb; + $sql = "select parenttabid,parenttab_label from vtiger_parenttab where visible=0 order by sequence"; + $result = $adb->pquery($sql, array()); + $num_rows=$adb->num_rows($result); + $result_array=Array(); + for($i=0;$i<$num_rows;$i++) + { + $parenttabid=$adb->query_result($result,$i,'parenttabid'); + $parenttab_label=$adb->query_result($result,$i,'parenttab_label'); + $result_array[$parenttabid]=$parenttab_label; + + } + + $filename = 'parent_tabdata.php'; + + + if (file_exists($filename)) { + + if (is_writable($filename)) + { + + if (!$handle = fopen($filename, 'w+')) + { + echo "Cannot open file ($filename)"; + exit; + } + require_once('modules/Users/CreateUserPrivilegeFile.php'); + $newbuf=''; + $newbuf .="$parvalue) + { + $childArray=Array(); + //$sql = "select * from vtiger_parenttabrel where parenttabid=? order by sequence"; + // vtlib customization: Disabling the tab item based on presence + $sql = "select * from vtiger_parenttabrel where parenttabid=? + and tabid in (select tabid from vtiger_tab where presence in (0,2)) order by sequence"; + // END + $result = $adb->pquery($sql, array($parid)); + $num_rows=$adb->num_rows($result); + $result_array=Array(); + for($i=0;$i<$num_rows;$i++) + { + $tabid=$adb->query_result($result,$i,'tabid'); + $childArray[]=$tabid; + } + $parChildTabRelArray[$parid]=$childArray; + + } + $newbuf .= "\n"; + $newbuf .= "\$parent_child_tab_rel_array=".constructTwoDimensionalValueArray($parChildTabRelArray).";\n"; + $newbuf .="\n"; + $newbuf .="\n"; + $newbuf .="\n"; + $newbuf .= "?>"; + fputs($handle, $newbuf); + fclose($handle); + + } + else + { + echo "The file $filename is not writable"; + } + + } + else + { + echo "The file $filename does not exist"; + $log->debug("Exiting create_parenttab_data_file method ..."); + return; + } +} + +/** + * This function is used to get the all the modules that have Quick Create Feature. + * Returns Tab Name and Tablabel. + */ + +function getQuickCreateModules() +{ + global $log; + $log->debug("Entering getQuickCreateModules() method ..."); + global $adb; + global $mod_strings; + + // vtlib customization: Ignore disabled modules. + //$qc_query = "select distinct vtiger_tab.tablabel,vtiger_tab.name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where quickcreate=0 order by vtiger_tab.tablabel"; + $qc_query = "select distinct vtiger_tab.tablabel,vtiger_tab.name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where quickcreate=0 and vtiger_tab.presence != 1 order by vtiger_tab.tablabel"; + // END + + $result = $adb->pquery($qc_query, array()); + $noofrows = $adb->num_rows($result); + $return_qcmodule = Array(); + for($i = 0; $i < $noofrows; $i++) + { + $tablabel = $adb->query_result($result,$i,'tablabel'); + + $tabname = $adb->query_result($result,$i,'name'); + $tablabel = getTranslatedString("SINGLE_$tabname", $tabname); + if(isPermitted($tabname,'EditView','') == 'yes') + { + $return_qcmodule[] = $tablabel; + $return_qcmodule[] = $tabname; + } + } + if(sizeof($return_qcmodule >0)) + { + $return_qcmodule = array_chunk($return_qcmodule,2); + } + + $log->debug("Exiting getQuickCreateModules method ..."); + return $return_qcmodule; +} + +/** + * This function is used to get the Quick create form vtiger_field parameters for a given module. + * Param $module - module name + * returns the value in array format + */ + + +function QuickCreate($module) +{ + global $log; + $log->debug("Entering QuickCreate(".$module.") method ..."); + global $adb; + global $current_user; + global $mod_strings; + + $tabid = getTabid($module); + + //Adding Security Check + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $quickcreate_query = "select * from vtiger_field where quickcreate in (0,2) and tabid = ? and vtiger_field.presence in (0,2) and displaytype != 2 order by quickcreatesequence"; + $params = array($tabid); + } + else + { + $profileList = getCurrentUserProfileList(); + $quickcreate_query = "SELECT vtiger_field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND quickcreate in (0,2) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) and displaytype != 2 GROUP BY vtiger_field.fieldid ORDER BY quickcreatesequence"; + $params = array($tabid, $profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $quickcreate_query = fixPostgresQuery( $quickcreate_query, $log, 0); + } + $category = getParentTab(); + $result = $adb->pquery($quickcreate_query, $params); + $noofrows = $adb->num_rows($result); + $fieldName_array = Array(); + for($i=0; $i<$noofrows; $i++) + { + $fieldtablename = $adb->query_result($result,$i,'tablename'); + $uitype = $adb->query_result($result,$i,"uitype"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $maxlength = $adb->query_result($result,$i,"maximumlength"); + $generatedtype = $adb->query_result($result,$i,"generatedtype"); + $typeofdata = $adb->query_result($result,$i,"typeofdata"); + + //to get validationdata + $fldLabel_array = Array(); + $fldLabel_array[getTranslatedString($fieldlabel)] = $typeofdata; + $fieldName_array[$fieldname] = $fldLabel_array; + $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,$module,'',$typeofdata); + $qcreate_arr[]=$custfld; + } + for ($i=0,$j=0;$i $key1,1 => $key2); + } + $form_data['form'] = $return_data; + $form_data['data'] = $fieldName_array; + $log->debug("Exiting QuickCreate method ...".print_r($form_data,true)); + return $form_data; +} + +/** Function to send the Notification mail to the assigned to owner about the entity creation or updation + * @param string $module -- module name + * @param object $focus -- reference of the object +**/ +function sendNotificationToOwner($module,$focus) +{ + global $log,$app_strings; + $log->debug("Entering sendNotificationToOwner(".$module.",".get_class($focus).") method ..."); + require_once("modules/Emails/mail.php"); + global $current_user; + + $ownername = getUserName($focus->column_fields['assigned_user_id']); + $ownermailid = getUserEmailId('id',$focus->column_fields['assigned_user_id']); + $recseqnumber = ''; + + if($module == 'Contacts') + { + $objectname = $focus->column_fields['lastname'].' '.$focus->column_fields['firstname']; + $recseqnumber=$focus->column_fields['contact_no']; + $mod_name = 'Contact'; + $object_column_fields = array( + 'lastname'=>'Last Name', + 'firstname'=>'First Name', + 'leadsource'=>'Lead Source', + 'department'=>'Department', + 'description'=>'Description', + ); + } + if($module == 'Accounts') + { + $objectname = $focus->column_fields['accountname']; + $recseqnumber=$focus->column_fields['account_no']; + $mod_name = 'Account'; + $object_column_fields = array( + 'accountname'=>'Account Name', + 'rating'=>'Rating', + 'industry'=>'Industry', + 'accounttype'=>'Account Type', + 'description'=>'Description', + ); + } + if($module == 'Potentials') + { + $objectname = $focus->column_fields['potentialname']; + $recseqnumber=$focus->column_fields['potential_no']; + $mod_name = 'Potential'; + $object_column_fields = array( + 'potentialname'=>'Potential Name', + 'amount'=>'Amount', + 'closingdate'=>'Expected Close Date', + 'opportunity_type'=>'Type', + 'description'=>'Description', + ); + } + + if($module == "Accounts" || $module == "Potentials" || $module == "Contacts") + { + $description = $app_strings['MSG_DEAR'].' '.$ownername.',

'; + + if(!empty($recseqnumber)) $recseqnumber = "[$recseqnumber]"; + + if($focus->mode == 'edit') + { + $subject = $app_strings['MSG_REGARDING'].' '.$mod_name.' '.$app_strings['MSG_UPDATION']." $recseqnumber ".$objectname; + $description .= $app_strings['MSG_THE'].' '.$mod_name.' '.$app_strings['MSG_HAS_BEEN_UPDATED'].'.'; + } + else + { + $subject = $app_strings['MSG_REGARDING'].' '.$mod_name.' '.$app_strings['MSG_ASSIGNMENT']." $recseqnumber ".$objectname; + $description .= $app_strings['MSG_THE'].' '.$mod_name.' '.$app_strings['MSG_HAS_BEEN_ASSIGNED_TO_YOU'].'.'; + } + $description .= '
'.$app_strings['MSG_THE'].' '.$mod_name.' '.$app_strings['MSG_DETAILS_ARE'].':

'; + $description .= $mod_name.' '.$app_strings['MSG_ID'].' '.''.$focus->id.'
'; + foreach($object_column_fields as $fieldname => $fieldlabel) + { + //Get the translated string + $temp_label = isset($app_strings[$fieldlabel])?$app_strings[$fieldlabel]:(isset($mod_strings[$fieldlabel])?$mod_strings[$fieldlabel]:$fieldlabel); + + $description .= $temp_label.' : '.$focus->column_fields[$fieldname].'
'; + } + + $description .= '

'.$app_strings['MSG_THANK_YOU'].',
'.$current_user->user_name.'.
'; + $status = send_mail($module,$ownermailid,$current_user->user_name,'',$subject,$description); + + $log->debug("Exiting sendNotificationToOwner method ..."); + return $status; + } +} + +//Function to send notification to the users of a group +function sendNotificationToGroups($groupid,$crmid,$module) +{ + global $adb,$app_strings,$current_user; + $returnEntity=Array(); + $returnEntity=getEntityName($module,Array($crmid)); + $mycrmid=$groupid; + require_once('include/utils/GetGroupUsers.php'); + $getGroupObj=new GetGroupUsers(); + $getGroupObj->getAllUsersInGroup($mycrmid); + $userIds=$getGroupObj->group_users; + if (count($userIds) > 0) { + $groupqry="select email1,id,user_name from vtiger_users WHERE status='Active' AND id in(". generateQuestionMarks($userIds) .")"; + $groupqry_res=$adb->pquery($groupqry, array($userIds)); + for($z=0;$z < $adb->num_rows($groupqry_res);$z++) + { + //handle the mail send to vtiger_users + $emailadd = $adb->query_result($groupqry_res,$z,'email1'); + $curr_userid = $adb->query_result($groupqry_res,$z,'id'); + $tosender=$adb->query_result($groupqry_res,$z,'user_name'); + $pmodule = 'Users'; + $description = $app_strings['MSG_DEAR']." ".$tosender.",
".$returnEntity[$crmid]." ".$app_strings['MSG_HAS_BEEN_CREATED_FOR']." ".$module."

".$app_strings['MSG_THANKS'].",
".$app_strings['MSG_VTIGERTEAM']; + require_once('modules/Emails/mail.php'); + $mail_status = send_mail('Emails',$emailadd,$current_user->user_name,'','Record created-vTiger Team',$description,'','','all',$focus->id); + $all_to_emailids []= $emailadd; + $mail_status_str .= $emailadd."=".$mail_status."&&&"; + } + } +} + + +function getUserslist($setdefval=true) +{ + global $log,$current_user,$module,$adb,$assigned_user_id; + $log->debug("Entering getUserslist() method ..."); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); + } + else + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id),$current_user->id); + } + foreach($users_combo as $userid=>$value) + { + + foreach($value as $username=>$selected) + { + if ($setdefval == false) { + $change_owner .= ""; + } else { + $change_owner .= ""; + } + } + } + + $log->debug("Exiting getUserslist method ..."); + return $change_owner; +} + + +function getGroupslist() +{ + global $log,$adb,$module,$current_user; + $log->debug("Entering getGroupslist() method ..."); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + //Commented to avoid security check for groups + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) + { + $result=get_current_user_access_groups($module); + } + else + { + $result = get_group_options(); + } + + if($result) $nameArray = $adb->fetch_array($result); + if(!empty($nameArray)) + { + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) + { + $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); + } + else + { + $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id), $current_user->id); + } + } + if(count($groups_combo) > 0) { + foreach($groups_combo as $groupid=>$value) + { + foreach($value as $groupname=>$selected) + { + $change_groups_owner .= ""; + } + } + } + $log->debug("Exiting getGroupslist method ..."); + return $change_groups_owner; +} + + +/** + * Function to Check for Security whether the Buttons are permitted in List/Edit/Detail View of all Modules + * @param string $module -- module name + * Returns an array with permission as Yes or No +**/ +function Button_Check($module) +{ + global $log; + $log->debug("Entering Button_Check(".$module.") method ..."); + $permit_arr = array ('EditView' => '', + 'index' => '', + 'Import' => '', + 'Export' => '', + 'Merge' => '', + 'DuplicatesHandling' => '' ); + + foreach($permit_arr as $action => $perr){ + $tempPer=isPermitted($module,$action,''); + $permit_arr[$action] = $tempPer; + } + $permit_arr["Calendar"] = isPermitted("Calendar","index",''); + $permit_arr["moduleSettings"] = isModuleSettingPermitted($module); + $log->debug("Exiting Button_Check method ..."); + return $permit_arr; + +} + +/** + * Function to Check whether the User is allowed to delete a particular record from listview of each module using + * mass delete button. + * @param string $module -- module name + * @param array $ids_list -- Record id + * Returns the Record Names of each module that is not permitted to delete +**/ +function getEntityName($module, $ids_list) +{ + global $adb; + global $log; + $log->debug("Entering getEntityName(".$module.") method ..."); + + if($module != '') + { + $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?"; + $result = $adb->pquery($query, array($module)); + $fieldsname = $adb->query_result($result,0,'fieldname'); + $tablename = $adb->query_result($result,0,'tablename'); + $entityidfield = $adb->query_result($result,0,'entityidfield'); + if(!(strpos($fieldsname,',') === false)) + { + $fieldlists = explode(',',$fieldsname); + $fieldsname = "concat("; + $fieldsname = $fieldsname.implode(",' ',",$fieldlists); + $fieldsname = $fieldsname.")"; + } + if (count($ids_list) <= 0) { + return array(); + } + + $query1 = "select $fieldsname as entityname,$entityidfield from $tablename where ". + "$entityidfield in (". generateQuestionMarks($ids_list) .")"; + $params1 = array($ids_list); + $result = $adb->pquery($query1, $params1); + $numrows = $adb->num_rows($result); + $account_name = array(); + $entity_info = array(); + for ($i = 0; $i < $numrows; $i++) + { + $entity_id = $adb->query_result($result,$i,$entityidfield); + $entity_info[$entity_id] = $adb->query_result($result,$i,'entityname'); + } + return $entity_info; + } + $log->debug("Exiting getEntityName method ..."); +} + +/**Function to get all permitted modules for a user with their parent +*/ + +function getAllParenttabmoduleslist() +{ + global $adb; + global $current_user; + $resultant_array = Array(); + + //$query = 'select name,tablabel,parenttab_label,vtiger_tab.tabid from vtiger_parenttabrel inner join vtiger_tab on vtiger_parenttabrel.tabid = vtiger_tab.tabid inner join vtiger_parenttab on vtiger_parenttabrel.parenttabid = vtiger_parenttab.parenttabid and vtiger_tab.presence order by vtiger_parenttab.sequence, vtiger_parenttabrel.sequence'; + + // vtlib customization: Disabling the tab item based on presence + $query = 'select name,tablabel,parenttab_label,vtiger_tab.tabid from vtiger_parenttabrel inner join vtiger_tab on vtiger_parenttabrel.tabid = vtiger_tab.tabid inner join vtiger_parenttab on vtiger_parenttabrel.parenttabid = vtiger_parenttab.parenttabid and vtiger_tab.presence in (0,2) order by vtiger_parenttab.sequence, vtiger_parenttabrel.sequence'; + // END + + $result = $adb->pquery($query, array()); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + for($i=0;$i<$adb->num_rows($result);$i++) + { + $parenttabname = $adb->query_result($result,$i,'parenttab_label'); + $modulename = $adb->query_result($result,$i,'name'); + $tablabel = $adb->query_result($result,$i,'tablabel'); + $tabid = $adb->query_result($result,$i,'tabid'); + if($is_admin){ + $resultant_array[$parenttabname][] = Array($modulename,$tablabel); + } + elseif($profileGlobalPermission[2]==0 || $profileGlobalPermission[1]==0 || $profileTabsPermission[$tabid]==0) { + $resultant_array[$parenttabname][] = Array($modulename,$tablabel); + } + } + + if($is_admin){ + $resultant_array['Settings'][] = Array('Settings','Settings'); + $resultant_array['Settings'][] = Array('Settings',getTranslatedString('VTLIB_LBL_MODULE_MANAGER', 'Settings'), 'ModuleManager'); + } + return $resultant_array; +} + +/** + * This function is used to decide the File Storage Path in where we will upload the file in the server. + * return string $filepath - filepath inwhere the file should be stored in the server will be return +*/ +function decideFilePath() +{ + global $log, $adb; + $log->debug("Entering into decideFilePath() method ..."); + + $filepath = 'storage/'; + + $year = date('Y'); + $month = date('F'); + $day = date('j'); + $week = ''; + + if(!is_dir($filepath.$year)) + { + //create new folder + mkdir($filepath.$year); + } + + if(!is_dir($filepath.$year."/".$month)) + { + //create new folder + mkdir($filepath."$year/$month"); + } + + if($day > 0 && $day <= 7) + $week = 'week1'; + elseif($day > 7 && $day <= 14) + $week = 'week2'; + elseif($day > 14 && $day <= 21) + $week = 'week3'; + elseif($day > 21 && $day <= 28 ) + $week = 'week4'; + else + $week = 'week5'; + + if(!is_dir($filepath.$year."/".$month."/".$week)) + { + //create new folder + mkdir($filepath."$year/$month/$week"); + } + + $filepath = $filepath.$year."/".$month."/".$week."/"; + + $log->debug("Year=$year & Month=$month & week=$week && filepath=\"$filepath\""); + $log->debug("Exiting from decideFilePath() method ..."); + + return $filepath; +} + +/** + * This function is used to get the Path in where we store the vtiger_files based on the module. + * @param string $module - module name + * return string $storage_path - path inwhere the file will be uploaded (also where it was stored) will be return based on the module +*/ +function getModuleFileStoragePath($module) +{ + global $log; + $log->debug("Entering into getModuleFileStoragePath($module) method ..."); + + $storage_path = "test/"; + + if($module == 'Products') + { + $storage_path .= 'product/'; + } + if($module == 'Contacts') + { + $storage_path .= 'contact/'; + } + + $log->debug("Exiting from getModuleFileStoragePath($module) method. return storage_path = \"$storage_path\""); + return $storage_path; +} + +/** + * This function is used to check whether the attached file is a image file or not + * @param string $file_details - vtiger_files array which contains all the uploaded file details + * return string $save_image - true or false. if the image can be uploaded then true will return otherwise false. +*/ +function validateImageFile($file_details) +{ + global $adb, $log,$app_strings; + $log->debug("Entering into validateImageFile($file_details) method."); + + $savefile = 'true'; + $file_type_details = explode("/",$file_details['type']); + $filetype = $file_type_details['1']; + + if(!empty($filetype)) $filetype = strtolower($filetype); + if (($filetype == "jpeg" ) || ($filetype == "png") || ($filetype == "jpg" ) || ($filetype == "pjpeg" ) || ($filetype == "x-png") || ($filetype == "gif") || ($filetype == 'bmp') ) + { + $saveimage = 'true'; + } + else + { + $saveimage = 'false'; + $_SESSION['image_type_error'] .= "
  ".$file_details[name]."".$app_strings['MSG_IS_NOT_UPLOADED']; + $log->debug("Invalid Image type == $filetype"); + } + + $log->debug("Exiting from validateImageFile($file_details) method. return saveimage=$saveimage"); + return $saveimage; +} + +/** + * This function is used to get the Email Template Details like subject and content for particular template. + * @param integer $templateid - Template Id for an Email Template + * return array $returndata - Returns Subject, Body of Template of the the particular email template. +*/ + +function getTemplateDetails($templateid) +{ + global $adb,$log; + $log->debug("Entering into getTemplateDetails($templateid) method ..."); + $returndata = Array(); + $result = $adb->pquery("select * from vtiger_emailtemplates where templateid=?", array($templateid)); + $returndata[] = $templateid; + $returndata[] = $adb->query_result($result,0,'body'); + $returndata[] = $adb->query_result($result,0,'subject'); + $log->debug("Exiting from getTemplateDetails($templateid) method ..."); + return $returndata; +} +/** + * This function is used to merge the Template Details with the email description + * @param string $description -body of the mail(ie template) + * @param integer $tid - Id of the entity + * @param string $parent_type - module of the entity + * return string $description - Returns description, merged with the input template. +*/ + +function getMergedDescription($description,$id,$parent_type) +{ + global $adb,$log; + $log->debug("Entering getMergedDescription ..."); + $token_data_pair = explode('$',$description); + $fields = Array(); + for($i=1;$i < count($token_data_pair);$i+=2) + { + + $module = explode('-',$token_data_pair[$i]); + $fields[$module[0]][] = $module[1]; + + } + //replace the tokens with the values for the selected parent + switch($parent_type) + { + case 'Accounts': + if(is_array($fields["accounts"])) + { + $columnfields = implode(',',$fields["accounts"]); + $query = "select $columnfields from vtiger_account inner join vtiger_accountscf where vtiger_account.accountid =? and vtiger_accountscf.accountid =?"; + $result = $adb->pquery($query, array($id,$id)); + foreach($fields["accounts"] as $columnname) + { + $token_data = '$accounts-'.$columnname.'$'; + $description = str_replace($token_data,$adb->query_result($result,0,$columnname),$description); + } + } + break; + case 'Contacts': + if(is_array($fields["contacts"])) + { + //Checking for salutation type and checking the table column to be queried + $key = array_search('salutationtype',$fields["contacts"]); + if(isset($key) && $key !='') + { + $fields["contacts"][$key]='salutation'; + } + + $columnfields = implode(',',$fields["contacts"]); + $query = "select $columnfields from vtiger_contactdetails inner join vtiger_contactscf inner join vtiger_customerdetails on vtiger_customerdetails.customerid=vtiger_contactdetails.contactid and vtiger_customerdetails.customerid=vtiger_contactscf.contactid where vtiger_contactdetails.contactid=?"; + $result = $adb->pquery($query, array($id,$id)); + foreach($fields["contacts"] as $columnname) + { + $token_data = '$contacts-'.$columnname.'$'; + $token_value = $adb->query_result($result,0,$columnname); + // Fix for #5417 + if($columnname == 'salutation') $token_value = getTranslatedString($token_value, 'Contacts'); + $description = str_replace($token_data,$token_value,$description); + } + } + break; + case 'Leads': + if(is_array($fields["leads"])) + { + //Checking for salutation type and checking the table column to be queried + $key = array_search('salutationtype',$fields["leads"]); + if(isset($key) && $key !='') + { + $fields["leads"][$key]='salutation'; + } + $columnfields = implode(',',$fields["leads"]); + $query = "select $columnfields from vtiger_leaddetails inner join vtiger_leadscf where vtiger_leaddetails.leadid=? and vtiger_leadscf.leadid=?"; + $result = $adb->pquery($query, array($id,$id)); + foreach($fields["leads"] as $columnname) + { + $token_data = '$leads-'.$columnname.'$'; + $token_value = $adb->query_result($result,0,$columnname); + // Fix for #5417 + if($columnname == 'salutation') $token_value = getTranslatedString($token_value, 'Leads'); + $description = str_replace($token_data,$token_value,$description); + } + } + break; + case 'Users': + if(is_array($fields["users"])) + { + $columnfields = implode(',',$fields["users"]); + $query = "select $columnfields from vtiger_users where id=?"; + $result = $adb->pquery($query, array($id)); + foreach($fields["users"] as $columnname) + { + $token_data = '$users-'.$columnname.'$'; + $description = str_replace($token_data,$adb->query_result($result,0,$columnname),$description); + } + } + break; + } + + $description = getMergedDescriptionCustomVars($fields, $description);//Puneeth : Added for custom date & time fields + $log->debug("Exiting from getMergedDescription ..."); + return $description; +} + +/* Function to merge the custom date & time fields in email templates */ +function getMergedDescriptionCustomVars($fields, $description) { + foreach($fields['custom'] as $columnname) + { + $token_data = '$custom-'.$columnname.'$'; + $token_value = ''; + switch($columnname) { + case 'currentdate': $token_value = date("F j, Y"); break; + case 'currenttime': $token_value = date("G:i:s T"); break; + } + $description = str_replace($token_data, $token_value, $description); + } + return $description; +} +//End : Custom date & time fields + +/** Function used to retrieve a single field value from database + * @param string $tablename - tablename from which we will retrieve the field value + * @param string $fieldname - fieldname to which we want to get the value from database + * @param string $idname - idname which is the name of the entity id in the table like, inoviceid, quoteid, etc., + * @param int $id - entity id + * return string $fieldval - field value of the needed fieldname from database will be returned + */ +function getSingleFieldValue($tablename, $fieldname, $idname, $id) +{ + global $log, $adb; + $log->debug("Entering into function getSingleFieldValue($tablename, $fieldname, $idname, $id)"); + + $fieldval = $adb->query_result($adb->pquery("select $fieldname from $tablename where $idname = ?", array($id)),0,$fieldname); + + $log->debug("Exit from function getSingleFieldValue. return value ==> \"$fieldval\""); + + return $fieldval; +} + +/** Function used to retrieve the announcements from database + * The function accepts no argument and returns the announcements + * return string $announcement - List of announments for the CRM users + */ + +function get_announcements() +{ + global $adb; + $sql=" select * from vtiger_announcement inner join vtiger_users on vtiger_announcement.creatorid=vtiger_users.id"; + $sql.=" AND vtiger_users.is_admin='on' AND vtiger_users.status='Active' AND vtiger_users.deleted = 0"; + $result=$adb->pquery($sql, array()); + for($i=0;$i<$adb->num_rows($result);$i++) + { + $announce = getUserName($adb->query_result($result,$i,'creatorid')).' : '.$adb->query_result($result,$i,'announcement').' '; + if($adb->query_result($result,$i,'announcement')!='') + $announcement.=$announce; + } + return $announcement; +} + +/** Function used to retrieve the rate converted into dollar tobe saved into database + * The function accepts the price in the current currency + * return integer $conv_price - + */ + function getConvertedPrice($price) + { + global $current_user; + $currencyid=fetchCurrency($current_user->id); + $rate_symbol = getCurrencySymbolandCRate($currencyid); + $conv_price = convertToDollar($price,$rate_symbol['rate']); + return $conv_price; + } + + +/** Function used to get the converted amount from dollar which will be showed to the user + * @param float $price - amount in dollor which we want to convert to the user configured amount + * @return float $conv_price - amount in user configured currency + */ +function getConvertedPriceFromDollar($price) +{ + global $current_user; + $currencyid=fetchCurrency($current_user->id); + $rate_symbol = getCurrencySymbolandCRate($currencyid); + $conv_price = convertFromDollar($price,$rate_symbol['rate']); + return $conv_price; +} + + +/** + * Function to get recurring info depending on the recurring type + * return $recurObj - Object of class RecurringType + */ + +function getrecurringObjValue() +{ + $recurring_data = array(); + if(isset($_REQUEST['recurringtype']) && $_REQUEST['recurringtype'] != null && $_REQUEST['recurringtype'] != '--None--' ) + { + if(isset($_REQUEST['date_start']) && $_REQUEST['date_start'] != null) + { + $recurring_data['startdate'] = $_REQUEST['date_start']; + } + if(isset($_REQUEST['due_date']) && $_REQUEST['due_date'] != null) + { + $recurring_data['enddate'] = $_REQUEST['due_date']; + } + $recurring_data['type'] = $_REQUEST['recurringtype']; + if($_REQUEST['recurringtype'] == 'Weekly') + { + if(isset($_REQUEST['sun_flag']) && $_REQUEST['sun_flag'] != null) + $recurring_data['sun_flag'] = true; + if(isset($_REQUEST['mon_flag']) && $_REQUEST['mon_flag'] != null) + $recurring_data['mon_flag'] = true; + if(isset($_REQUEST['tue_flag']) && $_REQUEST['tue_flag'] != null) + $recurring_data['tue_flag'] = true; + if(isset($_REQUEST['wed_flag']) && $_REQUEST['wed_flag'] != null) + $recurring_data['wed_flag'] = true; + if(isset($_REQUEST['thu_flag']) && $_REQUEST['thu_flag'] != null) + $recurring_data['thu_flag'] = true; + if(isset($_REQUEST['fri_flag']) && $_REQUEST['fri_flag'] != null) + $recurring_data['fri_flag'] = true; + if(isset($_REQUEST['sat_flag']) && $_REQUEST['sat_flag'] != null) + $recurring_data['sat_flag'] = true; + } + elseif($_REQUEST['recurringtype'] == 'Monthly') + { + if(isset($_REQUEST['repeatMonth']) && $_REQUEST['repeatMonth'] != null) + $recurring_data['repeatmonth_type'] = $_REQUEST['repeatMonth']; + if($recurring_data['repeatmonth_type'] == 'date') + { + if(isset($_REQUEST['repeatMonth_date']) && $_REQUEST['repeatMonth_date'] != null) + $recurring_data['repeatmonth_date'] = $_REQUEST['repeatMonth_date']; + else + $recurring_data['repeatmonth_date'] = 1; + } + elseif($recurring_data['repeatmonth_type'] == 'day') + { + $recurring_data['repeatmonth_daytype'] = $_REQUEST['repeatMonth_daytype']; + switch($_REQUEST['repeatMonth_day']) + { + case 0 : + $recurring_data['sun_flag'] = true; + break; + case 1 : + $recurring_data['mon_flag'] = true; + break; + case 2 : + $recurring_data['tue_flag'] = true; + break; + case 3 : + $recurring_data['wed_flag'] = true; + break; + case 4 : + $recurring_data['thu_flag'] = true; + break; + case 5 : + $recurring_data['fri_flag'] = true; + break; + case 6 : + $recurring_data['sat_flag'] = true; + break; + } + } + } + if(isset($_REQUEST['repeat_frequency']) && $_REQUEST['repeat_frequency'] != null) + $recurring_data['repeat_frequency'] = $_REQUEST['repeat_frequency']; + $recurObj = new RecurringType($recurring_data); + return $recurObj; + } + +} + +/** Function used to get the translated string to the input string + * @param string $str - input string which we want to translate + * @return string $str - translated string, if the translated string is available then the translated string other wise original string will be returned + */ +function getTranslatedString($str,$module='') +{ + global $app_strings, $mod_strings, $log,$current_language; + $temp_mod_strings = ($module != '' )?return_module_language($current_language,$module):$mod_strings; + $trans_str = ($temp_mod_strings[$str] != '')?$temp_mod_strings[$str]:(($app_strings[$str] != '')?$app_strings[$str]:$str); + $log->debug("function getTranslatedString($str) - translated to ($trans_str)"); + return $trans_str; +} + +/** + * Get translated currency name string. + * @param String $str - input currency name + * @return String $str - translated currency name + */ +function getTranslatedCurrencyString($str) { + global $app_currency_strings; + if(isset($app_currency_strings) && isset($app_currency_strings[$str])) { + return $app_currency_strings[$str]; + } + return $str; +} + +/** function used to get the list of importable fields + * @param string $module - module name + * @return array $fieldslist - array with list of fieldnames and the corresponding translated fieldlabels. The return array will be in the format of [fieldname]=>[fieldlabel] where as the fieldlabel will be translated + */ +function getImportFieldsList($module) +{ + global $adb, $log; + $log->debug("Entering into function getImportFieldsList($module)"); + + $tabid = getTabid($module); + + //Here we can add special cases for module basis, ie., if we want the fields of display type 3, we can add + $displaytype = " displaytype=1 and vtiger_field.presence in (0,2) "; + + $fieldnames = ""; + //For module basis we can add the list of fields for Import mapping + if($module == "Leads" || $module == "Contacts") + { + $fieldnames = " fieldname='salutationtype' "; + } + + //Form the where condition based on tabid , displaytype and extra fields + $where = " WHERE tabid=? and ( $displaytype "; + $params = array($tabid); + if($fieldnames != "") + { + $where .= " or $fieldnames "; + } + $where .= ")"; + + //Get the list of fields and form as array with [fieldname] => [fieldlabel] + $query = "SELECT fieldname, fieldlabel FROM vtiger_field $where"; + $result = $adb->pquery($query, $params); + for($i=0;$i<$adb->num_rows($result);$i++) + { + $fieldname = $adb->query_result($result,$i,'fieldname'); + $fieldlabel = $adb->query_result($result,$i,'fieldlabel'); + $fieldslist[$fieldname] = getTranslatedString($fieldlabel, $module); + } + + $log->debug("Exit from function getImportFieldsList($module)"); + + return $fieldslist; +} +/** Function to get all the comments for a troubleticket + * @param int $ticketid -- troubleticket id + * return all the comments as a sequencial string which are related to this ticket +**/ +function getTicketComments($ticketid) +{ + global $log; + $log->debug("Entering getTicketComments(".$ticketid.") method ..."); + global $adb; + + $commentlist = ''; + $sql = "select * from vtiger_ticketcomments where ticketid=?"; + $result = $adb->pquery($sql, array($ticketid)); + for($i=0;$i<$adb->num_rows($result);$i++) + { + $comment = $adb->query_result($result,$i,'comments'); + if($comment != '') + { + $commentlist .= '

'.$comment; + } + } + if($commentlist != '') + $commentlist = '

The comments are : '.$commentlist; + + $log->debug("Exiting getTicketComments method ..."); + return $commentlist; +} + +function getTicketDetails($id,$whole_date) +{ + global $adb,$mod_strings; + if($whole_date['mode'] == 'edit') + { + $reply = $mod_strings["replied"]; + $temp = "Re : "; + } + else + { + $reply = $mod_strings["created"]; + $temp = " "; + } + + $desc = $mod_strings['Ticket ID'] .' : '.$id.'
Ticket Title : '. $temp .' '.$whole_date['sub']; + $desc .= "

".$mod_strings['Hi']." ". $whole_date['parent_name'].",

".$mod_strings['LBL_PORTAL_BODY_MAILINFO']." ".$reply." ".$mod_strings['LBL_DETAIL']."
"; + $desc .= "
".$mod_strings['Ticket No']." : ".$whole_date['ticketno']; + $desc .= "
".$mod_strings['Status']." : ".$whole_date['status']; + $desc .= "
".$mod_strings['Category']." : ".$whole_date['category']; + $desc .= "
".$mod_strings['Severity']." : ".$whole_date['severity']; + $desc .= "
".$mod_strings['Priority']." : ".$whole_date['priority']; + $desc .= "

".$mod_strings['Description']." :
".$whole_date['description']; + $desc .= "

".$mod_strings['Solution']." :
".$whole_date['solution']; + $desc .= getTicketComments($id); + + $sql = "SELECT * FROM vtiger_ticketcf WHERE ticketid = ?"; + $result = $adb->pquery($sql, array($id)); + $cffields = $adb->getFieldsArray($result); + foreach ($cffields as $cfOneField) + { + if ($cfOneField != 'ticketid') + { + $cfData = $adb->query_result($result,0,$cfOneField); + $sql = "SELECT fieldlabel FROM vtiger_field WHERE columnname = ? and vtiger_field.presence in (0,2)"; + $cfLabel = $adb->query_result($adb->pquery($sql,array($cfOneField)),0,'fieldlabel'); + $desc .= '

'.$cfLabel.' :
'.$cfData; + } + } + // end of contribution + $desc .= '


'; + $desc .= '
'.$mod_strings["LBL_REGARDS"].',
'.$mod_strings["LBL_TEAM"].'.
'; + return $desc; + +} + +function getPortalInfo_Ticket($id,$title,$contactname,$portal_url) +{ + global $mod_strings; + $bodydetails =$mod_strings['Dear']." ".$contactname.",

"; + $bodydetails .= $mod_strings['reply'].' '.$title.''.$mod_strings['customer_portal']; + $bodydetails .= $mod_strings["link"].'
'; + $bodydetails .= $portal_url; + $bodydetails .= '

'.$mod_strings["Thanks"].'

'.$mod_strings["Support_team"]; + return $bodydetails; +} + +/** + * This function is used to get a random password. + * @return a random password with alpha numeric chanreters of length 8 + */ +function makeRandomPassword() +{ + global $log; + $log->debug("Entering makeRandomPassword() method ..."); + $salt = "abcdefghijklmnopqrstuvwxyz0123456789"; + srand((double)microtime()*1000000); + $i = 0; + while ($i <= 7) + { + $num = rand() % 33; + $tmp = substr($salt, $num, 1); + $pass = $pass . $tmp; + $i++; + } + $log->debug("Exiting makeRandomPassword method ..."); + return $pass; +} + +//added to get mail info for portal user +//type argument included when when addin customizable tempalte for sending portal login details +function getmail_contents_portalUser($request_array,$password,$type='') +{ + global $mod_strings ,$adb; + + $subject = $mod_strings['Customer Portal Login Details']; + + //here id is hardcoded with 5. it is for support start notification in vtiger_notificationscheduler + + $query='select vtiger_emailtemplates.subject,vtiger_emailtemplates.body from vtiger_notificationscheduler inner join vtiger_emailtemplates on vtiger_emailtemplates.templateid=vtiger_notificationscheduler.notificationbody where schedulednotificationid=5'; + + $result = $adb->pquery($query, array()); + $body=$adb->query_result($result,0,'body'); + $contents=$body; + $contents = str_replace('$contact_name$',$request_array['first_name']." ".$request_array['last_name'],$contents); + $contents = str_replace('$login_name$',$request_array['email'],$contents); + $contents = str_replace('$password$',$password,$contents); + $contents = str_replace('$URL$',$request_array['portal_url'],$contents); + $contents = str_replace('$support_team$',$mod_strings['Support Team'],$contents); + $contents = str_replace('$logo$','',$contents); + + if($type == "LoginDetails") + { + $temp=$contents; + $value["subject"]=$adb->query_result($result,0,'subject'); + $value["body"]=$temp; + return $value; + } + + return $contents; + +} + +/** + * Function to get the UItype for a field. + * Takes the input as $module - module name,and columnname of the field + * returns the uitype, integer type + */ +function getUItype($module,$columnname) +{ + global $log; + $log->debug("Entering getUItype(".$module.") method ..."); + $tabIdList = array(); + //To find tabid for this module + $tabIdList[] = getTabid($module); + global $adb; + if($module == 'Calendar') { + $tabIdList[] = getTabid('Events'); + } + $sql = "select uitype from vtiger_field where tabid IN (".generateQuestionMarks($tabIdList). + ") and columnname=?"; + $result = $adb->pquery($sql, array($tabIdList, $columnname)); + $uitype = $adb->query_result($result,0,"uitype"); + $log->debug("Exiting getUItype method ..."); + return $uitype; + +} + +// This function looks like not used anymore. May have to be removed +function is_emailId($entity_id) +{ + global $log,$adb; + $log->debug("Entering is_EmailId(".$entity_id.") method"); + + $module = getSalesEntityType($entity_id); + if($module == 'Contacts') + { + $sql = "select email,yahooid from vtiger_contactdetails inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid where contactid = ?"; + $result = $adb->pquery($sql, array($entity_id)); + $email1 = $adb->query_result($result,0,"email"); + $email2 = $adb->query_result($result,0,"yahooid"); + if($email1 != "" || $email2 != "") { + $check_mailids = "true"; + } else { + $check_mailids = "false"; + } + } + elseif($module == 'Leads') + { + $sql = "select email,yahooid from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_leaddetails.leadid where leadid = ?"; + $result = $adb->pquery($sql, array($entity_id)); + $email1 = $adb->query_result($result,0,"email"); + $email2 = $adb->query_result($result,0,"yahooid"); + if($email1 != "" || $email2 != "") { + $check_mailids = "true"; + } else { + $check_mailids = "false"; + } + } + $log->debug("Exiting is_EmailId() method ..."); + return $check_mailids; +} + +/** + * This function is used to get cvid of default "all" view for any module. + * @return a cvid of a module + */ +function getCvIdOfAll($module) +{ + global $adb,$log; + $log->debug("Entering getCvIdOfAll($module)"); + $qry_res = $adb->pquery("select cvid from vtiger_customview where viewname='All' and entitytype=?", array($module)); + $cvid = $adb->query_result($qry_res,0,"cvid"); + $log->debug("Exiting getCvIdOfAll($module)"); + return $cvid; + + +} + +/** gives the option to display the tagclouds or not for the current user + ** @param $id -- user id:: Type integer + ** @returns true or false in $tag_cloud_view + ** Added to provide User based Tagcloud + **/ + +function getTagCloudView($id=""){ + global $log; + global $adb; + $log->debug("Entering in function getTagCloudView($id)"); + if($id == ''){ + $tag_cloud_status =1; + }else{ + $query = "select visible from vtiger_homestuff where userid=? and stufftype='Tag Cloud'"; + $tag_cloud_status = $adb->query_result($adb->pquery($query, array($id)),0,'visible'); + } + + if($tag_cloud_status == 0){ + $tag_cloud_view='true'; + }else{ + $tag_cloud_view='false'; + } + + $log->debug("Exiting from function getTagCloudView($id)"); + return $tag_cloud_view; +} + +/** Stores the option in database to display the tagclouds or not for the current user + ** @param $id -- user id:: Type integer + ** Added to provide User based Tagcloud + **/ +function SaveTagCloudView($id="") +{ + global $log; + global $adb; + $log->debug("Entering in function SaveTagCloudView($id)"); + $tag_cloud_status=$_REQUEST['tagcloudview']; + + if($tag_cloud_status == "true"){ + $tag_cloud_view = 0; + }else{ + $tag_cloud_view = 1; + } + + if($id == ''){ + $tag_cloud_view =1; + }else{ + $query = "update vtiger_homestuff set visible = ? where userid=? and stufftype='Tag Cloud'"; + $adb->pquery($query, array($tag_cloud_view,$id)); + } + + $log->debug("Exiting from function SaveTagCloudView($id)"); +} + +/** function used to change the Type of Data for advanced filters in custom view and Reports + ** @param string $table_name - tablename value from field table + ** @param string $column_nametable_name - columnname value from field table + ** @param string $type_of_data - current type of data of the field. It is to return the same TypeofData + ** if the field is not matched with the $new_field_details array. + ** return string $type_of_data - If the string matched with the $new_field_details array then the Changed + ** typeofdata will return, else the same typeofdata will return. + ** + ** EXAMPLE: If you have a field entry like this: + ** + ** fieldlabel | typeofdata | tablename | columnname | + ** -------------------+------------+----------------------+------------------+ + ** Potential Name | I~O | vtiger_quotes | potentialid | + ** + ** Then put an entry in $new_field_details like this: + ** + ** "vtiger_quotes:potentialid"=>"V", + ** + ** Now in customview and report's advance filter this field's criteria will be show like string. + ** + **/ +function ChangeTypeOfData_Filter($table_name,$column_name,$type_of_data) +{ + global $adb,$log; + //$log->debug("Entering function ChangeTypeOfData_Filter($table_name,$column_name,$type_of_data)"); + $field=$table_name.":".$column_name; + //Add the field details in this array if you want to change the advance filter field details + + $new_field_details = Array( + + //Contacts Related Fields + "vtiger_contactdetails:accountid"=>"V", + "vtiger_contactsubdetails:birthday"=>"D", + "vtiger_contactdetails:email"=>"V", + "vtiger_contactdetails:yahooid"=>"V", + + //Potential Related Fields + "vtiger_potential:campaignid"=>"V", + + //Account Related Fields + "vtiger_account:parentid"=>"V", + "vtiger_account:email1"=>"V", + "vtiger_account:email2"=>"V", + + //Lead Related Fields + "vtiger_leaddetails:email"=>"V", + "vtiger_leaddetails:yahooid"=>"V", + + //Documents Related Fields + "vtiger_senotesrel:crmid"=>"V", + + //Calendar Related Fields + "vtiger_seactivityrel:crmid"=>"V", + "vtiger_seactivityrel:contactid"=>"V", + "vtiger_recurringevents:recurringtype"=>"V", + + //HelpDesk Related Fields + "vtiger_troubletickets:parent_id"=>"V", + "vtiger_troubletickets:product_id"=>"V", + + //Product Related Fields + "vtiger_products:discontinued"=>"C", + "vtiger_products:vendor_id"=>"V", + "vtiger_products:handler"=>"V", + "vtiger_products:parentid"=>"V", + + //Faq Related Fields + "vtiger_faq:product_id"=>"V", + + //Vendor Related Fields + "vtiger_vendor:email"=>"V", + + //Quotes Related Fields + "vtiger_quotes:potentialid"=>"V", + "vtiger_quotes:inventorymanager"=>"V", + "vtiger_quotes:accountid"=>"V", + + //Purchase Order Related Fields + "vtiger_purchaseorder:vendorid"=>"V", + "vtiger_purchaseorder:contactid"=>"V", + + //SalesOrder Related Fields + "vtiger_salesorder:potentialid"=>"V", + "vtiger_salesorder:quoteid"=>"V", + "vtiger_salesorder:contactid"=>"V", + "vtiger_salesorder:accountid"=>"V", + + //Invoice Related Fields + "vtiger_invoice:salesorderid"=>"V", + "vtiger_invoice:contactid"=>"V", + "vtiger_invoice:accountid"=>"V", + + //Campaign Related Fields + "vtiger_campaign:product_id"=>"V", + + //Related List Entries(For Report Module) + "vtiger_activityproductrel:activityid"=>"V", + "vtiger_activityproductrel:productid"=>"V", + + "vtiger_campaigncontrel:campaignid"=>"V", + "vtiger_campaigncontrel:contactid"=>"V", + + "vtiger_campaignleadrel:campaignid"=>"V", + "vtiger_campaignleadrel:leadid"=>"V", + + "vtiger_cntactivityrel:contactid"=>"V", + "vtiger_cntactivityrel:activityid"=>"V", + + "vtiger_contpotentialrel:contactid"=>"V", + "vtiger_contpotentialrel:potentialid"=>"V", + + "vtiger_crmentitynotesrel:crmid"=>"V", + "vtiger_crmentitynotesrel:notesid"=>"V", + + "vtiger_leadacctrel:leadid"=>"V", + "vtiger_leadacctrel:accountid"=>"V", + + "vtiger_leadcontrel:leadid"=>"V", + "vtiger_leadcontrel:contactid"=>"V", + + "vtiger_leadpotrel:leadid"=>"V", + "vtiger_leadpotrel:potentialid"=>"V", + + "vtiger_pricebookproductrel:pricebookid"=>"V", + "vtiger_pricebookproductrel:productid"=>"V", + + "vtiger_seactivityrel:crmid"=>"V", + "vtiger_seactivityrel:activityid"=>"V", + + "vtiger_senotesrel:crmid"=>"V", + "vtiger_senotesrel:notesid"=>"V", + + "vtiger_seproductsrel:crmid"=>"V", + "vtiger_seproductsrel:productid"=>"V", + + "vtiger_seticketsrel:crmid"=>"V", + "vtiger_seticketsrel:ticketid"=>"V", + + "vtiger_vendorcontactrel:vendorid"=>"V", + "vtiger_vendorcontactrel:contactid"=>"V", + + "vtiger_pricebook:currency_id"=>"V", + "vtiger_service:handler"=>"V", + ); + + //If the Fields details does not match with the array, then we return the same typeofdata + if(isset($new_field_details[$field])) + { + $type_of_data = $new_field_details[$field]; + } + //$log->debug("Exiting function with the typeofdata: $type_of_data "); + return $type_of_data; +} + + +/** Returns the URL for Basic and Advance Search + ** Added to fix the issue 4600 + **/ +function getBasic_Advance_SearchURL() +{ + + $url = ''; + if($_REQUEST['searchtype'] == 'BasicSearch') + { + $url .= (isset($_REQUEST['query']))?'&query='.vtlib_purify($_REQUEST['query']):''; + $url .= (isset($_REQUEST['search_field']))?'&search_field='.vtlib_purify($_REQUEST['search_field']):''; + $url .= (isset($_REQUEST['search_text']))?'&search_text='.to_html(vtlib_purify($_REQUEST['search_text'])):''; + $url .= (isset($_REQUEST['searchtype']))?'&searchtype='.vtlib_purify($_REQUEST['searchtype']):''; + $url .= (isset($_REQUEST['type']))?'&type='.vtlib_purify($_REQUEST['type']):''; + } + if ($_REQUEST['searchtype'] == 'advance') + { + $url .= (isset($_REQUEST['query']))?'&query='.vtlib_purify($_REQUEST['query']):''; + $count=$_REQUEST['search_cnt']; + for($i=0;$i<$count;$i++) + { + $url .= (isset($_REQUEST['Fields'.$i]))?'&Fields'.$i.'='.stripslashes(str_replace("'","",vtlib_purify($_REQUEST['Fields'.$i]))):''; + $url .= (isset($_REQUEST['Condition'.$i]))?'&Condition'.$i.'='.vtlib_purify($_REQUEST['Condition'.$i]):''; + $url .= (isset($_REQUEST['Srch_value'.$i]))?'&Srch_value'.$i.'='.to_html(vtlib_purify($_REQUEST['Srch_value'.$i])):''; + } + $url .= (isset($_REQUEST['searchtype']))?'&searchtype='.vtlib_purify($_REQUEST['searchtype']):''; + $url .= (isset($_REQUEST['search_cnt']))?'&search_cnt='.vtlib_purify($_REQUEST['search_cnt']):''; + $url .= (isset($_REQUEST['matchtype']))?'&matchtype='.vtlib_purify($_REQUEST['matchtype']):''; + } + return $url; + +} + +/** Clear the Smarty cache files(in Smarty/smarty_c) + ** This function will called after migration. + **/ +function clear_smarty_cache($path=null) { + + global $root_directory; + if($path == null) { + $path=$root_directory.'Smarty/templates_c/'; + } + $mydir = @opendir($path); + while(false !== ($file = readdir($mydir))) { + if($file != "." && $file != ".." && $file != ".svn") { + //chmod($path.$file, 0777); + if(is_dir($path.$file)) { + chdir('.'); + clear_smarty_cache($path.$file.'/'); + //rmdir($path.$file) or DIE("couldn't delete $path$file
"); // No need to delete the directories. + } + else { + // Delete only files ending with .tpl.php + if(strripos($file, '.tpl.php') == (strlen($file)-strlen('.tpl.php'))) { + unlink($path.$file) or DIE("couldn't delete $path$file
"); + } + } + } + } + @closedir($mydir); +} + +/** Get Smarty compiled file for the specified template filename. + ** @param $template_file Template filename for which the compiled file has to be returned. + ** @return Compiled file for the specified template file. + **/ +function get_smarty_compiled_file($template_file, $path=null) { + + global $root_directory; + if($path == null) { + $path=$root_directory.'Smarty/templates_c/'; + } + $mydir = @opendir($path); + $compiled_file = null; + while(false !== ($file = readdir($mydir)) && $compiled_file == null) { + if($file != "." && $file != ".." && $file != ".svn") { + //chmod($path.$file, 0777); + if(is_dir($path.$file)) { + chdir('.'); + $compiled_file = get_smarty_compiled_file($template_file, $path.$file.'/'); + //rmdir($path.$file) or DIE("couldn't delete $path$file
"); // No need to delete the directories. + } + else { + // Check if the file name matches the required template fiel name + if(strripos($file, $template_file.'.php') == (strlen($file)-strlen($template_file.'.php'))) { + $compiled_file = $path.$file; + } + } + } + } + @closedir($mydir); + return $compiled_file; +} + +/** Function to carry out all the necessary actions after migration */ +function perform_post_migration_activities() { + //After applying all the DB Changes,Here we clear the Smarty cache files + clear_smarty_cache(); + //Writing tab data in flat file + create_tab_data_file(); + create_parenttab_data_file(); +} + +/** Function To create Email template variables dynamically -- Pavani */ +function getEmailTemplateVariables(){ + global $adb; + $modules_list = array('Accounts', 'Contacts', 'Leads', 'Users'); + $module_cf_table = array('Accounts' => 'vtiger_accountscf', + 'Contacts' => 'vtiger_contactscf', + 'Leads' => 'vtiger_leadscf'); + foreach($modules_list as $index=>$module){ + if($module == 'Calendar') { + $focus = new Activity(); + } else { + $focus = new $module(); + } + $tabname = $focus->table_name; + $default_fields = $focus->emailTemplate_defaultFields; + // Set the default email template fields for the given module + if ($default_fields != null) { + foreach($default_fields as $index=>$field){ + if($field=='support_start_date' || $field=='support_end_date'){ + $tabname='vtiger_customerdetails'; + } + $sql="select fieldlabel from vtiger_field where tablename=? and columnname=? and vtiger_field.presence in (0,2)"; + $result=$adb->pquery($sql,array($tabname,$field)); + $norows = $adb->num_rows($result); + if($norows > 0){ + $option=array(getTranslatedString($module).': '.getTranslatedString($adb->query_result($result,'fieldlabel')),"$".strtolower($module)."-".$field."$"); + $allFields[] = $option; + } + } + } + // Set the custom fields of a given module for Email templates + $custFields=getCustomFieldArray($module); + foreach($custFields as $val=>$key){ + $sql="select fieldlabel from vtiger_field where tablename=? and columnname=? and uitype!=56 and vtiger_field.presence in (0,2)"; + $result=$adb->pquery($sql,array($module_cf_table[$module],$val)); + $norows = $adb->num_rows($result); + if($norows > 0){ + if($adb->query_result($result,'fieldlabel') != '' and $adb->query_result($result,'fieldlabel') !=NULL){ + $option=array(getTranslatedString($module).': '.getTranslatedString($adb->query_result($result,'fieldlabel')),"$".strtolower($module)."-".$val."$"); + $allFields[] = $option; + } + } + } + //} + $allOptions[] = $allFields; + $allFields=""; + } + $option=array('Current Date','$custom-currentdate$'); + $allFields[] = $option; + $option=array('Current Time','$custom-currenttime$'); + $allFields[] = $option; + $allOptions[] = $allFields; + return $allOptions; +} + +/** Function to get picklist values for the given field that are accessible for the given role. + * @ param $tablename picklist fieldname. + * It gets the picklist values for the given fieldname + * $fldVal = Array(0=>value,1=>value1,-------------,n=>valuen) + * @return Array of picklist values accessible by the user. + */ +function getPickListValues($tablename,$roleid) +{ + global $adb; + $query = "select $tablename from vtiger_$tablename inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$tablename.picklist_valueid where roleid=? and picklistid in (select picklistid from vtiger_picklist) order by sortid"; + $result = $adb->pquery($query, array($roleid)); + $fldVal = Array(); + while($row = $adb->fetch_array($result)) + { + $fldVal []= $row[$tablename]; + } + return $fldVal; +} + +/** Function to check the file access is made within web root directory. */ +function checkFileAccess($filepath) { + global $root_directory; + // Set the base directory to compare with + $use_root_directory = $root_directory; + if(empty($use_root_directory)) { + $use_root_directory = realpath(dirname(__FILE__).'/../../.'); + } + + $realfilepath = realpath($filepath); + + /** Replace all \\ with \ first */ + $realfilepath = str_replace('\\\\', '\\', $realfilepath); + $rootdirpath = str_replace('\\\\', '\\', $use_root_directory); + + /** Replace all \ with / now */ + $realfilepath = str_replace('\\', '/', $realfilepath); + $rootdirpath = str_replace('\\', '/', $rootdirpath); + + if(stripos($realfilepath, $rootdirpath) !== 0) { + die("Sorry! Attempt to access restricted file."); + } +} + +/** Function to get the ActivityType for the given entity id + * @param entityid : Type Integer + * return the activity type for the given id + */ +function getActivityType($id) +{ + global $adb; + $quer = "select activitytype from vtiger_activity where activityid=?"; + $res = $adb->pquery($quer, array($id)); + $acti_type = $adb->query_result($res,0,"activitytype"); + return $acti_type; +} + +/** Function to get owner name either user or group */ +function getOwnerName($id) +{ + global $adb, $log; + $log->debug("Entering getOwnerName(".$id.") method ..."); + $log->info("in getOwnerName ".$id); + + $ownerList = getOwnerNameList(array($id)); + return $ownerList[$id]; +} + +/** Function to get owner name either user or group */ +function getOwnerNameList($idList) { + global $log; + + if(!is_array($idList) || count($idList) == 0) { + return array(); + } + + $nameList = array(); + $db = PearDatabase::getInstance(); + $sql = "select user_name,id from vtiger_users where id in (".generateQuestionMarks($idList).")"; + $result = $db->pquery($sql, $idList); + $it = new SqlResultIterator($db, $result); + foreach ($it as $row) { + $nameList[$row->id] = $row->user_name; + } + $groupIdList = array_diff($idList, array_keys($nameList)); + if(count($groupIdList) > 0) { + $sql = "select groupname,groupid from vtiger_groups where groupid in (". + generateQuestionMarks($groupIdList).")"; + $result = $db->pquery($sql, $groupIdList); + $it = new SqlResultIterator($db, $result); + foreach ($it as $row) { + $nameList[$row->groupid] = $row->groupname; + } + } + return $nameList; +} + +/** + * This function is used to get the blockid of the settings block for a given label. + * @param $label - settings label + * @return string type value + */ +function getSettingsBlockId($label) { + global $log, $adb; + $log->debug("Entering getSettingsBlockId(".$label.") method ..."); + + $blockid = ''; + $query = "select blockid from vtiger_settings_blocks where label = ?"; + $result = $adb->pquery($query, array($label)); + $noofrows = $adb->num_rows($result); + if($noofrows == 1) { + $blockid = $adb->query_result($result,0,"blockid"); + } + $log->debug("Exiting getSettingsBlockId method ..."); + return $blockid; +} + +// Function to check if the logged in user is admin +// and if the module is an entity module +// and the module has a Settings.php file within it +function isModuleSettingPermitted($module){ + if (file_exists("modules/$module/Settings.php") && + isPermitted('Settings','index','') == 'yes') { + + return 'yes'; + } + return 'no'; +} + +/** + * this function returns the entity field name for a given module; for e.g. for Contacts module it return concat(lastname, ' ', firstname) + * @param string $module - the module name + * @return string $fieldsname - the entity field name for the module + */ +function getEntityField($module){ + global $adb; + $data = array(); + if(!empty($module)){ + $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?"; + $result = $adb->pquery($query, array($module)); + $fieldsname = $adb->query_result($result,0,'fieldname'); + $tablename = $adb->query_result($result,0,'tablename'); + $entityidfield = $adb->query_result($result,0,'entityidfield'); + if(!(strpos($fieldsname,',') === false)){ + $fieldlists = explode(',',$fieldsname); + $fieldsname = "concat("; + $fieldsname = $fieldsname.implode(",' ',",$fieldlists); + $fieldsname = $fieldsname.")"; + } + } + $data = array("tablename"=>$tablename, "fieldname"=>$fieldsname); + return $data; +} + +// vtiger cache utility +require_once('include/utils/VTCacheUtils.php'); + +// vtlib customization: Extended vtiger CRM utlitiy functions +require_once('include/utils/VtlibUtils.php'); +// END + +function vt_suppressHTMLTags($string){ + return preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); +} + +function vt_hasRTE() { + global $FCKEDITOR_DISPLAY, $USE_RTE; + return ((!empty($FCKEDITOR_DISPLAY) && $FCKEDITOR_DISPLAY == 'true') || + (!empty($USE_RTE) && $USE_RTE == 'true')); +} + ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/DBHealthCheck.php b/oss/vtiger/trunk/include/utils/DBHealthCheck.php index 609bdfa3..39bfc86b 100644 --- a/oss/vtiger/trunk/include/utils/DBHealthCheck.php +++ b/oss/vtiger/trunk/include/utils/DBHealthCheck.php @@ -1,103 +1,104 @@ -db = $db; - $this->dbType = $db->databaseType; - $this->dbName = $db->databaseName; - $this->dbHostName = $db->host; - } - - function isDBHealthy() { - $tablesList = $this->getUnhealthyTablesList(); - if (count($tablesList) > 0) { - return false; - } - return true; - } - - function getUnhealthyTablesList() { - $tablesList = array(); - $dbApiName = '_'.($this->dbType).'_getUnhealthyTables'; - if(method_exists($this,$dbApiName)) { - $tablesList = $this->$dbApiName(); - } - return $tablesList; - } - - function updateTableEngineType($tableName) { - $dbApiName = '_'.($this->dbType).'_updateEngineType'; - if(method_exists($this,$dbApiName)) { - $this->$dbApiName($tableName); - } - } - - function updateAllTablesEngineType() { - $dbApiName = '_'.($this->dbType).'_updateEngineTypeForAllTables'; - if(method_exists($this,$dbApiName)) { - $this->$dbApiName(); - } - } - - function _mysql_getUnhealthyTables() { - $tablesResult = $this->db->_Execute("SHOW TABLE STATUS FROM $this->dbName"); - $noOfTables = $tablesResult->NumRows($tablesResult); - $unHealthyTables = array(); - $i=0; - for($j=0; $j<$noOfTables; ++$j) { - $tableInfo = $tablesResult->GetRowAssoc(0); - $isHealthy = false; - // If already InnoDB type, skip it. - if ($tableInfo['engine'] == 'InnoDB') { - $isHealthy = true; - } - // If table is a sequence table, then skip it. - $tableNameParts = explode("_",$tableInfo['name']); - $tableNamePartsCount = count($tableNameParts); - if ($tableNameParts[$tableNamePartsCount-1] == 'seq') { - $isHealthy = true; - } - - if(!$isHealthy) { - $unHealthyTables[$i]['name'] = $tableInfo['name']; - $unHealthyTables[$i]['engine'] = $tableInfo['engine']; - $unHealthyTables[$i]['autoincrementValue'] = $tableInfo['auto_increment']; - $tableCollation = $tableInfo['collation']; - $unHealthyTables[$i]['characterset'] = substr($tableCollation, 0, strpos($tableCollation,'_')); - $unHealthyTables[$i]['collation'] = $tableCollation; - $unHealthyTables[$i]['createOptions'] = $tableInfo['create_options']; - ++$i; - } - $tablesResult->MoveNext(); - } - return $unHealthyTables; - } - - function _mysql_updateEngineType($tableName) { - $this->db->_Execute("ALTER TABLE $tableName ENGINE=$this->recommendedEngineType"); - } - - function _mysql_updateEngineTypeForAllTables() { - $unHealthyTables = $this->_mysql_getUnhealthyTables(); - $noOfTables = count($unHealthyTables); - for($i=0; $i<$noOfTables; ++$i) { - $tableName = $unHealthyTables[$i]['name']; - $this->db->_Execute("ALTER TABLE $tableName ENGINE=$this->recommendedEngineType"); - } - } -} +db = $db; + $this->dbType = $db->databaseType; + $this->dbName = $db->databaseName; + $this->dbHostName = $db->host; + } + + function isMySQL() { return (stripos($this->dbType ,'mysql') === 0);} + function isOracle() { return $this->dbType=='oci8'; } + function isPostgres() { return $this->dbType=='pgsql'; } + + function isDBHealthy() { + $tablesList = $this->getUnhealthyTablesList(); + if (count($tablesList) > 0) { + return false; + } + return true; + } + + function getUnhealthyTablesList() { + $tablesList = array(); + if($this->isMySql()) { + $tablesList = $this->_mysql_getUnhealthyTables(); + } + return $tablesList; + } + + function updateTableEngineType($tableName) { + if($this->isMySql()) { + $this->_mysql_updateEngineType($tableName); + } + } + + function updateAllTablesEngineType() { + if($this->isMySql()) { + $this->_mysql_updateEngineTypeForAllTables(); + } + } + + function _mysql_getUnhealthyTables() { + $tablesResult = $this->db->_Execute("SHOW TABLE STATUS FROM `$this->dbName`"); + $noOfTables = $tablesResult->NumRows($tablesResult); + $unHealthyTables = array(); + $i=0; + for($j=0; $j<$noOfTables; ++$j) { + $tableInfo = $tablesResult->GetRowAssoc(0); + $isHealthy = false; + // If already InnoDB type, skip it. + if ($tableInfo['engine'] == 'InnoDB') { + $isHealthy = true; + } + // If table is a sequence table, then skip it. + $tableNameParts = explode("_",$tableInfo['name']); + $tableNamePartsCount = count($tableNameParts); + if ($tableNameParts[$tableNamePartsCount-1] == 'seq') { + $isHealthy = true; + } + + if(!$isHealthy) { + $unHealthyTables[$i]['name'] = $tableInfo['name']; + $unHealthyTables[$i]['engine'] = $tableInfo['engine']; + $unHealthyTables[$i]['autoincrementValue'] = $tableInfo['auto_increment']; + $tableCollation = $tableInfo['collation']; + $unHealthyTables[$i]['characterset'] = substr($tableCollation, 0, strpos($tableCollation,'_')); + $unHealthyTables[$i]['collation'] = $tableCollation; + $unHealthyTables[$i]['createOptions'] = $tableInfo['create_options']; + ++$i; + } + $tablesResult->MoveNext(); + } + return $unHealthyTables; + } + + function _mysql_updateEngineType($tableName) { + $this->db->_Execute("ALTER TABLE $tableName ENGINE=$this->recommendedEngineType"); + } + + function _mysql_updateEngineTypeForAllTables() { + $unHealthyTables = $this->_mysql_getUnhealthyTables(); + $noOfTables = count($unHealthyTables); + for($i=0; $i<$noOfTables; ++$i) { + $tableName = $unHealthyTables[$i]['name']; + $this->db->_Execute("ALTER TABLE $tableName ENGINE=$this->recommendedEngineType"); + } + } +} ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/DetailViewUtils.php b/oss/vtiger/trunk/include/utils/DetailViewUtils.php index 2ea4eee0..773ef881 100644 --- a/oss/vtiger/trunk/include/utils/DetailViewUtils.php +++ b/oss/vtiger/trunk/include/utils/DetailViewUtils.php @@ -1,1904 +1,1989 @@ -debug("Entering getDetailViewOutputHtml(".$uitype.",". $fieldname.",". $fieldlabel.",". $col_fields.",".$generatedtype.",".$tabid.") method ..."); - global $adb; - global $mod_strings; - global $app_strings; - global $current_user; - global $theme; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $fieldlabel = from_html($fieldlabel); - $custfld = ''; - $value =''; - $arr_data =Array(); - $label_fld = Array(); - $data_fld = Array(); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - - // vtlib customization: New uitype to handle relation between modules - if($uitype == '10'){ - $fieldlabel = getTranslatedString($fieldlabel, $module); - - $parent_id = $col_fields[$fieldname]; - if(!empty($parent_id)) { - $parent_module = getSalesEntityType($parent_id); - $valueTitle=$parent_module; - if($app_strings[$valueTitle]) $valueTitle = $app_strings[$valueTitle]; - - $displayValueArray = getEntityName($parent_module, $parent_id); - if(!empty($displayValueArray)){ - foreach($displayValueArray as $key=>$value){ - $displayValue = $value; - } - } - $label_fld=array($fieldlabel, - "$displayValue"); - } else { - $moduleSpecificMessage = 'MODULE_NOT_SELECTED'; - if($mod_strings[$moduleSpecificMessage] != ""){ - $moduleSpecificMessage = $mod_strings[$moduleSpecificMessage]; - } - $label_fld=array($fieldlabel, ''); - } - } // END - else if($uitype == 99) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - if($fieldname == 'confirm_password') - return null; - }elseif($uitype == 116 || $uitype == 117) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = getCurrencyName($col_fields[$fieldname]); - $pick_query="select * from vtiger_currency_info where currency_status = 'Active' and deleted=0"; - $pickListResult = $adb->pquery($pick_query, array()); - $noofpickrows = $adb->num_rows($pickListResult); - - //Mikecrowe fix to correctly default for custom pick lists - $options = array(); - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,'currency_name'); - $currency_id=$adb->query_result($pickListResult,$j,'id'); - if($col_fields[$fieldname] == $currency_id) - { - $chk_val = "selected"; - $found = true; - } - else - { - $chk_val = ''; - } - $options[$currency_id] = array($pickListValue=>$chk_val ); - } - $label_fld ["options"] = $options; - } - elseif($uitype == 13 || $uitype == 104) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - } - elseif($uitype == 16) { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - - $fieldname = $adb->sql_escape_string($fieldname); - $pick_query="select $fieldname from vtiger_$fieldname order by sortorderid"; - $params = array(); - $pickListResult = $adb->pquery($pick_query, $params); - $noofpickrows = $adb->num_rows($pickListResult); - - $options = array(); - $count=0; - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=decode_html($adb->query_result($pickListResult,$j,strtolower($fieldname))); - $col_fields[$fieldname] = decode_html($col_fields[$fieldname]); - - if($col_fields[$fieldname] == $pickListValue) - { - $chk_val = "selected"; - $count++; - $found = true; - } - else - { - $chk_val = ''; - } - $pickListValue = to_html($pickListValue); - $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); - } - - $label_fld ["options"] = $options; - } - elseif($uitype == 15) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - $roleid=$current_user->roleid; - - $subrole = getRoleSubordinates($roleid); - if(count($subrole)> 0) - { - $roleids = $subrole; - array_push($roleids, $roleid); - } - else - { - $roleids = $roleid; - } - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) - { - $pick_query="select $fieldname from vtiger_$fieldname"; - $params = array(); - }else - { - if (count($roleids) > 0) { - $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; - $params = array($roleids); - } else { - $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; - $params = array(); - } - } - $pickListResult = $adb->pquery($pick_query, $params); - $noofpickrows = $adb->num_rows($pickListResult); - - //Mikecrowe fix to correctly default for custom pick lists - $options = array(); - $count=0; - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=decode_html($adb->query_result($pickListResult,$j,strtolower($fieldname))); - $col_fields[$fieldname] = decode_html($col_fields[$fieldname]); - - if($col_fields[$fieldname] == $pickListValue) - { - $chk_val = "selected"; - $count++; - $found = true; - } - else - { - $chk_val = ''; - } - $pickListValue = to_html($pickListValue); - $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); - } - if($count == 0 && $col_fields[$fieldname] != '') - { - $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'],$col_fields[$fieldname],'selected'); - } - - - $label_fld ["options"] = $options; - } - elseif($uitype == 115) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = getTranslatedString($col_fields[$fieldname]); - - $pick_query="select * from vtiger_" . $adb->sql_escape_string($fieldname); - $pickListResult = $adb->pquery($pick_query, array()); - $noofpickrows = $adb->num_rows($pickListResult); - $options = array(); - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,strtolower($fieldname)); - - if($col_fields[$fieldname] == $pickListValue) - { - $chk_val = "selected"; - $found = true; - } - else - { - $chk_val = ''; - } - $options[] = array($pickListValue=>$chk_val ); - } - $label_fld ["options"] = $options; - } - elseif($uitype == 33) //uitype 33 added for multiselector picklist - Jeri - { - $roleid=$current_user->roleid; - $subrole = getRoleSubordinates($roleid); - if(count($subrole)> 0) - { - $roleids = $subrole; - array_push($roleids, $roleid); - } - else - { - $roleids = $roleid; - } - $editview_label[]=getTranslatedString($fieldlabel, $module); - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) - { - $pick_query="select $fieldname from vtiger_$fieldname order by $fieldname asc"; - $params = array(); - }else - { - if (count($roleids) > 0) { - $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; - $params = array($roleids); - } else { - $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; - $params = array(); - } - } - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = str_ireplace(' |##| ',', ',$col_fields[$fieldname]); - - $pickListResult = $adb->pquery($pick_query, $params); - $noofpickrows = $adb->num_rows($pickListResult); - - $options = array(); - $selected_entries = Array(); - $selected_entries = explode(' |##| ',$col_fields[$fieldname]); - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue = $adb->query_result($pickListResult,$j,strtolower($fieldname)); - $chk_val = ''; - foreach($selected_entries as $selected_entries_value) - { - if(trim($selected_entries_value) == trim($pickListValue)) - { - $chk_val = 'selected'; - break; - } - else - { - $chk_val = ''; - } - } - $options[] = array($pickListValue,$pickListValue,$chk_val); - } - foreach($selected_entries as $selected_entries_value) - { - $mul_count =0; - $options_length = count($options); - for($j=0;$j<$options_length;$j++) - { - if(in_array($selected_entries_value,$options[$j])) - { - $mul_count++; - } - - } - if($mul_count == 0 && $options_length > 0) - { - $not_access_lbl = "".$app_strings['LBL_NOT_ACCESSIBLE'].""; - $options[]=array($not_access_lbl,trim($selected_entries_value),'selected'); - } - $mul_count=0; - } - $label_fld ["options"] = $options; - } - elseif($uitype == 17) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - } - elseif($uitype == 19) - { - if($fieldname == 'notecontent') - $col_fields[$fieldname]= decode_html($col_fields[$fieldname]); - else - $col_fields[$fieldname]= str_replace("<br />","
",$col_fields[$fieldname]); - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - } - elseif($uitype == 20 || $uitype == 21 || $uitype == 22 || $uitype == 24) // Armando LC B'descriptionSpan -> Desc: removed $uitype == 19 and made an aditional elseif above - { - if($uitype == 20)//Fix the issue #4680 - $col_fields[$fieldname]=$col_fields[$fieldname]; - else - $col_fields[$fieldname]=nl2br($col_fields[$fieldname]); - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - } - elseif($uitype == 51 || $uitype == 50 || $uitype == 73) - { - $account_id = $col_fields[$fieldname]; - if($account_id != '') - { - $account_name = getAccountName($account_id); - } - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $account_name; - $label_fld["secid"] = $account_id; - $label_fld["link"] = "index.php?module=Accounts&action=DetailView&record=".$account_id; - //Account Name View - } - elseif($uitype == 52 || $uitype == 77 || $uitype == 101) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $user_id = $col_fields[$fieldname]; - $user_name = getUserName($user_id); - $assigned_user_id = $current_user->id; - if(is_admin($current_user)) - { - $label_fld[] =''.$user_name.''; - } - else - { - $label_fld[] =$user_name; - } - if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); - } - else - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $user_id), $assigned_user_id); - } - $label_fld ["options"] = $users_combo; - - } - elseif($uitype == 11){ - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname]; - } - elseif($uitype == 53) - { - global $noof_group_rows, $adb; - $owner_id = $col_fields[$fieldname]; - - $user = 'no'; - $result = $adb->pquery("SELECT count(*) as count from vtiger_users where id = ?",array($owner_id)); - if($adb->query_result($result,0,'count') > 0) { - $user = 'yes'; - } - - $owner_name = getOwnerName($owner_id); - $label_fld[] =getTranslatedString($fieldlabel, $module); - $label_fld[] =$owner_name; - - if(is_admin($current_user)) - { - $label_fld["secid"][] = $owner_id; - if($user == 'no') { - $label_fld["link"][] = "index.php?module=Settings&action=GroupDetailView&groupId=".$owner_id; - } - else { - $label_fld["link"][] = "index.php?module=Users&action=DetailView&record=".$owner_id; - } - //$label_fld["secid"][] = $groupid; - //$label_fld["link"][] = "index.php?module=Settings&action=GroupDetailView&groupId=".$groupid; - } - - //Security Checks - if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) - { - $result=get_current_user_access_groups($module_name); - } - else - { - $result = get_group_options(); - } - if($result) $nameArray = $adb->fetch_array($result); - - - global $current_user; - //$value = $user_id; - if($owner_id != '') { - if($user == 'yes') { - $label_fld ["options"][] = 'User'; - $assigned_user_id = $owner_id; - $user_checked = "checked"; - $team_checked = ''; - $user_style='display:block'; - $team_style='display:none'; - } - else { - //$record = $col_fields["record_id"]; - //$module = $col_fields["record_module"]; - $label_fld ["options"][] = 'Group'; - $assigned_group_id = $owner_id; - $user_checked = ''; - $team_checked = 'checked'; - $user_style='display:none'; - $team_style='display:block'; - } - } - else { - $label_fld ["options"][] = 'User'; - $assigned_user_id = $current_user->id; - $user_checked = "checked"; - $team_checked = ''; - $user_style='display:block'; - $team_style='display:none'; - } - - - if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); - } - else - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id), $current_user->id); - } - - if($noof_group_rows!=0) - { - if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) - { - $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); - } - else - { - $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id), $current_user->id); - } - } - - $label_fld ["options"][] = $users_combo; - $label_fld ["options"][] = $groups_combo; - } - elseif($uitype == 55 || $uitype == 255) - { - if($tabid == 4) - { - $query="select vtiger_contactdetails.imagename from vtiger_contactdetails where contactid=?"; - $result = $adb->pquery($query, array($col_fields['record_id'])); - $imagename=$adb->query_result($result,0,'imagename'); - if($imagename != '') - { - $imgpath = "test/contact/".$imagename; - $label_fld[] =getTranslatedString($fieldlabel, $module); - } - else - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - } - - } - else - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - } - $value = $col_fields[$fieldname]; - if($uitype==255) - { - global $currentModule; - $fieldpermission = getFieldVisibilityPermission($currentModule, $current_user->id,'firstname'); - } - if($uitype == 255 && $fieldpermission == 0 && $fieldpermission != '') - { - $fieldvalue[] = ''; - } - else - { - $roleid=$current_user->roleid; - $subrole = getRoleSubordinates($roleid); - if(count($subrole)> 0) - { - $roleids = implode("','",$subrole); - $roleids = $roleids."','".$roleid; - } - else - { - $roleids = $roleid; - } - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) - { - $pick_query="select salutationtype from vtiger_salutationtype order by salutationtype"; - $params = array(); - } - else - { - $pick_query="select * from vtiger_salutationtype left join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid=vtiger_salutationtype.picklist_valueid where picklistid in (select picklistid from vtiger_picklist where name='salutationtype') and roleid=? order by salutationtype"; - $params = array($current_user->roleid); - } - $pickListResult = $adb->pquery($pick_query, $params); - $noofpickrows = $adb->num_rows($pickListResult); - $sal_value = $col_fields["salutationtype"]; - $salcount =0; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,"salutationtype"); - - if($sal_value == $pickListValue) - { - $chk_val = "selected"; - $salcount++; - } - else - { - $chk_val = ''; - } - } - if($salcount == 0 && $sal_value != '') - { - $notacc = $app_strings['LBL_NOT_ACCESSIBLE']; - } - $sal_value = $col_fields["salutationtype"]; - if($sal_value == '--None--') - { - $sal_value=''; - } - $label_fld["salut"] = getTranslatedString($sal_value); - $label_fld["notaccess"] = $notacc; - } - $label_fld[] = $value; - } - elseif($uitype == 56) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $value = $col_fields[$fieldname]; - if($value == 1) - { - //Since "yes" is not been translated it is given as app strings here.. - $display_val = $app_strings['yes']; - } - else - { - $display_val = $app_strings['no']; - } - $label_fld[] = $display_val; - } - elseif($uitype == 57) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $contact_id = $col_fields[$fieldname]; - if($contact_id != '') - { - $contact_name = getContactName($contact_id); - } - $label_fld[] = $contact_name; - $label_fld["secid"] = $contact_id; - $label_fld["link"] = "index.php?module=Contacts&action=DetailView&record=".$contact_id; - } - elseif($uitype == 58) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $campaign_id = $col_fields[$fieldname]; - if($campaign_id != '') - { - $campaign_name = getCampaignName($campaign_id); - } - $label_fld[] = $campaign_name; - $label_fld["secid"] = $campaign_id; - $label_fld["link"] = "index.php?module=Campaigns&action=DetailView&record=".$campaign_id; - - } - elseif($uitype == 59) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $product_id = $col_fields[$fieldname]; - if($product_id != '') - { - $product_name = getProductName($product_id); - } - //Account Name View - $label_fld[] = $product_name; - $label_fld["secid"] = $product_id; - $label_fld["link"] = "index.php?module=Products&action=DetailView&record=".$product_id; - - } - elseif($uitype == 61) - { - global $adb; - $label_fld[] =getTranslatedString($fieldlabel, $module); - - if($tabid ==10) - { - $attach_result = $adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])); - for($ii=0;$ii < $adb->num_rows($attach_result);$ii++) - { - $attachmentid = $adb->query_result($attach_result,$ii,'attachmentsid'); - if($attachmentid != '') - { - $attachquery = "select * from vtiger_attachments where attachmentsid=?"; - $attachmentsname = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); - if($attachmentsname != '') - $custfldval = ''.$attachmentsname.''; - else - $custfldval = ''; - } - $label_fld['options'][] = $custfldval; - } - } - else - { - $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); - if($col_fields[$fieldname] == '' && $attachmentid != '') - { - $attachquery = "select * from vtiger_attachments where attachmentsid=?"; - $col_fields[$fieldname] = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); - } - - //This is added to strip the crmid and _ from the file name and show the original filename - //$org_filename = ltrim($col_fields[$fieldname],$col_fields['record_id'].'_'); - /*Above line is not required as the filename in the database is stored as it is and doesn't have crmid attached to it. - This was the cause for the issue reported in ticket #4645 */ - $org_filename = $col_fields[$fieldname]; - // For Backward Compatibility version < 5.0.4 - $filename_pos = strpos($org_filename, $col_fields['record_id'].'_'); - if ($filename_pos === 0) { - $start_idx = $filename_pos+strlen($col_fields['record_id'].'_'); - $org_filename = substr($org_filename, $start_idx); - } - if($org_filename != '') { - if($col_fields['filelocationtype'] == 'E' ){ - if($col_fields['filestatus'] == 1 ){//&& strlen($col_fields['filename']) > 7 ){ - $custfldval = ''.$col_fields[$fieldname].''; - } - else{ - $custfldval = $col_fields[$fieldname]; - } - }elseif($col_fields['filelocationtype'] == 'I') { - if($col_fields['filestatus'] == 1){ - $custfldval = ''.$col_fields[$fieldname].''; - } - else{ - $custfldval = $col_fields[$fieldname]; - } - } else - $custfldval = ''; - } - $label_fld[] =$custfldval; - } - } - elseif($uitype==28){ - $label_fld[] =getTranslatedString($fieldlabel, $module); - $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); - if($col_fields[$fieldname] == '' && $attachmentid != '') - { - $attachquery = "select * from vtiger_attachments where attachmentsid=?"; - $col_fields[$fieldname] = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); - } - $org_filename = $col_fields[$fieldname]; - // For Backward Compatibility version < 5.0.4 - $filename_pos = strpos($org_filename, $col_fields['record_id'].'_'); - if ($filename_pos === 0) { - $start_idx = $filename_pos+strlen($col_fields['record_id'].'_'); - $org_filename = substr($org_filename, $start_idx); - } - if($org_filename != '') { - if($col_fields['filelocationtype'] == 'E' ){ - if($col_fields['filestatus'] == 1 ){//&& strlen($col_fields['filename']) > 7 ){ - $custfldval = ''.$col_fields[$fieldname].''; - } - else{ - $custfldval = $col_fields[$fieldname]; - } - }elseif($col_fields['filelocationtype'] == 'I') { - if($col_fields['filestatus'] == 1){ - $custfldval = ''.$col_fields[$fieldname].''; - } - else{ - $custfldval = $col_fields[$fieldname]; - } - } else - $custfldval = ''; - } - $label_fld[] =$custfldval; - } - elseif($uitype == 69) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - if($tabid==14) - { - $images=array(); - $query = 'select productname, vtiger_attachments.path, vtiger_attachments.attachmentsid, vtiger_attachments.name,vtiger_crmentity.setype from vtiger_products left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_products.productid inner join vtiger_attachments on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid where vtiger_crmentity.setype="Products Image" and productid=?'; - $result_image = $adb->pquery($query, array($col_fields['record_id'])); - for($image_iter=0;$image_iter < $adb->num_rows($result_image);$image_iter++) - { - $image_id_array[] = $adb->query_result($result_image,$image_iter,'attachmentsid'); - - //decode_html - added to handle UTF-8 characters in file names - //urlencode - added to handle special characters like #, %, etc., - $image_array[] = urlencode(decode_html($adb->query_result($result_image,$image_iter,'name'))); - $image_orgname_array[] = decode_html($adb->query_result($result_image,$image_iter,'name')); - - $imagepath_array[] = $adb->query_result($result_image,$image_iter,'path'); - } - if(count($image_array)>1) - { - if(count($image_array) < 4) - $sides=count($image_array)*2; - else - $sides=8; - - $image_lists = ''; - $label_fld[] =$image_lists; - }elseif(count($image_array)==1) - { - list($pro_image_width, $pro_image_height) = getimagesize($imagepath_array[0].$image_id_array[0]."_".$image_orgname_array[0]); - if($pro_image_width > 450 || $pro_image_height > 300) - $label_fld[] =''; - else - $label_fld[] =''; - }else - { - $label_fld[] =''; - } - - } - if($tabid==4) - { - //$imgpath = getModuleFileStoragePath('Contacts').$col_fields[$fieldname]; - $sql = "select vtiger_attachments.*,vtiger_crmentity.setype from vtiger_attachments inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid where vtiger_crmentity.setype='Contacts Image' and vtiger_seattachmentsrel.crmid=?"; - $image_res = $adb->pquery($sql, array($col_fields['record_id'])); - $image_id = $adb->query_result($image_res,0,'attachmentsid'); - $image_path = $adb->query_result($image_res,0,'path'); - - - //decode_html - added to handle UTF-8 characters in file names - //urlencode - added to handle special characters like #, %, etc., - $image_name = urlencode(decode_html($adb->query_result($image_res,0,'name'))); - - $imgpath = $image_path.$image_id."_".$image_name; - if($image_name != '') - $label_fld[] =''.$mod_strings['Contact Image'].''; - else - $label_fld[] = ''; - } - - } - elseif($uitype == 62) - { - $value = $col_fields[$fieldname]; - if($value != '') - { - $parent_module = getSalesEntityType($value); - if($parent_module == "Leads") - { - $label_fld[] =$app_strings['LBL_LEAD_NAME']; - $lead_name = getLeadName($value); - - $label_fld[] =''.$lead_name.''; - } - elseif($parent_module == "Accounts") - { - $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $account_name = $adb->query_result($result,0,"accountname"); - - $label_fld[] =''.$account_name.''; - } - elseif($parent_module == "Potentials") - { - $label_fld[] =$app_strings['LBL_POTENTIAL_NAME']; - $sql = "select * from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($value)); - $potentialname = $adb->query_result($result,0,"potentialname"); - - $label_fld[] =''.$potentialname.''; - } - elseif($parent_module == "Products") - { - $label_fld[] =$app_strings['LBL_PRODUCT_NAME']; - $sql = "select * from vtiger_products where productid=?"; - $result = $adb->pquery($sql, array($value)); - $productname= $adb->query_result($result,0,"productname"); - - $label_fld[] =''.$productname.''; - } - elseif($parent_module == "PurchaseOrder") - { - $label_fld[] =$app_strings['LBL_PORDER_NAME']; - $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($sql, array($value)); - $pordername= $adb->query_result($result,0,"subject"); - - $label_fld[] = ''.$pordername.''; - } - elseif($parent_module == "SalesOrder") - { - $label_fld[] = $app_strings['LBL_SORDER_NAME']; - $sql = "select * from vtiger_salesorder where salesorderid=?"; - $result = $adb->pquery($sql, array($value)); - $sordername= $adb->query_result($result,0,"subject"); - - $label_fld[] = ''.$sordername.''; - } - elseif($parent_module == "Invoice") - { - $label_fld[] = $app_strings['LBL_INVOICE_NAME']; - $sql = "select * from vtiger_invoice where invoiceid=?"; - $result = $adb->pquery($sql, array($value)); - $invoicename= $adb->query_result($result,0,"subject"); - - $label_fld[] =''.$invoicename.''; - } - elseif($parent_module == "Quotes") - { - $label_fld[] = $app_strings['LBL_QUOTES_NAME']; - $sql = "select * from vtiger_quotes where quoteid=?"; - $result = $adb->pquery($sql, array($value)); - $quotename= $adb->query_result($result,0,"subject"); - - $label_fld[] =''.$quotename.''; - } - elseif($parent_module == "HelpDesk") - { - $label_fld[] = $app_strings['LBL_HELPDESK_NAME']; - $sql = "select * from vtiger_troubletickets where ticketid=?"; - $result = $adb->pquery($sql, array($value)); - $title= $adb->query_result($result,0,"title"); - $label_fld[] =''.$title.''; - } - } - else - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $value; - } - - - } - elseif($uitype == 105)//Added for user image - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - //$imgpath = getModuleFileStoragePath('Contacts').$col_fields[$fieldname]; - $sql = "select vtiger_attachments.* from vtiger_attachments left join vtiger_salesmanattachmentsrel on vtiger_salesmanattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid where vtiger_salesmanattachmentsrel.smid=?"; - $image_res = $adb->pquery($sql, array($col_fields['record_id'])); - $image_id = $adb->query_result($image_res,0,'attachmentsid'); - $image_path = $adb->query_result($image_res,0,'path'); - $image_name = $adb->query_result($image_res,0,'name'); - $imgpath = $image_path.$image_id."_".$image_name; - if($image_name != '') { - //Added the following check for the image to retain its in original size. - list($pro_image_width, $pro_image_height) = getimagesize(decode_html($imgpath)); - $label_fld[] =''.$col_fields['user_name'].''; - } else - $label_fld[] = ''; - } - elseif($uitype == 66) - { - $value = $col_fields[$fieldname]; - if($value != '') - { - $parent_module = getSalesEntityType($value); - if($parent_module == "Leads") - { - $label_fld[] =$app_strings['LBL_LEAD_NAME']; - $lead_name = getLeadName($value); - $label_fld[] = ''.$lead_name.''; - } - elseif($parent_module == "Accounts") - { - $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $account_name = $adb->query_result($result,0,"accountname"); - - $label_fld[] = ''.$account_name.''; - } - elseif($parent_module == "Potentials") - { - $label_fld[] =$app_strings['LBL_POTENTIAL_NAME']; - $sql = "select * from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($value)); - $potentialname = $adb->query_result($result,0,"potentialname"); - - $label_fld[] = ''.$potentialname.''; - } - elseif($parent_module == "Quotes") - { - $label_fld[] =$app_strings['LBL_QUOTE_NAME']; - $sql = "select * from vtiger_quotes where quoteid=?"; - $result = $adb->pquery($sql, array($value)); - $quotename = $adb->query_result($result,0,"subject"); - - $label_fld[] = ''.$quotename.''; - } - elseif($parent_module == "PurchaseOrder") - { - $label_fld[] = $app_strings['LBL_PORDER_NAME']; - $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($sql, array($value)); - $pordername = $adb->query_result($result,0,"subject"); - - $label_fld[] = ''.$pordername.''; - } - elseif($parent_module == "SalesOrder") - { - $label_fld[] = $app_strings['LBL_SORDER_NAME']; - $sql = "select * from vtiger_salesorder where salesorderid=?"; - $result = $adb->pquery($sql, array($value)); - $sordername = $adb->query_result($result,0,"subject"); - - $label_fld[] = ''.$sordername.''; - } - elseif($parent_module == "Invoice") - { - $label_fld[] = $app_strings['LBL_INVOICE_NAME']; - $sql = "select * from vtiger_invoice where invoiceid=?"; - $result = $adb->pquery($sql, array($value)); - $invoicename = $adb->query_result($result,0,"subject"); - - $label_fld[] = ''.$invoicename.''; - } - elseif($parent_module == "Campaigns") - { - $label_fld[] = $app_strings['LBL_CAMPAIGN_NAME']; - $sql = "select * from vtiger_campaign where campaignid=?"; - $result = $adb->pquery($sql, array($value)); - $campaignname = $adb->query_result($result,0,"campaignname"); - $label_fld[] = ''.$campaignname.''; - } - elseif($parent_module == "HelpDesk") - { - $label_fld[] = $app_strings['LBL_HELPDESK_NAME']; - $sql = "select * from vtiger_troubletickets where ticketid=?"; - $result = $adb->pquery($sql, array($value)); - $tickettitle = $adb->query_result($result,0,"title"); - if(strlen($tickettitle) > 25) - { - $tickettitle = substr($tickettitle,0,25).'...'; - } - $label_fld[] = ''.$tickettitle.''; - } - - } - else - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $value; - } - } - elseif($uitype == 67) - { - $value = $col_fields[$fieldname]; - if($value != '') - { - $parent_module = getSalesEntityType($value); - if($parent_module == "Leads") - { - $label_fld[] = $app_strings['LBL_LEAD_NAME']; - $lead_name = getLeadName($value); - $label_fld[] = ''.$lead_name.''; - } - elseif($parent_module == "Contacts") - { - $label_fld[] = $app_strings['LBL_CONTACT_NAME']; - $contact_name = getContactName($value); - $label_fld[] = ''.$contact_name.''; - } - } - else - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $value; - - } - } - //added by raju/rdhital for better emails - elseif($uitype == 357) - { - $value = $col_fields[$fieldname]; - if($value != '') - { - $parent_name=''; - $parent_id=''; - $myemailid= $_REQUEST['record']; - $mysql = "select crmid from vtiger_seactivityrel where activityid=?"; - $myresult = $adb->pquery($mysql, array($myemailid)); - $mycount=$adb->num_rows($myresult); - if ($mycount>1){ - $label_fld[] = $app_strings['LBL_RELATED_TO']; - $label_fld[] =$app_strings['LBL_MULTIPLE']; - } - else - { - $parent_module = getSalesEntityType($value); - if($parent_module == "Leads") - { - $label_fld[] = $app_strings['LBL_LEAD_NAME']; - $lead_name = getLeadName($value); - $label_fld[] = ''.$lead_name.''; - } - elseif($parent_module == "Contacts") - { - $label_fld[] = $app_strings['LBL_CONTACT_NAME']; - $contact_name = getContactName($value); - $label_fld[] = ''.$contact_name.''; - } - elseif($parent_module == "Accounts") - { - $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $accountname = $adb->query_result($result,0,"accountname"); - $label_fld[] = ''.$accountname.''; - } - - } - } - else - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $value; - } - }//Code added by raju for better email ends - - elseif($uitype == 68) - { - $value = $col_fields[$fieldname]; - if($value != '') - { - $parent_module = getSalesEntityType($value); - if($parent_module == "Contacts") - { - $label_fld[] = $app_strings['LBL_CONTACT_NAME']; - $contact_name = getContactName($value); - $label_fld[] =''.$contact_name.''; - } - elseif($parent_module == "Accounts") - { - $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $account_name = $adb->query_result($result,0,"accountname"); - - $label_fld[] = ''.$account_name.''; - } - else - { - $value =''; - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $value; - } - - - } - else - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - $label_fld[] = $value; - } - } - - elseif($uitype==63) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $label_fld[] = $col_fields[$fieldname].'h  '.$col_fields['duration_minutes'].'m'; - } - elseif($uitype == 6) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - if($col_fields[$fieldname]=='0') - $col_fields[$fieldname]=''; - if($col_fields['time_start']!='') - { - $start_time = $col_fields['time_start']; - } - if($col_fields[$fieldname] == '0000-00-00') - { - $displ_date = ''; - } - else - { - $displ_date = getDisplayDate($col_fields[$fieldname]); - } - if(empty($start_time)) $label_fld[] = $displ_date; - else $label_fld[] = $displ_date.' '.$start_time; - - } - elseif($uitype == 5 || $uitype == 23 || $uitype == 70) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $cur_date_val = $col_fields[$fieldname]; - if($col_fields['time_end']!='' && ($tabid == 9 || $tabid == 16) && $uitype == 23) - { - $end_time = $col_fields['time_end']; - } - if($cur_date_val == '0000-00-00') - { - $display_val = ''; - } - else - { - $display_val = getDisplayDate($cur_date_val); - } - if(empty($end_time)) $label_fld[] = $display_val; - else $label_fld[] = $display_val . ' ' . $end_time; - } - elseif($uitype == 71 || $uitype == 72) - { - $label_fld[] = getTranslatedString($fieldlabel, $module); - if($fieldname == 'unit_price') { - $rate_symbol=getCurrencySymbolandCRate(getProductBaseCurrency($col_fields['record_id'], $module)); - $label_fld[] = $col_fields[$fieldname]; - } else { - $rate_symbol=getCurrencySymbolandCRate($user_info['currency_id']); - $rate = $rate_symbol['rate']; - $label_fld[] = convertFromDollar($col_fields[$fieldname],$rate); - } - $currency = $rate_symbol['symbol']; - $label_fld["cursymb"] = $currency; - } - elseif($uitype == 75 || $uitype == 81) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $vendor_id = $col_fields[$fieldname]; - if($vendor_id != '') - { - $vendor_name = getVendorName($vendor_id); - } - $label_fld[] = $vendor_name; - $label_fld["secid"] = $vendor_id; - $label_fld["link"] = "index.php?module=Vendors&action=DetailView&record=".$vendor_id; - } - elseif($uitype == 76) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $potential_id = $col_fields[$fieldname]; - if($potential_id != '') - { - $potential_name = getPotentialName($potential_id); - } - $label_fld[] = $potential_name; - $label_fld["secid"] = $potential_id; - $label_fld["link"] = "index.php?module=Potentials&action=DetailView&record=".$potential_id; - } - elseif($uitype == 78) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $quote_id = $col_fields[$fieldname]; - if($quote_id != '') - { - $quote_name = getQuoteName($quote_id); - } - $label_fld[] = $quote_name; - $label_fld["secid"] = $quote_id; - $label_fld["link"] = "index.php?module=Quotes&action=DetailView&record=".$quote_id; - } - elseif($uitype == 79) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $purchaseorder_id = $col_fields[$fieldname]; - if($purchaseorder_id != '') - { - $purchaseorder_name = getPoName($purchaseorder_id); - } - $label_fld[] = $purchaseorder_name; - $label_fld["secid"] = $purchaseorder_id; - $label_fld["link"] = "index.php?module=PurchaseOrder&action=DetailView&record=".$purchaseorder_id; - } - elseif($uitype == 80) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $salesorder_id = $col_fields[$fieldname]; - if($salesorder_id != '') - { - $salesorder_name = getSoName($salesorder_id); - } - $label_fld[] = $salesorder_name; - $label_fld["secid"] = $salesorder_id; - $label_fld["link"] = "index.php?module=SalesOrder&action=DetailView&record=".$salesorder_id; - } - elseif($uitype == 30) - { - $rem_days = 0; - $rem_hrs = 0; - $rem_min = 0; - $reminder_str =""; - $rem_days = floor($col_fields[$fieldname]/(24*60)); - $rem_hrs = floor(($col_fields[$fieldname]-$rem_days*24*60)/60); - $rem_min = ($col_fields[$fieldname]-$rem_days*24*60)%60; - - $label_fld[] =getTranslatedString($fieldlabel, $module); - if($col_fields[$fieldname]) - { - $reminder_str= $rem_days.' '.$mod_strings['LBL_DAYS'].' '.$rem_hrs.' '.$mod_strings['LBL_HOURS'].' '.$rem_min.' '.$mod_strings['LBL_MINUTES'].'  '.$mod_strings['LBL_BEFORE_EVENT']; - } - $label_fld[] = ' '.$reminder_str; - }elseif($uitype == 98) - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - if(is_admin($current_user)) - $label_fld[] = ''.getRoleName($col_fields[$fieldname]).''; - else - $label_fld[] = getRoleName($col_fields[$fieldname]); - }elseif($uitype == 85) //Added for Skype by Minnie - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - $label_fld[]= $col_fields[$fieldname]; - } - elseif($uitype == 26){ - $label_fld[] =getTranslatedString($fieldlabel, $module); - $query = "select foldername from vtiger_attachmentsfolder where folderid = ?"; - $result = $adb->pquery($query, array($col_fields[$fieldname])); - $folder_name = $adb->query_result($result,0,"foldername"); - $label_fld[] = $folder_name; - } - elseif($uitype == 27){ - if($col_fields[$fieldname] == 'I'){ - $label_fld[]=getTranslatedString($fieldlabel, $module); - $label_fld[]= $mod_strings['LBL_INTERNAL']; - } - else{ - $label_fld[]=getTranslatedString($fieldlabel, $module); - $label_fld[]= $mod_strings['LBL_EXTERNAL']; - } - } - else - { - $label_fld[] =getTranslatedString($fieldlabel, $module); - if($col_fields[$fieldname]=='0' && $fieldname != 'filedownloadcount' && $fieldname != 'filestatus' && $fieldname != 'filesize') - $col_fields[$fieldname]=''; - if($uitype == 1 && ($fieldname=='expectedrevenue' || $fieldname=='budgetcost' || $fieldname=='actualcost' || $fieldname=='expectedroi' || $fieldname=='actualroi' )) - { - $rate_symbol=getCurrencySymbolandCRate($user_info['currency_id']); - $label_fld[] = convertFromDollar($col_fields[$fieldname],$rate_symbol['rate']); - } - else - { - //code for Documents module :start - if($tabid == 8) - { - $downloadtype = $col_fields['filelocationtype']; - if($fieldname == 'filename') - { - if($downloadtype == 'I') - { - //$file_value = $mod_strings['LBL_INTERNAL']; - $fld_value = $col_fields['filename']; - $ext_pos = strrpos($fld_value, "."); - $ext =substr($fld_value, $ext_pos + 1); - $ext = strtolower($ext); - if($ext == 'bin' || $ext == 'exe' || $ext == 'rpm') - $fileicon=""; - elseif($ext == 'jpg' || $ext == 'gif' || $ext == 'bmp') - $fileicon=""; - elseif($ext == 'txt' || $ext == 'doc' || $ext == 'xls') - $fileicon=""; - elseif($ext == 'zip' || $ext == 'gz' || $ext == 'rar') - $fileicon=""; - else - $fileicon=""; - } - else - { - $fld_value = $col_fields['filename']; - $fileicon = "".$mod_strings["; - } - $label_fld[] = $fileicon.$fld_value; - } - if($fieldname == 'filesize') - { - if($col_fields['filelocationtype'] == 'I') - { - $filesize = $col_fields[$fieldname]; - if($filesize < 1024) - $label_fld[]=$filesize.' B'; - elseif($filesize > 1024 && $filesize < 1048576) - $label_fld[]=round($filesize/1024,2).' KB'; - else if($filesize > 1048576) - $label_fld[]=round($filesize/(1024*1024),2).' MB'; - } - else - { - $label_fld[]=' --'; - } - } - if($fieldname == 'filetype' && $col_fields['filelocationtype'] == 'E') - { - $label_fld[]=' --'; - } - /*if($fieldname == 'filestatus') - { - $filestatus = $col_fields[$fieldname]; - if($filestatus == 0) - $label_fld[]=$mod_strings['LBL_ACTIVE']; - else - $label_fld[]=$mod_strings['LBL_INACTIVE']; - }*/ - } - //code for Documents module :end - $label_fld[] = $col_fields[$fieldname]; - } - } - $label_fld[]=$uitype; - - //sets whether the currenct user is admin or not - if(is_admin($current_user)) - { - $label_fld["isadmin"] = 1; - }else - { - $label_fld["isadmin"] = 0; - } - - $log->debug("Exiting getDetailViewOutputHtml method ..."); - return $label_fld; -} - -/** This function returns a HTML output of associated vtiger_products for a given entity (Quotes,Invoice,Sales order or Purchase order) - * Param $module - module name - * Param $focus - module object - * Return type string - */ - -function getDetailAssociatedProducts($module,$focus) -{ - global $log; - $log->debug("Entering getDetailAssociatedProducts(".$module.",".get_class($focus).") method ..."); - global $adb; - global $mod_strings; - global $theme; - global $log; - global $app_strings,$current_user; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - - if($module != 'PurchaseOrder') - { - $colspan = '2'; - } - else - { - $colspan = '1'; - } - - //Get the taxtype of this entity - $taxtype = getInventoryTaxType($module,$focus->id); - $currencytype = getInventoryCurrencyInfo($module, $focus->id); - - $output = ''; - //Header Rows - $output .= ' - - - - - - - - - '; - - //Add Quantity in Stock column for SO, Quotes and Invoice - if($module == 'Quotes' || $module == 'SalesOrder' || $module == 'Invoice') - $output .= ''; - - $output .= ' - - - - - - - '; - - - // DG 15 Aug 2006 - // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items - - if($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') - { - $query="select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . - " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . - " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . - " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, vtiger_inventoryproductrel.* " . - " from vtiger_inventoryproductrel" . - " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . - " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . - " where id=? ORDER BY sequence_no"; - } - - $result = $adb->pquery($query, array($focus->id)); - $num_rows=$adb->num_rows($result); - $netTotal = '0.00'; - for($i=1;$i<=$num_rows;$i++) - { - $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($focus->id,$i)); - $subprodname_str=''; - if($adb->num_rows($sub_prod_query)>0){ - for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ - $sprod_id = $adb->query_result($sub_prod_query,$j,'productid'); - $sprod_name = getProductName($sprod_id); - $str_sep = ""; - if($j>0) $str_sep = ":"; - $subprodname_str .= $str_sep." - ".$sprod_name; - } - } - $subprodname_str = str_replace(":","
",$subprodname_str); - - $productid=$adb->query_result($result,$i-1,'productid'); - $entitytype=$adb->query_result($result,$i-1,'entitytype'); - $productname=$adb->query_result($result,$i-1,'productname'); - if($subprodname_str!='') $productname .= "
".$subprodname_str.""; - $comment=$adb->query_result($result,$i-1,'comment'); - $qtyinstock=$adb->query_result($result,$i-1,'qtyinstock'); - $qty=$adb->query_result($result,$i-1,'quantity'); - $unitprice=$adb->query_result($result,$i-1,'unit_price'); - $listprice=$adb->query_result($result,$i-1,'listprice'); - $total = $qty*$listprice; - - //Product wise Discount calculation - starts - $discount_percent=$adb->query_result($result,$i-1,'discount_percent'); - $discount_amount=$adb->query_result($result,$i-1,'discount_amount'); - $totalAfterDiscount = $total; - - $productDiscount = '0.00'; - if($discount_percent != 'NULL' && $discount_percent != '') - { - $productDiscount = $total*$discount_percent/100; - $totalAfterDiscount = $total-$productDiscount; - //if discount is percent then show the percentage - $discount_info_message = "$discount_percent % of $total = $productDiscount"; - } - elseif($discount_amount != 'NULL' && $discount_amount != '') - { - $productDiscount = $discount_amount; - $totalAfterDiscount = $total-$productDiscount; - $discount_info_message = $app_strings['LBL_DIRECT_AMOUNT_DISCOUNT']." = $productDiscount"; - } - else - { - $discount_info_message = $app_strings['LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM']; - } - //Product wise Discount calculation - ends - - $netprice = $totalAfterDiscount; - //Calculate the individual tax if taxtype is individual - if($taxtype == 'individual') - { - $taxtotal = '0.00'; - $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT']." = $totalAfterDiscount \\n"; - $tax_details = getTaxDetailsForProduct($productid,'all'); - for($tax_count=0;$tax_countid, $productid, $tax_name); - - $individual_taxamount = $totalAfterDiscount*$tax_value/100; - $taxtotal = $taxtotal + $individual_taxamount; - $tax_info_message .= "$tax_label : $tax_value % = $individual_taxamount \\n"; - } - $tax_info_message .= "\\n ".$app_strings['LBL_TOTAL_TAX_AMOUNT']." = $taxtotal"; - $netprice = $netprice + $taxtotal; - } - - $sc_image_tag = ''; - if ($entitytype == 'Services') { - $sc_image_tag = '' . - '' . - ''; - } - - //For Product Name - $output .= ' - - '; - //Upto this added to display the Product name and comment - - - if($module != 'PurchaseOrder') - { - $output .= ''; - } - $output .= ''; - $output .= ' - '; - - $output .= ' - '; - $output .= ''; - $output .= ''; - - $netTotal = $netTotal + $netprice; - } - - $output .= '
'.$app_strings['LBL_ITEM_DETAILS'].''. - $app_strings['LBL_CURRENCY'].' : '. getTranslatedCurrencyString($currencytype['currency_name']). ' ('. $currencytype['currency_symbol'] .') - '. - $app_strings['LBL_TAX_MODE'].' : '.$app_strings[$taxtype].' -
* - '.$app_strings['LBL_ITEM_NAME'].' - '.$app_strings['LBL_QTY_IN_STOCK'].''.$app_strings['LBL_QTY'].''.$app_strings['LBL_LIST_PRICE'].''.$app_strings['LBL_TOTAL'].''.$app_strings['LBL_NET_PRICE'].'
- '.$productname.' '.$sc_image_tag.' -
'.$comment.' -
'.$qtyinstock.''.$qty.' - - - - - - - - - - '; - if($taxtype == 'individual') - { - $output .= ' - - - '; - } - $output .= ' -
'.$listprice.'
(-) '.$app_strings['LBL_DISCOUNT'].' :
'.$app_strings['LBL_TOTAL_AFTER_DISCOUNT'].' :
(+) '.$app_strings['LBL_TAX'].' :
-
- - - - '; - - if($taxtype == 'individual') - { - $output .= ''; - } - - $output .= ' -
'.$total.'
'.$productDiscount.'
'.$totalAfterDiscount.'
'.$taxtotal.'
-
'.$netprice.'
'; - - //$netTotal should be equal to $focus->column_fields['hdnSubTotal'] - $netTotal = $focus->column_fields['hdnSubTotal']; - - //Display the total, adjustment, S&H details - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - - //Decide discount - $finalDiscount = '0.00'; - $final_discount_info = '0'; - //if($focus->column_fields['hdnDiscountPercent'] != '') - previously (before changing to prepared statement) the selected option (either percent or amount) will have value and the other remains empty. So we can find the non selected item by empty check. But now with prepared statement, the non selected option stored as 0 - if($focus->column_fields['hdnDiscountPercent'] != '0') - { - $finalDiscount = ($netTotal*$focus->column_fields['hdnDiscountPercent']/100); - $final_discount_info = $focus->column_fields['hdnDiscountPercent']." % of $netTotal = $finalDiscount"; - } - elseif($focus->column_fields['hdnDiscountAmount'] != '0') - { - $finalDiscount = $focus->column_fields['hdnDiscountAmount']; - $final_discount_info = $finalDiscount; - } - - //Alert the Final Discount amount even it is zero - $final_discount_info = $app_strings['LBL_FINAL_DISCOUNT_AMOUNT']." = $final_discount_info"; - $final_discount_info = 'onclick="alert(\''.$final_discount_info.'\');"'; - - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - - if($taxtype == 'group') - { - $taxtotal = '0.00'; - $final_totalAfterDiscount = $netTotal - $finalDiscount; - $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT']." = $final_totalAfterDiscount \\n"; - //First we should get all available taxes and then retrieve the corresponding tax values - $tax_details = getAllTaxes('available','','edit',$focus->id); - //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table - for($tax_count=0;$tax_countquery_result($result,0,$tax_name); - if($tax_value == '' || $tax_value == 'NULL') - $tax_value = '0.00'; - - $taxamount = ($netTotal-$finalDiscount)*$tax_value/100; - $taxtotal = $taxtotal + $taxamount; - $tax_info_message .= "$tax_label : $tax_value % = $taxamount \\n"; - } - $tax_info_message .= "\\n ".$app_strings['LBL_TOTAL_TAX_AMOUNT']." = $taxtotal"; - - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - } - - $shAmount = ($focus->column_fields['hdnS_H_Amount'] != '')?$focus->column_fields['hdnS_H_Amount']:'0.00'; - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - - //calculate S&H tax - $shtaxtotal = '0.00'; - //First we should get all available taxes and then retrieve the corresponding tax values - $shtax_details = getAllTaxes('available','sh','edit',$focus->id); - //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table - $shtax_info_message = $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGE']." = $shAmount \\n"; - for($shtax_count=0;$shtax_countid,$shtax_name); - $shtaxamount = $shAmount*$shtax_percent/100; - $shtaxtotal = $shtaxtotal + $shtaxamount; - $shtax_info_message .= "$shtax_label : $shtax_percent % = $shtaxamount \\n"; - } - $shtax_info_message .= "\\n ".$app_strings['LBL_TOTAL_TAX_AMOUNT']." = $shtaxtotal"; - - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - - $adjustment = ($focus->column_fields['txtAdjustment'] != '')?$focus->column_fields['txtAdjustment']:'0.00'; - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - - $grandTotal = ($focus->column_fields['hdnGrandTotal'] != '')?$focus->column_fields['hdnGrandTotal']:'0.00'; - $output .= ''; - $output .= ''; - $output .= ''; - $output .= ''; - $output .= '
'.$app_strings['LBL_NET_TOTAL'].''.$netTotal.'
(-) '.$app_strings['LBL_DISCOUNT'].''.$finalDiscount.'
(+) '.$app_strings['LBL_TAX'].''.$taxtotal.'
(+) '.$app_strings['LBL_SHIPPING_AND_HANDLING_CHARGES'].''.$shAmount.'
(+) '.$app_strings['LBL_TAX_FOR_SHIPPING_AND_HANDLING'].''.$shtaxtotal.'
 '.$app_strings['LBL_ADJUSTMENT'].''.$adjustment.'
'.$app_strings['LBL_GRAND_TOTAL'].''.$grandTotal.'
'; - - $log->debug("Exiting getDetailAssociatedProducts method ..."); - return $output; - -} - -/** This function returns the related vtiger_tab details for a given entity or a module. -* Param $module - module name -* Param $focus - module object -* Return type is an array -*/ - -function getRelatedLists($module,$focus) -{ - global $log; - $log->debug("Entering getRelatedLists(".$module.",".get_class($focus).") method ..."); - global $adb; - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - $cur_tab_id = getTabid($module); - - //$sql1 = "select * from vtiger_relatedlists where tabid=? order by sequence"; - // vtlib customization: Do not picklist module which are set as in-active - $sql1 = "select * from vtiger_relatedlists where tabid=? and related_tabid not in (SELECT tabid FROM vtiger_tab WHERE presence = 1) order by sequence"; - // END - $result = $adb->pquery($sql1, array($cur_tab_id)); - $num_row = $adb->num_rows($result); - for($i=0; $i<$num_row; $i++) - { - $rel_tab_id = $adb->query_result($result,$i,"related_tabid"); - $function_name = $adb->query_result($result,$i,"name"); - $label = $adb->query_result($result,$i,"label"); - $actions = $adb->query_result($result,$i,"actions"); - if($rel_tab_id != 0) - { - - if($profileTabsPermission[$rel_tab_id] == 0) - { - if($profileActionPermission[$rel_tab_id][3] == 0) - { - // vtlib customization: Send more information (from module, related module) to the callee - $focus_list[$label] = $focus->$function_name($focus->id, $cur_tab_id, $rel_tab_id, $actions); - // END - } - } - } - else - { - // vtlib customization: Send more information (from module, related module) to the callee - $focus_list[$label] = $focus->$function_name($focus->id, $cur_tab_id, $rel_tab_id, $actions); - // END - } - } - $log->debug("Exiting getRelatedLists method ..."); - return $focus_list; -} - -/** This function returns whether related lists is present for this particular module or not -* Param $module - module name -* Param $activity_mode - mode of activity -* Return type true or false -*/ - - -function isPresentRelatedLists($module,$activity_mode='') -{ - global $adb; - $retval='true'; - $tab_id=getTabid($module); - // We need to check if there is atleast 1 relation, no need to use count(*) - $query= "select relation_id from vtiger_relatedlists where tabid=? LIMIT 1"; - $result=$adb->pquery($query, array($tab_id)); - $count=$adb->num_rows($result); - if($count < 1 || ($module =='Calendar' && $activity_mode=='task')) - { - $retval='false'; - } - return $retval; - - -} - -/** This function returns the detailed block information of a record in a module. -* Param $module - module name -* Param $block - block id -* Param $col_fields - column vtiger_fields array for the module -* Param $tabid - vtiger_tab id -* Return type is an array -*/ - -function getDetailBlockInformation($module, $result,$col_fields,$tabid,$block_label) -{ - global $log; - $log->debug("Entering getDetailBlockInformation(".$module.",". $result.",".$col_fields.",".$tabid.",".$block_label.") method ..."); - global $adb; - global $current_user; - global $mod_strings; - $label_data = Array(); - - $noofrows = $adb->num_rows($result); - for($i=0; $i<$noofrows; $i++) - { - $fieldtablename = $adb->query_result($result,$i,"tablename"); - $fieldcolname = $adb->query_result($result,$i,"columnname"); - $uitype = $adb->query_result($result,$i,"uitype"); - $fieldname = $adb->query_result($result,$i,"fieldname"); - $fieldid = $adb->query_result($result,$i,"fieldid"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $maxlength = $adb->query_result($result,$i,"maximumlength"); - $block = $adb->query_result($result,$i,"block"); - $generatedtype = $adb->query_result($result,$i,"generatedtype"); - $tabid = $adb->query_result($result,$i,"tabid"); - $displaytype = $adb->query_result($result,$i,'displaytype'); - $custfld = getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields,$generatedtype,$tabid,$module); - if(is_array($custfld)) - { - $label_data[$block][] = array($custfld[0]=>array("value"=>$custfld[1],"ui"=>$custfld[2],"options"=>$custfld["options"],"secid"=>$custfld["secid"],"link"=>$custfld["link"],"cursymb"=>$custfld["cursymb"],"salut"=>$custfld["salut"],"notaccess"=>$custfld["notaccess"],"cntimage"=>$custfld["cntimage"],"isadmin"=>$custfld["isadmin"],"tablename"=>$fieldtablename,"fldname"=>$fieldname,"fldid"=>$fieldid,"displaytype"=>$displaytype)); - } - $i++; - if($i<$noofrows) - { - $fieldtablename = $adb->query_result($result,$i,"tablename"); - $fieldcolname = $adb->query_result($result,$i,"columnname"); - $uitype = $adb->query_result($result,$i,"uitype"); - $fieldname = $adb->query_result($result,$i,"fieldname"); - $fieldid = $adb->query_result($result,$i,"fieldid"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $maxlength = $adb->query_result($result,$i,"maximumlength"); - $block = $adb->query_result($result,$i,"block"); - $generatedtype = $adb->query_result($result,$i,"generatedtype"); - $tabid = $adb->query_result($result,$i,"tabid"); - $displaytype = $adb->query_result($result,$i,'displaytype'); - $custfld = getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields,$generatedtype,$tabid,$module); - if(is_array($custfld)) - { - $label_data[$block][] = array($custfld[0]=>array("value"=>$custfld[1],"ui"=>$custfld[2],"options"=>$custfld["options"],"secid"=>$custfld["secid"],"link"=>$custfld["link"],"cursymb"=>$custfld["cursymb"],"salut"=>$custfld["salut"],"notaccess"=>$custfld["notaccess"],"cntimage"=>$custfld["cntimage"],"isadmin"=>$custfld["isadmin"],"tablename"=>$fieldtablename,"fldname"=>$fieldname,"fldid"=>$fieldid,"displaytype"=>$displaytype)); - } - } - } - foreach($label_data as $headerid=>$value_array) - { - $detailview_data = Array(); - for ($i=0,$j=0;$i $value_array[$i][$key1],$key2 => $value_array[$i+1][$key2]); - $i+=2; - }else{ - $detailview_data[$j]=array($use_key1 => $value_array[$i][$key1]); - $i++; - } - } - $label_data[$headerid] = $detailview_data; - } - foreach($block_label as $blockid=>$label) - { - if($label == '') - { - $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$label_data[$blockid]); - } - else - { - $curBlock = $label; - if(is_array($label_data[$blockid])) - $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$label_data[$blockid]); - } - } - $log->debug("Exiting getDetailBlockInformation method ..."); - return $returndata; - - -} - -function VT_detailViewNavigation($smarty,$recordNavigationInfo,$currrentRecordId){ - $pageNumber =0; - foreach ($recordNavigationInfo as $start=>$recordIdList){ - $pageNumber++; - foreach ($recordIdList as $index=>$recordId) { - if($recordId === $currrentRecordId){ - if($index ==0 ){ - $smarty->assign('privrecordstart',$start-1); - $smarty->assign('privrecord',$recordNavigationInfo[$start-1][count($recordNavigationInfo[$start-1])-1]); - }else{ - $smarty->assign('privrecordstart',$start); - $smarty->assign('privrecord',$recordIdList[$index-1]); - } - if($index == count($recordIdList)-1){ - $smarty->assign('nextrecordstart',$start+1); - $smarty->assign('nextrecord',$recordNavigationInfo[$start+1][0]); - }else{ - $smarty->assign('nextrecordstart',$start); - $smarty->assign('nextrecord',$recordIdList[$index+1]); - } - } - } - } -} - - -?> +debug("Entering getDetailViewOutputHtml(".$uitype.",". $fieldname.",". $fieldlabel.",". $col_fields.",".$generatedtype.",".$tabid.") method ..."); + global $adb; + global $mod_strings; + global $app_strings; + global $current_user; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + $fieldlabel = from_html($fieldlabel); + $custfld = ''; + $value =''; + $arr_data =Array(); + $label_fld = Array(); + $data_fld = Array(); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + // vtlib customization: New uitype to handle relation between modules + if($uitype == '10'){ + $fieldlabel = getTranslatedString($fieldlabel, $module); + + $parent_id = $col_fields[$fieldname]; + if(!empty($parent_id)) { + $parent_module = getSalesEntityType($parent_id); + $valueTitle=$parent_module; + if($app_strings[$valueTitle]) $valueTitle = $app_strings[$valueTitle]; + + $displayValueArray = getEntityName($parent_module, $parent_id); + if(!empty($displayValueArray)){ + foreach($displayValueArray as $key=>$value){ + $displayValue = $value; + } + } + $label_fld=array($fieldlabel, + "$displayValue"); + } else { + $moduleSpecificMessage = 'MODULE_NOT_SELECTED'; + if($mod_strings[$moduleSpecificMessage] != ""){ + $moduleSpecificMessage = $mod_strings[$moduleSpecificMessage]; + } + $label_fld=array($fieldlabel, ''); + } + } // END + else if($uitype == 99) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + if($fieldname == 'confirm_password') + return null; + }elseif($uitype == 116 || $uitype == 117) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = getCurrencyName($col_fields[$fieldname]); + $pick_query="select * from vtiger_currency_info where currency_status = 'Active' and deleted=0"; + $pickListResult = $adb->pquery($pick_query, array()); + $noofpickrows = $adb->num_rows($pickListResult); + + //Mikecrowe fix to correctly default for custom pick lists + $options = array(); + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,'currency_name'); + $currency_id=$adb->query_result($pickListResult,$j,'id'); + if($col_fields[$fieldname] == $currency_id) + { + $chk_val = "selected"; + $found = true; + } + else + { + $chk_val = ''; + } + $options[$currency_id] = array($pickListValue=>$chk_val ); + } + $label_fld ["options"] = $options; + } + elseif($uitype == 13 || $uitype == 104) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + } + elseif($uitype == 16) { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + + $fieldname = $adb->sql_escape_string($fieldname); + $pick_query="select $fieldname from vtiger_$fieldname order by sortorderid"; + $params = array(); + $pickListResult = $adb->pquery($pick_query, $params); + $noofpickrows = $adb->num_rows($pickListResult); + + $options = array(); + $count=0; + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=decode_html($adb->query_result($pickListResult,$j,strtolower($fieldname))); + $col_fields[$fieldname] = decode_html($col_fields[$fieldname]); + + if($col_fields[$fieldname] == $pickListValue) + { + $chk_val = "selected"; + $count++; + $found = true; + } + else + { + $chk_val = ''; + } + $pickListValue = to_html($pickListValue); + $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); + } + + $label_fld ["options"] = $options; + } + elseif($uitype == 15) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + $roleid=$current_user->roleid; + + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $pick_query="select $fieldname from vtiger_$fieldname"; + $params = array(); + }else + { + if (count($roleids) > 0) { + $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; + $params = array($roleids); + } else { + $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; + $params = array(); + } + } + $pickListResult = $adb->pquery($pick_query, $params); + $noofpickrows = $adb->num_rows($pickListResult); + + //Mikecrowe fix to correctly default for custom pick lists + $options = array(); + $count=0; + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=decode_html($adb->query_result($pickListResult,$j,strtolower($fieldname))); + $col_fields[$fieldname] = decode_html($col_fields[$fieldname]); + + if($col_fields[$fieldname] == $pickListValue) + { + $chk_val = "selected"; + $count++; + $found = true; + } + else + { + $chk_val = ''; + } + $pickListValue = to_html($pickListValue); + $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); + } + if($count == 0 && $col_fields[$fieldname] != '') + { + $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'],$col_fields[$fieldname],'selected'); + } + + + $label_fld ["options"] = $options; + } + elseif($uitype == 115) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = getTranslatedString($col_fields[$fieldname]); + + $pick_query="select * from vtiger_" . $adb->sql_escape_string($fieldname); + $pickListResult = $adb->pquery($pick_query, array()); + $noofpickrows = $adb->num_rows($pickListResult); + $options = array(); + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,strtolower($fieldname)); + + if($col_fields[$fieldname] == $pickListValue) + { + $chk_val = "selected"; + $found = true; + } + else + { + $chk_val = ''; + } + $options[] = array($pickListValue=>$chk_val ); + } + $label_fld ["options"] = $options; + } + elseif($uitype == 33) //uitype 33 added for multiselector picklist - Jeri + { + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + $editview_label[]=getTranslatedString($fieldlabel, $module); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $pick_query="select $fieldname from vtiger_$fieldname order by $fieldname asc"; + $params = array(); + }else + { + if (count($roleids) > 0) { + $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; + $params = array($roleids); + } else { + $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where picklistid in (select picklistid from vtiger_picklist) order by $fieldname asc"; + $params = array(); + } + } + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = str_ireplace(' |##| ',', ',$col_fields[$fieldname]); + + $pickListResult = $adb->pquery($pick_query, $params); + $noofpickrows = $adb->num_rows($pickListResult); + + $options = array(); + $selected_entries = Array(); + $selected_entries = explode(' |##| ',$col_fields[$fieldname]); + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue = $adb->query_result($pickListResult,$j,strtolower($fieldname)); + $chk_val = ''; + foreach($selected_entries as $selected_entries_value) + { + if(trim($selected_entries_value) == trim($pickListValue)) + { + $chk_val = 'selected'; + break; + } + else + { + $chk_val = ''; + } + } + $options[] = array($pickListValue,$pickListValue,$chk_val); + } + foreach($selected_entries as $selected_entries_value) + { + $mul_count =0; + $options_length = count($options); + for($j=0;$j<$options_length;$j++) + { + if(in_array($selected_entries_value,$options[$j])) + { + $mul_count++; + } + + } + if($mul_count == 0 && $options_length > 0) + { + $not_access_lbl = "".$app_strings['LBL_NOT_ACCESSIBLE'].""; + $options[]=array($not_access_lbl,trim($selected_entries_value),'selected'); + } + $mul_count=0; + } + $label_fld ["options"] = $options; + } + elseif($uitype == 17) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + } + elseif($uitype == 19) + { + if($fieldname == 'notecontent') + $col_fields[$fieldname]= decode_html($col_fields[$fieldname]); + else + $col_fields[$fieldname]= str_replace("<br />","
",$col_fields[$fieldname]); + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + } + elseif($uitype == 20 || $uitype == 21 || $uitype == 22 || $uitype == 24) // Armando LC B'descriptionSpan -> Desc: removed $uitype == 19 and made an aditional elseif above + { + if($uitype == 20)//Fix the issue #4680 + $col_fields[$fieldname]=$col_fields[$fieldname]; + else + $col_fields[$fieldname]=nl2br($col_fields[$fieldname]); + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + } + elseif($uitype == 51 || $uitype == 50 || $uitype == 73) + { + $account_id = $col_fields[$fieldname]; + if($account_id != '') + { + $account_name = getAccountName($account_id); + } + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $account_name; + $label_fld["secid"] = $account_id; + $label_fld["link"] = "index.php?module=Accounts&action=DetailView&record=".$account_id; + //Account Name View + } + elseif($uitype == 52 || $uitype == 77 || $uitype == 101) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $user_id = $col_fields[$fieldname]; + $user_name = getUserName($user_id); + $assigned_user_id = $current_user->id; + if(is_admin($current_user)) + { + $label_fld[] =''.$user_name.''; + } + else + { + $label_fld[] =$user_name; + } + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); + } + else + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $user_id), $assigned_user_id); + } + $label_fld ["options"] = $users_combo; + + } + elseif($uitype == 11){ + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname]; + } + elseif($uitype == 53) + { + global $noof_group_rows, $adb; + $owner_id = $col_fields[$fieldname]; + + $user = 'no'; + $result = $adb->pquery("SELECT count(*) as count from vtiger_users where id = ?",array($owner_id)); + if($adb->query_result($result,0,'count') > 0) { + $user = 'yes'; + } + + $owner_name = getOwnerName($owner_id); + $label_fld[] =getTranslatedString($fieldlabel, $module); + $label_fld[] =$owner_name; + + if(is_admin($current_user)) + { + $label_fld["secid"][] = $owner_id; + if($user == 'no') { + $label_fld["link"][] = "index.php?module=Settings&action=GroupDetailView&groupId=".$owner_id; + } + else { + $label_fld["link"][] = "index.php?module=Users&action=DetailView&record=".$owner_id; + } + //$label_fld["secid"][] = $groupid; + //$label_fld["link"][] = "index.php?module=Settings&action=GroupDetailView&groupId=".$groupid; + } + + //Security Checks + if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) + { + $result=get_current_user_access_groups($module_name); + } + else + { + $result = get_group_options(); + } + if($result) $nameArray = $adb->fetch_array($result); + + + global $current_user; + //$value = $user_id; + if($owner_id != '') { + if($user == 'yes') { + $label_fld ["options"][] = 'User'; + $assigned_user_id = $owner_id; + $user_checked = "checked"; + $team_checked = ''; + $user_style='display:block'; + $team_style='display:none'; + } + else { + //$record = $col_fields["record_id"]; + //$module = $col_fields["record_module"]; + $label_fld ["options"][] = 'Group'; + $assigned_group_id = $owner_id; + $user_checked = ''; + $team_checked = 'checked'; + $user_style='display:none'; + $team_style='display:block'; + } + } + else { + $label_fld ["options"][] = 'User'; + $assigned_user_id = $current_user->id; + $user_checked = "checked"; + $team_checked = ''; + $user_style='display:block'; + $team_style='display:none'; + } + + + if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); + } + else + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id), $current_user->id); + } + + if($noof_group_rows!=0) + { + if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module)] == 3 or $defaultOrgSharingPermission[getTabid($module)] == 0)) + { + $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id,'private'), $current_user->id); + } + else + { + $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $current_user->id), $current_user->id); + } + } + + $label_fld ["options"][] = $users_combo; + $label_fld ["options"][] = $groups_combo; + } + elseif($uitype == 55 || $uitype == 255) + { + if($tabid == 4) + { + $query="select vtiger_contactdetails.imagename from vtiger_contactdetails where contactid=?"; + $result = $adb->pquery($query, array($col_fields['record_id'])); + $imagename=$adb->query_result($result,0,'imagename'); + if($imagename != '') + { + $imgpath = "test/contact/".$imagename; + $label_fld[] =getTranslatedString($fieldlabel, $module); + } + else + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + } + + } + else + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + } + $value = $col_fields[$fieldname]; + if($uitype==255) + { + global $currentModule; + $fieldpermission = getFieldVisibilityPermission($currentModule, $current_user->id,'firstname'); + } + if($uitype == 255 && $fieldpermission == 0 && $fieldpermission != '') + { + $fieldvalue[] = ''; + } + else + { + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = implode("','",$subrole); + $roleids = $roleids."','".$roleid; + } + else + { + $roleids = $roleid; + } + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $pick_query="select salutationtype from vtiger_salutationtype order by salutationtype"; + $params = array(); + } + else + { + $pick_query="select * from vtiger_salutationtype left join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid=vtiger_salutationtype.picklist_valueid where picklistid in (select picklistid from vtiger_picklist where name='salutationtype') and roleid=? order by salutationtype"; + $params = array($current_user->roleid); + } + $pickListResult = $adb->pquery($pick_query, $params); + $noofpickrows = $adb->num_rows($pickListResult); + $sal_value = $col_fields["salutationtype"]; + $salcount =0; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,"salutationtype"); + + if($sal_value == $pickListValue) + { + $chk_val = "selected"; + $salcount++; + } + else + { + $chk_val = ''; + } + } + if($salcount == 0 && $sal_value != '') + { + $notacc = $app_strings['LBL_NOT_ACCESSIBLE']; + } + $sal_value = $col_fields["salutationtype"]; + if($sal_value == '--None--') + { + $sal_value=''; + } + $label_fld["salut"] = getTranslatedString($sal_value); + $label_fld["notaccess"] = $notacc; + } + $label_fld[] = $value; + } + elseif($uitype == 56) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $value = $col_fields[$fieldname]; + if($value == 1) + { + //Since "yes" is not been translated it is given as app strings here.. + $display_val = $app_strings['yes']; + } + else + { + $display_val = $app_strings['no']; + } + $label_fld[] = $display_val; + } + elseif($uitype == 57) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $contact_id = $col_fields[$fieldname]; + if($contact_id != '') + { + $contact_name = getContactName($contact_id); + } + $label_fld[] = $contact_name; + $label_fld["secid"] = $contact_id; + $label_fld["link"] = "index.php?module=Contacts&action=DetailView&record=".$contact_id; + } + elseif($uitype == 58) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $campaign_id = $col_fields[$fieldname]; + if($campaign_id != '') + { + $campaign_name = getCampaignName($campaign_id); + } + $label_fld[] = $campaign_name; + $label_fld["secid"] = $campaign_id; + $label_fld["link"] = "index.php?module=Campaigns&action=DetailView&record=".$campaign_id; + + } + elseif($uitype == 59) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $product_id = $col_fields[$fieldname]; + if($product_id != '') + { + $product_name = getProductName($product_id); + } + //Account Name View + $label_fld[] = $product_name; + $label_fld["secid"] = $product_id; + $label_fld["link"] = "index.php?module=Products&action=DetailView&record=".$product_id; + + } + elseif($uitype == 61) + { + global $adb; + $label_fld[] =getTranslatedString($fieldlabel, $module); + + if($tabid ==10) + { + $attach_result = $adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])); + for($ii=0;$ii < $adb->num_rows($attach_result);$ii++) + { + $attachmentid = $adb->query_result($attach_result,$ii,'attachmentsid'); + if($attachmentid != '') + { + $attachquery = "select * from vtiger_attachments where attachmentsid=?"; + $attachmentsname = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); + if($attachmentsname != '') + $custfldval = ''.$attachmentsname.''; + else + $custfldval = ''; + } + $label_fld['options'][] = $custfldval; + } + } + else + { + $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); + if($col_fields[$fieldname] == '' && $attachmentid != '') + { + $attachquery = "select * from vtiger_attachments where attachmentsid=?"; + $col_fields[$fieldname] = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); + } + + //This is added to strip the crmid and _ from the file name and show the original filename + //$org_filename = ltrim($col_fields[$fieldname],$col_fields['record_id'].'_'); + /*Above line is not required as the filename in the database is stored as it is and doesn't have crmid attached to it. + This was the cause for the issue reported in ticket #4645 */ + $org_filename = $col_fields[$fieldname]; + // For Backward Compatibility version < 5.0.4 + $filename_pos = strpos($org_filename, $col_fields['record_id'].'_'); + if ($filename_pos === 0) { + $start_idx = $filename_pos+strlen($col_fields['record_id'].'_'); + $org_filename = substr($org_filename, $start_idx); + } + if($org_filename != '') { + if($col_fields['filelocationtype'] == 'E' ){ + if($col_fields['filestatus'] == 1 ){//&& strlen($col_fields['filename']) > 7 ){ + $custfldval = ''.$col_fields[$fieldname].''; + } + else{ + $custfldval = $col_fields[$fieldname]; + } + }elseif($col_fields['filelocationtype'] == 'I') { + if($col_fields['filestatus'] == 1){ + $custfldval = ''.$col_fields[$fieldname].''; + } + else{ + $custfldval = $col_fields[$fieldname]; + } + } else + $custfldval = ''; + } + $label_fld[] =$custfldval; + } + } + elseif($uitype==28){ + $label_fld[] =getTranslatedString($fieldlabel, $module); + $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); + if($col_fields[$fieldname] == '' && $attachmentid != '') + { + $attachquery = "select * from vtiger_attachments where attachmentsid=?"; + $col_fields[$fieldname] = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); + } + $org_filename = $col_fields[$fieldname]; + // For Backward Compatibility version < 5.0.4 + $filename_pos = strpos($org_filename, $col_fields['record_id'].'_'); + if ($filename_pos === 0) { + $start_idx = $filename_pos+strlen($col_fields['record_id'].'_'); + $org_filename = substr($org_filename, $start_idx); + } + if($org_filename != '') { + if($col_fields['filelocationtype'] == 'E' ){ + if($col_fields['filestatus'] == 1 ){//&& strlen($col_fields['filename']) > 7 ){ + $custfldval = ''.$col_fields[$fieldname].''; + } + else{ + $custfldval = $col_fields[$fieldname]; + } + }elseif($col_fields['filelocationtype'] == 'I') { + if($col_fields['filestatus'] == 1){ + $custfldval = ''.$col_fields[$fieldname].''; + } + else{ + $custfldval = $col_fields[$fieldname]; + } + } else + $custfldval = ''; + } + $label_fld[] =$custfldval; + } + elseif($uitype == 69) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + if($tabid==14) + { + $images=array(); + $query = 'select productname, vtiger_attachments.path, vtiger_attachments.attachmentsid, vtiger_attachments.name,vtiger_crmentity.setype from vtiger_products left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_products.productid inner join vtiger_attachments on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid where vtiger_crmentity.setype="Products Image" and productid=?'; + $result_image = $adb->pquery($query, array($col_fields['record_id'])); + for($image_iter=0;$image_iter < $adb->num_rows($result_image);$image_iter++) + { + $image_id_array[] = $adb->query_result($result_image,$image_iter,'attachmentsid'); + + //decode_html - added to handle UTF-8 characters in file names + //urlencode - added to handle special characters like #, %, etc., + $image_array[] = urlencode(decode_html($adb->query_result($result_image,$image_iter,'name'))); + $image_orgname_array[] = decode_html($adb->query_result($result_image,$image_iter,'name')); + + $imagepath_array[] = $adb->query_result($result_image,$image_iter,'path'); + } + if(count($image_array)>1) + { + if(count($image_array) < 4) + $sides=count($image_array)*2; + else + $sides=8; + + $image_lists = ''; + $label_fld[] =$image_lists; + }elseif(count($image_array)==1) + { + list($pro_image_width, $pro_image_height) = getimagesize($imagepath_array[0].$image_id_array[0]."_".$image_orgname_array[0]); + if($pro_image_width > 450 || $pro_image_height > 300) + $label_fld[] =''; + else + $label_fld[] =''; + }else + { + $label_fld[] =''; + } + + } + if($tabid==4) + { + //$imgpath = getModuleFileStoragePath('Contacts').$col_fields[$fieldname]; + $sql = "select vtiger_attachments.*,vtiger_crmentity.setype from vtiger_attachments inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid where vtiger_crmentity.setype='Contacts Image' and vtiger_seattachmentsrel.crmid=?"; + $image_res = $adb->pquery($sql, array($col_fields['record_id'])); + $image_id = $adb->query_result($image_res,0,'attachmentsid'); + $image_path = $adb->query_result($image_res,0,'path'); + + + //decode_html - added to handle UTF-8 characters in file names + //urlencode - added to handle special characters like #, %, etc., + $image_name = urlencode(decode_html($adb->query_result($image_res,0,'name'))); + + $imgpath = $image_path.$image_id."_".$image_name; + if($image_name != '') + $label_fld[] =''.$mod_strings['Contact Image'].''; + else + $label_fld[] = ''; + } + + } + elseif($uitype == 62) + { + $value = $col_fields[$fieldname]; + if($value != '') + { + $parent_module = getSalesEntityType($value); + if($parent_module == "Leads") + { + $label_fld[] =$app_strings['LBL_LEAD_NAME']; + $lead_name = getLeadName($value); + + $label_fld[] =''.$lead_name.''; + } + elseif($parent_module == "Accounts") + { + $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $account_name = $adb->query_result($result,0,"accountname"); + + $label_fld[] =''.$account_name.''; + } + elseif($parent_module == "Potentials") + { + $label_fld[] =$app_strings['LBL_POTENTIAL_NAME']; + $sql = "select * from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($value)); + $potentialname = $adb->query_result($result,0,"potentialname"); + + $label_fld[] =''.$potentialname.''; + } + elseif($parent_module == "Products") + { + $label_fld[] =$app_strings['LBL_PRODUCT_NAME']; + $sql = "select * from vtiger_products where productid=?"; + $result = $adb->pquery($sql, array($value)); + $productname= $adb->query_result($result,0,"productname"); + + $label_fld[] =''.$productname.''; + } + elseif($parent_module == "PurchaseOrder") + { + $label_fld[] =$app_strings['LBL_PORDER_NAME']; + $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($sql, array($value)); + $pordername= $adb->query_result($result,0,"subject"); + + $label_fld[] = ''.$pordername.''; + } + elseif($parent_module == "SalesOrder") + { + $label_fld[] = $app_strings['LBL_SORDER_NAME']; + $sql = "select * from vtiger_salesorder where salesorderid=?"; + $result = $adb->pquery($sql, array($value)); + $sordername= $adb->query_result($result,0,"subject"); + + $label_fld[] = ''.$sordername.''; + } + elseif($parent_module == "Invoice") + { + $label_fld[] = $app_strings['LBL_INVOICE_NAME']; + $sql = "select * from vtiger_invoice where invoiceid=?"; + $result = $adb->pquery($sql, array($value)); + $invoicename= $adb->query_result($result,0,"subject"); + + $label_fld[] =''.$invoicename.''; + } + elseif($parent_module == "Quotes") + { + $label_fld[] = $app_strings['LBL_QUOTES_NAME']; + $sql = "select * from vtiger_quotes where quoteid=?"; + $result = $adb->pquery($sql, array($value)); + $quotename= $adb->query_result($result,0,"subject"); + + $label_fld[] =''.$quotename.''; + } + elseif($parent_module == "HelpDesk") + { + $label_fld[] = $app_strings['LBL_HELPDESK_NAME']; + $sql = "select * from vtiger_troubletickets where ticketid=?"; + $result = $adb->pquery($sql, array($value)); + $title= $adb->query_result($result,0,"title"); + $label_fld[] =''.$title.''; + } + } + else + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $value; + } + + + } + elseif($uitype == 105)//Added for user image + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + //$imgpath = getModuleFileStoragePath('Contacts').$col_fields[$fieldname]; + $sql = "select vtiger_attachments.* from vtiger_attachments left join vtiger_salesmanattachmentsrel on vtiger_salesmanattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid where vtiger_salesmanattachmentsrel.smid=?"; + $image_res = $adb->pquery($sql, array($col_fields['record_id'])); + $image_id = $adb->query_result($image_res,0,'attachmentsid'); + $image_path = $adb->query_result($image_res,0,'path'); + $image_name = $adb->query_result($image_res,0,'name'); + $imgpath = $image_path.$image_id."_".$image_name; + if($image_name != '') { + //Added the following check for the image to retain its in original size. + list($pro_image_width, $pro_image_height) = getimagesize(decode_html($imgpath)); + $label_fld[] =''.$col_fields['user_name'].''; + } else + $label_fld[] = ''; + } + elseif($uitype == 66) + { + $value = $col_fields[$fieldname]; + if($value != '') + { + $parent_module = getSalesEntityType($value); + if($parent_module == "Leads") + { + $label_fld[] =$app_strings['LBL_LEAD_NAME']; + $lead_name = getLeadName($value); + $label_fld[] = ''.$lead_name.''; + } + elseif($parent_module == "Accounts") + { + $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $account_name = $adb->query_result($result,0,"accountname"); + + $label_fld[] = ''.$account_name.''; + } + elseif($parent_module == "Potentials") + { + $label_fld[] =$app_strings['LBL_POTENTIAL_NAME']; + $sql = "select * from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($value)); + $potentialname = $adb->query_result($result,0,"potentialname"); + + $label_fld[] = ''.$potentialname.''; + } + elseif($parent_module == "Quotes") + { + $label_fld[] =$app_strings['LBL_QUOTE_NAME']; + $sql = "select * from vtiger_quotes where quoteid=?"; + $result = $adb->pquery($sql, array($value)); + $quotename = $adb->query_result($result,0,"subject"); + + $label_fld[] = ''.$quotename.''; + } + elseif($parent_module == "PurchaseOrder") + { + $label_fld[] = $app_strings['LBL_PORDER_NAME']; + $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($sql, array($value)); + $pordername = $adb->query_result($result,0,"subject"); + + $label_fld[] = ''.$pordername.''; + } + elseif($parent_module == "SalesOrder") + { + $label_fld[] = $app_strings['LBL_SORDER_NAME']; + $sql = "select * from vtiger_salesorder where salesorderid=?"; + $result = $adb->pquery($sql, array($value)); + $sordername = $adb->query_result($result,0,"subject"); + + $label_fld[] = ''.$sordername.''; + } + elseif($parent_module == "Invoice") + { + $label_fld[] = $app_strings['LBL_INVOICE_NAME']; + $sql = "select * from vtiger_invoice where invoiceid=?"; + $result = $adb->pquery($sql, array($value)); + $invoicename = $adb->query_result($result,0,"subject"); + + $label_fld[] = ''.$invoicename.''; + } + elseif($parent_module == "Campaigns") + { + $label_fld[] = $app_strings['LBL_CAMPAIGN_NAME']; + $sql = "select * from vtiger_campaign where campaignid=?"; + $result = $adb->pquery($sql, array($value)); + $campaignname = $adb->query_result($result,0,"campaignname"); + $label_fld[] = ''.$campaignname.''; + } + elseif($parent_module == "HelpDesk") + { + $label_fld[] = $app_strings['LBL_HELPDESK_NAME']; + $sql = "select * from vtiger_troubletickets where ticketid=?"; + $result = $adb->pquery($sql, array($value)); + $tickettitle = $adb->query_result($result,0,"title"); + if(strlen($tickettitle) > 25) + { + $tickettitle = substr($tickettitle,0,25).'...'; + } + $label_fld[] = ''.$tickettitle.''; + } + + } + else + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $value; + } + } + elseif($uitype == 67) + { + $value = $col_fields[$fieldname]; + if($value != '') + { + $parent_module = getSalesEntityType($value); + if($parent_module == "Leads") + { + $label_fld[] = $app_strings['LBL_LEAD_NAME']; + $lead_name = getLeadName($value); + $label_fld[] = ''.$lead_name.''; + } + elseif($parent_module == "Contacts") + { + $label_fld[] = $app_strings['LBL_CONTACT_NAME']; + $contact_name = getContactName($value); + $label_fld[] = ''.$contact_name.''; + } + } + else + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $value; + + } + } + //added by raju/rdhital for better emails + elseif($uitype == 357) + { + $value = $col_fields[$fieldname]; + if($value != '') + { + $parent_name=''; + $parent_id=''; + $myemailid= $_REQUEST['record']; + $mysql = "select crmid from vtiger_seactivityrel where activityid=?"; + $myresult = $adb->pquery($mysql, array($myemailid)); + $mycount=$adb->num_rows($myresult); + if ($mycount>1){ + $label_fld[] = $app_strings['LBL_RELATED_TO']; + $label_fld[] =$app_strings['LBL_MULTIPLE']; + } + else + { + $parent_module = getSalesEntityType($value); + if($parent_module == "Leads") + { + $label_fld[] = $app_strings['LBL_LEAD_NAME']; + $lead_name = getLeadName($value); + $label_fld[] = ''.$lead_name.''; + } + elseif($parent_module == "Contacts") + { + $label_fld[] = $app_strings['LBL_CONTACT_NAME']; + $contact_name = getContactName($value); + $label_fld[] = ''.$contact_name.''; + } + elseif($parent_module == "Accounts") + { + $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $accountname = $adb->query_result($result,0,"accountname"); + $label_fld[] = ''.$accountname.''; + } + + } + } + else + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $value; + } + }//Code added by raju for better email ends + + elseif($uitype == 68) + { + $value = $col_fields[$fieldname]; + if($value != '') + { + $parent_module = getSalesEntityType($value); + if($parent_module == "Contacts") + { + $label_fld[] = $app_strings['LBL_CONTACT_NAME']; + $contact_name = getContactName($value); + $label_fld[] =''.$contact_name.''; + } + elseif($parent_module == "Accounts") + { + $label_fld[] = $app_strings['LBL_ACCOUNT_NAME']; + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $account_name = $adb->query_result($result,0,"accountname"); + + $label_fld[] = ''.$account_name.''; + } + else + { + $value =''; + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $value; + } + + + } + else + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + $label_fld[] = $value; + } + } + + elseif($uitype==63) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $label_fld[] = $col_fields[$fieldname].'h  '.$col_fields['duration_minutes'].'m'; + } + elseif($uitype == 6) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + if($col_fields[$fieldname]=='0') + $col_fields[$fieldname]=''; + if($col_fields['time_start']!='') + { + $start_time = $col_fields['time_start']; + } + if($col_fields[$fieldname] == '0000-00-00') + { + $displ_date = ''; + } + else + { + $displ_date = getDisplayDate($col_fields[$fieldname]); + } + if(empty($start_time)) $label_fld[] = $displ_date; + else $label_fld[] = $displ_date.' '.$start_time; + + } + elseif($uitype == 5 || $uitype == 23 || $uitype == 70) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $cur_date_val = $col_fields[$fieldname]; + if($col_fields['time_end']!='' && ($tabid == 9 || $tabid == 16) && $uitype == 23) + { + $end_time = $col_fields['time_end']; + } + if($cur_date_val == '0000-00-00') + { + $display_val = ''; + } + else + { + $display_val = getDisplayDate($cur_date_val); + } + if(empty($end_time)) $label_fld[] = $display_val; + else $label_fld[] = $display_val . ' ' . $end_time; + } + elseif($uitype == 71 || $uitype == 72) + { + $label_fld[] = getTranslatedString($fieldlabel, $module); + if($fieldname == 'unit_price') { + $rate_symbol=getCurrencySymbolandCRate(getProductBaseCurrency($col_fields['record_id'], $module)); + $label_fld[] = $col_fields[$fieldname]; + } else { + $rate_symbol=getCurrencySymbolandCRate($user_info['currency_id']); + $rate = $rate_symbol['rate']; + $label_fld[] = convertFromDollar($col_fields[$fieldname],$rate); + } + $currency = $rate_symbol['symbol']; + $label_fld["cursymb"] = $currency; + } + elseif($uitype == 75 || $uitype == 81) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $vendor_id = $col_fields[$fieldname]; + if($vendor_id != '') + { + $vendor_name = getVendorName($vendor_id); + } + $label_fld[] = $vendor_name; + $label_fld["secid"] = $vendor_id; + $label_fld["link"] = "index.php?module=Vendors&action=DetailView&record=".$vendor_id; + } + elseif($uitype == 76) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $potential_id = $col_fields[$fieldname]; + if($potential_id != '') + { + $potential_name = getPotentialName($potential_id); + } + $label_fld[] = $potential_name; + $label_fld["secid"] = $potential_id; + $label_fld["link"] = "index.php?module=Potentials&action=DetailView&record=".$potential_id; + } + elseif($uitype == 78) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $quote_id = $col_fields[$fieldname]; + if($quote_id != '') + { + $quote_name = getQuoteName($quote_id); + } + $label_fld[] = $quote_name; + $label_fld["secid"] = $quote_id; + $label_fld["link"] = "index.php?module=Quotes&action=DetailView&record=".$quote_id; + } + elseif($uitype == 79) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $purchaseorder_id = $col_fields[$fieldname]; + if($purchaseorder_id != '') + { + $purchaseorder_name = getPoName($purchaseorder_id); + } + $label_fld[] = $purchaseorder_name; + $label_fld["secid"] = $purchaseorder_id; + $label_fld["link"] = "index.php?module=PurchaseOrder&action=DetailView&record=".$purchaseorder_id; + } + elseif($uitype == 80) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $salesorder_id = $col_fields[$fieldname]; + if($salesorder_id != '') + { + $salesorder_name = getSoName($salesorder_id); + } + $label_fld[] = $salesorder_name; + $label_fld["secid"] = $salesorder_id; + $label_fld["link"] = "index.php?module=SalesOrder&action=DetailView&record=".$salesorder_id; + } + elseif($uitype == 30) + { + $rem_days = 0; + $rem_hrs = 0; + $rem_min = 0; + $reminder_str =""; + $rem_days = floor($col_fields[$fieldname]/(24*60)); + $rem_hrs = floor(($col_fields[$fieldname]-$rem_days*24*60)/60); + $rem_min = ($col_fields[$fieldname]-$rem_days*24*60)%60; + + $label_fld[] =getTranslatedString($fieldlabel, $module); + if($col_fields[$fieldname]) + { + $reminder_str= $rem_days.' '.$mod_strings['LBL_DAYS'].' '.$rem_hrs.' '.$mod_strings['LBL_HOURS'].' '.$rem_min.' '.$mod_strings['LBL_MINUTES'].'  '.$mod_strings['LBL_BEFORE_EVENT']; + } + $label_fld[] = ' '.$reminder_str; + }elseif($uitype == 98) + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + if(is_admin($current_user)) + $label_fld[] = ''.getRoleName($col_fields[$fieldname]).''; + else + $label_fld[] = getRoleName($col_fields[$fieldname]); + }elseif($uitype == 85) //Added for Skype by Minnie + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + $label_fld[]= $col_fields[$fieldname]; + } + elseif($uitype == 26){ + $label_fld[] =getTranslatedString($fieldlabel, $module); + $query = "select foldername from vtiger_attachmentsfolder where folderid = ?"; + $result = $adb->pquery($query, array($col_fields[$fieldname])); + $folder_name = $adb->query_result($result,0,"foldername"); + $label_fld[] = $folder_name; + } + elseif($uitype == 27){ + if($col_fields[$fieldname] == 'I'){ + $label_fld[]=getTranslatedString($fieldlabel, $module); + $label_fld[]= $mod_strings['LBL_INTERNAL']; + } + else{ + $label_fld[]=getTranslatedString($fieldlabel, $module); + $label_fld[]= $mod_strings['LBL_EXTERNAL']; + } + } + else + { + $label_fld[] =getTranslatedString($fieldlabel, $module); + if($col_fields[$fieldname]=='0' && $fieldname != 'filedownloadcount' && $fieldname != 'filestatus' && $fieldname != 'filesize') + $col_fields[$fieldname]=''; + if($uitype == 1 && ($fieldname=='expectedrevenue' || $fieldname=='budgetcost' || $fieldname=='actualcost' || $fieldname=='expectedroi' || $fieldname=='actualroi' )) + { + $rate_symbol=getCurrencySymbolandCRate($user_info['currency_id']); + $label_fld[] = convertFromDollar($col_fields[$fieldname],$rate_symbol['rate']); + } + else + { + //code for Documents module :start + if($tabid == 8) + { + $downloadtype = $col_fields['filelocationtype']; + if($fieldname == 'filename') + { + if($downloadtype == 'I') + { + //$file_value = $mod_strings['LBL_INTERNAL']; + $fld_value = $col_fields['filename']; + $ext_pos = strrpos($fld_value, "."); + $ext =substr($fld_value, $ext_pos + 1); + $ext = strtolower($ext); + if($ext == 'bin' || $ext == 'exe' || $ext == 'rpm') + $fileicon=""; + elseif($ext == 'jpg' || $ext == 'gif' || $ext == 'bmp') + $fileicon=""; + elseif($ext == 'txt' || $ext == 'doc' || $ext == 'xls') + $fileicon=""; + elseif($ext == 'zip' || $ext == 'gz' || $ext == 'rar') + $fileicon=""; + else + $fileicon=""; + } + else + { + $fld_value = $col_fields['filename']; + $fileicon = "".$mod_strings["; + } + $label_fld[] = $fileicon.$fld_value; + } + if($fieldname == 'filesize') + { + if($col_fields['filelocationtype'] == 'I') + { + $filesize = $col_fields[$fieldname]; + if($filesize < 1024) + $label_fld[]=$filesize.' B'; + elseif($filesize > 1024 && $filesize < 1048576) + $label_fld[]=round($filesize/1024,2).' KB'; + else if($filesize > 1048576) + $label_fld[]=round($filesize/(1024*1024),2).' MB'; + } + else + { + $label_fld[]=' --'; + } + } + if($fieldname == 'filetype' && $col_fields['filelocationtype'] == 'E') + { + $label_fld[]=' --'; + } + /*if($fieldname == 'filestatus') + { + $filestatus = $col_fields[$fieldname]; + if($filestatus == 0) + $label_fld[]=$mod_strings['LBL_ACTIVE']; + else + $label_fld[]=$mod_strings['LBL_INACTIVE']; + }*/ + } + //code for Documents module :end + $label_fld[] = $col_fields[$fieldname]; + } + } + $label_fld[]=$uitype; + + //sets whether the currenct user is admin or not + if(is_admin($current_user)) + { + $label_fld["isadmin"] = 1; + }else + { + $label_fld["isadmin"] = 0; + } + + $log->debug("Exiting getDetailViewOutputHtml method ..."); + return $label_fld; +} + +/** This function returns a HTML output of associated vtiger_products for a given entity (Quotes,Invoice,Sales order or Purchase order) + * Param $module - module name + * Param $focus - module object + * Return type string + */ + +function getDetailAssociatedProducts($module,$focus) +{ + global $log; + $log->debug("Entering getDetailAssociatedProducts(".$module.",".get_class($focus).") method ..."); + global $adb; + global $mod_strings; + global $theme; + global $log; + global $app_strings,$current_user; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + if($module != 'PurchaseOrder') + { + $colspan = '2'; + } + else + { + $colspan = '1'; + } + + //Get the taxtype of this entity + $taxtype = getInventoryTaxType($module,$focus->id); + $currencytype = getInventoryCurrencyInfo($module, $focus->id); + + $output = ''; + //Header Rows + $output .= ' + + + + + + + + + '; + + //Add Quantity in Stock column for SO, Quotes and Invoice + if($module == 'Quotes' || $module == 'SalesOrder' || $module == 'Invoice') + $output .= ''; + + $output .= ' + + + + + + + '; + + + // DG 15 Aug 2006 + // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items + + if($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') + { + $query="select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . + " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . + " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . + " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, vtiger_inventoryproductrel.* " . + " from vtiger_inventoryproductrel" . + " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . + " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . + " where id=? ORDER BY sequence_no"; + } + + $result = $adb->pquery($query, array($focus->id)); + $num_rows=$adb->num_rows($result); + $netTotal = '0.00'; + for($i=1;$i<=$num_rows;$i++) + { + $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($focus->id,$i)); + $subprodname_str=''; + if($adb->num_rows($sub_prod_query)>0){ + for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ + $sprod_id = $adb->query_result($sub_prod_query,$j,'productid'); + $sprod_name = getProductName($sprod_id); + $str_sep = ""; + if($j>0) $str_sep = ":"; + $subprodname_str .= $str_sep." - ".$sprod_name; + } + } + $subprodname_str = str_replace(":","
",$subprodname_str); + + $productid=$adb->query_result($result,$i-1,'productid'); + $entitytype=$adb->query_result($result,$i-1,'entitytype'); + $productname=$adb->query_result($result,$i-1,'productname'); + if($subprodname_str!='') $productname .= "
".$subprodname_str.""; + $comment=$adb->query_result($result,$i-1,'comment'); + $qtyinstock=$adb->query_result($result,$i-1,'qtyinstock'); + $qty=$adb->query_result($result,$i-1,'quantity'); + $unitprice=$adb->query_result($result,$i-1,'unit_price'); + $listprice=$adb->query_result($result,$i-1,'listprice'); + $total = $qty*$listprice; + + //Product wise Discount calculation - starts + $discount_percent=$adb->query_result($result,$i-1,'discount_percent'); + $discount_amount=$adb->query_result($result,$i-1,'discount_amount'); + $totalAfterDiscount = $total; + + $productDiscount = '0.00'; + if($discount_percent != 'NULL' && $discount_percent != '') + { + $productDiscount = $total*$discount_percent/100; + $totalAfterDiscount = $total-$productDiscount; + //if discount is percent then show the percentage + $discount_info_message = "$discount_percent % of $total = $productDiscount"; + } + elseif($discount_amount != 'NULL' && $discount_amount != '') + { + $productDiscount = $discount_amount; + $totalAfterDiscount = $total-$productDiscount; + $discount_info_message = $app_strings['LBL_DIRECT_AMOUNT_DISCOUNT']." = $productDiscount"; + } + else + { + $discount_info_message = $app_strings['LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM']; + } + //Product wise Discount calculation - ends + + $netprice = $totalAfterDiscount; + //Calculate the individual tax if taxtype is individual + if($taxtype == 'individual') + { + $taxtotal = '0.00'; + $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT']." = $totalAfterDiscount \\n"; + $tax_details = getTaxDetailsForProduct($productid,'all'); + for($tax_count=0;$tax_countid, $productid, $tax_name); + + $individual_taxamount = $totalAfterDiscount*$tax_value/100; + $taxtotal = $taxtotal + $individual_taxamount; + $tax_info_message .= "$tax_label : $tax_value % = $individual_taxamount \\n"; + } + $tax_info_message .= "\\n ".$app_strings['LBL_TOTAL_TAX_AMOUNT']." = $taxtotal"; + $netprice = $netprice + $taxtotal; + } + + $sc_image_tag = ''; + if ($entitytype == 'Services') { + $sc_image_tag = '' . + '' . + ''; + } + + //For Product Name + $output .= ' + + '; + //Upto this added to display the Product name and comment + + + if($module != 'PurchaseOrder') + { + $output .= ''; + } + $output .= ''; + $output .= ' + '; + + $output .= ' + '; + $output .= ''; + $output .= ''; + + $netTotal = $netTotal + $netprice; + } + + $output .= '
'.$app_strings['LBL_ITEM_DETAILS'].''. + $app_strings['LBL_CURRENCY'].' : '. getTranslatedCurrencyString($currencytype['currency_name']). ' ('. $currencytype['currency_symbol'] .') + '. + $app_strings['LBL_TAX_MODE'].' : '.$app_strings[$taxtype].' +
* + '.$app_strings['LBL_ITEM_NAME'].' + '.$app_strings['LBL_QTY_IN_STOCK'].''.$app_strings['LBL_QTY'].''.$app_strings['LBL_LIST_PRICE'].''.$app_strings['LBL_TOTAL'].''.$app_strings['LBL_NET_PRICE'].'
+ '.$productname.' '.$sc_image_tag.' +
'.$comment.' +
'.$qtyinstock.''.$qty.' + + + + + + + + + + '; + if($taxtype == 'individual') + { + $output .= ' + + + '; + } + $output .= ' +
'.$listprice.'
(-) '.$app_strings['LBL_DISCOUNT'].' :
'.$app_strings['LBL_TOTAL_AFTER_DISCOUNT'].' :
(+) '.$app_strings['LBL_TAX'].' :
+
+ + + + '; + + if($taxtype == 'individual') + { + $output .= ''; + } + + $output .= ' +
'.$total.'
'.$productDiscount.'
'.$totalAfterDiscount.'
'.$taxtotal.'
+
'.$netprice.'
'; + + //$netTotal should be equal to $focus->column_fields['hdnSubTotal'] + $netTotal = $focus->column_fields['hdnSubTotal']; + + //Display the total, adjustment, S&H details + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + + //Decide discount + $finalDiscount = '0.00'; + $final_discount_info = '0'; + //if($focus->column_fields['hdnDiscountPercent'] != '') - previously (before changing to prepared statement) the selected option (either percent or amount) will have value and the other remains empty. So we can find the non selected item by empty check. But now with prepared statement, the non selected option stored as 0 + if($focus->column_fields['hdnDiscountPercent'] != '0') + { + $finalDiscount = ($netTotal*$focus->column_fields['hdnDiscountPercent']/100); + $final_discount_info = $focus->column_fields['hdnDiscountPercent']." % of $netTotal = $finalDiscount"; + } + elseif($focus->column_fields['hdnDiscountAmount'] != '0') + { + $finalDiscount = $focus->column_fields['hdnDiscountAmount']; + $final_discount_info = $finalDiscount; + } + + //Alert the Final Discount amount even it is zero + $final_discount_info = $app_strings['LBL_FINAL_DISCOUNT_AMOUNT']." = $final_discount_info"; + $final_discount_info = 'onclick="alert(\''.$final_discount_info.'\');"'; + + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + + if($taxtype == 'group') + { + $taxtotal = '0.00'; + $final_totalAfterDiscount = $netTotal - $finalDiscount; + $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT']." = $final_totalAfterDiscount \\n"; + //First we should get all available taxes and then retrieve the corresponding tax values + $tax_details = getAllTaxes('available','','edit',$focus->id); + //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table + for($tax_count=0;$tax_countquery_result($result,0,$tax_name); + if($tax_value == '' || $tax_value == 'NULL') + $tax_value = '0.00'; + + $taxamount = ($netTotal-$finalDiscount)*$tax_value/100; + $taxtotal = $taxtotal + $taxamount; + $tax_info_message .= "$tax_label : $tax_value % = $taxamount \\n"; + } + $tax_info_message .= "\\n ".$app_strings['LBL_TOTAL_TAX_AMOUNT']." = $taxtotal"; + + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + } + + $shAmount = ($focus->column_fields['hdnS_H_Amount'] != '')?$focus->column_fields['hdnS_H_Amount']:'0.00'; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + + //calculate S&H tax + $shtaxtotal = '0.00'; + //First we should get all available taxes and then retrieve the corresponding tax values + $shtax_details = getAllTaxes('available','sh','edit',$focus->id); + //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table + $shtax_info_message = $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGE']." = $shAmount \\n"; + for($shtax_count=0;$shtax_countid,$shtax_name); + $shtaxamount = $shAmount*$shtax_percent/100; + $shtaxtotal = $shtaxtotal + $shtaxamount; + $shtax_info_message .= "$shtax_label : $shtax_percent % = $shtaxamount \\n"; + } + $shtax_info_message .= "\\n ".$app_strings['LBL_TOTAL_TAX_AMOUNT']." = $shtaxtotal"; + + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + + $adjustment = ($focus->column_fields['txtAdjustment'] != '')?$focus->column_fields['txtAdjustment']:'0.00'; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + + $grandTotal = ($focus->column_fields['hdnGrandTotal'] != '')?$focus->column_fields['hdnGrandTotal']:'0.00'; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= ''; + $output .= '
'.$app_strings['LBL_NET_TOTAL'].''.$netTotal.'
(-) '.$app_strings['LBL_DISCOUNT'].''.$finalDiscount.'
(+) '.$app_strings['LBL_TAX'].''.$taxtotal.'
(+) '.$app_strings['LBL_SHIPPING_AND_HANDLING_CHARGES'].''.$shAmount.'
(+) '.$app_strings['LBL_TAX_FOR_SHIPPING_AND_HANDLING'].''.$shtaxtotal.'
 '.$app_strings['LBL_ADJUSTMENT'].''.$adjustment.'
'.$app_strings['LBL_GRAND_TOTAL'].''.$grandTotal.'
'; + + $log->debug("Exiting getDetailAssociatedProducts method ..."); + return $output; + +} + +/** This function returns the related vtiger_tab details for a given entity or a module. +* Param $module - module name +* Param $focus - module object +* Return type is an array +*/ + +function getRelatedListsInformation($module,$focus) +{ + global $log; + $log->debug("Entering getRelatedLists(".$module.",".get_class($focus).") method ..."); + global $adb; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $cur_tab_id = getTabid($module); + + //$sql1 = "select * from vtiger_relatedlists where tabid=? order by sequence"; + // vtlib customization: Do not picklist module which are set as in-active + $sql1 = "select * from vtiger_relatedlists where tabid=? and related_tabid not in (SELECT tabid FROM vtiger_tab WHERE presence = 1) order by sequence"; + // END + $result = $adb->pquery($sql1, array($cur_tab_id)); + $num_row = $adb->num_rows($result); + for($i=0; $i<$num_row; $i++) { + $rel_tab_id = $adb->query_result($result,$i,"related_tabid"); + $function_name = $adb->query_result($result,$i,"name"); + $label = $adb->query_result($result,$i,"label"); + $actions = $adb->query_result($result,$i,"actions"); + $relationId = $adb->query_result($result,$i,"relation_id"); + if($rel_tab_id != 0) { + if($profileTabsPermission[$rel_tab_id] == 0) { + if($profileActionPermission[$rel_tab_id][3] == 0) { + // vtlib customization: Send more information (from module, related module) + // to the callee + $focus_list[$label] = $focus->$function_name($focus->id, $cur_tab_id, + $rel_tab_id, $actions); + // END + } + } + } else { + // vtlib customization: Send more information (from module, related module) + // to the callee + $focus_list[$label] = $focus->$function_name($focus->id, $cur_tab_id, $rel_tab_id, + $actions); + // END + } + } + $log->debug("Exiting getRelatedLists method ..."); + return $focus_list; +} + +/** This function returns the related vtiger_tab details for a given entity or a module. +* Param $module - module name +* Param $focus - module object +* Return type is an array +*/ + +function getRelatedLists($module,$focus) +{ + global $log; + $log->debug("Entering getRelatedLists(".$module.",".get_class($focus).") method ..."); + global $adb; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $cur_tab_id = getTabid($module); + + //$sql1 = "select * from vtiger_relatedlists where tabid=? order by sequence"; + // vtlib customization: Do not picklist module which are set as in-active + $sql1 = "select * from vtiger_relatedlists where tabid=? and related_tabid not in (SELECT tabid FROM vtiger_tab WHERE presence = 1) order by sequence"; + // END + $result = $adb->pquery($sql1, array($cur_tab_id)); + $num_row = $adb->num_rows($result); + for($i=0; $i<$num_row; $i++) { + $rel_tab_id = $adb->query_result($result,$i,"related_tabid"); + $function_name = $adb->query_result($result,$i,"name"); + $label = $adb->query_result($result,$i,"label"); + $actions = $adb->query_result($result,$i,"actions"); + $relationId = $adb->query_result($result,$i,"relation_id"); + if($rel_tab_id != 0) { + if($profileTabsPermission[$rel_tab_id] == 0) { + if($profileActionPermission[$rel_tab_id][3] == 0) { + // vtlib customization: Send more information (from module, related module) + // to the callee + $focus_list[$label] = array('related_tabid' => $rel_tab_id,'relationId' => + $relationId, 'actions' => $actions); + // END + } + } + } else { + // vtlib customization: Send more information (from module, related module) + // to the callee + $focus_list[$label] = array('related_tabid' => $rel_tab_id, 'relationId' => + $relationId, 'actions' => $actions); + // END + } + } + $log->debug("Exiting getRelatedLists method ..."); + return $focus_list; +} + +/** This function returns whether related lists is present for this particular module or not +* Param $module - module name +* Param $activity_mode - mode of activity +* Return type true or false +*/ + + +function isPresentRelatedLists($module,$activity_mode='') { + static $moduleRelatedListCache = array(); + + global $adb,$current_user; + $retval=array(); + if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { + include('tabdata.php'); + } + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $tab_id=getTabid($module); + // We need to check if there is atleast 1 relation, no need to use count(*) + $query= "select relation_id,related_tabid, label from vtiger_relatedlists where tabid=? ". + "order by sequence"; + $result=$adb->pquery($query, array($tab_id)); + $count=$adb->num_rows($result); + if($count < 1 || ($module =='Calendar' && $activity_mode=='task')) { + $retval='false'; + }else if(empty($moduleRelatedListCache[$module])){ + for($i=0; $i<$count; ++$i) { + $relatedId = $adb->query_result($result, $i, 'relation_id'); + $relationLabel = $adb->query_result($result, $i, 'label'); + $relatedTabId = $adb->query_result($result, $i, 'related_tabid'); + //check for module disable. + $permitted = $tab_seq_array[$relatedTabId]; + if($permitted === 0 || empty($relatedTabId)){ + if($is_admin || $profileTabsPermission[$relatedTabId] === 0 || empty($relatedTabId)){ + $retval[$relatedId] = $relationLabel; + } + } + } + $moduleRelatedListCache[$module] = $retval; + } + return $moduleRelatedListCache[$module]; +} + +/** This function returns the detailed block information of a record in a module. +* Param $module - module name +* Param $block - block id +* Param $col_fields - column vtiger_fields array for the module +* Param $tabid - vtiger_tab id +* Return type is an array +*/ + +function getDetailBlockInformation($module, $result,$col_fields,$tabid,$block_label) +{ + global $log; + $log->debug("Entering getDetailBlockInformation(".$module.",". $result.",".$col_fields.",".$tabid.",".$block_label.") method ..."); + global $adb; + global $current_user; + global $mod_strings; + $label_data = Array(); + + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $uitype = $adb->query_result($result,$i,"uitype"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldid = $adb->query_result($result,$i,"fieldid"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $maxlength = $adb->query_result($result,$i,"maximumlength"); + $block = $adb->query_result($result,$i,"block"); + $generatedtype = $adb->query_result($result,$i,"generatedtype"); + $tabid = $adb->query_result($result,$i,"tabid"); + $displaytype = $adb->query_result($result,$i,'displaytype'); + $custfld = getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields,$generatedtype,$tabid,$module); + if(is_array($custfld)) + { + $label_data[$block][] = array($custfld[0]=>array("value"=>$custfld[1],"ui"=>$custfld[2],"options"=>$custfld["options"],"secid"=>$custfld["secid"],"link"=>$custfld["link"],"cursymb"=>$custfld["cursymb"],"salut"=>$custfld["salut"],"notaccess"=>$custfld["notaccess"],"cntimage"=>$custfld["cntimage"],"isadmin"=>$custfld["isadmin"],"tablename"=>$fieldtablename,"fldname"=>$fieldname,"fldid"=>$fieldid,"displaytype"=>$displaytype)); + } + $i++; + if($i<$noofrows) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $uitype = $adb->query_result($result,$i,"uitype"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldid = $adb->query_result($result,$i,"fieldid"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $maxlength = $adb->query_result($result,$i,"maximumlength"); + $block = $adb->query_result($result,$i,"block"); + $generatedtype = $adb->query_result($result,$i,"generatedtype"); + $tabid = $adb->query_result($result,$i,"tabid"); + $displaytype = $adb->query_result($result,$i,'displaytype'); + $custfld = getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields,$generatedtype,$tabid,$module); + if(is_array($custfld)) + { + $label_data[$block][] = array($custfld[0]=>array("value"=>$custfld[1],"ui"=>$custfld[2],"options"=>$custfld["options"],"secid"=>$custfld["secid"],"link"=>$custfld["link"],"cursymb"=>$custfld["cursymb"],"salut"=>$custfld["salut"],"notaccess"=>$custfld["notaccess"],"cntimage"=>$custfld["cntimage"],"isadmin"=>$custfld["isadmin"],"tablename"=>$fieldtablename,"fldname"=>$fieldname,"fldid"=>$fieldid,"displaytype"=>$displaytype)); + } + } + } + foreach($label_data as $headerid=>$value_array) + { + $detailview_data = Array(); + for ($i=0,$j=0;$i $value_array[$i][$key1],$key2 => $value_array[$i+1][$key2]); + $i+=2; + }else{ + $detailview_data[$j]=array($use_key1 => $value_array[$i][$key1]); + $i++; + } + } + $label_data[$headerid] = $detailview_data; + } + foreach($block_label as $blockid=>$label) + { + if($label == '') + { + $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$label_data[$blockid]); + } + else + { + $curBlock = $label; + if(is_array($label_data[$blockid])) + $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$label_data[$blockid]); + } + } + $log->debug("Exiting getDetailBlockInformation method ..."); + return $returndata; + + +} + +function VT_detailViewNavigation($smarty,$recordNavigationInfo,$currrentRecordId){ + $pageNumber =0; + foreach ($recordNavigationInfo as $start=>$recordIdList){ + $pageNumber++; + foreach ($recordIdList as $index=>$recordId) { + if($recordId === $currrentRecordId){ + if($index ==0 ){ + $smarty->assign('privrecordstart',$start-1); + $smarty->assign('privrecord',$recordNavigationInfo[$start-1][count($recordNavigationInfo[$start-1])-1]); + }else{ + $smarty->assign('privrecordstart',$start); + $smarty->assign('privrecord',$recordIdList[$index-1]); + } + if($index == count($recordIdList)-1){ + $smarty->assign('nextrecordstart',$start+1); + $smarty->assign('nextrecord',$recordNavigationInfo[$start+1][0]); + }else{ + $smarty->assign('nextrecordstart',$start); + $smarty->assign('nextrecord',$recordIdList[$index+1]); + } + } + } + } +} + +function getRelatedListInfoById($relationId){ + static $relatedInfoCache = array(); + if(isset($relatedInfoCache[$relationId])){ + return $relatedInfoCache[$relationId]; + } + $adb = PearDatabase::getInstance(); + $sql1 = "select * from vtiger_relatedlists where relation_id=?"; + $result = $adb->pquery($sql1, array($relationId)); + $rowCount = $adb->num_rows($result); + $relationInfo = array(); + if($rowCount > 0) { + $relationInfo['relatedTabId'] = $adb->query_result($result,0,"related_tabid"); + $relationInfo['functionName'] = $adb->query_result($result,0,"name"); + $relationInfo['label'] = $adb->query_result($result,0,"label"); + $relationInfo['actions'] = $adb->query_result($result,0,"actions"); + $relationInfo['relationId'] = $adb->query_result($result,0,"relation_id"); + } + $relatedInfoCache[$relationId] = $relationInfo; + return $relatedInfoCache[$relationId]; +} + +?> diff --git a/oss/vtiger/trunk/include/utils/EditViewUtils.php b/oss/vtiger/trunk/include/utils/EditViewUtils.php index 48f47c27..ddbe53bf 100644 --- a/oss/vtiger/trunk/include/utils/EditViewUtils.php +++ b/oss/vtiger/trunk/include/utils/EditViewUtils.php @@ -1,2065 +1,2077 @@ -debug("Entering getOutputHtml(".$uitype.",". $fieldname.",". $fieldlabel.",". $maxlength.",". $col_fields.",".$generatedtype.",".$module_name.") method ..."); - global $adb,$log,$default_charset; - global $theme; - global $mod_strings; - global $app_strings; - global $current_user; - - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $fieldlabel = from_html($fieldlabel); - $fieldvalue = Array(); - $final_arr = Array(); - $value = $col_fields[$fieldname]; - $custfld = ''; - $ui_type[]= $uitype; - $editview_fldname[] = $fieldname; - - // vtlib customization: Related type field - if($uitype == '10') { - global $adb; - $fldmod_result = $adb->pquery('SELECT relmodule, status FROM vtiger_fieldmodulerel WHERE fieldid= - (SELECT fieldid FROM vtiger_field, vtiger_tab WHERE vtiger_field.tabid=vtiger_tab.tabid AND fieldname=? AND name=? and vtiger_field.presence in (0,2))', - Array($fieldname, $module_name)); - - $entityTypes = Array(); - $parent_id = $value; - for($index = 0; $index < $adb->num_rows($fldmod_result); ++$index) { - $entityTypes[] = $adb->query_result($fldmod_result, $index, 'relmodule'); - } - - if(!empty($value)) { - $valueType = getSalesEntityType($value); - $displayValueArray = getEntityName($valueType, $value); - if(!empty($displayValueArray)){ - foreach($displayValueArray as $key=>$value){ - $displayValue = $value; - } - } - } else { - $displayValue=''; - $valueType=''; - $value=''; - } - - $editview_label[] = Array('options'=>$entityTypes, 'selected'=>$valueType, 'displaylabel'=>getTranslatedString($fieldlabel, $module_name)); - $fieldvalue[] = Array('displayvalue'=>$displayValue,'entityid'=>$parent_id); - - } // END - else if($uitype == 5 || $uitype == 6 || $uitype ==23) - { - $log->info("uitype is ".$uitype); - if($value=='') - { - //modified to fix the issue in trac(http://vtiger.fosslabs.com/cgi-bin/trac.cgi/ticket/1469) - if($fieldname != 'birthday' && $generatedtype != 2 && getTabid($module_name) !=14)// && $fieldname != 'due_date')//due date is today's date by default - $disp_value=getNewDisplayDate(); - - //Added to display the Contact - Support End Date as one year future instead of today's date -- 30-11-2005 - if($fieldname == 'support_end_date' && $_REQUEST['module'] == 'Contacts') - { - $addyear = strtotime("+1 year"); - global $current_user; - $dat_fmt = (($current_user->date_format == '')?('dd-mm-yyyy'):($current_user->date_format)); - - $disp_value = (($dat_fmt == 'dd-mm-yyyy')?(date('d-m-Y',$addyear)):(($dat_fmt == 'mm-dd-yyyy')?(date('m-d-Y',$addyear)):(($dat_fmt == 'yyyy-mm-dd')?(date('Y-m-d', $addyear)):('')))); - } - - if($fieldname == 'validtill' && $_REQUEST['module'] == 'Quotes') - { - $disp_value = ''; - } - - } - else - { - $disp_value = getDisplayDate($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']); - if($uitype == 6) - { - if($col_fields['time_start']!='') - { - $curr_time = $col_fields['time_start']; - } - else - { - $curr_time = date('H:i',(time() + (5 * 60))); - } - } - if($module_name == 'Events' && $uitype == 23) - { - if($col_fields['time_end']!='') - { - $curr_time = $col_fields['time_end']; - } - else - { - $endtime = time() + (10 * 60); - $curr_time = date('H:i',$endtime); - } - } - $fieldvalue[] = array($disp_value => $curr_time) ; - if($uitype == 5 || $uitype == 23) - { - if($module_name == 'Events' && $uitype == 23) - { - $fieldvalue[] = array($date_format=>$current_user->date_format.' '.$app_strings['YEAR_MONTH_DATE']); - } - else - $fieldvalue[] = array($date_format=>$current_user->date_format); - } - else - { - $fieldvalue[] = array($date_format=>$current_user->date_format.' '.$app_strings['YEAR_MONTH_DATE']); - } - } - elseif($uitype == 16) { - require_once 'modules/PickList/PickListUtils.php'; - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - - $fieldname = $adb->sql_escape_string($fieldname); - $pick_query="select $fieldname from vtiger_$fieldname order by sortorderid"; - $params = array(); - $pickListResult = $adb->pquery($pick_query, $params); - $noofpickrows = $adb->num_rows($pickListResult); - - $options = array(); - $pickcount=0; - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $value = decode_html($value); - $pickListValue=decode_html($adb->query_result($pickListResult,$j,strtolower($fieldname))); - if($value == trim($pickListValue)) - { - - $chk_val = "selected"; - $pickcount++; - $found = true; - } - else - { - $chk_val = ''; - } - $pickListValue = to_html($pickListValue); - if(isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate') - $options[] = array(htmlentities(getTranslatedString($pickListValue),ENT_QUOTES,$default_charset),$pickListValue,$chk_val ); - else - $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); - } - $fieldvalue [] = $options; - } - elseif($uitype == 15 || $uitype == 33){ - require_once 'modules/PickList/PickListUtils.php'; - $roleid=$current_user->roleid; - $picklistValues = getAssignedPicklistValues($fieldname, $roleid, $adb); - $valueArr = explode("|##|", $value); - $pickcount = 0; - - if(!empty($picklistValues)){ - foreach($picklistValues as $order=>$pickListValue){ - if(in_array(trim($pickListValue),array_map("trim", $valueArr))){ - $chk_val = "selected"; - $pickcount++; - }else{ - $chk_val = ''; - } - if(isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate'){ - $options[] = array(htmlentities(getTranslatedString($pickListValue),ENT_QUOTES,$default_charset),$pickListValue,$chk_val ); - }else{ - $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); - } - } - - if($pickcount == 0 && !empty($value)){ - $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'],$value,'selected'); - } - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue [] = $options; - } - elseif($uitype == 17) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue [] = $value; - } - elseif($uitype == 85) //added for Skype by Minnie - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue [] = $value; - }elseif($uitype == 19 || $uitype == 20) - { - if(isset($_REQUEST['body'])) - { - $value = ($_REQUEST['body']); - } - - if($fieldname == 'terms_conditions')//for default Terms & Conditions - { - //Assign the value from focus->column_fields (if we create Invoice from SO the SO's terms and conditions will be loaded to Invoice's terms and conditions, etc.,) - $value = $col_fields['terms_conditions']; - - //if the value is empty then only we should get the default Terms and Conditions - if($value == '' && $mode != 'edit') - $value=getTermsandConditions(); - } - - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue [] = $value; - } - elseif($uitype == 21 || $uitype == 24) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue [] = $value; - } - elseif($uitype == 22) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $value; - } - elseif($uitype == 52 || $uitype == 77) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - global $current_user; - if($value != '') - { - $assigned_user_id = $value; - } - else - { - $assigned_user_id = $current_user->id; - } - if($uitype == 52) - { - $combo_lbl_name = 'assigned_user_id'; - } - elseif($uitype == 77) - { - $combo_lbl_name = 'assigned_user_id1'; - } - - //Control will come here only for Products - Handler and Quotes - Inventory Manager - if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); - } - else - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); - } - $fieldvalue [] = $users_combo; - } - elseif($uitype == 53) - { - global $noof_group_rows; - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - //Security Checks - if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) - { - $result=get_current_user_access_groups($module_name); - } - else - { - $result = get_group_options(); - } - if($result) $nameArray = $adb->fetch_array($result); - - if($value != '' && $value != 0) - $assigned_user_id = $value; - else{ - if($value=='0'){ - if (isset($col_fields['assigned_group_info']) && $col_fields['assigned_group_info'] != '') { - $selected_groupname = $col_fields['assigned_group_info']; - } else { - $record = $col_fields["record_id"]; - $module = $col_fields["record_module"]; - $selected_groupname = getGroupName($record, $module); - } - }else - $assigned_user_id = $current_user->id; - } - - if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); - } - else - { - $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); - } - - if($noof_group_rows!=0) - { - if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) - { - $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); - } - else - { - $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); - } - } - $fieldvalue[]=$users_combo; - $fieldvalue[] = $groups_combo; - } - elseif($uitype == 51 || $uitype == 50 || $uitype == 73) - { - if($_REQUEST['convertmode'] != 'update_quote_val' && $_REQUEST['convertmode'] != 'update_so_val') - { - if(isset($_REQUEST['account_id']) && $_REQUEST['account_id'] != '') - $value = $_REQUEST['account_id']; - } - if($value != '') { - $account_name = getAccountName($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[]=$account_name; - $fieldvalue[] = $value; - } - elseif($uitype == 54) - { - $options = array(); - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $pick_query="select * from vtiger_groups"; - $pickListResult = $adb->pquery($pick_query, array()); - $noofpickrows = $adb->num_rows($pickListResult); - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,"name"); - - if($value == $pickListValue) - { - $chk_val = "selected"; - } - else - { - $chk_val = ''; - } - $options[] = array($pickListValue => $chk_val ); - } - $fieldvalue[] = $options; - - } - elseif($uitype == 55 || $uitype == 255){ - require_once 'modules/PickList/PickListUtils.php'; - if($uitype==255){ - $fieldpermission = getFieldVisibilityPermission($module_name, $current_user->id,'firstname'); - } - if($uitype == 255 && $fieldpermission == '0'){ - $fieldvalue[] = ''; - }else{ - $roleid=$current_user->roleid; - $picklistValues = getAssignedPicklistValues('salutationtype', $roleid, $adb); - $pickcount = 0; - $salt_value = $col_fields["salutationtype"]; - foreach($picklistValues as $order=>$pickListValue){ - if($salt_value == trim($pickListValue)){ - $chk_val = "selected"; - $pickcount++; - }else{ - $chk_val = ''; - } - if(isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate'){ - $options[] = array(htmlentities(getTranslatedString($pickListValue),ENT_QUOTES,$default_charset),$pickListValue,$chk_val ); - }else{ - $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val); - } - } - if($pickcount == 0 && $salt_value != ''){ - $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'],$salt_value,'selected'); - } - $fieldvalue [] = $options; - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $value; - }elseif($uitype == 59){ - if($_REQUEST['module'] == 'HelpDesk') - { - if(isset($_REQUEST['product_id']) & $_REQUEST['product_id'] != '') - $value = $_REQUEST['product_id']; - } - elseif(isset($_REQUEST['parent_id']) & $_REQUEST['parent_id'] != '') - $value = $_REQUEST['parent_id']; - - if($value != '') - { - $product_name = getProductName($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[]=$product_name; - $fieldvalue[]=$value; - } - elseif($uitype == 63) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - if($value=='') - $value=1; - $options = array(); - $pick_query="select * from vtiger_duration_minutes order by sortorderid"; - $pickListResult = $adb->pquery($pick_query, array()); - $noofpickrows = $adb->num_rows($pickListResult); - $salt_value = $col_fields["duration_minutes"]; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,"duration_minutes"); - - if($salt_value == $pickListValue) - { - $chk_val = "selected"; - } - else - { - $chk_val = ''; - } - $options[$pickListValue] = $chk_val; - } - $fieldvalue[]=$value; - $fieldvalue[]=$options; - } - elseif($uitype == 64) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']); - $fieldvalue[] = $value; - } - elseif($uitype == 156) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $value; - $fieldvalue[] = $is_admin; - } - elseif($uitype == 56) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $value; - } - elseif($uitype == 57){ - if($value != ''){ - $contact_name = getContactName($value); - }elseif(isset($_REQUEST['contact_id']) && $_REQUEST['contact_id'] != ''){ - if($_REQUEST['module'] == 'Contacts' && $fieldname = 'contact_id'){ - $contact_name = ''; - }else{ - $value = $_REQUEST['contact_id']; - $contact_name = getContactName($value); - } - - } - - //Checking for contacts duplicate - - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $contact_name; - $fieldvalue[] = $value; - } - - elseif($uitype == 58) - { - - if($value != '') - { - $campaign_name = getCampaignName($value); - } - elseif(isset($_REQUEST['campaignid']) && $_REQUEST['campaignid'] != '') - { - if($_REQUEST['module'] == 'Campaigns' && $fieldname = 'campaignid') - { - $campaign_name = ''; - } - else - { - $value = $_REQUEST['campaignid']; - $campaign_name = getCampaignName($value); - } - - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[]=$campaign_name; - $fieldvalue[] = $value; - } - - elseif($uitype == 61) - { - if($value != '') - { - $assigned_user_id = $value; - } - else - { - $assigned_user_id = $current_user->id; - } - if($module_name == 'Emails' && $col_fields['record_id'] != '') - { - $attach_result = $adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])); - //to fix the issue in mail attachment on forwarding mails - if(isset($_REQUEST['forward']) && $_REQUEST['forward'] != '') - global $att_id_list; - for($ii=0;$ii < $adb->num_rows($attach_result);$ii++) - { - $attachmentid = $adb->query_result($attach_result,$ii,'attachmentsid'); - if($attachmentid != '') - { - $attachquery = "select * from vtiger_attachments where attachmentsid=?"; - $attachmentsname = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); - if($attachmentsname != '') - $fieldvalue[$attachmentid] = '[ '.$attachmentsname.' ]'; - if(isset($_REQUEST['forward']) && $_REQUEST['forward'] != '') - $att_id_list .= $attachmentid.';'; - } - - } - }else - { - if($col_fields['record_id'] != '') - { - $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); - if($col_fields[$fieldname] == '' && $attachmentid != '') - { - $attachquery = "select * from vtiger_attachments where attachmentsid=?"; - $value = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); - } - } - if($value!='') - $filename=' [ '.$value. ' ]'; - - if($filename != '') - $fieldvalue[] = $filename; - if($value != '') - $fieldvalue[] = $value; - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - } - elseif($uitype == 28){ - if($col_fields['record_id'] != '') - { - $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); - if($col_fields[$fieldname] == '' && $attachmentid != '') - { - $attachquery = "select * from vtiger_attachments where attachmentsid=?"; - $value = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); - } - } - if($value!='' && $module_name != 'Documents') - $filename=' [ '.$value. ' ]'; - elseif($value != '' && $module_name == 'Documents') - $filename= $value; - if($filename != '') - $fieldvalue[] = $filename; - if($value != '') - $fieldvalue[] = $value; - - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - } - elseif($uitype == 69) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - if( $col_fields['record_id'] != "") - { - //This query is for Products only - if($module_name == 'Products') - { - $query = 'select vtiger_attachments.path, vtiger_attachments.attachmentsid, vtiger_attachments.name ,vtiger_crmentity.setype from vtiger_products left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_products.productid inner join vtiger_attachments on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_attachments.attachmentsid where vtiger_crmentity.setype="Products Image" and productid=?'; - } - else - { - $query="select vtiger_attachments.*,vtiger_crmentity.setype from vtiger_attachments inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_attachments.attachmentsid where vtiger_crmentity.setype='Contacts Image' and vtiger_seattachmentsrel.crmid=?"; - } - $result_image = $adb->pquery($query, array($col_fields['record_id'])); - for($image_iter=0;$image_iter < $adb->num_rows($result_image);$image_iter++) - { - $image_id_array[] = $adb->query_result($result_image,$image_iter,'attachmentsid'); - - //decode_html - added to handle UTF-8 characters in file names - //urlencode - added to handle special characters like #, %, etc., - $image_array[] = urlencode(decode_html($adb->query_result($result_image,$image_iter,'name'))); - $image_orgname_array[] = decode_html($adb->query_result($result_image,$image_iter,'name')); - - $image_path_array[] = $adb->query_result($result_image,$image_iter,'path'); - } - if(is_array($image_array)) - for($img_itr=0;$img_itr$image_array[$img_itr],'path'=>$image_path_array[$img_itr].$image_id_array[$img_itr]."_","orgname"=>$image_orgname_array[$img_itr]); - } - else - $fieldvalue[] = ''; - } - else - $fieldvalue[] = ''; - } - elseif($uitype == 62) - { - if(isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') - $value = $_REQUEST['parent_id']; - if($value != '') - $parent_module = getSalesEntityType($value); - if(isset($_REQUEST['account_id']) && $_REQUEST['account_id'] != '') - { - $parent_module = "Accounts"; - $value = $_REQUEST['account_id']; - } - if($parent_module != 'Contacts') - { - if($parent_module == "Leads") - { - $parent_name = getLeadName($value); - $lead_selected = "selected"; - - } - elseif($parent_module == "Accounts") - { - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"accountname"); - $account_selected = "selected"; - - } - elseif($parent_module == "Potentials") - { - $sql = "select * from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"potentialname"); - $potential_selected = "selected"; - - } - elseif($parent_module == "Products") - { - $sql = "select * from vtiger_products where productid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name= $adb->query_result($result,0,"productname"); - $product_selected = "selected"; - - } - elseif($parent_module == "PurchaseOrder") - { - $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name= $adb->query_result($result,0,"subject"); - $porder_selected = "selected"; - - } - elseif($parent_module == "SalesOrder") - { - $sql = "select * from vtiger_salesorder where salesorderid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name= $adb->query_result($result,0,"subject"); - $sorder_selected = "selected"; - - } - elseif($parent_module == "Invoice") - { - $sql = "select * from vtiger_invoice where invoiceid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name= $adb->query_result($result,0,"subject"); - $invoice_selected = "selected"; - } - elseif($parent_module == "Quotes") - { - $sql = "select * from vtiger_quotes where quoteid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name= $adb->query_result($result,0,"subject"); - $quote_selected = "selected"; - }elseif($parent_module == "HelpDesk") - { - $sql = "select * from vtiger_troubletickets where ticketid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name= $adb->query_result($result,0,"title"); - $ticket_selected = "selected"; - } - } - $editview_label[] = array($app_strings['COMBO_LEADS'], - $app_strings['COMBO_ACCOUNTS'], - $app_strings['COMBO_POTENTIALS'], - $app_strings['COMBO_PRODUCTS'], - $app_strings['COMBO_INVOICES'], - $app_strings['COMBO_PORDER'], - $app_strings['COMBO_SORDER'], - $app_strings['COMBO_QUOTES'], - $app_strings['COMBO_HELPDESK'] - ); - $editview_label[] = array($lead_selected, - $account_selected, - $potential_selected, - $product_selected, - $invoice_selected, - $porder_selected, - $sorder_selected, - $quote_selected, - $ticket_selected - ); - $editview_label[] = array("Leads&action=Popup","Accounts&action=Popup","Potentials&action=Popup","Products&action=Popup","Invoice&action=Popup","PurchaseOrder&action=Popup","SalesOrder&action=Popup","Quotes&action=Popup","HelpDesk&action=Popup"); - $fieldvalue[] =$parent_name; - $fieldvalue[] =$value; - - } - elseif($uitype == 66) - { - if(isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') - $value = $_REQUEST['parent_id']; - if($value != '') - $parent_module = getSalesEntityType($value); - // Check for vtiger_activity type if task orders to be added in select option - $act_mode = $_REQUEST['activity_mode']; - - if($parent_module != "Contacts") - { - if($parent_module == "Leads") - { - $parent_name = getLeadName($value); - $lead_selected = "selected"; - - } - elseif($parent_module == "Accounts") - { - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"accountname"); - $account_selected = "selected"; - - } - elseif($parent_module == "Potentials") - { - $sql = "select * from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"potentialname"); - $potential_selected = "selected"; - - } - elseif($parent_module == "HelpDesk") - { - $sql = "select title from vtiger_troubletickets where ticketid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"title"); - $ticket_selected = "selected"; - } - - elseif($act_mode == "Task") - { - if($parent_module == "PurchaseOrder") - { - $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"subject"); - $purchase_selected = "selected"; - } - if($parent_module == "SalesOrder") - { - $sql = "select * from vtiger_salesorder where salesorderid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"subject"); - $sales_selected = "selected"; - } - if($parent_module == "Invoice") - { - $sql = "select * from vtiger_invoice where invoiceid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"subject"); - $invoice_selected = "selected"; - } - if($parent_module == "Campaigns") - { - $sql = "select campaignname from vtiger_campaign where campaignid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"campaignname"); - $campaign_selected = "selected"; - } - if($parent_module == "Quotes") - { - $sql = "select * from vtiger_quotes where quoteid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"subject"); - $quote_selected = "selected"; - } - } - $fieldvalue[] =$parent_name; - $fieldvalue[] = $value; - } - $editview_label[0] = array( - $app_strings['COMBO_LEADS'], - $app_strings['COMBO_ACCOUNTS'], - $app_strings['COMBO_POTENTIALS'], - ); - $editview_label[1] = array( - $lead_selected, - $account_selected, - $potential_selected - ); - $editview_label[2] = array( - "Leads&action=Popup", - "Accounts&action=Popup", - "Potentials&action=Popup" - ); - - if($act_mode == "Task") - { - array_push($editview_label[0], - $app_strings['COMBO_QUOTES'], - $app_strings['COMBO_PORDER'], - $app_strings['COMBO_SORDER'], - $app_strings['COMBO_INVOICES'], - $app_strings['COMBO_CAMPAIGNS'], - $app_strings['COMBO_HELPDESK'] - ); - array_push($editview_label[1], - $quote_selected, - $purchase_selected, - $sales_selected, - $invoice_selected, - $campaign_selected, - $ticket_selected - ); - array_push($editview_label[2],"Quotes&action=Popup","PurchaseOrder&action=Popup","SalesOrder&action=Popup","Invoice&action=Popup","Campaigns&action=Popup","HelpDesk&action=Popup"); - } - elseif($act_mode == "Events") - { - array_push($editview_label[0],$app_strings['COMBO_HELPDESK']); - array_push($editview_label[1],$ticket_selected); - array_push($editview_label[2],"HelpDesk&action=Popup"); - } - } - //added by rdhital/Raju for better email support - elseif($uitype == 357) - { - if($_REQUEST['pmodule'] == 'Contacts') - { - $contact_selected = 'selected'; - } - elseif($_REQUEST['pmodule'] == 'Accounts') - { - $account_selected = 'selected'; - } - elseif($_REQUEST['pmodule'] == 'Leads') - { - $lead_selected = 'selected'; - } - elseif($_REQUEST['pmodule'] == 'Vendors') - { - $vendor_selected = 'selected'; - } - if(isset($_REQUEST['emailids']) && $_REQUEST['emailids'] != '') - { - $parent_id = $_REQUEST['emailids']; - $parent_name=''; - $pmodule=$_REQUEST['pmodule']; - $myids=explode("|",$parent_id); - for ($i=0;$i<(count($myids)-1);$i++) - { - $realid=explode("@",$myids[$i]); - $entityid=$realid[0]; - $nemail=count($realid); - - if ($pmodule=='Accounts'){ - require_once('modules/Accounts/Accounts.php'); - $myfocus = new Accounts(); - $myfocus->retrieve_entity_info($entityid,"Accounts"); - $fullname=br2nl($myfocus->column_fields['accountname']); - $account_selected = 'selected'; - } - elseif ($pmodule=='Contacts'){ - require_once('modules/Contacts/Contacts.php'); - $myfocus = new Contacts(); - $myfocus->retrieve_entity_info($entityid,"Contacts"); - $fname=br2nl($myfocus->column_fields['firstname']); - $lname=br2nl($myfocus->column_fields['lastname']); - $fullname=$lname.' '.$fname; - $contact_selected = 'selected'; - } - elseif ($pmodule=='Leads'){ - require_once('modules/Leads/Leads.php'); - $myfocus = new Leads(); - $myfocus->retrieve_entity_info($entityid,"Leads"); - $fname=br2nl($myfocus->column_fields['firstname']); - $lname=br2nl($myfocus->column_fields['lastname']); - $fullname=$lname.' '.$fname; - $lead_selected = 'selected'; - } - for ($j=1;$j<$nemail;$j++){ - $querystr='select columnname from vtiger_field where fieldid=? and vtiger_field.presence in (0,2)'; - $result=$adb->pquery($querystr, array($realid[$j])); - $temp=$adb->query_result($result,0,'columnname'); - $temp1=br2nl($myfocus->column_fields[$temp]); - - //Modified to display the entities in red which don't have email id - if(!empty($temp_parent_name) && strlen($temp_parent_name) > 150) - { - $parent_name .= '
'; - $temp_parent_name = ''; - } - - if($temp1 != '') - { - $parent_name .= $fullname.'<'.$temp1.'>; '; - $temp_parent_name .= $fullname.'<'.$temp1.'>; '; - } - else - { - $parent_name .= "".$fullname.'<'.$temp1.'>; '.""; - $temp_parent_name .= "".$fullname.'<'.$temp1.'>; '.""; - } - - } - } - } - else - { - if($_REQUEST['record'] != '' && $_REQUEST['record'] != NULL) - { - $parent_name=''; - $parent_id=''; - $myemailid= $_REQUEST['record']; - $mysql = "select crmid from vtiger_seactivityrel where activityid=?"; - $myresult = $adb->pquery($mysql, array($myemailid)); - $mycount=$adb->num_rows($myresult); - if($mycount >0) - { - for ($i=0;$i<$mycount;$i++) - { - $mycrmid=$adb->query_result($myresult,$i,'crmid'); - $parent_module = getSalesEntityType($mycrmid); - if($parent_module == "Leads") - { - $sql = "select firstname,lastname,email from vtiger_leaddetails where leadid=?"; - $result = $adb->pquery($sql, array($mycrmid)); - $full_name = getFullNameFromQResult($result,0,"Leads"); - $myemail=$adb->query_result($result,0,"email"); - $parent_id .=$mycrmid.'@0|' ; //make it such that the email adress sent is remebered and only that one is retrived - $parent_name .= $full_name.'<'.$myemail.'>; '; - $lead_selected = 'selected'; - } - elseif($parent_module == "Contacts") - { - $sql = "select * from vtiger_contactdetails where contactid=?"; - $result = $adb->pquery($sql, array($mycrmid)); - $full_name = getFullNameFromQResult($result,0,"Contacts"); - $myemail=$adb->query_result($result,0,"email"); - $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived - $parent_name .= $full_name.'<'.$myemail.'>; '; - $contact_selected = 'selected'; - } - elseif($parent_module == "Accounts") - { - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($mycrmid)); - $account_name = $adb->query_result($result,0,"accountname"); - $myemail=$adb->query_result($result,0,"email1"); - $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived - $parent_name .= $account_name.'<'.$myemail.'>; '; - $account_selected = 'selected'; - }elseif($parent_module == "Users") - { - $sql = "select user_name,email1 from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($mycrmid)); - $account_name = $adb->query_result($result,0,"user_name"); - $myemail=$adb->query_result($result,0,"email1"); - $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived - $parent_name .= $account_name.'<'.$myemail.'>; '; - $user_selected = 'selected'; - } - elseif($parent_module == "Vendors") - { - $sql = "select * from vtiger_vendor where vendorid=?"; - $result = $adb->pquery($sql, array($mycrmid)); - $vendor_name = $adb->query_result($result,0,"vendorname"); - $myemail=$adb->query_result($result,0,"email"); - $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived - $parent_name .= $vendor_name.'<'.$myemail.'>; '; - $vendor_selected = 'selected'; - } - } - } - } - $custfld .= ''.$app_strings['To'].' '; - $custfld .= ' Selectdebug("Exiting getOutputHtml method ..."); return window.open("index.php?module="+ document.EditView.parent_type.value +"&action=Popup&popuptype=set_$log->debug("Exiting getOutputHtml method ..."); return_emails&form=EmailEditView&form_submit=false","test","width=600,height=400,resizable=1,scrollbars=1,top=150,left=200");\' align="absmiddle" style=\'cursor:hand;cursor:pointer\'> '; - $editview_label[] = array( - 'Contacts'=>$contact_selected, - 'Accounts'=>$account_selected, - 'Vendors'=>$vendor_selected, - 'Leads'=>$lead_selected, - 'Users'=>$user_selected - ); - $fieldvalue[] =$parent_name; - $fieldvalue[] = $parent_id; - } - } - //end of rdhital/Raju - elseif($uitype == 68) - { - if(isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') - $value = $_REQUEST['parent_id']; - - if($value != '') - { - $parent_module = getSalesEntityType($value); - if($parent_module == "Contacts") - { - $parent_name = getContactName($value); - $contact_selected = "selected"; - - } - elseif($parent_module == "Accounts") - { - $sql = "select * from vtiger_account where accountid=?"; - $result = $adb->pquery($sql, array($value)); - $parent_name = $adb->query_result($result,0,"accountname"); - $account_selected = "selected"; - - } - else - { - $parent_name = ""; - $value = ""; - } - - } - $editview_label[] = array($app_strings['COMBO_CONTACTS'], - $app_strings['COMBO_ACCOUNTS'] - ); - $editview_label[] = array($contact_selected, - $account_selected - ); - $editview_label[] = array("Contacts","Accounts"); - $fieldvalue[] = $parent_name; - $fieldvalue[] = $value; - } - - elseif($uitype == 71 || $uitype == 72) - { - if($col_fields['record_id'] != '' && $fieldname == 'unit_price') { - $rate_symbol=getCurrencySymbolandCRate(getProductBaseCurrency($col_fields['record_id'],$module_name)); - $fieldvalue[] = $value; - } else { - $currency_id = fetchCurrency($current_user->id); - $rate_symbol=getCurrencySymbolandCRate($currency_id); - $rate = $rate_symbol['rate']; - $fieldvalue[] = convertFromDollar($value,$rate); - } - $currency = $rate_symbol['symbol']; - $editview_label[]=getTranslatedString($fieldlabel, $module_name).': ('.$currency.')'; - } - elseif($uitype == 75 || $uitype ==81) - { - if($value != '') - { - $vendor_name = getVendorName($value); - } - elseif(isset($_REQUEST['vendor_id']) && $_REQUEST['vendor_id'] != '') - { - $value = $_REQUEST['vendor_id']; - $vendor_name = getVendorName($value); - } - $pop_type = 'specific'; - if($uitype == 81) - { - $pop_type = 'specific_vendor_address'; - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $vendor_name; - $fieldvalue[] = $value; - } - elseif($uitype == 76) - { - if($value != '') - { - $potential_name = getPotentialName($value); - } - elseif(isset($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '') - { - $value = $_REQUEST['potental_id']; - $potential_name = getPotentialName($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $potential_name; - $fieldvalue[] = $value; - } - elseif($uitype == 78) - { - if($value != '') - { - $quote_name = getQuoteName($value); - } - elseif(isset($_REQUEST['quote_id']) && $_REQUEST['quote_id'] != '') - { - $value = $_REQUEST['quote_id']; - $potential_name = getQuoteName($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $quote_name; - $fieldvalue[] = $value; - } - elseif($uitype == 79) - { - if($value != '') - { - $purchaseorder_name = getPoName($value); - } - elseif(isset($_REQUEST['purchaseorder_id']) && $_REQUEST['purchaseorder_id'] != '') - { - $value = $_REQUEST['purchaseorder_id']; - $purchaseorder_name = getPoName($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $purchaseorder_name; - $fieldvalue[] = $value; - } - elseif($uitype == 80) - { - if($value != '') - { - $salesorder_name = getSoName($value); - } - elseif(isset($_REQUEST['salesorder_id']) && $_REQUEST['salesorder_id'] != '') - { - $value = $_REQUEST['salesorder_id']; - $salesorder_name = getSoName($value); - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $salesorder_name; - $fieldvalue[] = $value; - } - elseif($uitype == 30) - { - $rem_days = 0; - $rem_hrs = 0; - $rem_min = 0; - if($value!='') - $SET_REM = "CHECKED"; - $rem_days = floor($col_fields[$fieldname]/(24*60)); - $rem_hrs = floor(($col_fields[$fieldname]-$rem_days*24*60)/60); - $rem_min = ($col_fields[$fieldname]-$rem_days*24*60)%60; - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $day_options = getReminderSelectOption(0,31,'remdays',$rem_days); - $hr_options = getReminderSelectOption(0,23,'remhrs',$rem_hrs); - $min_options = getReminderSelectOption(1,59,'remmin',$rem_min); - $fieldvalue[] = array(array(0,32,'remdays',getTranslatedString('LBL_DAYS'),$rem_days),array(0,24,'remhrs',getTranslatedString('LBL_HOURS'),$rem_hrs),array(1,60,'remmin',getTranslatedString('LBL_MINUTES').'  '.getTranslatedString('LBL_BEFORE_EVENT'),$rem_min)); - $fieldvalue[] = array($SET_REM,getTranslatedString('LBL_YES'),getTranslatedString('LBL_NO')); - $SET_REM = ''; - } - elseif($uitype == 115) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $pick_query="select * from vtiger_" . $adb->sql_escape_string($fieldname); - $pickListResult = $adb->pquery($pick_query, array()); - $noofpickrows = $adb->num_rows($pickListResult); - - //Mikecrowe fix to correctly default for custom pick lists - $options = array(); - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,strtolower($fieldname)); - - if($value == $pickListValue) - { - $chk_val = "selected"; - $found = true; - } - else - { - $chk_val = ''; - } - $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); - } - $fieldvalue [] = $options; - $fieldvalue [] = $is_admin; - } - elseif($uitype == 116 || $uitype == 117) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $pick_query="select * from vtiger_currency_info where currency_status = 'Active' and deleted=0"; - $pickListResult = $adb->pquery($pick_query, array()); - $noofpickrows = $adb->num_rows($pickListResult); - - //Mikecrowe fix to correctly default for custom pick lists - $options = array(); - $found = false; - for($j = 0; $j < $noofpickrows; $j++) - { - $pickListValue=$adb->query_result($pickListResult,$j,'currency_name'); - $currency_id=$adb->query_result($pickListResult,$j,'id'); - if($value == $currency_id) - { - $chk_val = "selected"; - $found = true; - } - else - { - $chk_val = ''; - } - $options[$currency_id] = array($pickListValue=>$chk_val ); - } - $fieldvalue [] = $options; - $fieldvalue [] = $is_admin; - } - elseif($uitype ==98) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[]=$value; - $fieldvalue[]=getRoleName($value); - $fieldvalue[]=$is_admin; - } - elseif($uitype == 105) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - if( isset( $col_fields['record_id']) && $col_fields['record_id'] != '') { - $query = "select vtiger_attachments.path, vtiger_attachments.name from vtiger_contactdetails left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_contactdetails.contactid inner join vtiger_attachments on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid where vtiger_contactdetails.imagename=vtiger_attachments.name and contactid=?"; - $result_image = $adb->pquery($query, array($col_fields['record_id'])); - for($image_iter=0;$image_iter < $adb->num_rows($result_image);$image_iter++) - { - $image_array[] = $adb->query_result($result_image,$image_iter,'name'); - $image_path_array[] = $adb->query_result($result_image,$image_iter,'path'); - } - } - if(is_array($image_array)) - for($img_itr=0;$img_itr$image_array[$img_itr],'path'=>$image_path_array[$img_itr]); - } - else - $fieldvalue[] = ''; - }elseif($uitype == 101) - { - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = getUserName($value); - $fieldvalue[] = $value; - } - elseif($uitype == 26){ - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - $folderid=$col_fields['folderid']; - $foldername_query = 'select foldername from vtiger_attachmentsfolder where folderid = ?'; - $res = $adb->pquery($foldername_query,array($folderid)); - $foldername = $adb->query_result($res,0,'foldername'); - if($foldername != '' && $folderid != ''){ - $fldr_name[$folderid]=$foldername; - } - $sql="select foldername,folderid from vtiger_attachmentsfolder order by foldername"; - $res=$adb->pquery($sql,array()); - for($i=0;$i<$adb->num_rows($res);$i++) - { - $fid=$adb->query_result($res,$i,"folderid"); - $fldr_name[$fid]=$adb->query_result($res,$i,"foldername"); - } - $fieldvalue[] = $fldr_name; - } - elseif($uitype == 27){ - if($value == 'I'){ - $internal_selected = "selected"; - $filename = $col_fields['filename']; - } - else{ - $external_selected = "selected"; - $filename = $col_fields['filename']; - } - $editview_label[] = array(getTranslatedString('Internal'), - getTranslatedString('External') - ); - $editview_label[] = array($internal_selected, - $external_selected - ); - $editview_label[] = array("I","E"); - $editview_label[] = getTranslatedString($fieldlabel, $module_name); - $fieldvalue[] = $value; - $fieldvalue[] = $filename; - } - else - { - //Added condition to set the subject if click Reply All from web mail - if($_REQUEST['module'] == 'Emails' && $_REQUEST['mg_subject'] != '') - { - $value = $_REQUEST['mg_subject']; - } - $editview_label[]=getTranslatedString($fieldlabel, $module_name); - if($uitype == 1 && ($fieldname=='expectedrevenue' || $fieldname=='budgetcost' || $fieldname=='actualcost' || $fieldname=='expectedroi' || $fieldname=='actualroi' ) && ($module_name=='Campaigns')) - { - $rate_symbol = getCurrencySymbolandCRate($user_info['currency_id']); - $fieldvalue[] = convertFromDollar($value,$rate_symbol['rate']); - } - elseif($fieldname == 'fileversion'){ - if(empty($value)){ - $value = ''; - } - else{ - $fieldvalue[] = $value; - } - } - else - $fieldvalue[] = $value; - } - - // Mike Crowe Mod --------------------------------------------------------force numerics right justified. - if ( !eregi("id=",$custfld) ) - $custfld = preg_replace("/debug("Exiting getOutputHtml method ..."); - return $final_arr; -} - -/** This function returns the vtiger_invoice object populated with the details from sales order object. -* Param $focus - Invoice object -* Param $so_focus - Sales order focus -* Param $soid - sales order id -* Return type is an object array -*/ - -function getConvertSoToInvoice($focus,$so_focus,$soid) -{ - global $log,$current_user; - $log->debug("Entering getConvertSoToInvoice(".get_class($focus).",".get_class($so_focus).",".$soid.") method ..."); - $log->info("in getConvertSoToInvoice ".$soid); - $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); - for($i=0;$iid,$xyz[$i]) == '0'){ - $so_focus->column_fields[$xyz[$i]] = $so_focus->column_fields[$xyz[$i]]; - } - else - $so_focus->column_fields[$xyz[$i]] = ''; - } - $focus->column_fields['salesorder_id'] = $soid; - $focus->column_fields['subject'] = $so_focus->column_fields['subject']; - $focus->column_fields['customerno'] = $so_focus->column_fields['customerno']; - $focus->column_fields['duedate'] = $so_focus->column_fields['duedate']; - $focus->column_fields['contact_id'] = $so_focus->column_fields['contact_id'];//to include contact name in Invoice - $focus->column_fields['account_id'] = $so_focus->column_fields['account_id']; - $focus->column_fields['exciseduty'] = $so_focus->column_fields['exciseduty']; - $focus->column_fields['salescommission'] = $so_focus->column_fields['salescommission']; - $focus->column_fields['purchaseorder'] = $so_focus->column_fields['purchaseorder']; - $focus->column_fields['bill_street'] = $so_focus->column_fields['bill_street']; - $focus->column_fields['ship_street'] = $so_focus->column_fields['ship_street']; - $focus->column_fields['bill_city'] = $so_focus->column_fields['bill_city']; - $focus->column_fields['ship_city'] = $so_focus->column_fields['ship_city']; - $focus->column_fields['bill_state'] = $so_focus->column_fields['bill_state']; - $focus->column_fields['ship_state'] = $so_focus->column_fields['ship_state']; - $focus->column_fields['bill_code'] = $so_focus->column_fields['bill_code']; - $focus->column_fields['ship_code'] = $so_focus->column_fields['ship_code']; - $focus->column_fields['bill_country'] = $so_focus->column_fields['bill_country']; - $focus->column_fields['ship_country'] = $so_focus->column_fields['ship_country']; - $focus->column_fields['bill_pobox'] = $so_focus->column_fields['bill_pobox']; - $focus->column_fields['ship_pobox'] = $so_focus->column_fields['ship_pobox']; - $focus->column_fields['description'] = $so_focus->column_fields['description']; - $focus->column_fields['terms_conditions'] = $so_focus->column_fields['terms_conditions']; - $focus->column_fields['currency_id'] = $so_focus->column_fields['currency_id']; - $focus->column_fields['conversion_rate'] = $so_focus->column_fields['conversion_rate']; - - $log->debug("Exiting getConvertSoToInvoice method ..."); - return $focus; - -} - -/** This function returns the vtiger_invoice object populated with the details from quote object. -* Param $focus - Invoice object -* Param $quote_focus - Quote order focus -* Param $quoteid - quote id -* Return type is an object array -*/ - - -function getConvertQuoteToInvoice($focus,$quote_focus,$quoteid) -{ - global $log,$current_user; - $log->debug("Entering getConvertQuoteToInvoice(".get_class($focus).",".get_class($quote_focus).",".$quoteid.") method ..."); - $log->info("in getConvertQuoteToInvoice ".$quoteid); - $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); - for($i=0;$i<12;$i++){ - if (getFieldVisibilityPermission('Quotes', $current_user->id,$xyz[$i]) == '0'){ - $quote_focus->column_fields[$xyz[$i]] = $quote_focus->column_fields[$xyz[$i]]; - } - else - $quote_focus->column_fields[$xyz[$i]] = ''; - } - $focus->column_fields['subject'] = $quote_focus->column_fields['subject']; - $focus->column_fields['account_id'] = $quote_focus->column_fields['account_id']; - $focus->column_fields['bill_street'] = $quote_focus->column_fields['bill_street']; - $focus->column_fields['ship_street'] = $quote_focus->column_fields['ship_street']; - $focus->column_fields['bill_city'] = $quote_focus->column_fields['bill_city']; - $focus->column_fields['ship_city'] = $quote_focus->column_fields['ship_city']; - $focus->column_fields['bill_state'] = $quote_focus->column_fields['bill_state']; - $focus->column_fields['ship_state'] = $quote_focus->column_fields['ship_state']; - $focus->column_fields['bill_code'] = $quote_focus->column_fields['bill_code']; - $focus->column_fields['ship_code'] = $quote_focus->column_fields['ship_code']; - $focus->column_fields['bill_country'] = $quote_focus->column_fields['bill_country']; - $focus->column_fields['ship_country'] = $quote_focus->column_fields['ship_country']; - $focus->column_fields['bill_pobox'] = $quote_focus->column_fields['bill_pobox']; - $focus->column_fields['ship_pobox'] = $quote_focus->column_fields['ship_pobox']; - $focus->column_fields['description'] = $quote_focus->column_fields['description']; - $focus->column_fields['terms_conditions'] = $quote_focus->column_fields['terms_conditions']; - $focus->column_fields['currency_id'] = $quote_focus->column_fields['currency_id']; - $focus->column_fields['conversion_rate'] = $quote_focus->column_fields['conversion_rate']; - - $log->debug("Exiting getConvertQuoteToInvoice method ..."); - return $focus; - -} - -/** This function returns the sales order object populated with the details from quote object. -* Param $focus - Sales order object -* Param $quote_focus - Quote order focus -* Param $quoteid - quote id -* Return type is an object array -*/ - -function getConvertQuoteToSoObject($focus,$quote_focus,$quoteid) -{ - global $log,$current_user; - $log->debug("Entering getConvertQuoteToSoObject(".get_class($focus).",".get_class($quote_focus).",".$quoteid.") method ..."); - $log->info("in getConvertQuoteToSoObject ".$quoteid); - $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); - for($i=0;$i<12;$i++){ - if (getFieldVisibilityPermission('Quotes', $current_user->id,$xyz[$i]) == '0'){ - $quote_focus->column_fields[$xyz[$i]] = $quote_focus->column_fields[$xyz[$i]]; - } - else - $quote_focus->column_fields[$xyz[$i]] = ''; - } - $focus->column_fields['quote_id'] = $quoteid; - $focus->column_fields['subject'] = $quote_focus->column_fields['subject']; - $focus->column_fields['contact_id'] = $quote_focus->column_fields['contact_id']; - $focus->column_fields['potential_id'] = $quote_focus->column_fields['potential_id']; - $focus->column_fields['account_id'] = $quote_focus->column_fields['account_id']; - $focus->column_fields['carrier'] = $quote_focus->column_fields['carrier']; - $focus->column_fields['bill_street'] = $quote_focus->column_fields['bill_street']; - $focus->column_fields['ship_street'] = $quote_focus->column_fields['ship_street']; - $focus->column_fields['bill_city'] = $quote_focus->column_fields['bill_city']; - $focus->column_fields['ship_city'] = $quote_focus->column_fields['ship_city']; - $focus->column_fields['bill_state'] = $quote_focus->column_fields['bill_state']; - $focus->column_fields['ship_state'] = $quote_focus->column_fields['ship_state']; - $focus->column_fields['bill_code'] = $quote_focus->column_fields['bill_code']; - $focus->column_fields['ship_code'] = $quote_focus->column_fields['ship_code']; - $focus->column_fields['bill_country'] = $quote_focus->column_fields['bill_country']; - $focus->column_fields['ship_country'] = $quote_focus->column_fields['ship_country']; - $focus->column_fields['bill_pobox'] = $quote_focus->column_fields['bill_pobox']; - $focus->column_fields['ship_pobox'] = $quote_focus->column_fields['ship_pobox']; - $focus->column_fields['description'] = $quote_focus->column_fields['description']; - $focus->column_fields['terms_conditions'] = $quote_focus->column_fields['terms_conditions']; - $focus->column_fields['currency_id'] = $quote_focus->column_fields['currency_id']; - $focus->column_fields['conversion_rate'] = $quote_focus->column_fields['conversion_rate']; - - $log->debug("Exiting getConvertQuoteToSoObject method ..."); - return $focus; - -} - -/** This function returns the detailed list of vtiger_products associated to a given entity or a record. -* Param $module - module name -* Param $focus - module object -* Param $seid - sales entity id -* Return type is an object array -*/ - - -function getAssociatedProducts($module,$focus,$seid='') -{ - global $log; - $log->debug("Entering getAssociatedProducts(".$module.",".get_class($focus).",".$seid."='') method ..."); - global $adb; - $output = ''; - global $theme,$current_user; - - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $product_Detail = Array(); - - // DG 15 Aug 2006 - // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items - - if($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') - { - $query="SELECT - case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname, - case when vtiger_products.productid != '' then vtiger_products.productcode else vtiger_service.service_no end as productcode, - case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price, - case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, - case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype, - vtiger_inventoryproductrel.listprice, - vtiger_inventoryproductrel.description AS product_description, - vtiger_inventoryproductrel.* - FROM vtiger_inventoryproductrel - LEFT JOIN vtiger_products - ON vtiger_products.productid=vtiger_inventoryproductrel.productid - LEFT JOIN vtiger_service - ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid - WHERE id=? - ORDER BY sequence_no"; - $params = array($focus->id); - } - elseif($module == 'Potentials') - { - $query="SELECT - vtiger_products.productname, - vtiger_products.productcode, - vtiger_products.unit_price, - vtiger_products.qtyinstock, - vtiger_seproductsrel.*, - vtiger_crmentity.description AS product_description - FROM vtiger_products - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid=vtiger_products.productid - INNER JOIN vtiger_seproductsrel - ON vtiger_seproductsrel.productid=vtiger_products.productid - WHERE vtiger_seproductsrel.crmid=?"; - $params = array($seid); - } - elseif($module == 'Products') - { - $query="SELECT - vtiger_products.productid, - vtiger_products.productcode, - vtiger_products.productname, - vtiger_products.unit_price, - vtiger_products.qtyinstock, - vtiger_crmentity.description AS product_description, - 'Products' AS entitytype - FROM vtiger_products - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid=vtiger_products.productid - WHERE vtiger_crmentity.deleted=0 - AND productid=?"; - $params = array($seid); - } - elseif($module == 'Services') - { - $query="SELECT - vtiger_service.serviceid AS productid, - 'NA' AS productcode, - vtiger_service.servicename AS productname, - vtiger_service.unit_price AS unit_price, - 'NA' AS qtyinstock, - vtiger_crmentity.description AS product_description, - 'Services' AS entitytype - FROM vtiger_service - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid=vtiger_service.serviceid - WHERE vtiger_crmentity.deleted=0 - AND serviceid=?"; - $params = array($seid); - } - - $result = $adb->pquery($query, $params); - $num_rows=$adb->num_rows($result); - for($i=1;$i<=$num_rows;$i++) - { - $hdnProductId = $adb->query_result($result,$i-1,'productid'); - $hdnProductcode = $adb->query_result($result,$i-1,'productcode'); - $productname=$adb->query_result($result,$i-1,'productname'); - $productdescription=$adb->query_result($result,$i-1,'product_description'); - $comment=$adb->query_result($result,$i-1,'comment'); - $qtyinstock=$adb->query_result($result,$i-1,'qtyinstock'); - //$qty=$adb->query_result($result,$i-1,'quantity'); - $qty=number_format($adb->query_result($result,$i-1,'quantity'),0,'',''); - $unitprice=$adb->query_result($result,$i-1,'unit_price'); - $listprice=$adb->query_result($result,$i-1,'listprice'); - $entitytype=$adb->query_result($result,$i-1,'entitytype'); - if (!empty($entitytype)) { - $product_Detail[$i]['entityType'.$i]=$entitytype; - } - - if($listprice == '') - $listprice = $unitprice; - if($qty =='') - $qty = 1; - - //calculate productTotal - $productTotal = $qty*$listprice; - - //Delete link in First column - if($i != 1) - { - $product_Detail[$i]['delRow'.$i]="Del"; - } - if(!isset($focus->mode) && $seid!=''){ - $sub_prod_query = $adb->pquery("SELECT crmid as prod_id from vtiger_seproductsrel WHERE productid=? AND setype='Products'",array($seid)); - } else { - $sub_prod_query = $adb->pquery("SELECT productid as prod_id from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($focus->id,$i)); - } - $subprodid_str=''; - $subprodname_str=''; - - if($adb->num_rows($sub_prod_query)>0){ - for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ - $sprod_id = $adb->query_result($sub_prod_query,$j,'prod_id'); - $sprod_name = getProductName($sprod_id); - $str_sep = ""; - if($j>0) $str_sep = ":"; - $subprodid_str .= $str_sep.$sprod_id; - $subprodname_str .= $str_sep." - ".$sprod_name; - } - } - - $subprodname_str = str_replace(":","
",$subprodname_str); - - $product_Detail[$i]['hdnProductId'.$i] = $hdnProductId; - $product_Detail[$i]['productName'.$i]= from_html($productname); - /* Added to fix the issue Product Pop-up name display*/ - if($_REQUEST['action'] == 'CreateSOPDF' || $_REQUEST['action'] == 'CreatePDF' || $_REQUEST['action'] == 'SendPDFMail') - $product_Detail[$i]['productName'.$i]= htmlspecialchars($product_Detail[$i]['productName'.$i]); - $product_Detail[$i]['hdnProductcode'.$i] = $hdnProductcode; - $product_Detail[$i]['productDescription'.$i]= from_html($productdescription); - $product_Detail[$i]['comment'.$i]= $comment; - - if($module != 'PurchaseOrder' && $focus->object_name != 'Order') - { - $product_Detail[$i]['qtyInStock'.$i]=$qtyinstock; - } - $product_Detail[$i]['qty'.$i]=$qty; - $product_Detail[$i]['listPrice'.$i]=$listprice; - $product_Detail[$i]['unitPrice'.$i]=$unitprice; - $product_Detail[$i]['productTotal'.$i]=$productTotal; - $product_Detail[$i]['subproduct_ids'.$i]=$subprodid_str; - $product_Detail[$i]['subprod_names'.$i]=$subprodname_str; - $discount_percent=$adb->query_result($result,$i-1,'discount_percent'); - $discount_amount=$adb->query_result($result,$i-1,'discount_amount'); - $discountTotal = '0.00'; - //Based on the discount percent or amount we will show the discount details - - //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(for Each Product) - $product_Detail[$i]['discount_percent'.$i] = 0; - $product_Detail[$i]['discount_amount'.$i] = 0; - - if($discount_percent != 'NULL' && $discount_percent != '') - { - $product_Detail[$i]['discount_type'.$i] = "percentage"; - $product_Detail[$i]['discount_percent'.$i] = $discount_percent; - $product_Detail[$i]['checked_discount_percent'.$i] = ' checked'; - $product_Detail[$i]['style_discount_percent'.$i] = ' style="visibility:visible"'; - $product_Detail[$i]['style_discount_amount'.$i] = ' style="visibility:hidden"'; - $discountTotal = $productTotal*$discount_percent/100; - } - elseif($discount_amount != 'NULL' && $discount_amount != '') - { - $product_Detail[$i]['discount_type'.$i] = "amount"; - $product_Detail[$i]['discount_amount'.$i] = $discount_amount; - $product_Detail[$i]['checked_discount_amount'.$i] = ' checked'; - $product_Detail[$i]['style_discount_amount'.$i] = ' style="visibility:visible"'; - $product_Detail[$i]['style_discount_percent'.$i] = ' style="visibility:hidden"'; - $discountTotal = $discount_amount; - } - else - { - $product_Detail[$i]['checked_discount_zero'.$i] = ' checked'; - } - $totalAfterDiscount = $productTotal-$discountTotal; - $product_Detail[$i]['discountTotal'.$i] = $discountTotal; - $product_Detail[$i]['totalAfterDiscount'.$i] = $totalAfterDiscount; - - $taxTotal = '0.00'; - $product_Detail[$i]['taxTotal'.$i] = $taxTotal; - - //Calculate netprice - $netPrice = $totalAfterDiscount+$taxTotal; - //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module - if($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') - { - $taxtype = getInventoryTaxType($module,$focus->id); - if($taxtype == 'individual') - { - //Add the tax with product total and assign to netprice - $netPrice = $netPrice+$taxTotal; - } - } - $product_Detail[$i]['netPrice'.$i] = $netPrice; - - //First we will get all associated taxes as array - $tax_details = getTaxDetailsForProduct($hdnProductId,'all'); - //Now retrieve the tax values from the current query with the name - for($tax_count=0;$tax_countid != '') - { - if($taxtype == 'individual')//if individual then show the entered tax percentage - $tax_value = getInventoryProductTaxValue($focus->id, $hdnProductId, $tax_name); - else//if group tax then we have to show the default value when change to individual tax - $tax_value = $tax_details[$tax_count]['percentage']; - } - else//if the above function not called then assign the default associated value of the product - $tax_value = $tax_details[$tax_count]['percentage']; - - $product_Detail[$i]['taxes'][$tax_count]['taxname'] = $tax_name; - $product_Detail[$i]['taxes'][$tax_count]['taxlabel'] = $tax_label; - $product_Detail[$i]['taxes'][$tax_count]['percentage'] = $tax_value; - } - - } - - //set the taxtype - $product_Detail[1]['final_details']['taxtype'] = $taxtype; - - //Get the Final Discount, S&H charge, Tax for S&H and Adjustment values - //To set the Final Discount details - $finalDiscount = '0.00'; - $product_Detail[1]['final_details']['discount_type_final'] = 'zero'; - - $subTotal = ($focus->column_fields['hdnSubTotal'] != '')?$focus->column_fields['hdnSubTotal']:'0.00'; - - $product_Detail[1]['final_details']['hdnSubTotal'] = $subTotal; - $discountPercent = ($focus->column_fields['hdnDiscountPercent'] != '')?$focus->column_fields['hdnDiscountPercent']:'0.00'; - $discountAmount = ($focus->column_fields['hdnDiscountAmount'] != '')?$focus->column_fields['hdnDiscountAmount']:'0.00'; - - //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(For Final Discount) - $product_Detail[1]['final_details']['discount_percentage_final'] = 0; - $product_Detail[1]['final_details']['discount_amount_final'] = 0; - - if($focus->column_fields['hdnDiscountPercent'] != '0') - { - $finalDiscount = ($subTotal*$discountPercent/100); - $product_Detail[1]['final_details']['discount_type_final'] = 'percentage'; - $product_Detail[1]['final_details']['discount_percentage_final'] = $discountPercent; - $product_Detail[1]['final_details']['checked_discount_percentage_final'] = ' checked'; - $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:visible"'; - $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:hidden"'; - } - elseif($focus->column_fields['hdnDiscountAmount'] != '0') - { - $finalDiscount = $focus->column_fields['hdnDiscountAmount']; - $product_Detail[1]['final_details']['discount_type_final'] = 'amount'; - $product_Detail[1]['final_details']['discount_amount_final'] = $discountAmount; - $product_Detail[1]['final_details']['checked_discount_amount_final'] = ' checked'; - $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:visible"'; - $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:hidden"'; - } - $product_Detail[1]['final_details']['discountTotal_final'] = $finalDiscount; - - //To set the Final Tax values - //we will get all taxes. if individual then show the product related taxes only else show all taxes - //suppose user want to change individual to group or vice versa in edit time the we have to show all taxes. so that here we will store all the taxes and based on need we will show the corresponding taxes - - $taxtotal = '0.00'; - //First we should get all available taxes and then retrieve the corresponding tax values - $tax_details = getAllTaxes('available','','edit',$focus->id); - - for($tax_count=0;$tax_countquery_result($result,0,$tax_name); - else - $tax_percent = $tax_details[$tax_count]['percentage'];//$adb->query_result($result,0,$tax_name); - - if($tax_percent == '' || $tax_percent == 'NULL') - $tax_percent = '0.00'; - $taxamount = ($subTotal-$finalDiscount)*$tax_percent/100; - $taxtotal = $taxtotal + $taxamount; - $product_Detail[1]['final_details']['taxes'][$tax_count]['taxname'] = $tax_name; - $product_Detail[1]['final_details']['taxes'][$tax_count]['taxlabel'] = $tax_label; - $product_Detail[1]['final_details']['taxes'][$tax_count]['percentage'] = $tax_percent; - $product_Detail[1]['final_details']['taxes'][$tax_count]['amount'] = $taxamount; - } - $product_Detail[1]['final_details']['tax_totalamount'] = $taxtotal; - - //To set the Shipping & Handling charge - $shCharge = ($focus->column_fields['hdnS_H_Amount'] != '')?$focus->column_fields['hdnS_H_Amount']:'0.00'; - $product_Detail[1]['final_details']['shipping_handling_charge'] = $shCharge; - - //To set the Shipping & Handling tax values - //calculate S&H tax - $shtaxtotal = '0.00'; - //First we should get all available taxes and then retrieve the corresponding tax values - $shtax_details = getAllTaxes('available','sh','edit',$focus->id); - - //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table - for($shtax_count=0;$shtax_countid,$shtax_name); - } - $shtaxamount = $shCharge*$shtax_percent/100; - $shtaxtotal = $shtaxtotal + $shtaxamount; - $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxname'] = $shtax_name; - $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxlabel'] = $shtax_label; - $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['percentage'] = $shtax_percent; - $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['amount'] = $shtaxamount; - } - $product_Detail[1]['final_details']['shtax_totalamount'] = $shtaxtotal; - - //To set the Adjustment value - $adjustment = ($focus->column_fields['txtAdjustment'] != '')?$focus->column_fields['txtAdjustment']:'0.00'; - $product_Detail[1]['final_details']['adjustment'] = $adjustment; - - //To set the grand total - $grandTotal = ($focus->column_fields['hdnGrandTotal'] != '')?$focus->column_fields['hdnGrandTotal']:'0.00'; - $product_Detail[1]['final_details']['grandTotal'] = $grandTotal; - - $log->debug("Exiting getAssociatedProducts method ..."); - - return $product_Detail; - -} - -/** This function returns the no of vtiger_products associated to the given entity or a record. -* Param $module - module name -* Param $focus - module object -* Param $seid - sales entity id -* Return type is an object array -*/ - -function getNoOfAssocProducts($module,$focus,$seid='') -{ - global $log; - $log->debug("Entering getNoOfAssocProducts(".$module.",".get_class($focus).",".$seid."='') method ..."); - global $adb; - $output = ''; - if($module == 'Quotes') - { - $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; - $params = array($focus->id); - } - elseif($module == 'PurchaseOrder') - { - $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; - $params = array($focus->id); - } - elseif($module == 'SalesOrder') - { - $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; - $params = array($focus->id); - } - elseif($module == 'Invoice') - { - $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; - $params = array($focus->id); - } - elseif($module == 'Potentials') - { - $query="select vtiger_products.productname,vtiger_products.unit_price,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?"; - $params = array($seid); - } - elseif($module == 'Products') - { - $query="select vtiger_products.productname,vtiger_products.unit_price, vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?"; - $params = array($seid); - } - - $result = $adb->pquery($query, $params); - $num_rows=$adb->num_rows($result); - $log->debug("Exiting getNoOfAssocProducts method ..."); - return $num_rows; -} - -/** This function returns the detail block information of a record for given block id. -* Param $module - module name -* Param $block - block name -* Param $mode - view type (detail/edit/create) -* Param $col_fields - vtiger_fields array -* Param $tabid - vtiger_tab id -* Param $info_type - information type (basic/advance) default "" -* Return type is an object array -*/ - -function getBlockInformation($module, $result, $col_fields,$tabid,$block_label,$mode) -{ - global $log; - $log->debug("Entering getBlockInformation(".$module.",". $result.",". $col_fields.",".$tabid.",".$block_label.") method ..."); - global $adb; - $editview_arr = Array(); - - global $current_user,$mod_strings; - - $noofrows = $adb->num_rows($result); - if (($module == 'Accounts' || $module == 'Contacts' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder'|| $module == 'Invoice') && $block == 2) - { - global $log; - $log->info("module is ".$module); - - $mvAdd_flag = true; - $moveAddress = "

- "; - } - - - for($i=0; $i<$noofrows; $i++) - { - $fieldtablename = $adb->query_result($result,$i,"tablename"); - $fieldcolname = $adb->query_result($result,$i,"columnname"); - $uitype = $adb->query_result($result,$i,"uitype"); - $fieldname = $adb->query_result($result,$i,"fieldname"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $block = $adb->query_result($result,$i,"block"); - $maxlength = $adb->query_result($result,$i,"maximumlength"); - $generatedtype = $adb->query_result($result,$i,"generatedtype"); - $typeofdata = $adb->query_result($result,$i,"typeofdata"); - - $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,$module,$mode,$typeofdata); - $editview_arr[$block][]=$custfld; - if ($mvAdd_flag == true) - $mvAdd_flag = false; - $i++; - if($i<$noofrows) - { - $fieldtablename = $adb->query_result($result,$i,"tablename"); - $fieldcolname = $adb->query_result($result,$i,"columnname"); - $uitype = $adb->query_result($result,$i,"uitype"); - $fieldname = $adb->query_result($result,$i,"fieldname"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $block = $adb->query_result($result,$i,"block"); - $maxlength = $adb->query_result($result,$i,"maximumlength"); - $generatedtype = $adb->query_result($result,$i,"generatedtype"); - $typeofdata = $adb->query_result($result,$i,"typeofdata"); - $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,$module,$mode,$typeofdata); - $editview_arr[$block][]=$custfld; - } - } - foreach($editview_arr as $headerid=>$editview_value) - { - $editview_data = Array(); - for ($i=0,$j=0;$i $key1,1 => $key2); - $i+=2; - } - else{ - $editview_data[$j]=array(0 => $key1); - $i++; - } - } - $editview_arr[$headerid] = $editview_data; - } - foreach($block_label as $blockid=>$label) - { - if($label == '') - { - $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$editview_arr[$blockid]); - } - else - { - $curBlock = $label; - if(is_array($editview_arr[$blockid])) - $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$editview_arr[$blockid]); - } - } - $log->debug("Exiting getBlockInformation method ..."); - return $returndata; - -} - -/** This function returns the data type of the vtiger_fields, with vtiger_field label, which is used for javascript validation. -* Param $validationData - array of vtiger_fieldnames with datatype -* Return type array -*/ - -function split_validationdataArray($validationData) -{ - global $log; - $log->debug("Entering split_validationdataArray(".$validationData.") method ..."); - $fieldName = ''; - $fieldLabel = ''; - $fldDataType = ''; - $rows = count($validationData); - foreach($validationData as $fldName => $fldLabel_array) - { - if($fieldName == '') - { - $fieldName="'".$fldName."'"; - } - else - { - $fieldName .= ",'".$fldName ."'"; - } - foreach($fldLabel_array as $fldLabel => $datatype) - { - if($fieldLabel == '') - { - $fieldLabel = "'".addslashes($fldLabel)."'"; - } - else - { - $fieldLabel .= ",'".addslashes($fldLabel)."'"; - } - if($fldDataType == '') - { - $fldDataType = "'".$datatype ."'"; - } - else - { - $fldDataType .= ",'".$datatype ."'"; - } - } - } - $data['fieldname'] = $fieldName; - $data['fieldlabel'] = $fieldLabel; - $data['datatype'] = $fldDataType; - $log->debug("Exiting split_validationdataArray method ..."); - return $data; -} - - -?> +debug("Entering getOutputHtml(".$uitype.",". $fieldname.",". $fieldlabel.",". $maxlength.",". $col_fields.",".$generatedtype.",".$module_name.") method ..."); + global $adb,$log,$default_charset; + global $theme; + global $mod_strings; + global $app_strings; + global $current_user; + + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + $fieldlabel = from_html($fieldlabel); + $fieldvalue = Array(); + $final_arr = Array(); + $value = $col_fields[$fieldname]; + $custfld = ''; + $ui_type[]= $uitype; + $editview_fldname[] = $fieldname; + + // vtlib customization: Related type field + if($uitype == '10') { + global $adb; + $fldmod_result = $adb->pquery('SELECT relmodule, status FROM vtiger_fieldmodulerel WHERE fieldid= + (SELECT fieldid FROM vtiger_field, vtiger_tab WHERE vtiger_field.tabid=vtiger_tab.tabid AND fieldname=? AND name=? and vtiger_field.presence in (0,2))', + Array($fieldname, $module_name)); + + $entityTypes = Array(); + $parent_id = $value; + for($index = 0; $index < $adb->num_rows($fldmod_result); ++$index) { + $entityTypes[] = $adb->query_result($fldmod_result, $index, 'relmodule'); + } + + if(!empty($value)) { + $valueType = getSalesEntityType($value); + $displayValueArray = getEntityName($valueType, $value); + if(!empty($displayValueArray)){ + foreach($displayValueArray as $key=>$value){ + $displayValue = $value; + } + } + } else { + $displayValue=''; + $valueType=''; + $value=''; + } + + $editview_label[] = Array('options'=>$entityTypes, 'selected'=>$valueType, 'displaylabel'=>getTranslatedString($fieldlabel, $module_name)); + $fieldvalue[] = Array('displayvalue'=>$displayValue,'entityid'=>$parent_id); + + } // END + else if($uitype == 5 || $uitype == 6 || $uitype ==23) + { + $log->info("uitype is ".$uitype); + if($value=='') + { + //modified to fix the issue in trac(http://vtiger.fosslabs.com/cgi-bin/trac.cgi/ticket/1469) + if($fieldname != 'birthday' && $generatedtype != 2 && getTabid($module_name) !=14)// && $fieldname != 'due_date')//due date is today's date by default + $disp_value=getNewDisplayDate(); + + //Added to display the Contact - Support End Date as one year future instead of today's date -- 30-11-2005 + if($fieldname == 'support_end_date' && $_REQUEST['module'] == 'Contacts') + { + $addyear = strtotime("+1 year"); + global $current_user; + $dat_fmt = (($current_user->date_format == '')?('dd-mm-yyyy'):($current_user->date_format)); + + $disp_value = (($dat_fmt == 'dd-mm-yyyy')?(date('d-m-Y',$addyear)):(($dat_fmt == 'mm-dd-yyyy')?(date('m-d-Y',$addyear)):(($dat_fmt == 'yyyy-mm-dd')?(date('Y-m-d', $addyear)):('')))); + } + + if($fieldname == 'validtill' && $_REQUEST['module'] == 'Quotes') + { + $disp_value = ''; + } + + } + else + { + $disp_value = getValidDisplayDate($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + if($uitype == 6) + { + if($col_fields['time_start']!='') + { + $curr_time = $col_fields['time_start']; + } + else + { + $curr_time = date('H:i',(time() + (5 * 60))); + } + } + if($module_name == 'Events' && $uitype == 23) + { + if($col_fields['time_end']!='') + { + $curr_time = $col_fields['time_end']; + } + else + { + $endtime = time() + (10 * 60); + $curr_time = date('H:i',$endtime); + } + } + $fieldvalue[] = array($disp_value => $curr_time) ; + if($uitype == 5 || $uitype == 23) + { + if($module_name == 'Events' && $uitype == 23) + { + $fieldvalue[] = array($date_format=>$current_user->date_format.' '.$app_strings['YEAR_MONTH_DATE']); + } + else + $fieldvalue[] = array($date_format=>$current_user->date_format); + } + else + { + $fieldvalue[] = array($date_format=>$current_user->date_format.' '.$app_strings['YEAR_MONTH_DATE']); + } + } + elseif($uitype == 16) { + require_once 'modules/PickList/PickListUtils.php'; + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + + $fieldname = $adb->sql_escape_string($fieldname); + $pick_query="select $fieldname from vtiger_$fieldname order by sortorderid"; + $params = array(); + $pickListResult = $adb->pquery($pick_query, $params); + $noofpickrows = $adb->num_rows($pickListResult); + + $options = array(); + $pickcount=0; + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $value = decode_html($value); + $pickListValue=decode_html($adb->query_result($pickListResult,$j,strtolower($fieldname))); + if($value == trim($pickListValue)) + { + + $chk_val = "selected"; + $pickcount++; + $found = true; + } + else + { + $chk_val = ''; + } + $pickListValue = to_html($pickListValue); + if(isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate') + $options[] = array(htmlentities(getTranslatedString($pickListValue),ENT_QUOTES,$default_charset),$pickListValue,$chk_val ); + else + $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); + } + $fieldvalue [] = $options; + } + elseif($uitype == 15 || $uitype == 33){ + require_once 'modules/PickList/PickListUtils.php'; + $roleid=$current_user->roleid; + $picklistValues = getAssignedPicklistValues($fieldname, $roleid, $adb); + $valueArr = explode("|##|", $value); + $pickcount = 0; + + if(!empty($picklistValues)){ + foreach($picklistValues as $order=>$pickListValue){ + if(in_array(trim($pickListValue),array_map("trim", $valueArr))){ + $chk_val = "selected"; + $pickcount++; + }else{ + $chk_val = ''; + } + if(isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate'){ + $options[] = array(htmlentities(getTranslatedString($pickListValue),ENT_QUOTES,$default_charset),$pickListValue,$chk_val ); + }else{ + $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); + } + } + + if($pickcount == 0 && !empty($value)){ + $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'],$value,'selected'); + } + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue [] = $options; + } + elseif($uitype == 17) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue [] = $value; + } + elseif($uitype == 85) //added for Skype by Minnie + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue [] = $value; + }elseif($uitype == 19 || $uitype == 20) + { + if(isset($_REQUEST['body'])) + { + $value = ($_REQUEST['body']); + } + + if($fieldname == 'terms_conditions')//for default Terms & Conditions + { + //Assign the value from focus->column_fields (if we create Invoice from SO the SO's terms and conditions will be loaded to Invoice's terms and conditions, etc.,) + $value = $col_fields['terms_conditions']; + + //if the value is empty then only we should get the default Terms and Conditions + if($value == '' && $mode != 'edit') + $value=getTermsandConditions(); + } + + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue [] = $value; + } + elseif($uitype == 21 || $uitype == 24) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue [] = $value; + } + elseif($uitype == 22) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $value; + } + elseif($uitype == 52 || $uitype == 77) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + global $current_user; + if($value != '') + { + $assigned_user_id = $value; + } + else + { + $assigned_user_id = $current_user->id; + } + if($uitype == 52) + { + $combo_lbl_name = 'assigned_user_id'; + } + elseif($uitype == 77) + { + $combo_lbl_name = 'assigned_user_id1'; + } + + //Control will come here only for Products - Handler and Quotes - Inventory Manager + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); + } + else + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); + } + $fieldvalue [] = $users_combo; + } + elseif($uitype == 53) + { + global $noof_group_rows; + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + //Security Checks + if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) + { + $result=get_current_user_access_groups($module_name); + } + else + { + $result = get_group_options(); + } + if($result) $nameArray = $adb->fetch_array($result); + + if($value != '' && $value != 0) + $assigned_user_id = $value; + else{ + if($value=='0'){ + if (isset($col_fields['assigned_group_info']) && $col_fields['assigned_group_info'] != '') { + $selected_groupname = $col_fields['assigned_group_info']; + } else { + $record = $col_fields["record_id"]; + $module = $col_fields["record_module"]; + $selected_groupname = getGroupName($record, $module); + } + }else + $assigned_user_id = $current_user->id; + } + + if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); + } + else + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); + } + + if($noof_group_rows!=0) + { + if($fieldlabel == 'Assigned To' && $is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid($module_name)] == 3 or $defaultOrgSharingPermission[getTabid($module_name)] == 0)) + { + $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); + } + else + { + $groups_combo = get_select_options_array(get_group_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); + } + } + $fieldvalue[]=$users_combo; + $fieldvalue[] = $groups_combo; + } + elseif($uitype == 51 || $uitype == 50 || $uitype == 73) + { + if($_REQUEST['convertmode'] != 'update_quote_val' && $_REQUEST['convertmode'] != 'update_so_val') + { + if(isset($_REQUEST['account_id']) && $_REQUEST['account_id'] != '') + $value = $_REQUEST['account_id']; + } + if($value != '') { + $account_name = getAccountName($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[]=$account_name; + $fieldvalue[] = $value; + } + elseif($uitype == 54) + { + $options = array(); + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $pick_query="select * from vtiger_groups"; + $pickListResult = $adb->pquery($pick_query, array()); + $noofpickrows = $adb->num_rows($pickListResult); + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,"name"); + + if($value == $pickListValue) + { + $chk_val = "selected"; + } + else + { + $chk_val = ''; + } + $options[] = array($pickListValue => $chk_val ); + } + $fieldvalue[] = $options; + + } + elseif($uitype == 55 || $uitype == 255){ + require_once 'modules/PickList/PickListUtils.php'; + if($uitype==255){ + $fieldpermission = getFieldVisibilityPermission($module_name, $current_user->id,'firstname'); + } + if($uitype == 255 && $fieldpermission == '0'){ + $fieldvalue[] = ''; + }else{ + $roleid=$current_user->roleid; + $picklistValues = getAssignedPicklistValues('salutationtype', $roleid, $adb); + $pickcount = 0; + $salt_value = $col_fields["salutationtype"]; + foreach($picklistValues as $order=>$pickListValue){ + if($salt_value == trim($pickListValue)){ + $chk_val = "selected"; + $pickcount++; + }else{ + $chk_val = ''; + } + if(isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate'){ + $options[] = array(htmlentities(getTranslatedString($pickListValue),ENT_QUOTES,$default_charset),$pickListValue,$chk_val ); + }else{ + $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val); + } + } + if($pickcount == 0 && $salt_value != ''){ + $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'],$salt_value,'selected'); + } + $fieldvalue [] = $options; + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $value; + }elseif($uitype == 59){ + if($_REQUEST['module'] == 'HelpDesk') + { + if(isset($_REQUEST['product_id']) & $_REQUEST['product_id'] != '') + $value = $_REQUEST['product_id']; + } + elseif(isset($_REQUEST['parent_id']) & $_REQUEST['parent_id'] != '') + $value = $_REQUEST['parent_id']; + + if($value != '') + { + $product_name = getProductName($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[]=$product_name; + $fieldvalue[]=$value; + } + elseif($uitype == 63) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + if($value=='') + $value=1; + $options = array(); + $pick_query="select * from vtiger_duration_minutes order by sortorderid"; + $pickListResult = $adb->pquery($pick_query, array()); + $noofpickrows = $adb->num_rows($pickListResult); + $salt_value = $col_fields["duration_minutes"]; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,"duration_minutes"); + + if($salt_value == $pickListValue) + { + $chk_val = "selected"; + } + else + { + $chk_val = ''; + } + $options[$pickListValue] = $chk_val; + } + $fieldvalue[]=$value; + $fieldvalue[]=$options; + } + elseif($uitype == 64) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + $fieldvalue[] = $value; + } + elseif($uitype == 156) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $value; + $fieldvalue[] = $is_admin; + } + elseif($uitype == 56) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $value; + } + elseif($uitype == 57){ + if($value != ''){ + $contact_name = getContactName($value); + }elseif(isset($_REQUEST['contact_id']) && $_REQUEST['contact_id'] != ''){ + if($_REQUEST['module'] == 'Contacts' && $fieldname = 'contact_id'){ + $contact_name = ''; + }else{ + $value = $_REQUEST['contact_id']; + $contact_name = getContactName($value); + } + + } + + //Checking for contacts duplicate + + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $contact_name; + $fieldvalue[] = $value; + } + + elseif($uitype == 58) + { + + if($value != '') + { + $campaign_name = getCampaignName($value); + } + elseif(isset($_REQUEST['campaignid']) && $_REQUEST['campaignid'] != '') + { + if($_REQUEST['module'] == 'Campaigns' && $fieldname = 'campaignid') + { + $campaign_name = ''; + } + else + { + $value = $_REQUEST['campaignid']; + $campaign_name = getCampaignName($value); + } + + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[]=$campaign_name; + $fieldvalue[] = $value; + } + + elseif($uitype == 61) + { + if($value != '') + { + $assigned_user_id = $value; + } + else + { + $assigned_user_id = $current_user->id; + } + if($module_name == 'Emails' && $col_fields['record_id'] != '') + { + $attach_result = $adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])); + //to fix the issue in mail attachment on forwarding mails + if(isset($_REQUEST['forward']) && $_REQUEST['forward'] != '') + global $att_id_list; + for($ii=0;$ii < $adb->num_rows($attach_result);$ii++) + { + $attachmentid = $adb->query_result($attach_result,$ii,'attachmentsid'); + if($attachmentid != '') + { + $attachquery = "select * from vtiger_attachments where attachmentsid=?"; + $attachmentsname = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); + if($attachmentsname != '') + $fieldvalue[$attachmentid] = '[ '.$attachmentsname.' ]'; + if(isset($_REQUEST['forward']) && $_REQUEST['forward'] != '') + $att_id_list .= $attachmentid.';'; + } + + } + }else + { + if($col_fields['record_id'] != '') + { + $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); + if($col_fields[$fieldname] == '' && $attachmentid != '') + { + $attachquery = "select * from vtiger_attachments where attachmentsid=?"; + $value = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); + } + } + if($value!='') + $filename=' [ '.$value. ' ]'; + + if($filename != '') + $fieldvalue[] = $filename; + if($value != '') + $fieldvalue[] = $value; + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + } + elseif($uitype == 28){ + if($col_fields['record_id'] != '') + { + $attachmentid=$adb->query_result($adb->pquery("select * from vtiger_seattachmentsrel where crmid = ?", array($col_fields['record_id'])),0,'attachmentsid'); + if($col_fields[$fieldname] == '' && $attachmentid != '') + { + $attachquery = "select * from vtiger_attachments where attachmentsid=?"; + $value = $adb->query_result($adb->pquery($attachquery, array($attachmentid)),0,'name'); + } + } + if($value!='' && $module_name != 'Documents') + $filename=' [ '.$value. ' ]'; + elseif($value != '' && $module_name == 'Documents') + $filename= $value; + if($filename != '') + $fieldvalue[] = $filename; + if($value != '') + $fieldvalue[] = $value; + + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + } + elseif($uitype == 69) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + if( $col_fields['record_id'] != "") + { + //This query is for Products only + if($module_name == 'Products') + { + $query = 'select vtiger_attachments.path, vtiger_attachments.attachmentsid, vtiger_attachments.name ,vtiger_crmentity.setype from vtiger_products left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_products.productid inner join vtiger_attachments on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_attachments.attachmentsid where vtiger_crmentity.setype="Products Image" and productid=?'; + } + else + { + $query="select vtiger_attachments.*,vtiger_crmentity.setype from vtiger_attachments inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_attachments.attachmentsid where vtiger_crmentity.setype='Contacts Image' and vtiger_seattachmentsrel.crmid=?"; + } + $result_image = $adb->pquery($query, array($col_fields['record_id'])); + for($image_iter=0;$image_iter < $adb->num_rows($result_image);$image_iter++) + { + $image_id_array[] = $adb->query_result($result_image,$image_iter,'attachmentsid'); + + //decode_html - added to handle UTF-8 characters in file names + //urlencode - added to handle special characters like #, %, etc., + $image_array[] = urlencode(decode_html($adb->query_result($result_image,$image_iter,'name'))); + $image_orgname_array[] = decode_html($adb->query_result($result_image,$image_iter,'name')); + + $image_path_array[] = $adb->query_result($result_image,$image_iter,'path'); + } + if(is_array($image_array)) + for($img_itr=0;$img_itr$image_array[$img_itr],'path'=>$image_path_array[$img_itr].$image_id_array[$img_itr]."_","orgname"=>$image_orgname_array[$img_itr]); + } + else + $fieldvalue[] = ''; + } + else + $fieldvalue[] = ''; + } + elseif($uitype == 62) + { + if(isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') + $value = $_REQUEST['parent_id']; + if($value != '') + $parent_module = getSalesEntityType($value); + if(isset($_REQUEST['account_id']) && $_REQUEST['account_id'] != '') + { + $parent_module = "Accounts"; + $value = $_REQUEST['account_id']; + } + if($parent_module != 'Contacts') + { + if($parent_module == "Leads") + { + $parent_name = getLeadName($value); + $lead_selected = "selected"; + + } + elseif($parent_module == "Accounts") + { + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"accountname"); + $account_selected = "selected"; + + } + elseif($parent_module == "Potentials") + { + $sql = "select * from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"potentialname"); + $potential_selected = "selected"; + + } + elseif($parent_module == "Products") + { + $sql = "select * from vtiger_products where productid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name= $adb->query_result($result,0,"productname"); + $product_selected = "selected"; + + } + elseif($parent_module == "PurchaseOrder") + { + $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name= $adb->query_result($result,0,"subject"); + $porder_selected = "selected"; + + } + elseif($parent_module == "SalesOrder") + { + $sql = "select * from vtiger_salesorder where salesorderid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name= $adb->query_result($result,0,"subject"); + $sorder_selected = "selected"; + + } + elseif($parent_module == "Invoice") + { + $sql = "select * from vtiger_invoice where invoiceid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name= $adb->query_result($result,0,"subject"); + $invoice_selected = "selected"; + } + elseif($parent_module == "Quotes") + { + $sql = "select * from vtiger_quotes where quoteid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name= $adb->query_result($result,0,"subject"); + $quote_selected = "selected"; + }elseif($parent_module == "HelpDesk") + { + $sql = "select * from vtiger_troubletickets where ticketid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name= $adb->query_result($result,0,"title"); + $ticket_selected = "selected"; + } + } + $editview_label[] = array($app_strings['COMBO_LEADS'], + $app_strings['COMBO_ACCOUNTS'], + $app_strings['COMBO_POTENTIALS'], + $app_strings['COMBO_PRODUCTS'], + $app_strings['COMBO_INVOICES'], + $app_strings['COMBO_PORDER'], + $app_strings['COMBO_SORDER'], + $app_strings['COMBO_QUOTES'], + $app_strings['COMBO_HELPDESK'] + ); + $editview_label[] = array($lead_selected, + $account_selected, + $potential_selected, + $product_selected, + $invoice_selected, + $porder_selected, + $sorder_selected, + $quote_selected, + $ticket_selected + ); + $editview_label[] = array("Leads&action=Popup","Accounts&action=Popup","Potentials&action=Popup","Products&action=Popup","Invoice&action=Popup","PurchaseOrder&action=Popup","SalesOrder&action=Popup","Quotes&action=Popup","HelpDesk&action=Popup"); + $fieldvalue[] =$parent_name; + $fieldvalue[] =$value; + + } + elseif($uitype == 66) + { + if(isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') + $value = $_REQUEST['parent_id']; + if($value != '') + $parent_module = getSalesEntityType($value); + // Check for vtiger_activity type if task orders to be added in select option + $act_mode = $_REQUEST['activity_mode']; + + if($parent_module != "Contacts") + { + if($parent_module == "Leads") + { + $parent_name = getLeadName($value); + $lead_selected = "selected"; + + } + elseif($parent_module == "Accounts") + { + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"accountname"); + $account_selected = "selected"; + + } + elseif($parent_module == "Potentials") + { + $sql = "select * from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"potentialname"); + $potential_selected = "selected"; + + } + elseif($parent_module == "HelpDesk") + { + $sql = "select title from vtiger_troubletickets where ticketid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"title"); + $ticket_selected = "selected"; + } + + elseif($act_mode == "Task") + { + if($parent_module == "PurchaseOrder") + { + $sql = "select * from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"subject"); + $purchase_selected = "selected"; + } + if($parent_module == "SalesOrder") + { + $sql = "select * from vtiger_salesorder where salesorderid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"subject"); + $sales_selected = "selected"; + } + if($parent_module == "Invoice") + { + $sql = "select * from vtiger_invoice where invoiceid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"subject"); + $invoice_selected = "selected"; + } + if($parent_module == "Campaigns") + { + $sql = "select campaignname from vtiger_campaign where campaignid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"campaignname"); + $campaign_selected = "selected"; + } + if($parent_module == "Quotes") + { + $sql = "select * from vtiger_quotes where quoteid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"subject"); + $quote_selected = "selected"; + } + } + $fieldvalue[] =$parent_name; + $fieldvalue[] = $value; + } + $editview_label[0] = array( + $app_strings['COMBO_LEADS'], + $app_strings['COMBO_ACCOUNTS'], + $app_strings['COMBO_POTENTIALS'], + ); + $editview_label[1] = array( + $lead_selected, + $account_selected, + $potential_selected + ); + $editview_label[2] = array( + "Leads&action=Popup", + "Accounts&action=Popup", + "Potentials&action=Popup" + ); + + if($act_mode == "Task") + { + array_push($editview_label[0], + $app_strings['COMBO_QUOTES'], + $app_strings['COMBO_PORDER'], + $app_strings['COMBO_SORDER'], + $app_strings['COMBO_INVOICES'], + $app_strings['COMBO_CAMPAIGNS'], + $app_strings['COMBO_HELPDESK'] + ); + array_push($editview_label[1], + $quote_selected, + $purchase_selected, + $sales_selected, + $invoice_selected, + $campaign_selected, + $ticket_selected + ); + array_push($editview_label[2],"Quotes&action=Popup","PurchaseOrder&action=Popup","SalesOrder&action=Popup","Invoice&action=Popup","Campaigns&action=Popup","HelpDesk&action=Popup"); + } + elseif($act_mode == "Events") + { + array_push($editview_label[0],$app_strings['COMBO_HELPDESK']); + array_push($editview_label[1],$ticket_selected); + array_push($editview_label[2],"HelpDesk&action=Popup"); + } + } + //added by rdhital/Raju for better email support + elseif($uitype == 357) + { + $pmodule = $_REQUEST['pmodule']; + if(empty($pmodule)) + $pmodule = $_REQUEST['par_module']; + + if($pmodule == 'Contacts') + { + $contact_selected = 'selected'; + } + elseif($pmodule == 'Accounts') + { + $account_selected = 'selected'; + } + elseif($pmodule == 'Leads') + { + $lead_selected = 'selected'; + } + elseif($pmodule == 'Vendors') + { + $vendor_selected = 'selected'; + } + elseif($pmodule == 'Users') + { + $user_selected = 'selected'; + } + if(isset($_REQUEST['emailids']) && $_REQUEST['emailids'] != '') + { + $parent_id = $_REQUEST['emailids']; + $parent_name=''; + + $myids=explode("|",$parent_id); + for ($i=0;$i<(count($myids)-1);$i++) + { + $realid=explode("@",$myids[$i]); + $entityid=$realid[0]; + $nemail=count($realid); + + if ($pmodule=='Accounts'){ + require_once('modules/Accounts/Accounts.php'); + $myfocus = new Accounts(); + $myfocus->retrieve_entity_info($entityid,"Accounts"); + $fullname=br2nl($myfocus->column_fields['accountname']); + $account_selected = 'selected'; + } + elseif ($pmodule=='Contacts'){ + require_once('modules/Contacts/Contacts.php'); + $myfocus = new Contacts(); + $myfocus->retrieve_entity_info($entityid,"Contacts"); + $fname=br2nl($myfocus->column_fields['firstname']); + $lname=br2nl($myfocus->column_fields['lastname']); + $fullname=$lname.' '.$fname; + $contact_selected = 'selected'; + } + elseif ($pmodule=='Leads'){ + require_once('modules/Leads/Leads.php'); + $myfocus = new Leads(); + $myfocus->retrieve_entity_info($entityid,"Leads"); + $fname=br2nl($myfocus->column_fields['firstname']); + $lname=br2nl($myfocus->column_fields['lastname']); + $fullname=$lname.' '.$fname; + $lead_selected = 'selected'; + } + for ($j=1;$j<$nemail;$j++){ + $querystr='select columnname from vtiger_field where fieldid=? and vtiger_field.presence in (0,2)'; + $result=$adb->pquery($querystr, array($realid[$j])); + $temp=$adb->query_result($result,0,'columnname'); + $temp1=br2nl($myfocus->column_fields[$temp]); + + //Modified to display the entities in red which don't have email id + if(!empty($temp_parent_name) && strlen($temp_parent_name) > 150) + { + $parent_name .= '
'; + $temp_parent_name = ''; + } + + if($temp1 != '') + { + $parent_name .= $fullname.'<'.$temp1.'>; '; + $temp_parent_name .= $fullname.'<'.$temp1.'>; '; + } + else + { + $parent_name .= "".$fullname.'<'.$temp1.'>; '.""; + $temp_parent_name .= "".$fullname.'<'.$temp1.'>; '.""; + } + + } + } + } + else + { + if($_REQUEST['record'] != '' && $_REQUEST['record'] != NULL) + { + $parent_name=''; + $parent_id=''; + $myemailid= $_REQUEST['record']; + $mysql = "select crmid from vtiger_seactivityrel where activityid=?"; + $myresult = $adb->pquery($mysql, array($myemailid)); + $mycount=$adb->num_rows($myresult); + if($mycount >0) + { + for ($i=0;$i<$mycount;$i++) + { + $mycrmid=$adb->query_result($myresult,$i,'crmid'); + $parent_module = getSalesEntityType($mycrmid); + if($parent_module == "Leads") + { + $sql = "select firstname,lastname,email from vtiger_leaddetails where leadid=?"; + $result = $adb->pquery($sql, array($mycrmid)); + $full_name = getFullNameFromQResult($result,0,"Leads"); + $myemail=$adb->query_result($result,0,"email"); + $parent_id .=$mycrmid.'@0|' ; //make it such that the email adress sent is remebered and only that one is retrived + $parent_name .= $full_name.'<'.$myemail.'>; '; + $lead_selected = 'selected'; + } + elseif($parent_module == "Contacts") + { + $sql = "select * from vtiger_contactdetails where contactid=?"; + $result = $adb->pquery($sql, array($mycrmid)); + $full_name = getFullNameFromQResult($result,0,"Contacts"); + $myemail=$adb->query_result($result,0,"email"); + $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived + $parent_name .= $full_name.'<'.$myemail.'>; '; + $contact_selected = 'selected'; + } + elseif($parent_module == "Accounts") + { + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($mycrmid)); + $account_name = $adb->query_result($result,0,"accountname"); + $myemail=$adb->query_result($result,0,"email1"); + $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived + $parent_name .= $account_name.'<'.$myemail.'>; '; + $account_selected = 'selected'; + }elseif($parent_module == "Users") + { + $sql = "select user_name,email1 from vtiger_users where id=?"; + $result = $adb->pquery($sql, array($mycrmid)); + $account_name = $adb->query_result($result,0,"user_name"); + $myemail=$adb->query_result($result,0,"email1"); + $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived + $parent_name .= $account_name.'<'.$myemail.'>; '; + $user_selected = 'selected'; + } + elseif($parent_module == "Vendors") + { + $sql = "select * from vtiger_vendor where vendorid=?"; + $result = $adb->pquery($sql, array($mycrmid)); + $vendor_name = $adb->query_result($result,0,"vendorname"); + $myemail=$adb->query_result($result,0,"email"); + $parent_id .=$mycrmid.'@0|' ;//make it such that the email adress sent is remebered and only that one is retrived + $parent_name .= $vendor_name.'<'.$myemail.'>; '; + $vendor_selected = 'selected'; + } + } + } + } + $custfld .= ''.$app_strings['To'].' '; + $custfld .= ' Selectdebug("Exiting getOutputHtml method ..."); return window.open("index.php?module="+ document.EditView.parent_type.value +"&action=Popup&popuptype=set_$log->debug("Exiting getOutputHtml method ..."); return_emails&form=EmailEditView&form_submit=false","test","width=600,height=400,resizable=1,scrollbars=1,top=150,left=200");\' align="absmiddle" style=\'cursor:hand;cursor:pointer\'> '; + $editview_label[] = array( + 'Contacts'=>$contact_selected, + 'Accounts'=>$account_selected, + 'Vendors'=>$vendor_selected, + 'Leads'=>$lead_selected, + 'Users'=>$user_selected + ); + $fieldvalue[] =$parent_name; + $fieldvalue[] = $parent_id; + } + } + //end of rdhital/Raju + elseif($uitype == 68) + { + if(isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') + $value = $_REQUEST['parent_id']; + + if($value != '') + { + $parent_module = getSalesEntityType($value); + if($parent_module == "Contacts") + { + $parent_name = getContactName($value); + $contact_selected = "selected"; + + } + elseif($parent_module == "Accounts") + { + $sql = "select * from vtiger_account where accountid=?"; + $result = $adb->pquery($sql, array($value)); + $parent_name = $adb->query_result($result,0,"accountname"); + $account_selected = "selected"; + + } + else + { + $parent_name = ""; + $value = ""; + } + + } + $editview_label[] = array($app_strings['COMBO_CONTACTS'], + $app_strings['COMBO_ACCOUNTS'] + ); + $editview_label[] = array($contact_selected, + $account_selected + ); + $editview_label[] = array("Contacts","Accounts"); + $fieldvalue[] = $parent_name; + $fieldvalue[] = $value; + } + + elseif($uitype == 71 || $uitype == 72) + { + if($col_fields['record_id'] != '' && $fieldname == 'unit_price') { + $rate_symbol=getCurrencySymbolandCRate(getProductBaseCurrency($col_fields['record_id'],$module_name)); + $fieldvalue[] = $value; + } else { + $currency_id = fetchCurrency($current_user->id); + $rate_symbol=getCurrencySymbolandCRate($currency_id); + $rate = $rate_symbol['rate']; + $fieldvalue[] = convertFromDollar($value,$rate); + } + $currency = $rate_symbol['symbol']; + $editview_label[]=getTranslatedString($fieldlabel, $module_name).': ('.$currency.')'; + } + elseif($uitype == 75 || $uitype ==81) + { + if($value != '') + { + $vendor_name = getVendorName($value); + } + elseif(isset($_REQUEST['vendor_id']) && $_REQUEST['vendor_id'] != '') + { + $value = $_REQUEST['vendor_id']; + $vendor_name = getVendorName($value); + } + $pop_type = 'specific'; + if($uitype == 81) + { + $pop_type = 'specific_vendor_address'; + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $vendor_name; + $fieldvalue[] = $value; + } + elseif($uitype == 76) + { + if($value != '') + { + $potential_name = getPotentialName($value); + } + elseif(isset($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '') + { + $value = $_REQUEST['potental_id']; + $potential_name = getPotentialName($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $potential_name; + $fieldvalue[] = $value; + } + elseif($uitype == 78) + { + if($value != '') + { + $quote_name = getQuoteName($value); + } + elseif(isset($_REQUEST['quote_id']) && $_REQUEST['quote_id'] != '') + { + $value = $_REQUEST['quote_id']; + $potential_name = getQuoteName($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $quote_name; + $fieldvalue[] = $value; + } + elseif($uitype == 79) + { + if($value != '') + { + $purchaseorder_name = getPoName($value); + } + elseif(isset($_REQUEST['purchaseorder_id']) && $_REQUEST['purchaseorder_id'] != '') + { + $value = $_REQUEST['purchaseorder_id']; + $purchaseorder_name = getPoName($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $purchaseorder_name; + $fieldvalue[] = $value; + } + elseif($uitype == 80) + { + if($value != '') + { + $salesorder_name = getSoName($value); + } + elseif(isset($_REQUEST['salesorder_id']) && $_REQUEST['salesorder_id'] != '') + { + $value = $_REQUEST['salesorder_id']; + $salesorder_name = getSoName($value); + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $salesorder_name; + $fieldvalue[] = $value; + } + elseif($uitype == 30) + { + $rem_days = 0; + $rem_hrs = 0; + $rem_min = 0; + if($value!='') + $SET_REM = "CHECKED"; + $rem_days = floor($col_fields[$fieldname]/(24*60)); + $rem_hrs = floor(($col_fields[$fieldname]-$rem_days*24*60)/60); + $rem_min = ($col_fields[$fieldname]-$rem_days*24*60)%60; + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $day_options = getReminderSelectOption(0,31,'remdays',$rem_days); + $hr_options = getReminderSelectOption(0,23,'remhrs',$rem_hrs); + $min_options = getReminderSelectOption(1,59,'remmin',$rem_min); + $fieldvalue[] = array(array(0,32,'remdays',getTranslatedString('LBL_DAYS'),$rem_days),array(0,24,'remhrs',getTranslatedString('LBL_HOURS'),$rem_hrs),array(1,60,'remmin',getTranslatedString('LBL_MINUTES').'  '.getTranslatedString('LBL_BEFORE_EVENT'),$rem_min)); + $fieldvalue[] = array($SET_REM,getTranslatedString('LBL_YES'),getTranslatedString('LBL_NO')); + $SET_REM = ''; + } + elseif($uitype == 115) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $pick_query="select * from vtiger_" . $adb->sql_escape_string($fieldname); + $pickListResult = $adb->pquery($pick_query, array()); + $noofpickrows = $adb->num_rows($pickListResult); + + //Mikecrowe fix to correctly default for custom pick lists + $options = array(); + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,strtolower($fieldname)); + + if($value == $pickListValue) + { + $chk_val = "selected"; + $found = true; + } + else + { + $chk_val = ''; + } + $options[] = array(getTranslatedString($pickListValue),$pickListValue,$chk_val ); + } + $fieldvalue [] = $options; + $fieldvalue [] = $is_admin; + } + elseif($uitype == 116 || $uitype == 117) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $pick_query="select * from vtiger_currency_info where currency_status = 'Active' and deleted=0"; + $pickListResult = $adb->pquery($pick_query, array()); + $noofpickrows = $adb->num_rows($pickListResult); + + //Mikecrowe fix to correctly default for custom pick lists + $options = array(); + $found = false; + for($j = 0; $j < $noofpickrows; $j++) + { + $pickListValue=$adb->query_result($pickListResult,$j,'currency_name'); + $currency_id=$adb->query_result($pickListResult,$j,'id'); + if($value == $currency_id) + { + $chk_val = "selected"; + $found = true; + } + else + { + $chk_val = ''; + } + $options[$currency_id] = array($pickListValue=>$chk_val ); + } + $fieldvalue [] = $options; + $fieldvalue [] = $is_admin; + } + elseif($uitype ==98) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[]=$value; + $fieldvalue[]=getRoleName($value); + $fieldvalue[]=$is_admin; + } + elseif($uitype == 105) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + if( isset( $col_fields['record_id']) && $col_fields['record_id'] != '') { + $query = "select vtiger_attachments.path, vtiger_attachments.name from vtiger_contactdetails left join vtiger_seattachmentsrel on vtiger_seattachmentsrel.crmid=vtiger_contactdetails.contactid inner join vtiger_attachments on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid where vtiger_contactdetails.imagename=vtiger_attachments.name and contactid=?"; + $result_image = $adb->pquery($query, array($col_fields['record_id'])); + for($image_iter=0;$image_iter < $adb->num_rows($result_image);$image_iter++) + { + $image_array[] = $adb->query_result($result_image,$image_iter,'name'); + $image_path_array[] = $adb->query_result($result_image,$image_iter,'path'); + } + } + if(is_array($image_array)) + for($img_itr=0;$img_itr$image_array[$img_itr],'path'=>$image_path_array[$img_itr]); + } + else + $fieldvalue[] = ''; + }elseif($uitype == 101) + { + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = getUserName($value); + $fieldvalue[] = $value; + } + elseif($uitype == 26){ + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + $folderid=$col_fields['folderid']; + $foldername_query = 'select foldername from vtiger_attachmentsfolder where folderid = ?'; + $res = $adb->pquery($foldername_query,array($folderid)); + $foldername = $adb->query_result($res,0,'foldername'); + if($foldername != '' && $folderid != ''){ + $fldr_name[$folderid]=$foldername; + } + $sql="select foldername,folderid from vtiger_attachmentsfolder order by foldername"; + $res=$adb->pquery($sql,array()); + for($i=0;$i<$adb->num_rows($res);$i++) + { + $fid=$adb->query_result($res,$i,"folderid"); + $fldr_name[$fid]=$adb->query_result($res,$i,"foldername"); + } + $fieldvalue[] = $fldr_name; + } + elseif($uitype == 27){ + if($value == 'I'){ + $internal_selected = "selected"; + $filename = $col_fields['filename']; + } + else{ + $external_selected = "selected"; + $filename = $col_fields['filename']; + } + $editview_label[] = array(getTranslatedString('Internal'), + getTranslatedString('External') + ); + $editview_label[] = array($internal_selected, + $external_selected + ); + $editview_label[] = array("I","E"); + $editview_label[] = getTranslatedString($fieldlabel, $module_name); + $fieldvalue[] = $value; + $fieldvalue[] = $filename; + } + else + { + //Added condition to set the subject if click Reply All from web mail + if($_REQUEST['module'] == 'Emails' && $_REQUEST['mg_subject'] != '') + { + $value = $_REQUEST['mg_subject']; + } + $editview_label[]=getTranslatedString($fieldlabel, $module_name); + if($uitype == 1 && ($fieldname=='expectedrevenue' || $fieldname=='budgetcost' || $fieldname=='actualcost' || $fieldname=='expectedroi' || $fieldname=='actualroi' ) && ($module_name=='Campaigns')) + { + $rate_symbol = getCurrencySymbolandCRate($user_info['currency_id']); + $fieldvalue[] = convertFromDollar($value,$rate_symbol['rate']); + } + elseif($fieldname == 'fileversion'){ + if(empty($value)){ + $value = ''; + } + else{ + $fieldvalue[] = $value; + } + } + else + $fieldvalue[] = $value; + } + + // Mike Crowe Mod --------------------------------------------------------force numerics right justified. + if ( !preg_match("/id=/i",$custfld) ) + $custfld = preg_replace("/debug("Exiting getOutputHtml method ..."); + return $final_arr; +} + +/** This function returns the vtiger_invoice object populated with the details from sales order object. +* Param $focus - Invoice object +* Param $so_focus - Sales order focus +* Param $soid - sales order id +* Return type is an object array +*/ + +function getConvertSoToInvoice($focus,$so_focus,$soid) +{ + global $log,$current_user; + $log->debug("Entering getConvertSoToInvoice(".get_class($focus).",".get_class($so_focus).",".$soid.") method ..."); + $log->info("in getConvertSoToInvoice ".$soid); + $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); + for($i=0;$iid,$xyz[$i]) == '0'){ + $so_focus->column_fields[$xyz[$i]] = $so_focus->column_fields[$xyz[$i]]; + } + else + $so_focus->column_fields[$xyz[$i]] = ''; + } + $focus->column_fields['salesorder_id'] = $soid; + $focus->column_fields['subject'] = $so_focus->column_fields['subject']; + $focus->column_fields['customerno'] = $so_focus->column_fields['customerno']; + $focus->column_fields['duedate'] = $so_focus->column_fields['duedate']; + $focus->column_fields['contact_id'] = $so_focus->column_fields['contact_id'];//to include contact name in Invoice + $focus->column_fields['account_id'] = $so_focus->column_fields['account_id']; + $focus->column_fields['exciseduty'] = $so_focus->column_fields['exciseduty']; + $focus->column_fields['salescommission'] = $so_focus->column_fields['salescommission']; + $focus->column_fields['purchaseorder'] = $so_focus->column_fields['purchaseorder']; + $focus->column_fields['bill_street'] = $so_focus->column_fields['bill_street']; + $focus->column_fields['ship_street'] = $so_focus->column_fields['ship_street']; + $focus->column_fields['bill_city'] = $so_focus->column_fields['bill_city']; + $focus->column_fields['ship_city'] = $so_focus->column_fields['ship_city']; + $focus->column_fields['bill_state'] = $so_focus->column_fields['bill_state']; + $focus->column_fields['ship_state'] = $so_focus->column_fields['ship_state']; + $focus->column_fields['bill_code'] = $so_focus->column_fields['bill_code']; + $focus->column_fields['ship_code'] = $so_focus->column_fields['ship_code']; + $focus->column_fields['bill_country'] = $so_focus->column_fields['bill_country']; + $focus->column_fields['ship_country'] = $so_focus->column_fields['ship_country']; + $focus->column_fields['bill_pobox'] = $so_focus->column_fields['bill_pobox']; + $focus->column_fields['ship_pobox'] = $so_focus->column_fields['ship_pobox']; + $focus->column_fields['description'] = $so_focus->column_fields['description']; + $focus->column_fields['terms_conditions'] = $so_focus->column_fields['terms_conditions']; + $focus->column_fields['currency_id'] = $so_focus->column_fields['currency_id']; + $focus->column_fields['conversion_rate'] = $so_focus->column_fields['conversion_rate']; + + $log->debug("Exiting getConvertSoToInvoice method ..."); + return $focus; + +} + +/** This function returns the vtiger_invoice object populated with the details from quote object. +* Param $focus - Invoice object +* Param $quote_focus - Quote order focus +* Param $quoteid - quote id +* Return type is an object array +*/ + + +function getConvertQuoteToInvoice($focus,$quote_focus,$quoteid) +{ + global $log,$current_user; + $log->debug("Entering getConvertQuoteToInvoice(".get_class($focus).",".get_class($quote_focus).",".$quoteid.") method ..."); + $log->info("in getConvertQuoteToInvoice ".$quoteid); + $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); + for($i=0;$i<12;$i++){ + if (getFieldVisibilityPermission('Quotes', $current_user->id,$xyz[$i]) == '0'){ + $quote_focus->column_fields[$xyz[$i]] = $quote_focus->column_fields[$xyz[$i]]; + } + else + $quote_focus->column_fields[$xyz[$i]] = ''; + } + $focus->column_fields['subject'] = $quote_focus->column_fields['subject']; + $focus->column_fields['account_id'] = $quote_focus->column_fields['account_id']; + $focus->column_fields['bill_street'] = $quote_focus->column_fields['bill_street']; + $focus->column_fields['ship_street'] = $quote_focus->column_fields['ship_street']; + $focus->column_fields['bill_city'] = $quote_focus->column_fields['bill_city']; + $focus->column_fields['ship_city'] = $quote_focus->column_fields['ship_city']; + $focus->column_fields['bill_state'] = $quote_focus->column_fields['bill_state']; + $focus->column_fields['ship_state'] = $quote_focus->column_fields['ship_state']; + $focus->column_fields['bill_code'] = $quote_focus->column_fields['bill_code']; + $focus->column_fields['ship_code'] = $quote_focus->column_fields['ship_code']; + $focus->column_fields['bill_country'] = $quote_focus->column_fields['bill_country']; + $focus->column_fields['ship_country'] = $quote_focus->column_fields['ship_country']; + $focus->column_fields['bill_pobox'] = $quote_focus->column_fields['bill_pobox']; + $focus->column_fields['ship_pobox'] = $quote_focus->column_fields['ship_pobox']; + $focus->column_fields['description'] = $quote_focus->column_fields['description']; + $focus->column_fields['terms_conditions'] = $quote_focus->column_fields['terms_conditions']; + $focus->column_fields['currency_id'] = $quote_focus->column_fields['currency_id']; + $focus->column_fields['conversion_rate'] = $quote_focus->column_fields['conversion_rate']; + + $log->debug("Exiting getConvertQuoteToInvoice method ..."); + return $focus; + +} + +/** This function returns the sales order object populated with the details from quote object. +* Param $focus - Sales order object +* Param $quote_focus - Quote order focus +* Param $quoteid - quote id +* Return type is an object array +*/ + +function getConvertQuoteToSoObject($focus,$quote_focus,$quoteid) +{ + global $log,$current_user; + $log->debug("Entering getConvertQuoteToSoObject(".get_class($focus).",".get_class($quote_focus).",".$quoteid.") method ..."); + $log->info("in getConvertQuoteToSoObject ".$quoteid); + $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); + for($i=0;$i<12;$i++){ + if (getFieldVisibilityPermission('Quotes', $current_user->id,$xyz[$i]) == '0'){ + $quote_focus->column_fields[$xyz[$i]] = $quote_focus->column_fields[$xyz[$i]]; + } + else + $quote_focus->column_fields[$xyz[$i]] = ''; + } + $focus->column_fields['quote_id'] = $quoteid; + $focus->column_fields['subject'] = $quote_focus->column_fields['subject']; + $focus->column_fields['contact_id'] = $quote_focus->column_fields['contact_id']; + $focus->column_fields['potential_id'] = $quote_focus->column_fields['potential_id']; + $focus->column_fields['account_id'] = $quote_focus->column_fields['account_id']; + $focus->column_fields['carrier'] = $quote_focus->column_fields['carrier']; + $focus->column_fields['bill_street'] = $quote_focus->column_fields['bill_street']; + $focus->column_fields['ship_street'] = $quote_focus->column_fields['ship_street']; + $focus->column_fields['bill_city'] = $quote_focus->column_fields['bill_city']; + $focus->column_fields['ship_city'] = $quote_focus->column_fields['ship_city']; + $focus->column_fields['bill_state'] = $quote_focus->column_fields['bill_state']; + $focus->column_fields['ship_state'] = $quote_focus->column_fields['ship_state']; + $focus->column_fields['bill_code'] = $quote_focus->column_fields['bill_code']; + $focus->column_fields['ship_code'] = $quote_focus->column_fields['ship_code']; + $focus->column_fields['bill_country'] = $quote_focus->column_fields['bill_country']; + $focus->column_fields['ship_country'] = $quote_focus->column_fields['ship_country']; + $focus->column_fields['bill_pobox'] = $quote_focus->column_fields['bill_pobox']; + $focus->column_fields['ship_pobox'] = $quote_focus->column_fields['ship_pobox']; + $focus->column_fields['description'] = $quote_focus->column_fields['description']; + $focus->column_fields['terms_conditions'] = $quote_focus->column_fields['terms_conditions']; + $focus->column_fields['currency_id'] = $quote_focus->column_fields['currency_id']; + $focus->column_fields['conversion_rate'] = $quote_focus->column_fields['conversion_rate']; + + $log->debug("Exiting getConvertQuoteToSoObject method ..."); + return $focus; + +} + +/** This function returns the detailed list of vtiger_products associated to a given entity or a record. +* Param $module - module name +* Param $focus - module object +* Param $seid - sales entity id +* Return type is an object array +*/ + + +function getAssociatedProducts($module,$focus,$seid='') +{ + global $log; + $log->debug("Entering getAssociatedProducts(".$module.",".get_class($focus).",".$seid."='') method ..."); + global $adb; + $output = ''; + global $theme,$current_user; + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + $product_Detail = Array(); + + // DG 15 Aug 2006 + // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items + + if($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') + { + $query="SELECT + case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname, + case when vtiger_products.productid != '' then vtiger_products.productcode else vtiger_service.service_no end as productcode, + case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price, + case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, + case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype, + vtiger_inventoryproductrel.listprice, + vtiger_inventoryproductrel.description AS product_description, + vtiger_inventoryproductrel.* + FROM vtiger_inventoryproductrel + LEFT JOIN vtiger_products + ON vtiger_products.productid=vtiger_inventoryproductrel.productid + LEFT JOIN vtiger_service + ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid + WHERE id=? + ORDER BY sequence_no"; + $params = array($focus->id); + } + elseif($module == 'Potentials') + { + $query="SELECT + vtiger_products.productname, + vtiger_products.productcode, + vtiger_products.unit_price, + vtiger_products.qtyinstock, + vtiger_seproductsrel.*, + vtiger_crmentity.description AS product_description + FROM vtiger_products + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid=vtiger_products.productid + INNER JOIN vtiger_seproductsrel + ON vtiger_seproductsrel.productid=vtiger_products.productid + WHERE vtiger_seproductsrel.crmid=?"; + $params = array($seid); + } + elseif($module == 'Products') + { + $query="SELECT + vtiger_products.productid, + vtiger_products.productcode, + vtiger_products.productname, + vtiger_products.unit_price, + vtiger_products.qtyinstock, + vtiger_crmentity.description AS product_description, + 'Products' AS entitytype + FROM vtiger_products + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid=vtiger_products.productid + WHERE vtiger_crmentity.deleted=0 + AND productid=?"; + $params = array($seid); + } + elseif($module == 'Services') + { + $query="SELECT + vtiger_service.serviceid AS productid, + 'NA' AS productcode, + vtiger_service.servicename AS productname, + vtiger_service.unit_price AS unit_price, + 'NA' AS qtyinstock, + vtiger_crmentity.description AS product_description, + 'Services' AS entitytype + FROM vtiger_service + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid=vtiger_service.serviceid + WHERE vtiger_crmentity.deleted=0 + AND serviceid=?"; + $params = array($seid); + } + + $result = $adb->pquery($query, $params); + $num_rows=$adb->num_rows($result); + for($i=1;$i<=$num_rows;$i++) + { + $hdnProductId = $adb->query_result($result,$i-1,'productid'); + $hdnProductcode = $adb->query_result($result,$i-1,'productcode'); + $productname=$adb->query_result($result,$i-1,'productname'); + $productdescription=$adb->query_result($result,$i-1,'product_description'); + $comment=$adb->query_result($result,$i-1,'comment'); + $qtyinstock=$adb->query_result($result,$i-1,'qtyinstock'); + $qty=$adb->query_result($result,$i-1,'quantity'); + $unitprice=$adb->query_result($result,$i-1,'unit_price'); + $listprice=$adb->query_result($result,$i-1,'listprice'); + $entitytype=$adb->query_result($result,$i-1,'entitytype'); + if (!empty($entitytype)) { + $product_Detail[$i]['entityType'.$i]=$entitytype; + } + + if($listprice == '') + $listprice = $unitprice; + if($qty =='') + $qty = 1; + + //calculate productTotal + $productTotal = $qty*$listprice; + + //Delete link in First column + if($i != 1) + { + $product_Detail[$i]['delRow'.$i]="Del"; + } + if(empty($focus->mode) && $seid!=''){ + $sub_prod_query = $adb->pquery("SELECT crmid as prod_id from vtiger_seproductsrel WHERE productid=? AND setype='Products'",array($seid)); + } else { + $sub_prod_query = $adb->pquery("SELECT productid as prod_id from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($focus->id,$i)); + } + $subprodid_str=''; + $subprodname_str=''; + $subProductArray = array(); + if($adb->num_rows($sub_prod_query)>0){ + for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ + $sprod_id = $adb->query_result($sub_prod_query,$j,'prod_id'); + $sprod_name = $subProductArray[] = getProductName($sprod_id); + $str_sep = ""; + if($j>0) $str_sep = ":"; + $subprodid_str .= $str_sep.$sprod_id; + $subprodname_str .= $str_sep." - ".$sprod_name; + } + } + + $subprodname_str = str_replace(":","
",$subprodname_str); + + $product_Detail[$i]['subProductArray'.$i] = $subProductArray; + $product_Detail[$i]['hdnProductId'.$i] = $hdnProductId; + $product_Detail[$i]['productName'.$i]= from_html($productname); + /* Added to fix the issue Product Pop-up name display*/ + if($_REQUEST['action'] == 'CreateSOPDF' || $_REQUEST['action'] == 'CreatePDF' || $_REQUEST['action'] == 'SendPDFMail') + $product_Detail[$i]['productName'.$i]= htmlspecialchars($product_Detail[$i]['productName'.$i]); + $product_Detail[$i]['hdnProductcode'.$i] = $hdnProductcode; + $product_Detail[$i]['productDescription'.$i]= from_html($productdescription); + if($module == 'Potentials' || $module == 'Products' || $module == 'Services') { + $product_Detail[$i]['comment'.$i]= $productdescription; + }else { + $product_Detail[$i]['comment'.$i]= $comment; + } + + if($module != 'PurchaseOrder' && $focus->object_name != 'Order') + { + $product_Detail[$i]['qtyInStock'.$i]=$qtyinstock; + } + $product_Detail[$i]['qty'.$i]=$qty; + $product_Detail[$i]['listPrice'.$i]=$listprice; + $product_Detail[$i]['unitPrice'.$i]=$unitprice; + $product_Detail[$i]['productTotal'.$i]=$productTotal; + $product_Detail[$i]['subproduct_ids'.$i]=$subprodid_str; + $product_Detail[$i]['subprod_names'.$i]=$subprodname_str; + $discount_percent=$adb->query_result($result,$i-1,'discount_percent'); + $discount_amount=$adb->query_result($result,$i-1,'discount_amount'); + $discountTotal = '0.00'; + //Based on the discount percent or amount we will show the discount details + + //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(for Each Product) + $product_Detail[$i]['discount_percent'.$i] = 0; + $product_Detail[$i]['discount_amount'.$i] = 0; + + if($discount_percent != 'NULL' && $discount_percent != '') + { + $product_Detail[$i]['discount_type'.$i] = "percentage"; + $product_Detail[$i]['discount_percent'.$i] = $discount_percent; + $product_Detail[$i]['checked_discount_percent'.$i] = ' checked'; + $product_Detail[$i]['style_discount_percent'.$i] = ' style="visibility:visible"'; + $product_Detail[$i]['style_discount_amount'.$i] = ' style="visibility:hidden"'; + $discountTotal = $productTotal*$discount_percent/100; + } + elseif($discount_amount != 'NULL' && $discount_amount != '') + { + $product_Detail[$i]['discount_type'.$i] = "amount"; + $product_Detail[$i]['discount_amount'.$i] = $discount_amount; + $product_Detail[$i]['checked_discount_amount'.$i] = ' checked'; + $product_Detail[$i]['style_discount_amount'.$i] = ' style="visibility:visible"'; + $product_Detail[$i]['style_discount_percent'.$i] = ' style="visibility:hidden"'; + $discountTotal = $discount_amount; + } + else + { + $product_Detail[$i]['checked_discount_zero'.$i] = ' checked'; + } + $totalAfterDiscount = $productTotal-$discountTotal; + $product_Detail[$i]['discountTotal'.$i] = $discountTotal; + $product_Detail[$i]['totalAfterDiscount'.$i] = $totalAfterDiscount; + + $taxTotal = '0.00'; + $product_Detail[$i]['taxTotal'.$i] = $taxTotal; + + //Calculate netprice + $netPrice = $totalAfterDiscount+$taxTotal; + //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module + if($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') + { + $taxtype = getInventoryTaxType($module,$focus->id); + if($taxtype == 'individual') + { + //Add the tax with product total and assign to netprice + $netPrice = $netPrice+$taxTotal; + } + } + $product_Detail[$i]['netPrice'.$i] = $netPrice; + + //First we will get all associated taxes as array + $tax_details = getTaxDetailsForProduct($hdnProductId,'all'); + //Now retrieve the tax values from the current query with the name + for($tax_count=0;$tax_countid != '') + { + if($taxtype == 'individual')//if individual then show the entered tax percentage + $tax_value = getInventoryProductTaxValue($focus->id, $hdnProductId, $tax_name); + else//if group tax then we have to show the default value when change to individual tax + $tax_value = $tax_details[$tax_count]['percentage']; + } + else//if the above function not called then assign the default associated value of the product + $tax_value = $tax_details[$tax_count]['percentage']; + + $product_Detail[$i]['taxes'][$tax_count]['taxname'] = $tax_name; + $product_Detail[$i]['taxes'][$tax_count]['taxlabel'] = $tax_label; + $product_Detail[$i]['taxes'][$tax_count]['percentage'] = $tax_value; + } + + } + + //set the taxtype + $product_Detail[1]['final_details']['taxtype'] = $taxtype; + + //Get the Final Discount, S&H charge, Tax for S&H and Adjustment values + //To set the Final Discount details + $finalDiscount = '0.00'; + $product_Detail[1]['final_details']['discount_type_final'] = 'zero'; + + $subTotal = ($focus->column_fields['hdnSubTotal'] != '')?$focus->column_fields['hdnSubTotal']:'0.00'; + + $product_Detail[1]['final_details']['hdnSubTotal'] = $subTotal; + $discountPercent = ($focus->column_fields['hdnDiscountPercent'] != '')?$focus->column_fields['hdnDiscountPercent']:'0.00'; + $discountAmount = ($focus->column_fields['hdnDiscountAmount'] != '')?$focus->column_fields['hdnDiscountAmount']:'0.00'; + + //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(For Final Discount) + $product_Detail[1]['final_details']['discount_percentage_final'] = 0; + $product_Detail[1]['final_details']['discount_amount_final'] = 0; + + if($focus->column_fields['hdnDiscountPercent'] != '0') + { + $finalDiscount = ($subTotal*$discountPercent/100); + $product_Detail[1]['final_details']['discount_type_final'] = 'percentage'; + $product_Detail[1]['final_details']['discount_percentage_final'] = $discountPercent; + $product_Detail[1]['final_details']['checked_discount_percentage_final'] = ' checked'; + $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:visible"'; + $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:hidden"'; + } + elseif($focus->column_fields['hdnDiscountAmount'] != '0') + { + $finalDiscount = $focus->column_fields['hdnDiscountAmount']; + $product_Detail[1]['final_details']['discount_type_final'] = 'amount'; + $product_Detail[1]['final_details']['discount_amount_final'] = $discountAmount; + $product_Detail[1]['final_details']['checked_discount_amount_final'] = ' checked'; + $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:visible"'; + $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:hidden"'; + } + $product_Detail[1]['final_details']['discountTotal_final'] = $finalDiscount; + + //To set the Final Tax values + //we will get all taxes. if individual then show the product related taxes only else show all taxes + //suppose user want to change individual to group or vice versa in edit time the we have to show all taxes. so that here we will store all the taxes and based on need we will show the corresponding taxes + + $taxtotal = '0.00'; + //First we should get all available taxes and then retrieve the corresponding tax values + $tax_details = getAllTaxes('available','','edit',$focus->id); + + for($tax_count=0;$tax_countquery_result($result,0,$tax_name); + else + $tax_percent = $tax_details[$tax_count]['percentage'];//$adb->query_result($result,0,$tax_name); + + if($tax_percent == '' || $tax_percent == 'NULL') + $tax_percent = '0.00'; + $taxamount = ($subTotal-$finalDiscount)*$tax_percent/100; + $taxtotal = $taxtotal + $taxamount; + $product_Detail[1]['final_details']['taxes'][$tax_count]['taxname'] = $tax_name; + $product_Detail[1]['final_details']['taxes'][$tax_count]['taxlabel'] = $tax_label; + $product_Detail[1]['final_details']['taxes'][$tax_count]['percentage'] = $tax_percent; + $product_Detail[1]['final_details']['taxes'][$tax_count]['amount'] = $taxamount; + } + $product_Detail[1]['final_details']['tax_totalamount'] = $taxtotal; + + //To set the Shipping & Handling charge + $shCharge = ($focus->column_fields['hdnS_H_Amount'] != '')?$focus->column_fields['hdnS_H_Amount']:'0.00'; + $product_Detail[1]['final_details']['shipping_handling_charge'] = $shCharge; + + //To set the Shipping & Handling tax values + //calculate S&H tax + $shtaxtotal = '0.00'; + //First we should get all available taxes and then retrieve the corresponding tax values + $shtax_details = getAllTaxes('available','sh','edit',$focus->id); + + //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table + for($shtax_count=0;$shtax_countid,$shtax_name); + } + $shtaxamount = $shCharge*$shtax_percent/100; + $shtaxtotal = $shtaxtotal + $shtaxamount; + $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxname'] = $shtax_name; + $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxlabel'] = $shtax_label; + $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['percentage'] = $shtax_percent; + $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['amount'] = $shtaxamount; + } + $product_Detail[1]['final_details']['shtax_totalamount'] = $shtaxtotal; + + //To set the Adjustment value + $adjustment = ($focus->column_fields['txtAdjustment'] != '')?$focus->column_fields['txtAdjustment']:'0.00'; + $product_Detail[1]['final_details']['adjustment'] = $adjustment; + + //To set the grand total + $grandTotal = ($focus->column_fields['hdnGrandTotal'] != '')?$focus->column_fields['hdnGrandTotal']:'0.00'; + $product_Detail[1]['final_details']['grandTotal'] = $grandTotal; + + $log->debug("Exiting getAssociatedProducts method ..."); + + return $product_Detail; + +} + +/** This function returns the no of vtiger_products associated to the given entity or a record. +* Param $module - module name +* Param $focus - module object +* Param $seid - sales entity id +* Return type is an object array +*/ + +function getNoOfAssocProducts($module,$focus,$seid='') +{ + global $log; + $log->debug("Entering getNoOfAssocProducts(".$module.",".get_class($focus).",".$seid."='') method ..."); + global $adb; + $output = ''; + if($module == 'Quotes') + { + $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; + $params = array($focus->id); + } + elseif($module == 'PurchaseOrder') + { + $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; + $params = array($focus->id); + } + elseif($module == 'SalesOrder') + { + $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; + $params = array($focus->id); + } + elseif($module == 'Invoice') + { + $query="select vtiger_products.productname, vtiger_products.unit_price, vtiger_inventoryproductrel.* from vtiger_inventoryproductrel inner join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid where id=?"; + $params = array($focus->id); + } + elseif($module == 'Potentials') + { + $query="select vtiger_products.productname,vtiger_products.unit_price,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?"; + $params = array($seid); + } + elseif($module == 'Products') + { + $query="select vtiger_products.productname,vtiger_products.unit_price, vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?"; + $params = array($seid); + } + + $result = $adb->pquery($query, $params); + $num_rows=$adb->num_rows($result); + $log->debug("Exiting getNoOfAssocProducts method ..."); + return $num_rows; +} + +/** This function returns the detail block information of a record for given block id. +* Param $module - module name +* Param $block - block name +* Param $mode - view type (detail/edit/create) +* Param $col_fields - vtiger_fields array +* Param $tabid - vtiger_tab id +* Param $info_type - information type (basic/advance) default "" +* Return type is an object array +*/ + +function getBlockInformation($module, $result, $col_fields,$tabid,$block_label,$mode) +{ + global $log; + $log->debug("Entering getBlockInformation(".$module.",". $result.",". $col_fields.",".$tabid.",".$block_label.") method ..."); + global $adb; + $editview_arr = Array(); + + global $current_user,$mod_strings; + + $noofrows = $adb->num_rows($result); + if (($module == 'Accounts' || $module == 'Contacts' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder'|| $module == 'Invoice') && $block == 2) + { + global $log; + $log->info("module is ".$module); + + $mvAdd_flag = true; + $moveAddress = "

+ "; + } + + + for($i=0; $i<$noofrows; $i++) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $uitype = $adb->query_result($result,$i,"uitype"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $block = $adb->query_result($result,$i,"block"); + $maxlength = $adb->query_result($result,$i,"maximumlength"); + $generatedtype = $adb->query_result($result,$i,"generatedtype"); + $typeofdata = $adb->query_result($result,$i,"typeofdata"); + + $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,$module,$mode,$typeofdata); + $editview_arr[$block][]=$custfld; + if ($mvAdd_flag == true) + $mvAdd_flag = false; + $i++; + if($i<$noofrows) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $uitype = $adb->query_result($result,$i,"uitype"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $block = $adb->query_result($result,$i,"block"); + $maxlength = $adb->query_result($result,$i,"maximumlength"); + $generatedtype = $adb->query_result($result,$i,"generatedtype"); + $typeofdata = $adb->query_result($result,$i,"typeofdata"); + $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,$module,$mode,$typeofdata); + $editview_arr[$block][]=$custfld; + } + } + foreach($editview_arr as $headerid=>$editview_value) + { + $editview_data = Array(); + for ($i=0,$j=0;$i $key1,1 => $key2); + $i+=2; + } + else{ + $editview_data[$j]=array(0 => $key1); + $i++; + } + } + $editview_arr[$headerid] = $editview_data; + } + foreach($block_label as $blockid=>$label) + { + if($label == '') + { + $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$editview_arr[$blockid]); + } + else + { + $curBlock = $label; + if(is_array($editview_arr[$blockid])) + $returndata[getTranslatedString($curBlock,$module)]=array_merge((array)$returndata[getTranslatedString($curBlock,$module)],(array)$editview_arr[$blockid]); + } + } + $log->debug("Exiting getBlockInformation method ..."); + return $returndata; + +} + +/** This function returns the data type of the vtiger_fields, with vtiger_field label, which is used for javascript validation. +* Param $validationData - array of vtiger_fieldnames with datatype +* Return type array +*/ + +function split_validationdataArray($validationData) +{ + global $log; + $log->debug("Entering split_validationdataArray(".$validationData.") method ..."); + $fieldName = ''; + $fieldLabel = ''; + $fldDataType = ''; + $rows = count($validationData); + foreach($validationData as $fldName => $fldLabel_array) + { + if($fieldName == '') + { + $fieldName="'".$fldName."'"; + } + else + { + $fieldName .= ",'".$fldName ."'"; + } + foreach($fldLabel_array as $fldLabel => $datatype) + { + if($fieldLabel == '') + { + $fieldLabel = "'".addslashes($fldLabel)."'"; + } + else + { + $fieldLabel .= ",'".addslashes($fldLabel)."'"; + } + if($fldDataType == '') + { + $fldDataType = "'".$datatype ."'"; + } + else + { + $fldDataType .= ",'".$datatype ."'"; + } + } + } + $data['fieldname'] = $fieldName; + $data['fieldlabel'] = $fieldLabel; + $data['datatype'] = $fldDataType; + $log->debug("Exiting split_validationdataArray method ..."); + return $data; +} + + +?> diff --git a/oss/vtiger/trunk/include/utils/ExportAjax.php b/oss/vtiger/trunk/include/utils/ExportAjax.php index cc61b73e..156c021d 100644 --- a/oss/vtiger/trunk/include/utils/ExportAjax.php +++ b/oss/vtiger/trunk/include/utils/ExportAjax.php @@ -1,51 +1,51 @@ ->>>>>>>. - if(($_REQUEST['search_type'] == 'includesearch' && $_REQUEST['export_data'] == 'all') && $_SESSION['export_where'] == '') - { - echo'NOT_SEARCH_WITHSEARCH_ALL'; - exit(); - } - elseif(($_REQUEST['search_type'] == 'includesearch' && $_REQUEST['export_data'] == 'currentpage') && $_SESSION['export_where'] == '') - { - echo'NOT_SEARCH_WITHSEARCH_CURRENTPAGE'; - exit(); - } - elseif(($_REQUEST['search_type'] == 'includesearch' && $_REQUEST['export_data'] == 'selecteddata') && $idstring == '') - { - echo'NO_DATA_SELECTED'; - exit(); - } - //This conditions user can select includesearch & (all |currentpage|selecteddata) but not search----ENDS<<<<<<<<. - //This conditions user can select withoutsearch & (all |currentpage|selecteddata) but search---STARTS>>>>>>>>. - elseif(($_REQUEST['search_type'] == 'withoutsearch' && $_REQUEST['export_data'] == 'all') && $_SESSION['export_where'] != '') - { - echo'SEARCH_WITHOUTSEARCH_ALL'; - exit(); - } - elseif(($_REQUEST['search_type'] == 'withoutsearch' && $_REQUEST['export_data'] == 'currentpage') && $_SESSION['export_where'] != '') - { - echo'SEARCH_WITHOUTSEARCH_CURRENTPAGE'; - exit(); - } - elseif(($_REQUEST['search_type'] == 'withoutsearch' && $_REQUEST['export_data'] == 'selecteddata') && $idstring == '') - { - echo'NO_DATA_SELECTED'; - exit(); - } - //This conditions user can select withoutsearch & (all |currentpage|selecteddata) but search---ENDS<<<<<<<<<<<< -} -?> +>>>>>>>. + if(($_REQUEST['search_type'] == 'includesearch' && $_REQUEST['export_data'] == 'all') && $_SESSION['export_where'] == '') + { + echo'NOT_SEARCH_WITHSEARCH_ALL'; + exit(); + } + elseif(($_REQUEST['search_type'] == 'includesearch' && $_REQUEST['export_data'] == 'currentpage') && $_SESSION['export_where'] == '') + { + echo'NOT_SEARCH_WITHSEARCH_CURRENTPAGE'; + exit(); + } + elseif(($_REQUEST['search_type'] == 'includesearch' && $_REQUEST['export_data'] == 'selecteddata') && $idstring == '') + { + echo'NO_DATA_SELECTED'; + exit(); + } + //This conditions user can select includesearch & (all |currentpage|selecteddata) but not search----ENDS<<<<<<<<. + //This conditions user can select withoutsearch & (all |currentpage|selecteddata) but search---STARTS>>>>>>>>. + elseif(($_REQUEST['search_type'] == 'withoutsearch' && $_REQUEST['export_data'] == 'all') && $_SESSION['export_where'] != '') + { + echo'SEARCH_WITHOUTSEARCH_ALL'; + exit(); + } + elseif(($_REQUEST['search_type'] == 'withoutsearch' && $_REQUEST['export_data'] == 'currentpage') && $_SESSION['export_where'] != '') + { + echo'SEARCH_WITHOUTSEARCH_CURRENTPAGE'; + exit(); + } + elseif(($_REQUEST['search_type'] == 'withoutsearch' && $_REQUEST['export_data'] == 'selecteddata') && $idstring == '') + { + echo'NO_DATA_SELECTED'; + exit(); + } + //This conditions user can select withoutsearch & (all |currentpage|selecteddata) but search---ENDS<<<<<<<<<<<< +} +?> diff --git a/oss/vtiger/trunk/include/utils/ExportRecords.php b/oss/vtiger/trunk/include/utils/ExportRecords.php index ed909bb0..3bb19a41 100644 --- a/oss/vtiger/trunk/include/utils/ExportRecords.php +++ b/oss/vtiger/trunk/include/utils/ExportRecords.php @@ -1,44 +1,44 @@ -assign("SESSION_WHERE",$_SESSION['export_where']); - -$smarty->assign('APP',$app_strings); -$smarty->assign('MOD',$mod_strings); -$smarty->assign("THEME", $theme_path); -$smarty->assign("IMAGE_PATH", $image_path); -$smarty->assign("CATEGORY",$category); -$smarty->assign("MODULE",$currentModule); -$smarty->assign("MODULELABEL",getTranslatedString($currentModule)); -$smarty->assign("IDSTRING",$idstring); -$smarty->assign("PERPAGE",$list_max_entries_per_page); - -if(!is_admin($current_user) && (isPermitted($currentModule, 'Export') != 'yes')) { - $smarty->display(vtlib_getModuleTemplate('Vtiger','OperationNotPermitted.tpl')); -} else { - $smarty->display('ExportRecords.tpl'); -} - - -?> +assign("SESSION_WHERE",$_SESSION['export_where']); + +$smarty->assign('APP',$app_strings); +$smarty->assign('MOD',$mod_strings); +$smarty->assign("THEME", $theme_path); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("CATEGORY",$category); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("MODULELABEL",getTranslatedString($currentModule)); +$smarty->assign("IDSTRING",$idstring); +$smarty->assign("PERPAGE",$list_max_entries_per_page); + +if(!is_admin($current_user) && (isPermitted($currentModule, 'Export') != 'yes')) { + $smarty->display(vtlib_getModuleTemplate('Vtiger','OperationNotPermitted.tpl')); +} else { + $smarty->display('ExportRecords.tpl'); +} + + +?> diff --git a/oss/vtiger/trunk/include/utils/ExportUtils.php b/oss/vtiger/trunk/include/utils/ExportUtils.php index 3a793c1e..b62e7a67 100644 --- a/oss/vtiger/trunk/include/utils/ExportUtils.php +++ b/oss/vtiger/trunk/include/utils/ExportUtils.php @@ -1,174 +1,174 @@ -debug("Entering into the function getPermittedBlocks($module, $disp_view)"); - - $tabid = getTabid($module); - $block_detail = Array(); - $query="select blockid,blocklabel,show_title from vtiger_blocks where tabid=? and $disp_view=0 and visible = 0 order by sequence"; - $result = $adb->pquery($query, array($tabid)); - $noofrows = $adb->num_rows($result); - $blockid_list ='('; - for($i=0; $i<$noofrows; $i++) - { - $blockid = $adb->query_result($result,$i,"blockid"); - if($i != 0) - $blockid_list .= ', '; - $blockid_list .= $blockid; - $block_label[$blockid] = $adb->query_result($result,$i,"blocklabel"); - } - $blockid_list .= ')'; - - $log->debug("Exit from the function getPermittedBlocks($module, $disp_view). Return value = $blockid_list"); - return $blockid_list; -} - -/** function used to get the query which will list the permitted fields - * @param string $module - module name - * @param string $disp_view - view name, this may be create_view, edit_view or detail_view - * @return string $sql - query to get the list of fields which are permitted to the current user - */ -function getPermittedFieldsQuery($module, $disp_view) -{ - global $adb, $log; - $log->debug("Entering into the function getPermittedFieldsQuery($module, $disp_view)"); - - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - //To get the permitted blocks - $blockid_list = getPermittedBlocks($module, $disp_view); - - $tabid = getTabid($module); - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users") - { - $sql = "SELECT vtiger_field.columnname, vtiger_field.fieldlabel, vtiger_field.tablename FROM vtiger_field WHERE vtiger_field.tabid=".$tabid." AND vtiger_field.block IN $blockid_list AND vtiger_field.displaytype IN (1,2,4) and vtiger_field.presence in (0,2) ORDER BY block,sequence"; - } - else - { - $profileList = getCurrentUserProfileList(); - $sql = "SELECT vtiger_field.columnname, vtiger_field.fieldlabel, vtiger_field.tablename FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=".$tabid." AND vtiger_field.block IN ".$blockid_list." AND vtiger_field.displaytype IN (1,2,4) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". implode(",", $profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; - } - - $log->debug("Exit from the function getPermittedFieldsQuery($module, $disp_view). Return value = $sql"); - return $sql; -} - -/** function used to get the list of fields from the input query as a comma seperated string - * @param string $query - field table query which contains the list of fields - * @return string $fields - list of fields as a comma seperated string - */ -function getFieldsListFromQuery($query) -{ - global $adb, $log; - $log->debug("Entering into the function getFieldsListFromQuery($query)"); - - $result = $adb->query($query); - $num_rows = $adb->num_rows($result); - - for($i=0; $i < $num_rows;$i++) - { - $columnName = $adb->query_result($result,$i,"columnname"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $tablename = $adb->query_result($result,$i,"tablename"); - - //HANDLE HERE - Mismatch fieldname-tablename in field table, in future we have to avoid these if elses - if($columnName == 'smownerid')//for all assigned to user name - { - $fields .= "case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_account' && $columnName == 'parentid')//Account - Member Of - { - $fields .= "vtiger_account2.accountname as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_contactdetails' && $columnName == 'accountid')//Contact - Account Name - { - $fields .= "vtiger_account.accountname as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_contactdetails' && $columnName == 'reportsto')//Contact - Reports To - { - $fields .= " concat(vtiger_contactdetails2.lastname,' ',vtiger_contactdetails2.firstname) as 'Reports To Contact',"; - } - elseif($tablename == 'vtiger_potential' && $columnName == 'related_to')//Potential - Related to (changed for B2C model support) - { - $fields .= "vtiger_potential.related_to as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_potential' && $columnName == 'campaignid')//Potential - Campaign Source - { - $fields .= "vtiger_campaign.campaignname as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_seproductsrel' && $columnName == 'crmid')//Product - Related To - { - $fields .= "case vtiger_crmentityRelatedTo.setype - when 'Leads' then concat('Leads ::: ',vtiger_ProductRelatedToLead.lastname,' ',vtiger_ProductRelatedToLead.firstname) - when 'Accounts' then concat('Accounts ::: ',vtiger_ProductRelatedToAccount.accountname) - when 'Potentials' then concat('Potentials ::: ',vtiger_ProductRelatedToPotential.potentialname) - End as 'Related To',"; - } - elseif($tablename == 'vtiger_products' && $columnName == 'contactid')//Product - Contact - { - $fields .= " concat(vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname) as 'Contact Name',"; - } - elseif($tablename == 'vtiger_products' && $columnName == 'vendor_id')//Product - Vendor Name - { - $fields .= "vtiger_vendor.vendorname as '".$fieldlabel."',"; - } - //Pavani- Handling product handler - elseif($tablename == 'vtiger_products' && $columnName == 'handler')//Product - Handler - { - $fields .= "vtiger_users.user_name as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_producttaxrel' && $columnName == 'taxclass')//avoid product - taxclass - { - $fields .= ""; - } - elseif($tablename == 'vtiger_attachments' && $columnName == 'name')//Emails filename - { - $fields .= $tablename.".name as '".$fieldlabel."',"; - } - //By Pavani...Handling mismatch field and table name for trouble tickets - elseif($tablename == 'vtiger_troubletickets' && $columnName == 'product_id')//Ticket - Product - { - $fields .= "vtiger_products.productname as '".$fieldlabel."',"; - } - elseif($tablename == 'vtiger_troubletickets' && $columnName == 'parent_id')//Ticket - Related To - { - $fields .= "case vtiger_crmentityRelatedTo.setype - when 'Accounts' then concat('Accounts ::: ',vtiger_account.accountname) - when 'Contacts' then concat('Contacts ::: ',vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname) - End as 'Related To',"; - } - elseif($tablename == 'vtiger_notes' && ($columnName == 'filename' || $columnName == 'filetype' || $columnName == 'filesize' || $columnName == 'filelocationtype' || $columnName == 'filestatus' || $columnName == 'filedownloadcount' ||$columnName == 'folderid')){ - continue; - } - else - { - $fields .= $tablename.".".$columnName. " as '" .$fieldlabel."',"; - } - } - $fields = trim($fields,","); - - $log->debug("Exit from the function getFieldsListFromQuery($query). Return value = $fields"); - return $fields; -} - - - -?> +debug("Entering into the function getPermittedBlocks($module, $disp_view)"); + + $tabid = getTabid($module); + $block_detail = Array(); + $query="select blockid,blocklabel,show_title from vtiger_blocks where tabid=? and $disp_view=0 and visible = 0 order by sequence"; + $result = $adb->pquery($query, array($tabid)); + $noofrows = $adb->num_rows($result); + $blockid_list ='('; + for($i=0; $i<$noofrows; $i++) + { + $blockid = $adb->query_result($result,$i,"blockid"); + if($i != 0) + $blockid_list .= ', '; + $blockid_list .= $blockid; + $block_label[$blockid] = $adb->query_result($result,$i,"blocklabel"); + } + $blockid_list .= ')'; + + $log->debug("Exit from the function getPermittedBlocks($module, $disp_view). Return value = $blockid_list"); + return $blockid_list; +} + +/** function used to get the query which will list the permitted fields + * @param string $module - module name + * @param string $disp_view - view name, this may be create_view, edit_view or detail_view + * @return string $sql - query to get the list of fields which are permitted to the current user + */ +function getPermittedFieldsQuery($module, $disp_view) +{ + global $adb, $log; + $log->debug("Entering into the function getPermittedFieldsQuery($module, $disp_view)"); + + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + //To get the permitted blocks + $blockid_list = getPermittedBlocks($module, $disp_view); + + $tabid = getTabid($module); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users") + { + $sql = "SELECT vtiger_field.columnname, vtiger_field.fieldlabel, vtiger_field.tablename FROM vtiger_field WHERE vtiger_field.tabid=".$tabid." AND vtiger_field.block IN $blockid_list AND vtiger_field.displaytype IN (1,2,4) and vtiger_field.presence in (0,2) ORDER BY block,sequence"; + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "SELECT vtiger_field.columnname, vtiger_field.fieldlabel, vtiger_field.tablename FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=".$tabid." AND vtiger_field.block IN ".$blockid_list." AND vtiger_field.displaytype IN (1,2,4) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". implode(",", $profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid ORDER BY block,sequence"; + } + + $log->debug("Exit from the function getPermittedFieldsQuery($module, $disp_view). Return value = $sql"); + return $sql; +} + +/** function used to get the list of fields from the input query as a comma seperated string + * @param string $query - field table query which contains the list of fields + * @return string $fields - list of fields as a comma seperated string + */ +function getFieldsListFromQuery($query) +{ + global $adb, $log; + $log->debug("Entering into the function getFieldsListFromQuery($query)"); + + $result = $adb->query($query); + $num_rows = $adb->num_rows($result); + + for($i=0; $i < $num_rows;$i++) + { + $columnName = $adb->query_result($result,$i,"columnname"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $tablename = $adb->query_result($result,$i,"tablename"); + + //HANDLE HERE - Mismatch fieldname-tablename in field table, in future we have to avoid these if elses + if($columnName == 'smownerid')//for all assigned to user name + { + $fields .= "case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_account' && $columnName == 'parentid')//Account - Member Of + { + $fields .= "vtiger_account2.accountname as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_contactdetails' && $columnName == 'accountid')//Contact - Account Name + { + $fields .= "vtiger_account.accountname as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_contactdetails' && $columnName == 'reportsto')//Contact - Reports To + { + $fields .= " concat(vtiger_contactdetails2.lastname,' ',vtiger_contactdetails2.firstname) as 'Reports To Contact',"; + } + elseif($tablename == 'vtiger_potential' && $columnName == 'related_to')//Potential - Related to (changed for B2C model support) + { + $fields .= "vtiger_potential.related_to as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_potential' && $columnName == 'campaignid')//Potential - Campaign Source + { + $fields .= "vtiger_campaign.campaignname as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_seproductsrel' && $columnName == 'crmid')//Product - Related To + { + $fields .= "case vtiger_crmentityRelatedTo.setype + when 'Leads' then concat('Leads ::: ',vtiger_ProductRelatedToLead.lastname,' ',vtiger_ProductRelatedToLead.firstname) + when 'Accounts' then concat('Accounts ::: ',vtiger_ProductRelatedToAccount.accountname) + when 'Potentials' then concat('Potentials ::: ',vtiger_ProductRelatedToPotential.potentialname) + End as 'Related To',"; + } + elseif($tablename == 'vtiger_products' && $columnName == 'contactid')//Product - Contact + { + $fields .= " concat(vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname) as 'Contact Name',"; + } + elseif($tablename == 'vtiger_products' && $columnName == 'vendor_id')//Product - Vendor Name + { + $fields .= "vtiger_vendor.vendorname as '".$fieldlabel."',"; + } + //Pavani- Handling product handler + elseif($tablename == 'vtiger_products' && $columnName == 'handler')//Product - Handler + { + $fields .= "vtiger_users.user_name as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_producttaxrel' && $columnName == 'taxclass')//avoid product - taxclass + { + $fields .= ""; + } + elseif($tablename == 'vtiger_attachments' && $columnName == 'name')//Emails filename + { + $fields .= $tablename.".name as '".$fieldlabel."',"; + } + //By Pavani...Handling mismatch field and table name for trouble tickets + elseif($tablename == 'vtiger_troubletickets' && $columnName == 'product_id')//Ticket - Product + { + $fields .= "vtiger_products.productname as '".$fieldlabel."',"; + } + elseif($tablename == 'vtiger_troubletickets' && $columnName == 'parent_id')//Ticket - Related To + { + $fields .= "case vtiger_crmentityRelatedTo.setype + when 'Accounts' then concat('Accounts ::: ',vtiger_account.accountname) + when 'Contacts' then concat('Contacts ::: ',vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname) + End as 'Related To',"; + } + elseif($tablename == 'vtiger_notes' && ($columnName == 'filename' || $columnName == 'filetype' || $columnName == 'filesize' || $columnName == 'filelocationtype' || $columnName == 'filestatus' || $columnName == 'filedownloadcount' ||$columnName == 'folderid')){ + continue; + } + else + { + $fields .= $tablename.".".$columnName. " as '" .$fieldlabel."',"; + } + } + $fields = trim($fields,","); + + $log->debug("Exit from the function getFieldsListFromQuery($query). Return value = $fields"); + return $fields; +} + + + +?> diff --git a/oss/vtiger/trunk/include/utils/GetGroupUsers.php b/oss/vtiger/trunk/include/utils/GetGroupUsers.php index 18e3b634..bc33fded 100644 --- a/oss/vtiger/trunk/include/utils/GetGroupUsers.php +++ b/oss/vtiger/trunk/include/utils/GetGroupUsers.php @@ -1,133 +1,133 @@ - Group Id :: Type Integer - * @returns the vtiger_users present in the group in the variable $parent_groups of the class - * @returns the sub vtiger_groups present in the group in the variable $group_subgroups of the class - */ - function getAllUsersInGroup($groupid) - { - global $adb,$log; - $log->debug("Entering getAllUsersInGroup(".$groupid.") method..."); - //Retreiving from the user2grouptable - $query="select * from vtiger_users2group where groupid=?"; - $result = $adb->pquery($query, array($groupid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_user_id=$adb->query_result($result,$i,'userid'); - if(! in_array($now_user_id,$this->group_users)) - { - $this->group_users[]=$now_user_id; - - } - } - - - //Retreiving from the vtiger_group2role - $query="select * from vtiger_group2role where groupid=?"; - $result = $adb->pquery($query, array($groupid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_role_id=$adb->query_result($result,$i,'roleid'); - $now_role_users=array(); - $now_role_users=getRoleUsers($now_role_id); - - foreach($now_role_users as $now_role_userid => $now_role_username) - { - if(! in_array($now_role_userid,$this->group_users)) - { - $this->group_users[]=$now_role_userid; - - } - } - - } - - //Retreiving from the vtiger_group2rs - $query="select * from vtiger_group2rs where groupid=?"; - $result = $adb->pquery($query, array($groupid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_rs_id=$adb->query_result($result,$i,'roleandsubid'); - $now_rs_users=getRoleAndSubordinateUsers($now_rs_id); - foreach($now_rs_users as $now_rs_userid => $now_rs_username) - { - if(! in_array($now_rs_userid,$this->group_users)) - { - $this->group_users[]=$now_rs_userid; - - } - } - - - } - //Retreving from group2group - $query="select * from vtiger_group2grouprel where groupid=?"; - $result = $adb->pquery($query, array($groupid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_grp_id=$adb->query_result($result,$i,'containsgroupid'); - - - $focus = new GetGroupUsers(); - $focus->getAllUsersInGroup($now_grp_id); - $now_grp_users=$focus->group_users; - $now_grp_grps=$focus->group_subgroups; - if(! array_key_exists($now_grp_id,$this->group_subgroups)) - { - $this->group_subgroups[$now_grp_id]=$now_grp_users; - } - - - - foreach($focus->group_users as $temp_user_id) - { - if(! in_array($temp_user_id,$this->group_users)) - { - $this->group_users[]=$temp_user_id; - } - } - - - foreach($focus->group_subgroups as $temp_grp_id => $users_array) - { - if(! array_key_exists($temp_grp_id,$this->group_subgroups)) - { - $this->group_subgroups[$temp_grp_id]=$focus->group_users; - } - } - - } - $log->debug("Exiting getAllUsersInGroup method..."); - - } - - -} - -?> + Group Id :: Type Integer + * @returns the vtiger_users present in the group in the variable $parent_groups of the class + * @returns the sub vtiger_groups present in the group in the variable $group_subgroups of the class + */ + function getAllUsersInGroup($groupid) + { + global $adb,$log; + $log->debug("Entering getAllUsersInGroup(".$groupid.") method..."); + //Retreiving from the user2grouptable + $query="select * from vtiger_users2group where groupid=?"; + $result = $adb->pquery($query, array($groupid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_user_id=$adb->query_result($result,$i,'userid'); + if(! in_array($now_user_id,$this->group_users)) + { + $this->group_users[]=$now_user_id; + + } + } + + + //Retreiving from the vtiger_group2role + $query="select * from vtiger_group2role where groupid=?"; + $result = $adb->pquery($query, array($groupid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_role_id=$adb->query_result($result,$i,'roleid'); + $now_role_users=array(); + $now_role_users=getRoleUsers($now_role_id); + + foreach($now_role_users as $now_role_userid => $now_role_username) + { + if(! in_array($now_role_userid,$this->group_users)) + { + $this->group_users[]=$now_role_userid; + + } + } + + } + + //Retreiving from the vtiger_group2rs + $query="select * from vtiger_group2rs where groupid=?"; + $result = $adb->pquery($query, array($groupid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_rs_id=$adb->query_result($result,$i,'roleandsubid'); + $now_rs_users=getRoleAndSubordinateUsers($now_rs_id); + foreach($now_rs_users as $now_rs_userid => $now_rs_username) + { + if(! in_array($now_rs_userid,$this->group_users)) + { + $this->group_users[]=$now_rs_userid; + + } + } + + + } + //Retreving from group2group + $query="select * from vtiger_group2grouprel where groupid=?"; + $result = $adb->pquery($query, array($groupid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_grp_id=$adb->query_result($result,$i,'containsgroupid'); + + + $focus = new GetGroupUsers(); + $focus->getAllUsersInGroup($now_grp_id); + $now_grp_users=$focus->group_users; + $now_grp_grps=$focus->group_subgroups; + if(! array_key_exists($now_grp_id,$this->group_subgroups)) + { + $this->group_subgroups[$now_grp_id]=$now_grp_users; + } + + + + foreach($focus->group_users as $temp_user_id) + { + if(! in_array($temp_user_id,$this->group_users)) + { + $this->group_users[]=$temp_user_id; + } + } + + + foreach($focus->group_subgroups as $temp_grp_id => $users_array) + { + if(! array_key_exists($temp_grp_id,$this->group_subgroups)) + { + $this->group_subgroups[$temp_grp_id]=$focus->group_users; + } + } + + } + $log->debug("Exiting getAllUsersInGroup method..."); + + } + + +} + +?> diff --git a/oss/vtiger/trunk/include/utils/GetParentGroups.php b/oss/vtiger/trunk/include/utils/GetParentGroups.php index fdb916e9..186bcb04 100644 --- a/oss/vtiger/trunk/include/utils/GetParentGroups.php +++ b/oss/vtiger/trunk/include/utils/GetParentGroups.php @@ -1,46 +1,46 @@ - Group Id :: Type Integer - * @returns updates the parent group in the varibale $parent_groups of the class - */ - function getAllParentGroups($groupid) - { - global $adb,$log; - $log->debug("Entering getAllParentGroups(".$groupid.") method..."); - $query="select groupid from vtiger_group2grouprel where containsgroupid=?"; - $result = $adb->pquery($query, array($groupid)); - $num_rows=$adb->num_rows($result); - if($num_rows > 0) - { - for($i=0;$i<$num_rows;$i++) - { - $group_id=$adb->query_result($result,$i,'groupid'); - if(! in_array($group_id,$this->parent_groups)) - { - $this->parent_groups[]=$group_id; - $this->getAllParentGroups($group_id); - } - } - } - $log->debug("Exiting getAllParentGroups method..."); - } -} - -?> + Group Id :: Type Integer + * @returns updates the parent group in the varibale $parent_groups of the class + */ + function getAllParentGroups($groupid) + { + global $adb,$log; + $log->debug("Entering getAllParentGroups(".$groupid.") method..."); + $query="select groupid from vtiger_group2grouprel where containsgroupid=?"; + $result = $adb->pquery($query, array($groupid)); + $num_rows=$adb->num_rows($result); + if($num_rows > 0) + { + for($i=0;$i<$num_rows;$i++) + { + $group_id=$adb->query_result($result,$i,'groupid'); + if(! in_array($group_id,$this->parent_groups)) + { + $this->parent_groups[]=$group_id; + $this->getAllParentGroups($group_id); + } + } + } + $log->debug("Exiting getAllParentGroups method..."); + } +} + +?> diff --git a/oss/vtiger/trunk/include/utils/GetUserGroups.php b/oss/vtiger/trunk/include/utils/GetUserGroups.php index 391ac691..c03153cd 100644 --- a/oss/vtiger/trunk/include/utils/GetUserGroups.php +++ b/oss/vtiger/trunk/include/utils/GetUserGroups.php @@ -1,103 +1,103 @@ - Group Id :: Type Integer - * @returns updates the parent group in the varibale $parent_groups of the class - */ - function getAllUserGroups($userid) - { - global $adb,$log; - $log->debug("Entering getAllUserGroups(".$userid.") method..."); - //Retreiving from the user2grouptable - $query="select * from vtiger_users2group where userid=?"; - $result = $adb->pquery($query, array($userid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_group_id=$adb->query_result($result,$i,'groupid'); - if(! in_array($now_group_id,$this->user_groups)) - { - $this->user_groups[]=$now_group_id; - - } - } - - //Setting the User Role - $userRole = fetchUserRole($userid); - //Retreiving from the vtiger_user2role - $query="select * from vtiger_group2role where roleid=?"; - $result = $adb->pquery($query, array($userRole)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_group_id=$adb->query_result($result,$i,'groupid'); - if(! in_array($now_group_id,$this->user_groups)) - { - $this->user_groups[]=$now_group_id; - - } - } - - //Retreiving from the user2rs - $parentRoles=getParentRole($userRole); - $parentRolelist= array(); - foreach($parentRoles as $par_rol_id) - { - array_push($parentRolelist, $par_rol_id); - } - array_push($parentRolelist, $userRole); - $query="select * from vtiger_group2rs where roleandsubid in (". generateQuestionMarks($parentRolelist) .")"; - $result = $adb->pquery($query, array($parentRolelist)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $now_group_id=$adb->query_result($result,$i,'groupid'); - - if(! in_array($now_group_id,$this->user_groups)) - { - $this->user_groups[]=$now_group_id; - } - } - foreach($this->user_groups as $grp_id) - { - $focus = new GetParentGroups(); - $focus->getAllParentGroups($grp_id); - - foreach($focus->parent_groups as $par_grp_id) - { - if(! in_array($par_grp_id,$this->user_groups)) - { - $this->user_groups[]=$par_grp_id; - - } - } - - } - $log->debug("Exiting getAllUserGroups method..."); - - } - - -} - -?> + Group Id :: Type Integer + * @returns updates the parent group in the varibale $parent_groups of the class + */ + function getAllUserGroups($userid) + { + global $adb,$log; + $log->debug("Entering getAllUserGroups(".$userid.") method..."); + //Retreiving from the user2grouptable + $query="select * from vtiger_users2group where userid=?"; + $result = $adb->pquery($query, array($userid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_group_id=$adb->query_result($result,$i,'groupid'); + if(! in_array($now_group_id,$this->user_groups)) + { + $this->user_groups[]=$now_group_id; + + } + } + + //Setting the User Role + $userRole = fetchUserRole($userid); + //Retreiving from the vtiger_user2role + $query="select * from vtiger_group2role where roleid=?"; + $result = $adb->pquery($query, array($userRole)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_group_id=$adb->query_result($result,$i,'groupid'); + if(! in_array($now_group_id,$this->user_groups)) + { + $this->user_groups[]=$now_group_id; + + } + } + + //Retreiving from the user2rs + $parentRoles=getParentRole($userRole); + $parentRolelist= array(); + foreach($parentRoles as $par_rol_id) + { + array_push($parentRolelist, $par_rol_id); + } + array_push($parentRolelist, $userRole); + $query="select * from vtiger_group2rs where roleandsubid in (". generateQuestionMarks($parentRolelist) .")"; + $result = $adb->pquery($query, array($parentRolelist)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $now_group_id=$adb->query_result($result,$i,'groupid'); + + if(! in_array($now_group_id,$this->user_groups)) + { + $this->user_groups[]=$now_group_id; + } + } + foreach($this->user_groups as $grp_id) + { + $focus = new GetParentGroups(); + $focus->getAllParentGroups($grp_id); + + foreach($focus->parent_groups as $par_grp_id) + { + if(! in_array($par_grp_id,$this->user_groups)) + { + $this->user_groups[]=$par_grp_id; + + } + } + + } + $log->debug("Exiting getAllUserGroups method..."); + + } + + +} + +?> diff --git a/oss/vtiger/trunk/include/utils/GraphUtils.php b/oss/vtiger/trunk/include/utils/GraphUtils.php index 1ea803aa..92f05bae 100644 --- a/oss/vtiger/trunk/include/utils/GraphUtils.php +++ b/oss/vtiger/trunk/include/utils/GraphUtils.php @@ -1,137 +1,136 @@ -debug("Entering calculate_font_name(".$locale.") method ..."); - - switch($locale) - { - case 'zh_cn': - $log->debug("Exiting calculate_font_name method ..."); - return FF_DROIDSANSFALLBACK; - case 'tw_zh': - if(!function_exists('iconv')){ - echo " Unable to display traditional Chinese on the graphs.
The function iconv does not exists please read more about iconv here
"; - $log->debug("Exiting calculate_font_name method ..."); - return FF_FONT1; - - } - else - { - $log->debug("Exiting calculate_font_name method ..."); - return FF_CHINESE; - } - default: - $log->debug("Exiting calculate_font_name method ..."); - return FF_FONT1; - } - - $log->debug("Exiting calculate_font_name method ..."); - return FF_FONT1; -} - -/**This function is used to generate the n colors. -* Param $count - number of colors to generate -* Param $start - value of first color -* Param $step - color increment to apply -* Return type array - array of n colors values -*/ - -function color_generator($count = 1, $start = '33CCFF', $step = '221133') -{ - global $log; - $log->debug("Entering color_generator(".$count.",".$start.",".$step.") method ..."); - // explode color strings to RGB array - if($start{0} == "#") $start = substr($start,1); - if($step{0} == "#") $step = substr($step,1); - // pad shorter strings with 0 - $start = substr($start."000000",0,6); - $step = substr($step."000000",0,6); - $colors = array(hexdec(substr($start,0,2)),hexdec(substr($start,2,2)),hexdec(substr($start,4,2))); - $steps = array(hexdec(substr($step,0,2)),hexdec(substr($step,2,2)),hexdec(substr($step,4,2))); - // buils $count colours adding $step to $start - $result = array(); - for($i=1; $i<=$count; $i++){ - array_push($result,"#".dechex($colors[0]).dechex($colors[1]).dechex($colors[2])); - for($j=0; $j<3; $j++) { - $colors[$j] += $steps[$j]; - if($colors[$j] > 0xFF) $colors[$j] -= 0xFF; - } - } - $log->debug("Exiting color_generator method ..."); - return $result; -} - -/**This function is used to define the optimum spacin for tick marks on an axis -* Param $max - maximum value of axis -* Return type array - array of 2 values major and minor spacing -*/ - -function get_tickspacing($max = 10) -{ - global $log,$app_strings; - $log->debug("Entering get_tickspacing(".$max.") method ..."); - $result = array(1,1); - - // normalize $max to get value between 1 and 10 - $coef = pow(10,floor(log10($max))); - if($coef == 0) - { - $data=0; - echo "

".$app_strings['NO_DATA_AVAILABLE_WITH_SPECIFIED_PERIOD']."

"; - $log->debug("Exiting get_tickspacing method ..."); - return $data; - } - $normalized = $max / $coef; - - if($normalized < 1.5){ - $result[0] = 0.2; - $result[1] = 0.1; - } - elseif($normalized < 5){ - $result[0] = 0.5; - $result[1] = 0.1; - } - elseif($normalized < 10){ - $result[0] = 1.0; - $result[1] = 0.5; - } - $result[0] *= $coef; - $result[1] *= $coef; - $log->debug("Exiting get_tickspacing method ..."); - return $result; -} -?> +debug("Entering calculate_font_name(".$locale.") method ..."); + + switch($locale) + { + case 'cn_zh': + $log->debug("Exiting calculate_font_name method ..."); + return FF_SIMSUN; + case 'tw_zh': + if(!function_exists('iconv')){ + echo " Unable to display traditional Chinese on the graphs.
The function iconv does not exists please read more about iconv here
"; + $log->debug("Exiting calculate_font_name method ..."); + return FF_FONT1; + + } + else + { + $log->debug("Exiting calculate_font_name method ..."); + return FF_CHINESE; + } + default: + $log->debug("Exiting calculate_font_name method ..."); + return FF_FONT1; + } + + $log->debug("Exiting calculate_font_name method ..."); + return FF_FONT1; +} + +/**This function is used to generate the n colors. +* Param $count - number of colors to generate +* Param $start - value of first color +* Param $step - color increment to apply +* Return type array - array of n colors values +*/ + +function color_generator($count = 1, $start = '33CCFF', $step = '221133') +{ + global $log; + $log->debug("Entering color_generator(".$count.",".$start.",".$step.") method ..."); + // explode color strings to RGB array + if($start{0} == "#") $start = substr($start,1); + if($step{0} == "#") $step = substr($step,1); + // pad shorter strings with 0 + $start = substr($start."000000",0,6); + $step = substr($step."000000",0,6); + $colors = array(hexdec(substr($start,0,2)),hexdec(substr($start,2,2)),hexdec(substr($start,4,2))); + $steps = array(hexdec(substr($step,0,2)),hexdec(substr($step,2,2)),hexdec(substr($step,4,2))); + // buils $count colours adding $step to $start + $result = array(); + for($i=1; $i<=$count; $i++){ + array_push($result,"#".dechex($colors[0]).dechex($colors[1]).dechex($colors[2])); + for($j=0; $j<3; $j++) { + $colors[$j] += $steps[$j]; + if($colors[$j] > 0xFF) $colors[$j] -= 0xFF; + } + } + $log->debug("Exiting color_generator method ..."); + return $result; +} + +/**This function is used to define the optimum spacin for tick marks on an axis +* Param $max - maximum value of axis +* Return type array - array of 2 values major and minor spacing +*/ + +function get_tickspacing($max = 10) +{ + global $log,$app_strings; + $log->debug("Entering get_tickspacing(".$max.") method ..."); + $result = array(1,1); + + // normalize $max to get value between 1 and 10 + $coef = pow(10,floor(log10($max))); + if($coef == 0) + { + $data=0; + echo "

".$app_strings['NO_DATA_AVAILABLE_WITH_SPECIFIED_PERIOD']."

"; + $log->debug("Exiting get_tickspacing method ..."); + return $data; + } + $normalized = $max / $coef; + + if($normalized < 1.5){ + $result[0] = 0.2; + $result[1] = 0.1; + } + elseif($normalized < 5){ + $result[0] = 0.5; + $result[1] = 0.1; + } + elseif($normalized < 10){ + $result[0] = 1.0; + $result[1] = 0.5; + } + $result[0] *= $coef; + $result[1] *= $coef; + $log->debug("Exiting get_tickspacing method ..."); + return $result; +} +?> diff --git a/oss/vtiger/trunk/include/utils/InventoryUtils.php b/oss/vtiger/trunk/include/utils/InventoryUtils.php index 06cbb59f..41d56074 100644 --- a/oss/vtiger/trunk/include/utils/InventoryUtils.php +++ b/oss/vtiger/trunk/include/utils/InventoryUtils.php @@ -1,1095 +1,1101 @@ -debug("Entering getProductDetailsBlockInfo(".$mode.",".$module.",".$num_of_products.",".$associated_prod.") method ..."); - - $productDetails = Array(); - $productBlock = Array(); - if($num_of_products=='') - { - $num_of_products = getNoOfAssocProducts($module,$focus); - } - $productDetails['no_products'] = $num_of_products; - if($associated_prod=='') - { - $productDetails['product_details'] = getAssociatedProducts($module,$focus); - } - else - { - $productDetails['product_details'] = $associated_prod; - } - if($focus != '') - { - $productBlock[] = Array('mode'=>$focus->mode); - $productBlock[] = $productDetails['product_details']; - $productBlock[] = Array('taxvalue' => $focus->column_fields['txtTax']); - $productBlock[] = Array('taxAdjustment' => $focus->column_fields['txtAdjustment']); - $productBlock[] = Array('hdnSubTotal' => $focus->column_fields['hdnSubTotal']); - $productBlock[] = Array('hdnGrandTotal' => $focus->column_fields['hdnGrandTotal']); - } - else - { - $productBlock[] = Array(Array()); - - } - $log->debug("Exiting getProductDetailsBlockInfo method ..."); - return $productBlock; -} - -/** - * This function updates the stock information once the product is ordered. - * Param $productid - product id - * Param $qty - product quantity in no's - * Param $mode - mode type - * Param $ext_prod_arr - existing vtiger_products - * Param $module - module name - * return type void - */ - -function updateStk($product_id,$qty,$mode,$ext_prod_arr,$module) -{ - global $log; - $log->debug("Entering updateStk(".$product_id.",".$qty.",".$mode.",".$ext_prod_arr.",".$module.") method ..."); - global $adb; - global $current_user; - - $log->debug("Inside updateStk function, module=".$module); - $log->debug("Product Id = $product_id & Qty = $qty"); - - $prod_name = getProductName($product_id); - $qtyinstk= getPrdQtyInStck($product_id); - $log->debug("Prd Qty in Stock ".$qtyinstk); - - $upd_qty = $qtyinstk-$qty; - sendPrdStckMail($product_id,$upd_qty,$prod_name,$qtyinstk,$qty,$module); - - $log->debug("Exiting updateStk method ..."); -} - -/** - * This function sends a mail to the handler whenever the product reaches the reorder level. - * Param $product_id - product id - * Param $upd_qty - updated product quantity in no's - * Param $prod_name - product name - * Param $qtyinstk - quantity in stock - * Param $qty - quantity - * Param $module - module name - * return type void - */ - -function sendPrdStckMail($product_id,$upd_qty,$prod_name,$qtyinstk,$qty,$module) -{ - global $log; - $log->debug("Entering sendPrdStckMail(".$product_id.",".$upd_qty.",".$prod_name.",".$qtyinstk.",".$qty.",".$module.") method ..."); - global $current_user; - global $adb; - $reorderlevel = getPrdReOrderLevel($product_id); - $log->debug("Inside sendPrdStckMail function, module=".$module); - $log->debug("Prd reorder level ".$reorderlevel); - if($upd_qty < $reorderlevel) - { - //send mail to the handler - $handler=getPrdHandler($product_id); - $handler_name = getUserName($handler); - $to_address= getUserEmail($handler); - - //Get the email details from database; - if($module == 'SalesOrder') - { - $notification_table = 'SalesOrderNotification'; - $quan_name = '{SOQUANTITY}'; - } - if($module == 'Quotes') - { - $notification_table = 'QuoteNotification'; - $quan_name = '{QUOTEQUANTITY}'; - } - if($module == 'Invoice') - { - $notification_table = 'InvoiceNotification'; - } - $query = "select * from vtiger_inventorynotification where notificationname=?"; - $result = $adb->pquery($query, array($notification_table)); - - $subject = $adb->query_result($result,0,'notificationsubject'); - $body = $adb->query_result($result,0,'notificationbody'); - - $subject = str_replace('{PRODUCTNAME}',$prod_name,$subject); - $body = str_replace('{HANDLER}',$handler_name,$body); - $body = str_replace('{PRODUCTNAME}',$prod_name,$body); - if($module == 'Invoice') - { - $body = str_replace('{CURRENTSTOCK}',$upd_qty,$body); - $body = str_replace('{REORDERLEVELVALUE}',$reorderlevel,$body); - } - else - { - $body = str_replace('{CURRENTSTOCK}',$qtyinstk,$body); - $body = str_replace($quan_name,$qty,$body); - } - $body = str_replace('{CURRENTUSER}',$current_user->user_name,$body); - - $mail_status = send_mail($module,$to_address,$current_user->user_name,$current_user->email1,decode_html($subject),nl2br(to_html($body))); - } - $log->debug("Exiting sendPrdStckMail method ..."); -} - -/**This function is used to get the quantity in stock of a given product -*Param $product_id - product id -*Returns type numeric -*/ -function getPrdQtyInStck($product_id) -{ - global $log; - $log->debug("Entering getPrdQtyInStck(".$product_id.") method ..."); - global $adb; - $query1 = "SELECT qtyinstock FROM vtiger_products WHERE productid = ?"; - $result=$adb->pquery($query1, array($product_id)); - $qtyinstck= $adb->query_result($result,0,"qtyinstock"); - $log->debug("Exiting getPrdQtyInStck method ..."); - return $qtyinstck; -} - -/**This function is used to get the reorder level of a product -*Param $product_id - product id -*Returns type numeric -*/ - -function getPrdReOrderLevel($product_id) -{ - global $log; - $log->debug("Entering getPrdReOrderLevel(".$product_id.") method ..."); - global $adb; - $query1 = "SELECT reorderlevel FROM vtiger_products WHERE productid = ?"; - $result=$adb->pquery($query1, array($product_id)); - $reorderlevel= $adb->query_result($result,0,"reorderlevel"); - $log->debug("Exiting getPrdReOrderLevel method ..."); - return $reorderlevel; -} - -/**This function is used to get the handler for a given product -*Param $product_id - product id -*Returns type numeric -*/ - -function getPrdHandler($product_id) -{ - global $log; - $log->debug("Entering getPrdHandler(".$product_id.") method ..."); - global $adb; - $query1 = "SELECT handler FROM vtiger_products WHERE productid = ?"; - $result=$adb->pquery($query1, array($product_id)); - $handler= $adb->query_result($result,0,"handler"); - $log->debug("Exiting getPrdHandler method ..."); - return $handler; -} - -/** function to get the taxid - * @param string $type - tax type (VAT or Sales or Service) - * return int $taxid - taxid corresponding to the Tax type from vtiger_inventorytaxinfo vtiger_table - */ -function getTaxId($type) -{ - global $adb, $log; - $log->debug("Entering into getTaxId($type) function."); - - $res = $adb->pquery("SELECT taxid FROM vtiger_inventorytaxinfo WHERE taxname=?", array($type)); - $taxid = $adb->query_result($res,0,'taxid'); - - $log->debug("Exiting from getTaxId($type) function. return value=$taxid"); - return $taxid; -} - -/** function to get the taxpercentage - * @param string $type - tax type (VAT or Sales or Service) - * return int $taxpercentage - taxpercentage corresponding to the Tax type from vtiger_inventorytaxinfo vtiger_table - */ -function getTaxPercentage($type) -{ - global $adb, $log; - $log->debug("Entering into getTaxPercentage($type) function."); - - $taxpercentage = ''; - - $res = $adb->pquery("SELECT percentage FROM vtiger_inventorytaxinfo WHERE taxname = ?", array($type)); - $taxpercentage = $adb->query_result($res,0,'percentage'); - - $log->debug("Exiting from getTaxPercentage($type) function. return value=$taxpercentage"); - return $taxpercentage; -} - -/** function to get the product's taxpercentage - * @param string $type - tax type (VAT or Sales or Service) - * @param id $productid - productid to which we want the tax percentage - * @param id $default - if 'default' then first look for product's tax percentage and product's tax is empty then it will return the default configured tax percentage, else it will return the product's tax (not look for default value) - * return int $taxpercentage - taxpercentage corresponding to the Tax type from vtiger_inventorytaxinfo vtiger_table - */ -function getProductTaxPercentage($type,$productid,$default='') -{ - global $adb, $log; - $log->debug("Entering into getProductTaxPercentage($type,$productid) function."); - - $taxpercentage = ''; - - $res = $adb->pquery("SELECT taxpercentage - FROM vtiger_inventorytaxinfo - INNER JOIN vtiger_producttaxrel - ON vtiger_inventorytaxinfo.taxid = vtiger_producttaxrel.taxid - WHERE vtiger_producttaxrel.productid = ? - AND vtiger_inventorytaxinfo.taxname = ?", array($productid, $type)); - $taxpercentage = $adb->query_result($res,0,'taxpercentage'); - - //This is to retrive the default configured value if the taxpercentage related to product is empty - if($taxpercentage == '' && $default == 'default') - $taxpercentage = getTaxPercentage($type); - - - $log->debug("Exiting from getProductTaxPercentage($productid,$type) function. return value=$taxpercentage"); - return $taxpercentage; -} - -/** Function used to add the history entry in the relevant tables for PO, SO, Quotes and Invoice modules - * @param string $module - current module name - * @param int $id - entity id - * @param string $relatedname - parent name of the entity ie, required field venor name for PO and account name for SO, Quotes and Invoice - * @param float $total - grand total value of the product details included tax - * @param string $history_fldval - history field value ie., quotestage for Quotes and status for PO, SO and Invoice - */ -function addInventoryHistory($module, $id, $relatedname, $total, $history_fldval) -{ - global $log, $adb; - $log->debug("Entering into function addInventoryHistory($module, $id, $relatedname, $total, $history_fieldvalue)"); - - $history_table_array = Array( - "PurchaseOrder"=>"vtiger_postatushistory", - "SalesOrder"=>"vtiger_sostatushistory", - "Quotes"=>"vtiger_quotestagehistory", - "Invoice"=>"vtiger_invoicestatushistory" - ); - - $histid = $adb->getUniqueID($history_table_array[$module]); - $modifiedtime = $adb->formatDate(date('Y-m-d H:i:s'), true); - $query = "insert into $history_table_array[$module] values(?,?,?,?,?,?)"; - $qparams = array($histid,$id,$relatedname,$total,$history_fldval,$modifiedtime); - $adb->pquery($query, $qparams); - - $log->debug("Exit from function addInventoryHistory"); -} - -/** Function used to get the list of Tax types as a array - * @param string $available - available or empty where as default is all, if available then the taxes which are available now will be returned otherwise all taxes will be returned - * @param string $sh - sh or empty, if sh passed then the shipping and handling related taxes will be returned - * @param string $mode - edit or empty, if mode is edit, then it will return taxes including desabled. - * @param string $id - crmid or empty, getting crmid to get tax values.. - * return array $taxtypes - return all the tax types as a array - */ -function getAllTaxes($available='all', $sh='',$mode='',$id='') -{ - global $adb, $log; - $log->debug("Entering into the function getAllTaxes($available,$sh,$mode,$id)"); - $taxtypes = Array(); - if($sh != '' && $sh == 'sh') - { - $tablename = 'vtiger_shippingtaxinfo'; - $value_table='vtiger_inventoryshippingrel'; - } - else - { - $tablename = 'vtiger_inventorytaxinfo'; - $value_table='vtiger_inventoryproductrel'; - } - - if($mode == 'edit' && $id != '' ) - { - //Getting total no of taxes - - $result_ids=array(); - $result=$adb->pquery("select taxname,taxid from $tablename",array()); - $noofrows=$adb->num_rows($result); - - $inventory_tax_val_result=$adb->pquery("select * from $value_table where id=?",array($id)); - - //Finding which taxes are associated with this (SO,PO,Invoice,Quotes) and getting its taxid. - for($i=0;$i<$noofrows;$i++) - { - - $taxname=$adb->query_result($result,$i,'taxname'); - $taxid=$adb->query_result($result,$i,'taxid'); - - $tax_val=$adb->query_result($inventory_tax_val_result,0,$taxname); - if($tax_val != '') - { - array_push($result_ids,$taxid); - } - - } - //We are selecting taxes using that taxids. So It will get the tax even if the tax is disabled. - $where_ids=''; - if (count($result_ids) > 0) - { - $insert_str = str_repeat("?,", count($result_ids)-1); - $insert_str .= "?"; - $where_ids="taxid in ($insert_str) or"; - } - - $res = $adb->pquery("select * from $tablename where $where_ids deleted=0 order by taxid",$result_ids); - } - else - { - //This where condition is added to get all products or only availble products - if($available != 'all' && $available == 'available') - { - $where = " where $tablename.deleted=0"; - } - - $res = $adb->pquery("select * from $tablename $where order by deleted",array()); - - } - - $noofrows = $adb->num_rows($res); - for($i=0;$i<$noofrows;$i++) - { - $taxtypes[$i]['taxid'] = $adb->query_result($res,$i,'taxid'); - $taxtypes[$i]['taxname'] = $adb->query_result($res,$i,'taxname'); - $taxtypes[$i]['taxlabel'] = $adb->query_result($res,$i,'taxlabel'); - $taxtypes[$i]['percentage'] = $adb->query_result($res,$i,'percentage'); - $taxtypes[$i]['deleted'] = $adb->query_result($res,$i,'deleted'); - } - $log->debug("Exit from the function getAllTaxes($available,$sh,$mode,$id)"); - - return $taxtypes; -} - - -/** Function used to get all the tax details which are associated to the given product - * @param int $productid - product id to which we want to get all the associated taxes - * @param string $available - available or empty or available_associated where as default is all, if available then the taxes which are available now will be returned, if all then all taxes will be returned otherwise if the value is available_associated then all the associated taxes even they are not available and all the available taxes will be retruned - * @return array $tax_details - tax details as a array with productid, taxid, taxname, percentage and deleted - */ -function getTaxDetailsForProduct($productid, $available='all') -{ - global $log, $adb; - $log->debug("Entering into function getTaxDetailsForProduct($productid)"); - if($productid != '') - { - //where condition added to avoid to retrieve the non available taxes - $where = ''; - if($available != 'all' && $available == 'available') - { - $where = ' and vtiger_inventorytaxinfo.deleted=0'; - } - if($available != 'all' && $available == 'available_associated') - { - $query = "SELECT vtiger_producttaxrel.*, vtiger_inventorytaxinfo.* FROM vtiger_inventorytaxinfo left JOIN vtiger_producttaxrel ON vtiger_inventorytaxinfo.taxid = vtiger_producttaxrel.taxid WHERE vtiger_producttaxrel.productid = ? or vtiger_inventorytaxinfo.deleted=0 GROUP BY vtiger_inventorytaxinfo.taxid"; - } - else - { - $query = "SELECT vtiger_producttaxrel.*, vtiger_inventorytaxinfo.* FROM vtiger_inventorytaxinfo INNER JOIN vtiger_producttaxrel ON vtiger_inventorytaxinfo.taxid = vtiger_producttaxrel.taxid WHERE vtiger_producttaxrel.productid = ? $where"; - } - $params = array($productid); - - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $query = fixPostgresQuery( $query, $log, 0); - - $res = $adb->pquery($query, $params); - for($i=0;$i<$adb->num_rows($res);$i++) - { - $tax_details[$i]['productid'] = $adb->query_result($res,$i,'productid'); - $tax_details[$i]['taxid'] = $adb->query_result($res,$i,'taxid'); - $tax_details[$i]['taxname'] = $adb->query_result($res,$i,'taxname'); - $tax_details[$i]['taxlabel'] = $adb->query_result($res,$i,'taxlabel'); - $tax_details[$i]['percentage'] = $adb->query_result($res,$i,'taxpercentage'); - $tax_details[$i]['deleted'] = $adb->query_result($res,$i,'deleted'); - } - } - else - { - $log->debug("Product id is empty. we cannot retrieve the associated products."); - } - - $log->debug("Exit from function getTaxDetailsForProduct($productid)"); - return $tax_details; -} - -/** Function used to delete the Inventory product details for the passed entity - * @param int $objectid - entity id to which we want to delete the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice - * @param string $return_old_values - string which contains the string return_old_values or may be empty, if the string is return_old_values then before delete old values will be retrieved - * @return array $ext_prod_arr - if the second input parameter is 'return_old_values' then the array which contains the productid and quantity which will be retrieved before delete the product details will be returned otherwise return empty - */ -function deleteInventoryProductDetails($focus) -{ - global $log, $adb,$updateInventoryProductRel_update_product_array; - $log->debug("Entering into function deleteInventoryProductDetails(".$focus->id.")."); - - $product_info = $adb->pquery("SELECT productid, quantity, sequence_no, incrementondel from vtiger_inventoryproductrel WHERE id=?",array($focus->id)); - $numrows = $adb->num_rows($product_info); - for($index = 0;$index <$numrows;$index++){ - $productid = $adb->query_result($product_info,$index,'productid'); - $sequence_no = $adb->query_result($product_info,$index,'sequence_no'); - $qty = $adb->query_result($product_info,$index,'quantity'); - $incrementondel = $adb->query_result($product_info,$index,'incrementondel'); - - if($incrementondel){ - $focus->update_product_array[$focus->id][$sequence_no][$productid]= $qty; - $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($focus->id,$sequence_no)); - if($adb->num_rows($sub_prod_query)>0){ - for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ - $sub_prod_id = $adb->query_result($sub_prod_query,$j,"productid"); - $focus->update_product_array[$focus->id][$sequence_no][$sub_prod_id]= $qty; - } - } - - } - } - $updateInventoryProductRel_update_product_array = $focus->update_product_array; - $adb->pquery("delete from vtiger_inventoryproductrel where id=?", array($focus->id)); - $adb->pquery("delete from vtiger_inventorysubproductrel where id=?", array($focus->id)); - $adb->pquery("delete from vtiger_inventoryshippingrel where id=?", array($focus->id)); - - $log->debug("Exit from function deleteInventoryProductDetails(".$focus->id.")"); -} - -function updateInventoryProductRel($entity) -{ - global $log, $adb,$updateInventoryProductRel_update_product_array; - $entity_id = vtws_getIdComponents($entity->getId()); - $entity_id = $entity_id[1]; - $update_product_array = $updateInventoryProductRel_update_product_array; - $log->debug("Entering into function updateInventoryProductRel(".$entity_id.")."); - - if(!empty($update_product_array)){ - foreach($update_product_array as $id=>$seq){ - foreach($seq as $seq=>$product_info) - { - foreach($product_info as $key=>$index){ - $updqtyinstk= getPrdQtyInStck($key); - $upd_qty = $updqtyinstk+$index; - updateProductQty($key, $upd_qty); - } - } - } - } - $adb->pquery("UPDATE vtiger_inventoryproductrel SET incrementondel=1 WHERE id=?",array($entity_id)); - - $product_info = $adb->pquery("SELECT productid,sequence_no, quantity from vtiger_inventoryproductrel WHERE id=?",array($entity_id)); - $numrows = $adb->num_rows($product_info); - for($index = 0;$index <$numrows;$index++){ - $productid = $adb->query_result($product_info,$index,'productid'); - $qty = $adb->query_result($product_info,$index,'quantity'); - $sequence_no = $adb->query_result($product_info,$index,'sequence_no'); - $qtyinstk= getPrdQtyInStck($productid); - $upd_qty = $qtyinstk-$qty; - updateProductQty($productid, $upd_qty); - $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($entity_id,$sequence_no)); - if($adb->num_rows($sub_prod_query)>0){ - for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ - $sub_prod_id = $adb->query_result($sub_prod_query,$j,"productid"); - $sqtyinstk= getPrdQtyInStck($sub_prod_id); - $supd_qty = $sqtyinstk-$qty; - updateProductQty($sub_prod_id, $supd_qty); - } - } - } - - $log->debug("Exit from function updateInventoryProductRel(".$entity_id.")"); -} - -/** Function used to save the Inventory product details for the passed entity - * @param object reference $focus - object reference to which we want to save the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice - * @param string $module - module name - * @param $update_prod_stock - true or false (default), if true we have to update the stock for PO only - * @return void - */ -function saveInventoryProductDetails($focus, $module, $update_prod_stock='false', $updateDemand='') -{ - global $log, $adb; - $id=$focus->id; - $log->debug("Entering into function saveInventoryProductDetails($module)."); - //Added to get the convertid - if(isset($_REQUEST['convert_from']) && $_REQUEST['convert_from'] !='') - { - $id=$_REQUEST['return_id']; - } - else if(isset($_REQUEST['duplicate_from']) && $_REQUEST['duplicate_from'] !='') - { - $id=$_REQUEST['duplicate_from']; - } - - $ext_prod_arr = Array(); - if($focus->mode == 'edit') - { - if($_REQUEST['taxtype'] == 'group') - $all_available_taxes = getAllTaxes('available','','edit',$id); - $return_old_values = ''; - if($module != 'PurchaseOrder') - { - $return_old_values = 'return_old_values'; - } - - //we will retrieve the existing product details and store it in a array and then delete all the existing product details and save new values, retrieve the old value and update stock only for SO, Quotes and Invoice not for PO - //$ext_prod_arr = deleteInventoryProductDetails($focus->id,$return_old_values); - deleteInventoryProductDetails($focus); - } - else - { - if($_REQUEST['taxtype'] == 'group') - $all_available_taxes = getAllTaxes('available','','edit',$id); - } - $tot_no_prod = $_REQUEST['totalProductCount']; - //If the taxtype is group then retrieve all available taxes, else retrive associated taxes for each product inside loop - $prod_seq=1; - for($i=1; $i<=$tot_no_prod; $i++) - { - //if the product is deleted then we should avoid saving the deleted products - if($_REQUEST["deleted".$i] == 1) - continue; - - $prod_id = $_REQUEST['hdnProductId'.$i]; - if(isset($_REQUEST['productDescription'.$i])) - $description = $_REQUEST['productDescription'.$i]; - /*else{ - $desc_duery = "select vtiger_crmentity.description AS product_description from vtiger_crmentity where vtiger_crmentity.crmid=?"; - $desc_res = $adb->pquery($desc_duery,array($prod_id)); - $description = $adb->query_result($desc_res,0,"product_description"); - } */ - $qty = $_REQUEST['qty'.$i]; - $listprice = $_REQUEST['listPrice'.$i]; - $comment = $_REQUEST['comment'.$i]; - - //we have to update the Product stock for PurchaseOrder if $update_prod_stock is true - if($module == 'PurchaseOrder' && $update_prod_stock == 'true') - { - addToProductStock($prod_id,$qty); - } - if($module == 'SalesOrder') - { - if($updateDemand == '-') - { - deductFromProductDemand($prod_id,$qty); - } - elseif($updateDemand == '+') - { - addToProductDemand($prod_id,$qty); - } - } - - $query ="insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice, comment, description) values(?,?,?,?,?,?,?)"; - $qparams = array($focus->id,$prod_id,$prod_seq,$qty,$listprice,$comment,$description); - $adb->pquery($query,$qparams); - - $sub_prod_str = $_REQUEST['subproduct_ids'.$i]; - if (!empty($sub_prod_str)) { - $sub_prod = split(":",$sub_prod_str); - for($j=0;$jid,$prod_seq,$sub_prod[$j]); - $adb->pquery($query,$qparams); - } - } - $prod_seq++; - - if($module != 'PurchaseOrder') - { - //update the stock with existing details - updateStk($prod_id,$qty,$focus->mode,$ext_prod_arr,$module); - } - - //we should update discount and tax details - $updatequery = "update vtiger_inventoryproductrel set "; - $updateparams = array(); - - //set the discount percentage or discount amount in update query, then set the tax values - if($_REQUEST['discount_type'.$i] == 'percentage') - { - $updatequery .= " discount_percent=?,"; - array_push($updateparams, $_REQUEST['discount_percentage'.$i]); - } - elseif($_REQUEST['discount_type'.$i] == 'amount') - { - $updatequery .= " discount_amount=?,"; - $discount_amount = $_REQUEST['discount_amount'.$i]; - array_push($updateparams, $discount_amount); - } - if($_REQUEST['taxtype'] == 'group') - { - for($tax_count=0;$tax_countid,$prod_id); - } - else - { - $taxes_for_product = getTaxDetailsForProduct($prod_id,'all'); - for($tax_count=0;$tax_countid,$prod_id); - } - // jens 2006/08/19 - protect against empy update queries - if( !preg_match( '/set\s+where/i', $updatequery)) { - $adb->pquery($updatequery,$updateparams); - } - } - - //we should update the netprice (subtotal), taxtype, group discount, S&H charge, S&H taxes, adjustment and total - //netprice, group discount, taxtype, S&H amount, adjustment and total to entity table - - $updatequery = " update $focus->table_name set "; - $updateparams = array(); - $subtotal = $_REQUEST['subtotal']; - $updatequery .= " subtotal=?,"; - array_push($updateparams, $subtotal); - - $updatequery .= " taxtype=?,"; - array_push($updateparams, $_REQUEST['taxtype']); - - //for discount percentage or discount amount - if($_REQUEST['discount_type_final'] == 'percentage') - { - $updatequery .= " discount_percent=?,"; - array_push($updateparams, $_REQUEST['discount_percentage_final']); - } - elseif($_REQUEST['discount_type_final'] == 'amount') - { - $discount_amount_final = $_REQUEST['discount_amount_final']; - $updatequery .= " discount_amount=?,"; - array_push($updateparams, $discount_amount_final); - } - - $shipping_handling_charge = $_REQUEST['shipping_handling_charge']; - $updatequery .= " s_h_amount=?,"; - array_push($updateparams, $shipping_handling_charge); - - //if the user gave - sign in adjustment then add with the value - $adjustmentType = ''; - if($_REQUEST['adjustmentType'] == '-') - $adjustmentType = $_REQUEST['adjustmentType']; - - $adjustment = $_REQUEST['adjustment']; - $updatequery .= " adjustment=?,"; - array_push($updateparams, $adjustmentType.$adjustment); - - $total = $_REQUEST['total']; - $updatequery .= " total=?"; - array_push($updateparams, $total); - - //$id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid'); - //Added where condition to which entity we want to update these values - $updatequery .= " where ".$focus->table_index."=?"; - array_push($updateparams, $focus->id); - - $adb->pquery($updatequery,$updateparams); - - //to save the S&H tax details in vtiger_inventoryshippingrel table - $sh_tax_details = getAllTaxes('all','sh'); - $sh_query_fields = "id,"; - $sh_query_values = "?,"; - $sh_query_params = array($focus->id); - for($i=0;$ipquery($sh_query,$sh_query_params); - - $log->debug("Exit from function saveInventoryProductDetails($module)."); -} - - -/** function used to get the tax type for the entity (PO, SO, Quotes or Invoice) - * @param string $module - module name - * @param int $id - id of the PO or SO or Quotes or Invoice - * @return string $taxtype - taxtype for the given entity which will be individual or group - */ -function getInventoryTaxType($module, $id) -{ - global $log, $adb; - - $log->debug("Entering into function getInventoryTaxType($module, $id)."); - - $inv_table_array = Array('PurchaseOrder'=>'vtiger_purchaseorder','SalesOrder'=>'vtiger_salesorder','Quotes'=>'vtiger_quotes','Invoice'=>'vtiger_invoice'); - $inv_id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid'); - - $res = $adb->pquery("select taxtype from $inv_table_array[$module] where $inv_id_array[$module]=?", array($id)); - - $taxtype = $adb->query_result($res,0,'taxtype'); - - $log->debug("Exit from function getInventoryTaxType($module, $id)."); - - return $taxtype; -} - -/** function used to get the price type for the entity (PO, SO, Quotes or Invoice) - * @param string $module - module name - * @param int $id - id of the PO or SO or Quotes or Invoice - * @return string $pricetype - pricetype for the given entity which will be unitprice or secondprice - */ -function getInventoryCurrencyInfo($module, $id) -{ - global $log, $adb; - - $log->debug("Entering into function getInventoryCurrencyInfo($module, $id)."); - - $inv_table_array = Array('PurchaseOrder'=>'vtiger_purchaseorder','SalesOrder'=>'vtiger_salesorder','Quotes'=>'vtiger_quotes','Invoice'=>'vtiger_invoice'); - $inv_id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid'); - - $inventory_table = $inv_table_array[$module]; - $inventory_id = $inv_id_array[$module]; - $res = $adb->pquery("select currency_id, $inventory_table.conversion_rate as conv_rate, vtiger_currency_info.* from $inventory_table - inner join vtiger_currency_info on $inventory_table.currency_id = vtiger_currency_info.id - where $inventory_id=?", array($id)); - - $currency_info = array(); - $currency_info['currency_id'] = $adb->query_result($res,0,'currency_id'); - $currency_info['conversion_rate'] = $adb->query_result($res,0,'conv_rate'); - $currency_info['currency_name'] = $adb->query_result($res,0,'currency_name'); - $currency_info['currency_code'] = $adb->query_result($res,0,'currency_code'); - $currency_info['currency_symbol'] = $adb->query_result($res,0,'currency_symbol'); - - $log->debug("Exit from function getInventoryCurrencyInfo($module, $id)."); - - return $currency_info; -} - -/** function used to get the taxvalue which is associated with a product for PO/SO/Quotes or Invoice - * @param int $id - id of PO/SO/Quotes or Invoice - * @param int $productid - product id - * @param string $taxname - taxname to which we want the value - * @return float $taxvalue - tax value - */ -function getInventoryProductTaxValue($id, $productid, $taxname) -{ - global $log, $adb; - $log->debug("Entering into function getInventoryProductTaxValue($id, $productid, $taxname)."); - - $res = $adb->pquery("select $taxname from vtiger_inventoryproductrel where id = ? and productid = ?", array($id, $productid)); - $taxvalue = $adb->query_result($res,0,$taxname); - - if($taxvalue == '') - $taxvalue = '0.00'; - - $log->debug("Exit from function getInventoryProductTaxValue($id, $productid, $taxname)."); - - return $taxvalue; -} - -/** function used to get the shipping & handling tax percentage for the given inventory id and taxname - * @param int $id - entity id which will be PO/SO/Quotes or Invoice id - * @param string $taxname - shipping and handling taxname - * @return float $taxpercentage - shipping and handling taxpercentage which is associated with the given entity - */ -function getInventorySHTaxPercent($id, $taxname) -{ - global $log, $adb; - $log->debug("Entering into function getInventorySHTaxPercent($id, $taxname)"); - - $res = $adb->pquery("select $taxname from vtiger_inventoryshippingrel where id= ?", array($id)); - $taxpercentage = $adb->query_result($res,0,$taxname); - - if($taxpercentage == '') - $taxpercentage = '0.00'; - - $log->debug("Exit from function getInventorySHTaxPercent($id, $taxname)"); - - return $taxpercentage; -} - -/** Function used to get the list of all Currencies as a array - * @param string available - if 'all' returns all the currencies, default value 'available' returns only the currencies which are available for use. - * return array $currency_details - return details of all the currencies as a array - */ -function getAllCurrencies($available='available') { - global $adb, $log; - $log->debug("Entering into function getAllCurrencies($available)"); - - $sql = "select * from vtiger_currency_info"; - if ($available != 'all') { - $sql .= " where currency_status='Active' and deleted=0"; - } - $res=$adb->pquery($sql, array()); - $noofrows = $adb->num_rows($res); - - for($i=0;$i<$noofrows;$i++) - { - $currency_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name'); - $currency_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code'); - $currency_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol'); - $currency_details[$i]['curid'] = $adb->query_result($res,$i,'id'); - $currency_details[$i]['conversionrate'] = $adb->query_result($res,$i,'conversion_rate'); - $currency_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id'); - } - - $log->debug("Entering into function getAllCurrencies($available)"); - return $currency_details; - -} - -/** Function used to get all the price details for different currencies which are associated to the given product - * @param int $productid - product id to which we want to get all the associated prices - * @param decimal $unit_price - Unit price of the product - * @param string $available - available or available_associated where as default is available, if available then the prices in the currencies which are available now will be returned, otherwise if the value is available_associated then prices of all the associated currencies will be retruned - * @return array $price_details - price details as a array with productid, curid, curname - */ -function getPriceDetailsForProduct($productid, $unit_price, $available='available', $itemtype='Products') -{ - global $log, $adb; - $log->debug("Entering into function getPriceDetailsForProduct($productid)"); - if($productid != '') - { - $product_currency_id = getProductBaseCurrency($productid, $itemtype); - $product_base_conv_rate = getBaseConversionRateForProduct($productid,'edit',$itemtype); - // Detail View - if ($available == 'available_associated') { - $query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price - from vtiger_currency_info - inner join vtiger_productcurrencyrel on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid - where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0 - and vtiger_productcurrencyrel.productid = ? and vtiger_currency_info.id != ?"; - $params = array($productid, $product_currency_id); - } else { // Edit View - $query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price - from vtiger_currency_info - left join vtiger_productcurrencyrel - on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid and vtiger_productcurrencyrel.productid = ? - where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0"; - $params = array($productid); - } - - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $query = fixPostgresQuery( $query, $log, 0); - - $res = $adb->pquery($query, $params); - for($i=0;$i<$adb->num_rows($res);$i++) - { - $price_details[$i]['productid'] = $productid; - $price_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name'); - $price_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code'); - $price_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol'); - $currency_id = $adb->query_result($res,$i,'id'); - $price_details[$i]['curid'] = $currency_id; - $price_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id'); - $cur_value = $adb->query_result($res,$i,'actual_price'); - - // Get the conversion rate for the given currency, get the conversion rate of the product currency to base currency. - // Both together will be the actual conversion rate for the given currency. - $conversion_rate = $adb->query_result($res,$i,'conversion_rate'); - $actual_conversion_rate = $product_base_conv_rate * $conversion_rate; - - if ($cur_value == null || $cur_value == '') { - $price_details[$i]['check_value'] = false; - if ($unit_price != null) { - $cur_value = convertFromMasterCurrency($unit_price, $actual_conversion_rate); - } else { - $cur_value = '0'; - } - } else { - $price_details[$i]['check_value'] = true; - } - $price_details[$i]['curvalue'] = $cur_value; - $price_details[$i]['conversionrate'] = $actual_conversion_rate; - - $is_basecurrency = false; - if ($currency_id == $product_currency_id) { - $is_basecurrency = true; - } - $price_details[$i]['is_basecurrency'] = $is_basecurrency; - } - } - else - { - if($available == 'available') { // Create View - global $current_user; - - $user_currency_id = fetchCurrency($current_user->id); - - $query = "select vtiger_currency_info.* from vtiger_currency_info - where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0"; - $params = array(); - - $res = $adb->pquery($query, $params); - for($i=0;$i<$adb->num_rows($res);$i++) - { - $price_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name'); - $price_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code'); - $price_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol'); - $currency_id = $adb->query_result($res,$i,'id'); - $price_details[$i]['curid'] = $currency_id; - $price_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id'); - - // Get the conversion rate for the given currency, get the conversion rate of the product currency(logged in user's currency) to base currency. - // Both together will be the actual conversion rate for the given currency. - $conversion_rate = $adb->query_result($res,$i,'conversion_rate'); - $user_cursym_convrate = getCurrencySymbolandCRate($user_currency_id); - $product_base_conv_rate = 1 / $user_cursym_convrate['rate']; - $actual_conversion_rate = $product_base_conv_rate * $conversion_rate; - - $price_details[$i]['check_value'] = false; - $price_details[$i]['curvalue'] = '0'; - $price_details[$i]['conversionrate'] = $actual_conversion_rate; - - $is_basecurrency = false; - if ($currency_id == $user_currency_id) { - $is_basecurrency = true; - } - $price_details[$i]['is_basecurrency'] = $is_basecurrency; - } - } else { - $log->debug("Product id is empty. we cannot retrieve the associated prices."); - } - } - - $log->debug("Exit from function getPriceDetailsForProduct($productid)"); - return $price_details; -} - -/** Function used to get the base currency used for the given Product - * @param int $productid - product id for which we want to get the id of the base currency - * @return int $currencyid - id of the base currency for the given product - */ -function getProductBaseCurrency($productid,$module='Products') { - global $adb, $log; - if ($module == 'Services') { - $sql = "select currency_id from vtiger_service where serviceid=?"; - } else { - $sql = "select currency_id from vtiger_products where productid=?"; - } - $params = array($productid); - $res = $adb->pquery($sql, $params); - $currencyid = $adb->query_result($res, 0, 'currency_id'); - return $currencyid; -} - -/** Function used to get the conversion rate for the product base currency with respect to the CRM base currency - * @param int $productid - product id for which we want to get the conversion rate of the base currency - * @param string $mode - Mode in which the function is called - * @return number $conversion_rate - conversion rate of the base currency for the given product based on the CRM base currency - */ -function getBaseConversionRateForProduct($productid, $mode='edit', $module='Products') { - global $adb, $log, $current_user; - - if ($mode == 'edit') { - if ($module == 'Services') { - $sql = "select conversion_rate from vtiger_service inner join vtiger_currency_info - on vtiger_service.currency_id = vtiger_currency_info.id where vtiger_service.serviceid=?"; - } else { - $sql = "select conversion_rate from vtiger_products inner join vtiger_currency_info - on vtiger_products.currency_id = vtiger_currency_info.id where vtiger_products.productid=?"; - } - $params = array($productid); - } else { - $sql = "select conversion_rate from vtiger_currency_info where id=?"; - $params = array(fetchCurrency($current_user->id)); - } - - $res = $adb->pquery($sql, $params); - $conv_rate = $adb->query_result($res, 0, 'conversion_rate'); - - return 1 / $conv_rate; -} - -/** Function used to get the prices for the given list of products based in the specified currency - * @param int $currencyid - currency id based on which the prices have to be provided - * @param array $product_ids - List of product id's for which we want to get the price based on given currency - * @return array $prices_list - List of prices for the given list of products based on the given currency in the form of 'product id' mapped to 'price value' - */ -function getPricesForProducts($currencyid, $product_ids, $module='Products') { - global $adb,$log,$current_user; - - $price_list = array(); - if (count($product_ids) > 0) { - if ($module == 'Services') { - $query = "SELECT vtiger_currency_info.id, vtiger_currency_info.conversion_rate, " . - "vtiger_service.serviceid AS productid, vtiger_service.unit_price, " . - "vtiger_productcurrencyrel.actual_price " . - "FROM (vtiger_currency_info, vtiger_service) " . - "left join vtiger_productcurrencyrel on vtiger_service.serviceid = vtiger_productcurrencyrel.productid " . - "and vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid " . - "where vtiger_service.serviceid in (". generateQuestionMarks($product_ids) .") and vtiger_currency_info.id = ?"; - } else { - $query = "SELECT vtiger_currency_info.id, vtiger_currency_info.conversion_rate, " . - "vtiger_products.productid, vtiger_products.unit_price, " . - "vtiger_productcurrencyrel.actual_price " . - "FROM (vtiger_currency_info, vtiger_products) " . - "left join vtiger_productcurrencyrel on vtiger_products.productid = vtiger_productcurrencyrel.productid " . - "and vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid " . - "where vtiger_products.productid in (". generateQuestionMarks($product_ids) .") and vtiger_currency_info.id = ?"; - } - $params = array($product_ids, $currencyid); - $result = $adb->pquery($query, $params); - - for($i=0;$i<$adb->num_rows($result);$i++) - { - $product_id = $adb->query_result($result, $i, 'productid'); - if(getFieldVisibilityPermission($module,$current_user->id,'unit_price') == '0') { - $actual_price = $adb->query_result($result, $i, 'actual_price'); - - if ($actual_price == null || $actual_price == '') { - $unit_price = $adb->query_result($result, $i, 'unit_price'); - $product_conv_rate = $adb->query_result($result, $i, 'conversion_rate'); - $product_base_conv_rate = getBaseConversionRateForProduct($product_id,'edit',$module); - $conversion_rate = $product_conv_rate * $product_base_conv_rate; - - $actual_price = $unit_price * $conversion_rate; - } - $price_list[$product_id] = $actual_price; - } else { - $price_list[$product_id] = ''; - } - } - } - return $price_list; -} - -/** Function used to get the currency used for the given Price book - * @param int $pricebook_id - pricebook id for which we want to get the id of the currency used - * @return int $currencyid - id of the currency used for the given pricebook - */ -function getPriceBookCurrency($pricebook_id) { - global $adb; - $result = $adb->pquery("select currency_id from vtiger_pricebook where pricebookid=?", array($pricebook_id)); - $currency_id = $adb->query_result($result,0,'currency_id'); - return $currency_id; -} +debug("Entering getProductDetailsBlockInfo(".$mode.",".$module.",".$num_of_products.",".$associated_prod.") method ..."); + + $productDetails = Array(); + $productBlock = Array(); + if($num_of_products=='') + { + $num_of_products = getNoOfAssocProducts($module,$focus); + } + $productDetails['no_products'] = $num_of_products; + if($associated_prod=='') + { + $productDetails['product_details'] = getAssociatedProducts($module,$focus); + } + else + { + $productDetails['product_details'] = $associated_prod; + } + if($focus != '') + { + $productBlock[] = Array('mode'=>$focus->mode); + $productBlock[] = $productDetails['product_details']; + $productBlock[] = Array('taxvalue' => $focus->column_fields['txtTax']); + $productBlock[] = Array('taxAdjustment' => $focus->column_fields['txtAdjustment']); + $productBlock[] = Array('hdnSubTotal' => $focus->column_fields['hdnSubTotal']); + $productBlock[] = Array('hdnGrandTotal' => $focus->column_fields['hdnGrandTotal']); + } + else + { + $productBlock[] = Array(Array()); + + } + $log->debug("Exiting getProductDetailsBlockInfo method ..."); + return $productBlock; +} + +/** + * This function updates the stock information once the product is ordered. + * Param $productid - product id + * Param $qty - product quantity in no's + * Param $mode - mode type + * Param $ext_prod_arr - existing vtiger_products + * Param $module - module name + * return type void + */ + +function updateStk($product_id,$qty,$mode,$ext_prod_arr,$module) +{ + global $log; + $log->debug("Entering updateStk(".$product_id.",".$qty.",".$mode.",".$ext_prod_arr.",".$module.") method ..."); + global $adb; + global $current_user; + + $log->debug("Inside updateStk function, module=".$module); + $log->debug("Product Id = $product_id & Qty = $qty"); + + $prod_name = getProductName($product_id); + $qtyinstk= getPrdQtyInStck($product_id); + $log->debug("Prd Qty in Stock ".$qtyinstk); + + $upd_qty = $qtyinstk-$qty; + sendPrdStckMail($product_id,$upd_qty,$prod_name,$qtyinstk,$qty,$module); + + $log->debug("Exiting updateStk method ..."); +} + +/** + * This function sends a mail to the handler whenever the product reaches the reorder level. + * Param $product_id - product id + * Param $upd_qty - updated product quantity in no's + * Param $prod_name - product name + * Param $qtyinstk - quantity in stock + * Param $qty - quantity + * Param $module - module name + * return type void + */ + +function sendPrdStckMail($product_id,$upd_qty,$prod_name,$qtyinstk,$qty,$module) +{ + global $log; + $log->debug("Entering sendPrdStckMail(".$product_id.",".$upd_qty.",".$prod_name.",".$qtyinstk.",".$qty.",".$module.") method ..."); + global $current_user; + global $adb; + $reorderlevel = getPrdReOrderLevel($product_id); + $log->debug("Inside sendPrdStckMail function, module=".$module); + $log->debug("Prd reorder level ".$reorderlevel); + if($upd_qty < $reorderlevel) + { + //send mail to the handler + $handler=getPrdHandler($product_id); + $handler_name = getUserName($handler); + $to_address= getUserEmail($handler); + + //Get the email details from database; + if($module == 'SalesOrder') + { + $notification_table = 'SalesOrderNotification'; + $quan_name = '{SOQUANTITY}'; + } + if($module == 'Quotes') + { + $notification_table = 'QuoteNotification'; + $quan_name = '{QUOTEQUANTITY}'; + } + if($module == 'Invoice') + { + $notification_table = 'InvoiceNotification'; + } + $query = "select * from vtiger_inventorynotification where notificationname=?"; + $result = $adb->pquery($query, array($notification_table)); + + $subject = $adb->query_result($result,0,'notificationsubject'); + $body = $adb->query_result($result,0,'notificationbody'); + $status = $adb->query_result($result,0,'status'); + + if($status == 0 || $status == '') + return false; + + $subject = str_replace('{PRODUCTNAME}',$prod_name,$subject); + $body = str_replace('{HANDLER}',$handler_name,$body); + $body = str_replace('{PRODUCTNAME}',$prod_name,$body); + if($module == 'Invoice') + { + $body = str_replace('{CURRENTSTOCK}',$upd_qty,$body); + $body = str_replace('{REORDERLEVELVALUE}',$reorderlevel,$body); + } + else + { + $body = str_replace('{CURRENTSTOCK}',$qtyinstk,$body); + $body = str_replace($quan_name,$qty,$body); + } + $body = str_replace('{CURRENTUSER}',$current_user->user_name,$body); + + $mail_status = send_mail($module,$to_address,$current_user->user_name,$current_user->email1,decode_html($subject),nl2br(to_html($body))); + } + $log->debug("Exiting sendPrdStckMail method ..."); +} + +/**This function is used to get the quantity in stock of a given product +*Param $product_id - product id +*Returns type numeric +*/ +function getPrdQtyInStck($product_id) +{ + global $log; + $log->debug("Entering getPrdQtyInStck(".$product_id.") method ..."); + global $adb; + $query1 = "SELECT qtyinstock FROM vtiger_products WHERE productid = ?"; + $result=$adb->pquery($query1, array($product_id)); + $qtyinstck= $adb->query_result($result,0,"qtyinstock"); + $log->debug("Exiting getPrdQtyInStck method ..."); + return $qtyinstck; +} + +/**This function is used to get the reorder level of a product +*Param $product_id - product id +*Returns type numeric +*/ + +function getPrdReOrderLevel($product_id) +{ + global $log; + $log->debug("Entering getPrdReOrderLevel(".$product_id.") method ..."); + global $adb; + $query1 = "SELECT reorderlevel FROM vtiger_products WHERE productid = ?"; + $result=$adb->pquery($query1, array($product_id)); + $reorderlevel= $adb->query_result($result,0,"reorderlevel"); + $log->debug("Exiting getPrdReOrderLevel method ..."); + return $reorderlevel; +} + +/**This function is used to get the handler for a given product +*Param $product_id - product id +*Returns type numeric +*/ + +function getPrdHandler($product_id) +{ + global $log; + $log->debug("Entering getPrdHandler(".$product_id.") method ..."); + global $adb; + $query1 = "SELECT handler FROM vtiger_products WHERE productid = ?"; + $result=$adb->pquery($query1, array($product_id)); + $handler= $adb->query_result($result,0,"handler"); + $log->debug("Exiting getPrdHandler method ..."); + return $handler; +} + +/** function to get the taxid + * @param string $type - tax type (VAT or Sales or Service) + * return int $taxid - taxid corresponding to the Tax type from vtiger_inventorytaxinfo vtiger_table + */ +function getTaxId($type) +{ + global $adb, $log; + $log->debug("Entering into getTaxId($type) function."); + + $res = $adb->pquery("SELECT taxid FROM vtiger_inventorytaxinfo WHERE taxname=?", array($type)); + $taxid = $adb->query_result($res,0,'taxid'); + + $log->debug("Exiting from getTaxId($type) function. return value=$taxid"); + return $taxid; +} + +/** function to get the taxpercentage + * @param string $type - tax type (VAT or Sales or Service) + * return int $taxpercentage - taxpercentage corresponding to the Tax type from vtiger_inventorytaxinfo vtiger_table + */ +function getTaxPercentage($type) +{ + global $adb, $log; + $log->debug("Entering into getTaxPercentage($type) function."); + + $taxpercentage = ''; + + $res = $adb->pquery("SELECT percentage FROM vtiger_inventorytaxinfo WHERE taxname = ?", array($type)); + $taxpercentage = $adb->query_result($res,0,'percentage'); + + $log->debug("Exiting from getTaxPercentage($type) function. return value=$taxpercentage"); + return $taxpercentage; +} + +/** function to get the product's taxpercentage + * @param string $type - tax type (VAT or Sales or Service) + * @param id $productid - productid to which we want the tax percentage + * @param id $default - if 'default' then first look for product's tax percentage and product's tax is empty then it will return the default configured tax percentage, else it will return the product's tax (not look for default value) + * return int $taxpercentage - taxpercentage corresponding to the Tax type from vtiger_inventorytaxinfo vtiger_table + */ +function getProductTaxPercentage($type,$productid,$default='') +{ + global $adb, $log; + $log->debug("Entering into getProductTaxPercentage($type,$productid) function."); + + $taxpercentage = ''; + + $res = $adb->pquery("SELECT taxpercentage + FROM vtiger_inventorytaxinfo + INNER JOIN vtiger_producttaxrel + ON vtiger_inventorytaxinfo.taxid = vtiger_producttaxrel.taxid + WHERE vtiger_producttaxrel.productid = ? + AND vtiger_inventorytaxinfo.taxname = ?", array($productid, $type)); + $taxpercentage = $adb->query_result($res,0,'taxpercentage'); + + //This is to retrive the default configured value if the taxpercentage related to product is empty + if($taxpercentage == '' && $default == 'default') + $taxpercentage = getTaxPercentage($type); + + + $log->debug("Exiting from getProductTaxPercentage($productid,$type) function. return value=$taxpercentage"); + return $taxpercentage; +} + +/** Function used to add the history entry in the relevant tables for PO, SO, Quotes and Invoice modules + * @param string $module - current module name + * @param int $id - entity id + * @param string $relatedname - parent name of the entity ie, required field venor name for PO and account name for SO, Quotes and Invoice + * @param float $total - grand total value of the product details included tax + * @param string $history_fldval - history field value ie., quotestage for Quotes and status for PO, SO and Invoice + */ +function addInventoryHistory($module, $id, $relatedname, $total, $history_fldval) +{ + global $log, $adb; + $log->debug("Entering into function addInventoryHistory($module, $id, $relatedname, $total, $history_fieldvalue)"); + + $history_table_array = Array( + "PurchaseOrder"=>"vtiger_postatushistory", + "SalesOrder"=>"vtiger_sostatushistory", + "Quotes"=>"vtiger_quotestagehistory", + "Invoice"=>"vtiger_invoicestatushistory" + ); + + $histid = $adb->getUniqueID($history_table_array[$module]); + $modifiedtime = $adb->formatDate(date('Y-m-d H:i:s'), true); + $query = "insert into $history_table_array[$module] values(?,?,?,?,?,?)"; + $qparams = array($histid,$id,$relatedname,$total,$history_fldval,$modifiedtime); + $adb->pquery($query, $qparams); + + $log->debug("Exit from function addInventoryHistory"); +} + +/** Function used to get the list of Tax types as a array + * @param string $available - available or empty where as default is all, if available then the taxes which are available now will be returned otherwise all taxes will be returned + * @param string $sh - sh or empty, if sh passed then the shipping and handling related taxes will be returned + * @param string $mode - edit or empty, if mode is edit, then it will return taxes including desabled. + * @param string $id - crmid or empty, getting crmid to get tax values.. + * return array $taxtypes - return all the tax types as a array + */ +function getAllTaxes($available='all', $sh='',$mode='',$id='') +{ + global $adb, $log; + $log->debug("Entering into the function getAllTaxes($available,$sh,$mode,$id)"); + $taxtypes = Array(); + if($sh != '' && $sh == 'sh') + { + $tablename = 'vtiger_shippingtaxinfo'; + $value_table='vtiger_inventoryshippingrel'; + } + else + { + $tablename = 'vtiger_inventorytaxinfo'; + $value_table='vtiger_inventoryproductrel'; + } + + if($mode == 'edit' && $id != '' ) + { + //Getting total no of taxes + + $result_ids=array(); + $result=$adb->pquery("select taxname,taxid from $tablename",array()); + $noofrows=$adb->num_rows($result); + + $inventory_tax_val_result=$adb->pquery("select * from $value_table where id=?",array($id)); + + //Finding which taxes are associated with this (SO,PO,Invoice,Quotes) and getting its taxid. + for($i=0;$i<$noofrows;$i++) + { + + $taxname=$adb->query_result($result,$i,'taxname'); + $taxid=$adb->query_result($result,$i,'taxid'); + + $tax_val=$adb->query_result($inventory_tax_val_result,0,$taxname); + if($tax_val != '') + { + array_push($result_ids,$taxid); + } + + } + //We are selecting taxes using that taxids. So It will get the tax even if the tax is disabled. + $where_ids=''; + if (count($result_ids) > 0) + { + $insert_str = str_repeat("?,", count($result_ids)-1); + $insert_str .= "?"; + $where_ids="taxid in ($insert_str) or"; + } + + $res = $adb->pquery("select * from $tablename where $where_ids deleted=0 order by taxid",$result_ids); + } + else + { + //This where condition is added to get all products or only availble products + if($available != 'all' && $available == 'available') + { + $where = " where $tablename.deleted=0"; + } + + $res = $adb->pquery("select * from $tablename $where order by deleted",array()); + + } + + $noofrows = $adb->num_rows($res); + for($i=0;$i<$noofrows;$i++) + { + $taxtypes[$i]['taxid'] = $adb->query_result($res,$i,'taxid'); + $taxtypes[$i]['taxname'] = $adb->query_result($res,$i,'taxname'); + $taxtypes[$i]['taxlabel'] = $adb->query_result($res,$i,'taxlabel'); + $taxtypes[$i]['percentage'] = $adb->query_result($res,$i,'percentage'); + $taxtypes[$i]['deleted'] = $adb->query_result($res,$i,'deleted'); + } + $log->debug("Exit from the function getAllTaxes($available,$sh,$mode,$id)"); + + return $taxtypes; +} + + +/** Function used to get all the tax details which are associated to the given product + * @param int $productid - product id to which we want to get all the associated taxes + * @param string $available - available or empty or available_associated where as default is all, if available then the taxes which are available now will be returned, if all then all taxes will be returned otherwise if the value is available_associated then all the associated taxes even they are not available and all the available taxes will be retruned + * @return array $tax_details - tax details as a array with productid, taxid, taxname, percentage and deleted + */ +function getTaxDetailsForProduct($productid, $available='all') +{ + global $log, $adb; + $log->debug("Entering into function getTaxDetailsForProduct($productid)"); + if($productid != '') + { + //where condition added to avoid to retrieve the non available taxes + $where = ''; + if($available != 'all' && $available == 'available') + { + $where = ' and vtiger_inventorytaxinfo.deleted=0'; + } + if($available != 'all' && $available == 'available_associated') + { + $query = "SELECT vtiger_producttaxrel.*, vtiger_inventorytaxinfo.* FROM vtiger_inventorytaxinfo left JOIN vtiger_producttaxrel ON vtiger_inventorytaxinfo.taxid = vtiger_producttaxrel.taxid WHERE vtiger_producttaxrel.productid = ? or vtiger_inventorytaxinfo.deleted=0 GROUP BY vtiger_inventorytaxinfo.taxid"; + } + else + { + $query = "SELECT vtiger_producttaxrel.*, vtiger_inventorytaxinfo.* FROM vtiger_inventorytaxinfo INNER JOIN vtiger_producttaxrel ON vtiger_inventorytaxinfo.taxid = vtiger_producttaxrel.taxid WHERE vtiger_producttaxrel.productid = ? $where"; + } + $params = array($productid); + + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query = fixPostgresQuery( $query, $log, 0); + + $res = $adb->pquery($query, $params); + for($i=0;$i<$adb->num_rows($res);$i++) + { + $tax_details[$i]['productid'] = $adb->query_result($res,$i,'productid'); + $tax_details[$i]['taxid'] = $adb->query_result($res,$i,'taxid'); + $tax_details[$i]['taxname'] = $adb->query_result($res,$i,'taxname'); + $tax_details[$i]['taxlabel'] = $adb->query_result($res,$i,'taxlabel'); + $tax_details[$i]['percentage'] = $adb->query_result($res,$i,'taxpercentage'); + $tax_details[$i]['deleted'] = $adb->query_result($res,$i,'deleted'); + } + } + else + { + $log->debug("Product id is empty. we cannot retrieve the associated products."); + } + + $log->debug("Exit from function getTaxDetailsForProduct($productid)"); + return $tax_details; +} + +/** Function used to delete the Inventory product details for the passed entity + * @param int $objectid - entity id to which we want to delete the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice + * @param string $return_old_values - string which contains the string return_old_values or may be empty, if the string is return_old_values then before delete old values will be retrieved + * @return array $ext_prod_arr - if the second input parameter is 'return_old_values' then the array which contains the productid and quantity which will be retrieved before delete the product details will be returned otherwise return empty + */ +function deleteInventoryProductDetails($focus) +{ + global $log, $adb,$updateInventoryProductRel_update_product_array; + $log->debug("Entering into function deleteInventoryProductDetails(".$focus->id.")."); + + $product_info = $adb->pquery("SELECT productid, quantity, sequence_no, incrementondel from vtiger_inventoryproductrel WHERE id=?",array($focus->id)); + $numrows = $adb->num_rows($product_info); + for($index = 0;$index <$numrows;$index++){ + $productid = $adb->query_result($product_info,$index,'productid'); + $sequence_no = $adb->query_result($product_info,$index,'sequence_no'); + $qty = $adb->query_result($product_info,$index,'quantity'); + $incrementondel = $adb->query_result($product_info,$index,'incrementondel'); + + if($incrementondel){ + $focus->update_product_array[$focus->id][$sequence_no][$productid]= $qty; + $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($focus->id,$sequence_no)); + if($adb->num_rows($sub_prod_query)>0){ + for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ + $sub_prod_id = $adb->query_result($sub_prod_query,$j,"productid"); + $focus->update_product_array[$focus->id][$sequence_no][$sub_prod_id]= $qty; + } + } + + } + } + $updateInventoryProductRel_update_product_array = $focus->update_product_array; + $adb->pquery("delete from vtiger_inventoryproductrel where id=?", array($focus->id)); + $adb->pquery("delete from vtiger_inventorysubproductrel where id=?", array($focus->id)); + $adb->pquery("delete from vtiger_inventoryshippingrel where id=?", array($focus->id)); + + $log->debug("Exit from function deleteInventoryProductDetails(".$focus->id.")"); +} + +function updateInventoryProductRel($entity) +{ + global $log, $adb,$updateInventoryProductRel_update_product_array; + $entity_id = vtws_getIdComponents($entity->getId()); + $entity_id = $entity_id[1]; + $update_product_array = $updateInventoryProductRel_update_product_array; + $log->debug("Entering into function updateInventoryProductRel(".$entity_id.")."); + + if(!empty($update_product_array)){ + foreach($update_product_array as $id=>$seq){ + foreach($seq as $seq=>$product_info) + { + foreach($product_info as $key=>$index){ + $updqtyinstk= getPrdQtyInStck($key); + $upd_qty = $updqtyinstk+$index; + updateProductQty($key, $upd_qty); + } + } + } + } + $adb->pquery("UPDATE vtiger_inventoryproductrel SET incrementondel=1 WHERE id=?",array($entity_id)); + + $product_info = $adb->pquery("SELECT productid,sequence_no, quantity from vtiger_inventoryproductrel WHERE id=?",array($entity_id)); + $numrows = $adb->num_rows($product_info); + for($index = 0;$index <$numrows;$index++){ + $productid = $adb->query_result($product_info,$index,'productid'); + $qty = $adb->query_result($product_info,$index,'quantity'); + $sequence_no = $adb->query_result($product_info,$index,'sequence_no'); + $qtyinstk= getPrdQtyInStck($productid); + $upd_qty = $qtyinstk-$qty; + updateProductQty($productid, $upd_qty); + $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($entity_id,$sequence_no)); + if($adb->num_rows($sub_prod_query)>0){ + for($j=0;$j<$adb->num_rows($sub_prod_query);$j++){ + $sub_prod_id = $adb->query_result($sub_prod_query,$j,"productid"); + $sqtyinstk= getPrdQtyInStck($sub_prod_id); + $supd_qty = $sqtyinstk-$qty; + updateProductQty($sub_prod_id, $supd_qty); + } + } + } + + $log->debug("Exit from function updateInventoryProductRel(".$entity_id.")"); +} + +/** Function used to save the Inventory product details for the passed entity + * @param object reference $focus - object reference to which we want to save the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice + * @param string $module - module name + * @param $update_prod_stock - true or false (default), if true we have to update the stock for PO only + * @return void + */ +function saveInventoryProductDetails(&$focus, $module, $update_prod_stock='false', $updateDemand='') +{ + global $log, $adb; + $id=$focus->id; + $log->debug("Entering into function saveInventoryProductDetails($module)."); + //Added to get the convertid + if(isset($_REQUEST['convert_from']) && $_REQUEST['convert_from'] !='') + { + $id=$_REQUEST['return_id']; + } + else if(isset($_REQUEST['duplicate_from']) && $_REQUEST['duplicate_from'] !='') + { + $id=$_REQUEST['duplicate_from']; + } + + $ext_prod_arr = Array(); + if($focus->mode == 'edit') + { + if($_REQUEST['taxtype'] == 'group') + $all_available_taxes = getAllTaxes('available','','edit',$id); + $return_old_values = ''; + if($module != 'PurchaseOrder') + { + $return_old_values = 'return_old_values'; + } + + //we will retrieve the existing product details and store it in a array and then delete all the existing product details and save new values, retrieve the old value and update stock only for SO, Quotes and Invoice not for PO + //$ext_prod_arr = deleteInventoryProductDetails($focus->id,$return_old_values); + deleteInventoryProductDetails($focus); + } + else + { + if($_REQUEST['taxtype'] == 'group') + $all_available_taxes = getAllTaxes('available','','edit',$id); + } + $tot_no_prod = $_REQUEST['totalProductCount']; + //If the taxtype is group then retrieve all available taxes, else retrive associated taxes for each product inside loop + $prod_seq=1; + for($i=1; $i<=$tot_no_prod; $i++) + { + //if the product is deleted then we should avoid saving the deleted products + if($_REQUEST["deleted".$i] == 1) + continue; + + $prod_id = $_REQUEST['hdnProductId'.$i]; + if(isset($_REQUEST['productDescription'.$i])) + $description = $_REQUEST['productDescription'.$i]; + /*else{ + $desc_duery = "select vtiger_crmentity.description AS product_description from vtiger_crmentity where vtiger_crmentity.crmid=?"; + $desc_res = $adb->pquery($desc_duery,array($prod_id)); + $description = $adb->query_result($desc_res,0,"product_description"); + } */ + $qty = $_REQUEST['qty'.$i]; + $listprice = $_REQUEST['listPrice'.$i]; + $comment = $_REQUEST['comment'.$i]; + + //we have to update the Product stock for PurchaseOrder if $update_prod_stock is true + if($module == 'PurchaseOrder' && $update_prod_stock == 'true') + { + addToProductStock($prod_id,$qty); + } + if($module == 'SalesOrder') + { + if($updateDemand == '-') + { + deductFromProductDemand($prod_id,$qty); + } + elseif($updateDemand == '+') + { + addToProductDemand($prod_id,$qty); + } + } + + $query ="insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice, comment, description) values(?,?,?,?,?,?,?)"; + $qparams = array($focus->id,$prod_id,$prod_seq,$qty,$listprice,$comment,$description); + $adb->pquery($query,$qparams); + + $lineitem_id = $adb->getLastInsertID(); + + $sub_prod_str = $_REQUEST['subproduct_ids'.$i]; + if (!empty($sub_prod_str)) { + $sub_prod = split(":",$sub_prod_str); + for($j=0;$jid,$prod_seq,$sub_prod[$j]); + $adb->pquery($query,$qparams); + } + } + $prod_seq++; + + if($module != 'PurchaseOrder') + { + //update the stock with existing details + updateStk($prod_id,$qty,$focus->mode,$ext_prod_arr,$module); + } + + //we should update discount and tax details + $updatequery = "update vtiger_inventoryproductrel set "; + $updateparams = array(); + + //set the discount percentage or discount amount in update query, then set the tax values + if($_REQUEST['discount_type'.$i] == 'percentage') + { + $updatequery .= " discount_percent=?,"; + array_push($updateparams, $_REQUEST['discount_percentage'.$i]); + } + elseif($_REQUEST['discount_type'.$i] == 'amount') + { + $updatequery .= " discount_amount=?,"; + $discount_amount = $_REQUEST['discount_amount'.$i]; + array_push($updateparams, $discount_amount); + } + if($_REQUEST['taxtype'] == 'group') + { + for($tax_count=0;$tax_countid,$prod_id, $lineitem_id); + } + else + { + $taxes_for_product = getTaxDetailsForProduct($prod_id,'all'); + for($tax_count=0;$tax_countid,$prod_id, $lineitem_id); + } + // jens 2006/08/19 - protect against empy update queries + if( !preg_match( '/set\s+where/i', $updatequery)) { + $adb->pquery($updatequery,$updateparams); + } + } + + //we should update the netprice (subtotal), taxtype, group discount, S&H charge, S&H taxes, adjustment and total + //netprice, group discount, taxtype, S&H amount, adjustment and total to entity table + + $updatequery = " update $focus->table_name set "; + $updateparams = array(); + $subtotal = $_REQUEST['subtotal']; + $updatequery .= " subtotal=?,"; + array_push($updateparams, $subtotal); + + $updatequery .= " taxtype=?,"; + array_push($updateparams, $_REQUEST['taxtype']); + + //for discount percentage or discount amount + if($_REQUEST['discount_type_final'] == 'percentage') + { + $updatequery .= " discount_percent=?,"; + array_push($updateparams, $_REQUEST['discount_percentage_final']); + } + elseif($_REQUEST['discount_type_final'] == 'amount') + { + $discount_amount_final = $_REQUEST['discount_amount_final']; + $updatequery .= " discount_amount=?,"; + array_push($updateparams, $discount_amount_final); + } + + $shipping_handling_charge = $_REQUEST['shipping_handling_charge']; + $updatequery .= " s_h_amount=?,"; + array_push($updateparams, $shipping_handling_charge); + + //if the user gave - sign in adjustment then add with the value + $adjustmentType = ''; + if($_REQUEST['adjustmentType'] == '-') + $adjustmentType = $_REQUEST['adjustmentType']; + + $adjustment = $_REQUEST['adjustment']; + $updatequery .= " adjustment=?,"; + array_push($updateparams, $adjustmentType.$adjustment); + + $total = $_REQUEST['total']; + $updatequery .= " total=?"; + array_push($updateparams, $total); + + //$id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid'); + //Added where condition to which entity we want to update these values + $updatequery .= " where ".$focus->table_index."=?"; + array_push($updateparams, $focus->id); + + $adb->pquery($updatequery,$updateparams); + + //to save the S&H tax details in vtiger_inventoryshippingrel table + $sh_tax_details = getAllTaxes('all','sh'); + $sh_query_fields = "id,"; + $sh_query_values = "?,"; + $sh_query_params = array($focus->id); + for($i=0;$ipquery($sh_query,$sh_query_params); + + $log->debug("Exit from function saveInventoryProductDetails($module)."); +} + + +/** function used to get the tax type for the entity (PO, SO, Quotes or Invoice) + * @param string $module - module name + * @param int $id - id of the PO or SO or Quotes or Invoice + * @return string $taxtype - taxtype for the given entity which will be individual or group + */ +function getInventoryTaxType($module, $id) +{ + global $log, $adb; + + $log->debug("Entering into function getInventoryTaxType($module, $id)."); + + $inv_table_array = Array('PurchaseOrder'=>'vtiger_purchaseorder','SalesOrder'=>'vtiger_salesorder','Quotes'=>'vtiger_quotes','Invoice'=>'vtiger_invoice'); + $inv_id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid'); + + $res = $adb->pquery("select taxtype from $inv_table_array[$module] where $inv_id_array[$module]=?", array($id)); + + $taxtype = $adb->query_result($res,0,'taxtype'); + + $log->debug("Exit from function getInventoryTaxType($module, $id)."); + + return $taxtype; +} + +/** function used to get the price type for the entity (PO, SO, Quotes or Invoice) + * @param string $module - module name + * @param int $id - id of the PO or SO or Quotes or Invoice + * @return string $pricetype - pricetype for the given entity which will be unitprice or secondprice + */ +function getInventoryCurrencyInfo($module, $id) +{ + global $log, $adb; + + $log->debug("Entering into function getInventoryCurrencyInfo($module, $id)."); + + $inv_table_array = Array('PurchaseOrder'=>'vtiger_purchaseorder','SalesOrder'=>'vtiger_salesorder','Quotes'=>'vtiger_quotes','Invoice'=>'vtiger_invoice'); + $inv_id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid'); + + $inventory_table = $inv_table_array[$module]; + $inventory_id = $inv_id_array[$module]; + $res = $adb->pquery("select currency_id, $inventory_table.conversion_rate as conv_rate, vtiger_currency_info.* from $inventory_table + inner join vtiger_currency_info on $inventory_table.currency_id = vtiger_currency_info.id + where $inventory_id=?", array($id)); + + $currency_info = array(); + $currency_info['currency_id'] = $adb->query_result($res,0,'currency_id'); + $currency_info['conversion_rate'] = $adb->query_result($res,0,'conv_rate'); + $currency_info['currency_name'] = $adb->query_result($res,0,'currency_name'); + $currency_info['currency_code'] = $adb->query_result($res,0,'currency_code'); + $currency_info['currency_symbol'] = $adb->query_result($res,0,'currency_symbol'); + + $log->debug("Exit from function getInventoryCurrencyInfo($module, $id)."); + + return $currency_info; +} + +/** function used to get the taxvalue which is associated with a product for PO/SO/Quotes or Invoice + * @param int $id - id of PO/SO/Quotes or Invoice + * @param int $productid - product id + * @param string $taxname - taxname to which we want the value + * @return float $taxvalue - tax value + */ +function getInventoryProductTaxValue($id, $productid, $taxname) +{ + global $log, $adb; + $log->debug("Entering into function getInventoryProductTaxValue($id, $productid, $taxname)."); + + $res = $adb->pquery("select $taxname from vtiger_inventoryproductrel where id = ? and productid = ?", array($id, $productid)); + $taxvalue = $adb->query_result($res,0,$taxname); + + if($taxvalue == '') + $taxvalue = '0.00'; + + $log->debug("Exit from function getInventoryProductTaxValue($id, $productid, $taxname)."); + + return $taxvalue; +} + +/** function used to get the shipping & handling tax percentage for the given inventory id and taxname + * @param int $id - entity id which will be PO/SO/Quotes or Invoice id + * @param string $taxname - shipping and handling taxname + * @return float $taxpercentage - shipping and handling taxpercentage which is associated with the given entity + */ +function getInventorySHTaxPercent($id, $taxname) +{ + global $log, $adb; + $log->debug("Entering into function getInventorySHTaxPercent($id, $taxname)"); + + $res = $adb->pquery("select $taxname from vtiger_inventoryshippingrel where id= ?", array($id)); + $taxpercentage = $adb->query_result($res,0,$taxname); + + if($taxpercentage == '') + $taxpercentage = '0.00'; + + $log->debug("Exit from function getInventorySHTaxPercent($id, $taxname)"); + + return $taxpercentage; +} + +/** Function used to get the list of all Currencies as a array + * @param string available - if 'all' returns all the currencies, default value 'available' returns only the currencies which are available for use. + * return array $currency_details - return details of all the currencies as a array + */ +function getAllCurrencies($available='available') { + global $adb, $log; + $log->debug("Entering into function getAllCurrencies($available)"); + + $sql = "select * from vtiger_currency_info"; + if ($available != 'all') { + $sql .= " where currency_status='Active' and deleted=0"; + } + $res=$adb->pquery($sql, array()); + $noofrows = $adb->num_rows($res); + + for($i=0;$i<$noofrows;$i++) + { + $currency_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name'); + $currency_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code'); + $currency_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol'); + $currency_details[$i]['curid'] = $adb->query_result($res,$i,'id'); + $currency_details[$i]['conversionrate'] = $adb->query_result($res,$i,'conversion_rate'); + $currency_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id'); + } + + $log->debug("Entering into function getAllCurrencies($available)"); + return $currency_details; + +} + +/** Function used to get all the price details for different currencies which are associated to the given product + * @param int $productid - product id to which we want to get all the associated prices + * @param decimal $unit_price - Unit price of the product + * @param string $available - available or available_associated where as default is available, if available then the prices in the currencies which are available now will be returned, otherwise if the value is available_associated then prices of all the associated currencies will be retruned + * @return array $price_details - price details as a array with productid, curid, curname + */ +function getPriceDetailsForProduct($productid, $unit_price, $available='available', $itemtype='Products') +{ + global $log, $adb; + $log->debug("Entering into function getPriceDetailsForProduct($productid)"); + if($productid != '') + { + $product_currency_id = getProductBaseCurrency($productid, $itemtype); + $product_base_conv_rate = getBaseConversionRateForProduct($productid,'edit',$itemtype); + // Detail View + if ($available == 'available_associated') { + $query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price + from vtiger_currency_info + inner join vtiger_productcurrencyrel on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid + where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0 + and vtiger_productcurrencyrel.productid = ? and vtiger_currency_info.id != ?"; + $params = array($productid, $product_currency_id); + } else { // Edit View + $query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price + from vtiger_currency_info + left join vtiger_productcurrencyrel + on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid and vtiger_productcurrencyrel.productid = ? + where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0"; + $params = array($productid); + } + + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query = fixPostgresQuery( $query, $log, 0); + + $res = $adb->pquery($query, $params); + for($i=0;$i<$adb->num_rows($res);$i++) + { + $price_details[$i]['productid'] = $productid; + $price_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name'); + $price_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code'); + $price_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol'); + $currency_id = $adb->query_result($res,$i,'id'); + $price_details[$i]['curid'] = $currency_id; + $price_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id'); + $cur_value = $adb->query_result($res,$i,'actual_price'); + + // Get the conversion rate for the given currency, get the conversion rate of the product currency to base currency. + // Both together will be the actual conversion rate for the given currency. + $conversion_rate = $adb->query_result($res,$i,'conversion_rate'); + $actual_conversion_rate = $product_base_conv_rate * $conversion_rate; + + if ($cur_value == null || $cur_value == '') { + $price_details[$i]['check_value'] = false; + if ($unit_price != null) { + $cur_value = convertFromMasterCurrency($unit_price, $actual_conversion_rate); + } else { + $cur_value = '0'; + } + } else { + $price_details[$i]['check_value'] = true; + } + $price_details[$i]['curvalue'] = $cur_value; + $price_details[$i]['conversionrate'] = $actual_conversion_rate; + + $is_basecurrency = false; + if ($currency_id == $product_currency_id) { + $is_basecurrency = true; + } + $price_details[$i]['is_basecurrency'] = $is_basecurrency; + } + } + else + { + if($available == 'available') { // Create View + global $current_user; + + $user_currency_id = fetchCurrency($current_user->id); + + $query = "select vtiger_currency_info.* from vtiger_currency_info + where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0"; + $params = array(); + + $res = $adb->pquery($query, $params); + for($i=0;$i<$adb->num_rows($res);$i++) + { + $price_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name'); + $price_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code'); + $price_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol'); + $currency_id = $adb->query_result($res,$i,'id'); + $price_details[$i]['curid'] = $currency_id; + $price_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id'); + + // Get the conversion rate for the given currency, get the conversion rate of the product currency(logged in user's currency) to base currency. + // Both together will be the actual conversion rate for the given currency. + $conversion_rate = $adb->query_result($res,$i,'conversion_rate'); + $user_cursym_convrate = getCurrencySymbolandCRate($user_currency_id); + $product_base_conv_rate = 1 / $user_cursym_convrate['rate']; + $actual_conversion_rate = $product_base_conv_rate * $conversion_rate; + + $price_details[$i]['check_value'] = false; + $price_details[$i]['curvalue'] = '0'; + $price_details[$i]['conversionrate'] = $actual_conversion_rate; + + $is_basecurrency = false; + if ($currency_id == $user_currency_id) { + $is_basecurrency = true; + } + $price_details[$i]['is_basecurrency'] = $is_basecurrency; + } + } else { + $log->debug("Product id is empty. we cannot retrieve the associated prices."); + } + } + + $log->debug("Exit from function getPriceDetailsForProduct($productid)"); + return $price_details; +} + +/** Function used to get the base currency used for the given Product + * @param int $productid - product id for which we want to get the id of the base currency + * @return int $currencyid - id of the base currency for the given product + */ +function getProductBaseCurrency($productid,$module='Products') { + global $adb, $log; + if ($module == 'Services') { + $sql = "select currency_id from vtiger_service where serviceid=?"; + } else { + $sql = "select currency_id from vtiger_products where productid=?"; + } + $params = array($productid); + $res = $adb->pquery($sql, $params); + $currencyid = $adb->query_result($res, 0, 'currency_id'); + return $currencyid; +} + +/** Function used to get the conversion rate for the product base currency with respect to the CRM base currency + * @param int $productid - product id for which we want to get the conversion rate of the base currency + * @param string $mode - Mode in which the function is called + * @return number $conversion_rate - conversion rate of the base currency for the given product based on the CRM base currency + */ +function getBaseConversionRateForProduct($productid, $mode='edit', $module='Products') { + global $adb, $log, $current_user; + + if ($mode == 'edit') { + if ($module == 'Services') { + $sql = "select conversion_rate from vtiger_service inner join vtiger_currency_info + on vtiger_service.currency_id = vtiger_currency_info.id where vtiger_service.serviceid=?"; + } else { + $sql = "select conversion_rate from vtiger_products inner join vtiger_currency_info + on vtiger_products.currency_id = vtiger_currency_info.id where vtiger_products.productid=?"; + } + $params = array($productid); + } else { + $sql = "select conversion_rate from vtiger_currency_info where id=?"; + $params = array(fetchCurrency($current_user->id)); + } + + $res = $adb->pquery($sql, $params); + $conv_rate = $adb->query_result($res, 0, 'conversion_rate'); + + return 1 / $conv_rate; +} + +/** Function used to get the prices for the given list of products based in the specified currency + * @param int $currencyid - currency id based on which the prices have to be provided + * @param array $product_ids - List of product id's for which we want to get the price based on given currency + * @return array $prices_list - List of prices for the given list of products based on the given currency in the form of 'product id' mapped to 'price value' + */ +function getPricesForProducts($currencyid, $product_ids, $module='Products') { + global $adb,$log,$current_user; + + $price_list = array(); + if (count($product_ids) > 0) { + if ($module == 'Services') { + $query = "SELECT vtiger_currency_info.id, vtiger_currency_info.conversion_rate, " . + "vtiger_service.serviceid AS productid, vtiger_service.unit_price, " . + "vtiger_productcurrencyrel.actual_price " . + "FROM (vtiger_currency_info, vtiger_service) " . + "left join vtiger_productcurrencyrel on vtiger_service.serviceid = vtiger_productcurrencyrel.productid " . + "and vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid " . + "where vtiger_service.serviceid in (". generateQuestionMarks($product_ids) .") and vtiger_currency_info.id = ?"; + } else { + $query = "SELECT vtiger_currency_info.id, vtiger_currency_info.conversion_rate, " . + "vtiger_products.productid, vtiger_products.unit_price, " . + "vtiger_productcurrencyrel.actual_price " . + "FROM (vtiger_currency_info, vtiger_products) " . + "left join vtiger_productcurrencyrel on vtiger_products.productid = vtiger_productcurrencyrel.productid " . + "and vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid " . + "where vtiger_products.productid in (". generateQuestionMarks($product_ids) .") and vtiger_currency_info.id = ?"; + } + $params = array($product_ids, $currencyid); + $result = $adb->pquery($query, $params); + + for($i=0;$i<$adb->num_rows($result);$i++) + { + $product_id = $adb->query_result($result, $i, 'productid'); + if(getFieldVisibilityPermission($module,$current_user->id,'unit_price') == '0') { + $actual_price = $adb->query_result($result, $i, 'actual_price'); + + if ($actual_price == null || $actual_price == '') { + $unit_price = $adb->query_result($result, $i, 'unit_price'); + $product_conv_rate = $adb->query_result($result, $i, 'conversion_rate'); + $product_base_conv_rate = getBaseConversionRateForProduct($product_id,'edit',$module); + $conversion_rate = $product_conv_rate * $product_base_conv_rate; + + $actual_price = $unit_price * $conversion_rate; + } + $price_list[$product_id] = $actual_price; + } else { + $price_list[$product_id] = ''; + } + } + } + return $price_list; +} + +/** Function used to get the currency used for the given Price book + * @param int $pricebook_id - pricebook id for which we want to get the id of the currency used + * @return int $currencyid - id of the currency used for the given pricebook + */ +function getPriceBookCurrency($pricebook_id) { + global $adb; + $result = $adb->pquery("select currency_id from vtiger_pricebook where pricebookid=?", array($pricebook_id)); + $currency_id = $adb->query_result($result,0,'currency_id'); + return $currency_id; +} ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/ListViewUtils.php b/oss/vtiger/trunk/include/utils/ListViewUtils.php index 871c8529..3458be02 100644 --- a/oss/vtiger/trunk/include/utils/ListViewUtils.php +++ b/oss/vtiger/trunk/include/utils/ListViewUtils.php @@ -1,4599 +1,4522 @@ -debug("Entering getListViewHeader(". $module.",".$sort_qry.",".$sorder.",".$order_by.",".$relatedlist.",".get_class($oCv).") method ..."); - global $adb; - global $theme; - global $app_strings; - global $mod_strings; - - $arrow=''; - $qry = getURLstring($focus); - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $list_header = Array(); - - //Get the vtiger_tabid of the module - $tabid = getTabid($module); - $tabname = getParentTab(); - global $current_user; - //added for vtiger_customview 27/5 - if($oCv) - { - if(isset($oCv->list_fields)) - { - $focus->list_fields = $oCv->list_fields; - } - } - - // Remove fields which are made inactive - $focus->filterInactiveFields($module); - - //Added to reduce the no. of queries logging for non-admin user -- by Minnie-start - $field_list = array(); - $j=0; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - foreach($focus->list_fields as $name=>$tableinfo) - { - $fieldname = $focus->list_fields_name[$name]; - if($oCv) - { - if(isset($oCv->list_fields_name)) - { - $fieldname = $oCv->list_fields_name[$name]; - } - } - if($fieldname == 'accountname' && $module != 'Accounts') - { - $fieldname = 'account_id'; - } - if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'||$module == 'Calendar' )) - { - $fieldname = 'contact_id'; - } - if($fieldname == 'productname' && $module != 'Products') - { - $fieldname = 'product_id'; - } - array_push($field_list, $fieldname); - $j++; - } - $field=Array(); - if($is_admin==false) - { - if($module == 'Emails') - { - $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; - $params = array($tabid); - } - else - { - $profileList = getCurrentUserProfileList(); - $params = array(); - - $query = "SELECT DISTINCT vtiger_field.fieldname - FROM vtiger_field - INNER JOIN vtiger_profile2field - ON vtiger_profile2field.fieldid = vtiger_field.fieldid - INNER JOIN vtiger_def_org_field - ON vtiger_def_org_field.fieldid = vtiger_field.fieldid"; - if($module == "Calendar") { - $query .=" WHERE vtiger_field.tabid in (9,16) and vtiger_field.presence in (0,2)"; - } else { - $query .=" WHERE vtiger_field.tabid = ? and vtiger_field.presence in (0,2)"; - array_push($params, $tabid); - } - - $query.=" AND vtiger_profile2field.visible = 0 - AND vtiger_def_org_field.visible = 0 - AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") - AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .")"; - - array_push($params, $profileList, $field_list); - } - $result = $adb->pquery($query, $params); - for($k=0;$k < $adb->num_rows($result);$k++) - { - $field[]=$adb->query_result($result,$k,"fieldname"); - } - } - //end - //modified for vtiger_customview 27/5 - $app_strings change to $mod_strings - foreach($focus->list_fields as $name=>$tableinfo) - { - //added for vtiger_customview 27/5 - if($oCv) - { - if(isset($oCv->list_fields_name)) - { - $fieldname = $oCv->list_fields_name[$name]; - if($fieldname == 'accountname' && $module != 'Accounts') - { - $fieldname = 'account_id'; - } - if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'|| $module == 'Calendar') ) - { - $fieldname = 'contact_id'; - } - if($fieldname == 'productname' && $module != 'Products') - { - $fieldname = 'product_id'; - } - }else - { - $fieldname = $focus->list_fields_name[$name]; - } - }else - { - $fieldname = $focus->list_fields_name[$name]; - if($fieldname == 'accountname' && $module != 'Accounts') - { - $fieldname = 'account_id'; - } - if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'|| $module == 'Calendar')) - { - $fieldname = 'contact_id'; - } - if($fieldname == 'productname' && $module != 'Products') - { - $fieldname = 'product_id'; - } - - } - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $fieldname == '' || ($name=='Close' && $module=='Calendar')) - { - if(isset($focus->sortby_fields) && $focus->sortby_fields !='') - { - //Added on 14-12-2005 to avoid if and else check for every list vtiger_field for arrow image and change order - $change_sorder = array('ASC'=>'DESC','DESC'=>'ASC'); - $arrow_gif = array('ASC'=>'arrow_down.gif','DESC'=>'arrow_up.gif'); - foreach($focus->list_fields[$name] as $tab=>$col) - { - if(in_array($col,$focus->sortby_fields)) - { - if($order_by == $col) - { - $temp_sorder = $change_sorder[$sorder]; - $arrow = " "; - } - else - { - $temp_sorder = 'ASC'; - } - $lbl_name = getTranslatedString($name, $module); - //added to display vtiger_currency symbol in listview header - if($lbl_name =='Amount') - { - $lbl_name .=' ('.$app_strings['LBL_IN'].' '.$user_info['currency_symbol'].')'; - } - if($relatedlist !='' && $relatedlist != 'global') - if($singlepane_view == 'true') - $name = "".$lbl_name."".$arrow.""; - else - $name = "".$lbl_name."".$arrow.""; - elseif($module == 'Users' && $name == 'User Name') - $name = "".getTranslatedString('LBL_LIST_USER_NAME_ROLE',$module)."".$arrow.""; - elseif($relatedlist == "global") - $name = $lbl_name; - else - $name = "".$lbl_name."".$arrow.""; - $arrow = ''; - } - else - { - if(stripos($col, 'cf_') === 0) { - $tablenameArray = array_keys($tableinfo,$col); - $tablename = $tablenameArray[0]; - $cf_columns = $adb->getColumnNames($tablename); - if (array_search($col, $cf_columns) != null) { - $pquery = "select fieldlabel,typeofdata from vtiger_field where tablename = ? and fieldname = ? and vtiger_field.presence in (0,2)"; - $cf_res = $adb->pquery($pquery, array($tablename, $col)); - if (count($cf_res) > 0){ - $cf_fld_label = $adb->query_result($cf_res, 0, "fieldlabel"); - $typeofdata = explode("~",$adb->query_result($cf_res, 0, "typeofdata")); - $new_field_label = $tablename. ":" . $col .":". $col .":". $module . "_" . str_replace(" ","_",$cf_fld_label) .":". $typeofdata[0]; - $name = $cf_fld_label; - - // Update the existing field name in the database with new field name. - $upd_query = "update vtiger_cvcolumnlist set columnname = ? where columnname like '" .$tablename. ":" . $col .":". $col ."%'"; - $upd_params = array($new_field_label); - $adb->pquery($upd_query, $upd_params); - - } - } - } else { - $name = getTranslatedString($name, $module); - } - } - } - } - //added to display vtiger_currency symbol in related listview header - if($name =='Amount' && $relatedlist !='' ) - { - $name .=' ('.$app_strings['LBL_IN'].' '.$user_info['currency_symbol'].')'; - } - - if($module == "Calendar" && $name == $app_strings['Close']) - { - if(isPermitted("Calendar","EditView") == 'yes') - { - if((getFieldVisibilityPermission('Events',$current_user->id,'eventstatus') == '0') || (getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0')) - { - array_push($list_header,$name); - } - } - } - else - { - $list_header[]=$name; - } - } - } - - //Added for Action - edit and delete link header in listview - if(!$skipActions && (isPermitted($module,"EditView","") == 'yes' || isPermitted($module,"Delete","") == 'yes')) - $list_header[] = $app_strings["LBL_ACTION"]; - - $log->debug("Exiting getListViewHeader method ..."); - return $list_header; -} - -/**This function is used to get the list view header in popup -*Param $focus - module object -*Param $module - module name -*Param $sort_qry - sort by value -*Param $sorder - sorting order (asc/desc) -*Param $order_by - order by -*Returns the listview header values in an array -*/ - -function getSearchListViewHeader($focus, $module,$sort_qry='',$sorder='',$order_by='') -{ - global $log; - $log->debug("Entering getSearchListViewHeader(".get_class($focus).",". $module.",".$sort_qry.",".$sorder.",".$order_by.") method ..."); - global $adb; - global $theme; - global $app_strings; - global $mod_strings,$current_user; - $arrow=''; - $list_header = Array(); - $tabid = getTabid($module); - if(isset($_REQUEST['task_relmod_id'])) - { - $task_relmod_id=vtlib_purify($_REQUEST['task_relmod_id']); - $pass_url .="&task_relmod_id=".$task_relmod_id; - } - if(isset($_REQUEST['relmod_id'])) - { - $relmod_id=vtlib_purify($_REQUEST['relmod_id']); - $pass_url .="&relmod_id=".$relmod_id; - } - if(isset($_REQUEST['task_parent_module'])) - { - $task_parent_module=vtlib_purify($_REQUEST['task_parent_module']); - $pass_url .="&task_parent_module=".$task_parent_module; - } - if(isset($_REQUEST['parent_module'])) - { - $parent_module=vtlib_purify($_REQUEST['parent_module']); - $pass_url .="&parent_module=".$parent_module; - } - if(isset($_REQUEST['fromPotential']) && (isset($_REQUEST['acc_id']) && $_REQUEST['acc_id']!= '')) - { - $pass_url .="&parent_module=Accounts&relmod_id=".vtlib_purify($_REQUEST['acc_id']); - } - - // vtlib Customization : For uitype 10 popup during paging - if($_REQUEST['form'] == 'vtlibPopupView') { - $pass_url .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); - } - // END - - //Added to reduce the no. of queries logging for non-admin user -- by Minnie-start - $field_list = array(); - $j=0; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - foreach($focus->search_fields as $name=>$tableinfo) - { - $fieldname = $focus->search_fields_name[$name]; - array_push($field_list, $fieldname); - $j++; - } - $field=Array(); - if($is_admin==false && $module != 'Users') - { - if($module == 'Emails') - { - $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; - $params = array($tabid); - } - else - { - $profileList = getCurrentUserProfileList(); - $query = "SELECT DISTINCT vtiger_field.fieldname - FROM vtiger_field - INNER JOIN vtiger_profile2field - ON vtiger_profile2field.fieldid = vtiger_field.fieldid - INNER JOIN vtiger_def_org_field - ON vtiger_def_org_field.fieldid = vtiger_field.fieldid - WHERE vtiger_field.tabid = ? - AND vtiger_profile2field.visible=0 - AND vtiger_def_org_field.visible=0 - AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") - AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2)"; - - $params = array($tabid, $profileList, $field_list); - } - - $result = $adb->pquery($query, $params); - for($k=0;$k < $adb->num_rows($result);$k++) - { - $field[]=$adb->query_result($result,$k,"fieldname"); - } - } - //end - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - - - $focus->filterInactiveFields($module); - - foreach($focus->search_fields as $name=>$tableinfo) - { - $fieldname = $focus->search_fields_name[$name]; - $tabid = getTabid($module); - - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $module == 'Users') - { - - if(isset($focus->sortby_fields) && $focus->sortby_fields !='') - { - foreach($focus->search_fields[$name] as $tab=>$col) - { - if(in_array($col,$focus->sortby_fields)) - { - if($order_by == $col) - { - if($sorder == 'ASC') - { - $sorder = "DESC"; - $arrow = ""; - } - else - { - $sorder = 'ASC'; - $arrow = ""; - } - } - // vtlib customization: If translation is not available use the given name - $tr_name = getTranslatedString($name, $module); - $name = "".$tr_name." ".$arrow.""; - // END - $arrow = ''; - } - else { - // vtlib customization: If translation is not available use the given name - $tr_name = getTranslatedString($name, $module); - $name = $tr_name; - // END - } - } - } - $list_header[]=$name; - } - } - $log->debug("Exiting getSearchListViewHeader method ..."); - return $list_header; - -} - -/**This function generates the navigation array in a listview -*Param $display - start value of the navigation -*Param $noofrows - no of records -*Param $limit - no of entries per page -*Returns an array type -*/ - -//code contributed by raju for improved pagination -function getNavigationValues($display, $noofrows, $limit) -{ - global $log; - $log->debug("Entering getNavigationValues(".$display.",".$noofrows.",".$limit.") method ..."); - $navigation_array = Array(); - global $limitpage_navigation; - if(isset($_REQUEST['allflag']) && $_REQUEST['allflag'] == 'All'){ - $navigation_array['start'] =1; - $navigation_array['first'] = 1; - $navigation_array['end'] = 1; - $navigation_array['prev'] =0; - $navigation_array['next'] =0; - $navigation_array['end_val'] =$noofrows; - $navigation_array['current'] =1; - $navigation_array['allflag'] ='Normal'; - $navigation_array['verylast'] =1; - $log->debug("Exiting getNavigationValues method ..."); - return $navigation_array; - } - if($noofrows != 0) - { - if(((($display * $limit)-$limit)+1) > $noofrows) - { - $display =floor($noofrows / $limit); - } - $start = ((($display * $limit) - $limit)+1); - } - else - { - $start = 0; - } - - $end = $start + ($limit-1); - if($end > $noofrows) - { - $end = $noofrows; - } - $paging = ceil ($noofrows / $limit); - // Display the navigation - if ($display > 1) { - $previous = $display - 1; - } - else { - $previous=0; - } - if($noofrows < $limit) - { - $first = ''; - } - elseif ($noofrows != $limit) { - $last = $paging; - $first = 1; - if ($paging > $limitpage_navigation) { - $first = $display-floor(($limitpage_navigation/2)); - if ($first<1) $first=1; - $last = ($limitpage_navigation - 1) + $first; - } - if ($last > $paging ) { - $first = $paging - ($limitpage_navigation - 1); - $last = $paging; - } - } - if ($display < $paging) { - $next = $display + 1; - } - else { - $next=0; - } - $navigation_array['start'] = $start; - $navigation_array['first'] = $first; - $navigation_array['end'] = $last; - $navigation_array['prev'] = $previous; - $navigation_array['next'] = $next; - $navigation_array['end_val'] = $end; - $navigation_array['current'] = $display; - $navigation_array['allflag'] ='All'; - $navigation_array['verylast'] =$paging; - $log->debug("Exiting getNavigationValues method ..."); - return $navigation_array; - -} - - -//End of code contributed by raju for improved pagination - -/**This function generates the List view entries in a list view -*Param $focus - module object -*Param $list_result - resultset of a listview query -*Param $navigation_array - navigation values in an array -*Param $relatedlist - check for related list flag -*Param $returnset - list query parameters in url string -*Param $edit_action - Edit action value -*Param $del_action - delete action value -*Param $oCv - vtiger_customview object -*Returns an array type -*/ - -//parameter added for vtiger_customview $oCv 27/5 -function getListViewEntries($focus, $module,$list_result,$navigation_array,$relatedlist='',$returnset='',$edit_action='EditView',$del_action='Delete',$oCv='',$page='',$selectedfields='',$contRelatedfields='',$skipActions=false) -{ - global $log; - global $mod_strings; - $log->debug("Entering getListViewEntries(".get_class($focus).",". $module.",".$list_result.",".$navigation_array.",".$relatedlist.",".$returnset.",".$edit_action.",".$del_action.",".get_class($oCv).") method ..."); - $tabname = getParentTab(); - global $adb,$current_user; - global $app_strings; - $noofrows = $adb->num_rows($list_result); - $list_block = Array(); - global $theme; - $evt_status = ''; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - //getting the vtiger_fieldtable entries from database - $tabid = getTabid($module); - - //added for vtiger_customview 27/5 - if($oCv) - { - if(isset($oCv->list_fields)) - { - $focus->list_fields = $oCv->list_fields; - } - } - if(is_array($selectedfields) && $selectedfields != '') - { - $focus->list_fields = $selectedfields; - } - - // Remove fields which are made inactive - $focus->filterInactiveFields($module); - - //Added to reduce the no. of queries logging for non-admin user -- by minnie-start - $field_list = array(); - $j=0; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - foreach($focus->list_fields as $name=>$tableinfo) - { - $fieldname = $focus->list_fields_name[$name]; - if($oCv) - { - if(isset($oCv->list_fields_name)) - { - $fieldname = $oCv->list_fields_name[$name]; - } - } - if($fieldname == 'accountname' && $module != 'Accounts') - { - $fieldname = 'account_id'; - } - if($fieldname == 'lastname' &&($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'||$module == 'Calendar')) - $fieldname = 'contact_id'; - - if($fieldname == 'productname' && $module != 'Products') - { - $fieldname = 'product_id'; - } - - array_push($field_list, $fieldname); - $j++; - } - $field=Array(); - if($is_admin==false) - { - if($module == 'Emails') - { - $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; - $params = array($tabid); - } - else - { - $profileList = getCurrentUserProfileList(); - $params = array(); - $query = "SELECT DISTINCT vtiger_field.fieldname - FROM vtiger_field - INNER JOIN vtiger_profile2field - ON vtiger_profile2field.fieldid = vtiger_field.fieldid - INNER JOIN vtiger_def_org_field - ON vtiger_def_org_field.fieldid = vtiger_field.fieldid"; - - if($module == "Calendar") - $query .=" WHERE vtiger_field.tabid in (9,16) and vtiger_field.presence in (0,2)"; - else { - $query .=" WHERE vtiger_field.tabid = ? and vtiger_field.presence in (0,2)"; - array_push($params, $tabid); - } - - $query .=" AND vtiger_profile2field.visible = 0 - AND vtiger_profile2field.visible = 0 - AND vtiger_def_org_field.visible = 0 - AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") - AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .")"; - - array_push($params, $profileList, $field_list); - } - - $result = $adb->pquery($query, $params); - for($k=0;$k < $adb->num_rows($result);$k++) - { - $field[]=$adb->query_result($result,$k,"fieldname"); - } - } - //constructing the uitype and columnname array - $ui_col_array=Array(); - - $params = array(); - $query = "SELECT uitype, columnname, fieldname FROM vtiger_field "; - - if($module == "Calendar") - $query .=" WHERE vtiger_field.tabid in (9,16) and vtiger_field.presence in (0,2)"; - else { - $query .=" WHERE vtiger_field.tabid = ? and vtiger_field.presence in (0,2)"; - array_push($params, $tabid); - } - $query .= " AND fieldname IN (". generateQuestionMarks($field_list).") "; - array_push($params, $field_list); - - $result = $adb->pquery($query, $params); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $tempArr=array(); - $uitype=$adb->query_result($result,$i,'uitype'); - $columnname=$adb->query_result($result,$i,'columnname'); - $field_name=$adb->query_result($result,$i,'fieldname'); - $tempArr[$uitype]=$columnname; - $ui_col_array[$field_name]=$tempArr; - } - //end - if($navigation_array['start'] !=0) - for ($i=1; $i<=$noofrows; $i++) - { - $list_header =Array(); - //Getting the entityid - if($module != 'Users') - { - $entity_id = $adb->query_result($list_result,$i-1,"crmid"); - $owner_id = $adb->query_result($list_result,$i-1,"smownerid"); - }else - { - $entity_id = $adb->query_result($list_result,$i-1,"id"); - } - // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 - // begin: Armando Lüscher 05.07.2005 -> §priority - // Code contri buted by fredy Desc: Set Priority color - $priority = $adb->query_result($list_result,$i-1,"priority"); - - $font_color_high = "color:#00DD00;"; - $font_color_medium = "color:#DD00DD;"; - $P_FONT_COLOR = ""; - switch ($priority) - { - case 'High': - $P_FONT_COLOR = $font_color_high; - break; - case 'Medium': - $P_FONT_COLOR = $font_color_medium; - break; - default: - $P_FONT_COLOR = ""; - } - //end: Armando Lüscher 05.07.2005 -> §priority - foreach($focus->list_fields as $name=>$tableinfo) - { - $fieldname = $focus->list_fields_name[$name]; - - //added for vtiger_customview 27/5 - if($oCv) { - if(isset($oCv->list_fields_name)) { - $fieldname = $oCv->list_fields_name[$name]; - if($fieldname == 'accountname' && $module != 'Accounts') { - $fieldname = 'account_id'; - } - if($fieldname == 'lastname' &&($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'||$module == 'Calendar' )) { - $fieldname = 'contact_id'; - } - if($fieldname == 'productname' && $module != 'Products') { - $fieldname = 'product_id'; - } - } else { - $fieldname = $focus->list_fields_name[$name]; - } - } else { - $fieldname = $focus->list_fields_name[$name]; - if($fieldname == 'accountname' && $module != 'Accounts') { - $fieldname = 'account_id'; - } - if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'|| $module == 'Calendar')) { - $fieldname = 'contact_id'; - } - if($fieldname == 'productname' && $module != 'Products') { - $fieldname = 'product_id'; - } - } - if($is_admin==true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $fieldname == '' || ($name=='Close' && $module=='Calendar')) { - if($fieldname == '') { - $table_name = ''; - $column_name = ''; - foreach($tableinfo as $tablename=>$colname) { - $table_name=$tablename; - $column_name = $colname; - } - $value = $adb->query_result($list_result,$i-1,$colname); - } - else { - if($module == 'Calendar') { - $act_id = $adb->query_result($list_result,$i-1,"activityid"); - - $cal_sql = "select activitytype from vtiger_activity where activityid=?"; - $cal_res = $adb->pquery($cal_sql,array($act_id)); - if($adb->num_rows($cal_res)>=0) - $activitytype = $adb->query_result($cal_res,0,"activitytype"); - } - if(($module == 'Calendar' || $module == 'Emails' || $module == 'HelpDesk' || $module == 'Invoice' || $module == 'Leads' || $module == 'Contacts') && (($fieldname=='parent_id') || ($name=='Contact Name') || ($name=='Close') || ($fieldname == 'firstname'))) { - if($module == 'Calendar'){ - if($fieldname=='status'){ - if($activitytype == 'Task'){ - $fieldname='taskstatus'; - } else { - $fieldname='eventstatus'; - } - } - if($activitytype == 'Task' ) { - if(getFieldVisibilityPermission('Calendar',$current_user->id,$fieldname) == '0'){ - $has_permission = 'yes'; - } else { - $has_permission = 'no'; - } - } else { - if(getFieldVisibilityPermission('Events',$current_user->id,$fieldname) == '0'){ - $has_permission = 'yes'; - } else { - $has_permission = 'no'; - } - } - } - if($module != 'Calendar' || ($module == 'Calendar' && $has_permission == 'yes')) { - if ($fieldname=='parent_id') { - $value=getRelatedTo($module,$list_result,$i-1); - } - if($name=='Contact Name') { - $contact_id = $adb->query_result($list_result,$i-1,"contactid"); - $contact_name = getFullNameFromQResult($list_result,$i-1,"Contacts"); - $value=""; - //Added to get the contactname for activities custom view - t=2190 - if($contact_id != '' && $contact_name == '') { - $contact_name = getContactName($contact_id); - } - if(($contact_name != "") && ($contact_id !='NULL')) { - // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 - $value = "".$contact_name.""; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" - } - } - if($fieldname == "firstname") { - $first_name = textlength_check($adb->query_result($list_result,$i-1,"firstname")); - - $value = ''.$first_name.''; - } - - if ($name == 'Close') { - $status = $adb->query_result($list_result,$i-1,"status"); - $activityid = $adb->query_result($list_result,$i-1,"activityid"); - if(empty($activityid)){ - $activityid = $adb->query_result($list_result, $i-1, "tmp_activity_id"); - } - $activitytype = $adb->query_result($list_result,$i-1,"activitytype"); - // TODO - Picking activitytype when it is not present in the Custom View. - // Going forward, this column should be added to the select list if not already present as a performance improvement. - if (empty($activitytype)) { - $activitytypeRes = $adb->pquery('SELECT activitytype FROM vtiger_activity WHERE activityid=?', array($activityid)); - if ($adb->num_rows($activitytypeRes) > 0) { - $activitytype = $adb->query_result($activitytypeRes, 0, 'activitytype'); - } - } - if ($activitytype != 'Task' && $activitytype != 'Emails') { - $eventstatus = $adb->query_result($list_result,$i-1,"eventstatus"); - if(isset($eventstatus)) { - $status = $eventstatus; - } - } - if($status =='Deferred' || $status == 'Completed' || $status == 'Held' || $status == '') { - $value=""; - } else { - if($activitytype=='Task') - $evt_status='&status=Completed'; - else - $evt_status='&eventstatus=Held'; - if(isPermitted("Calendar",'EditView',$activityid) == 'yes') { - if ($returnset == '') { - $returnset = '&return_module=Calendar&return_action=ListView&return_id='.$activityid.'&return_viewname='.$oCv->setdefaultviewid; - } - // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 - $value = "X"; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" - } else { - $value = ""; - } - } - } - - } else { - $value = ""; - } - } elseif($module == "Documents" && ($fieldname == 'filelocationtype' || $fieldname == 'filename' || $fieldname == 'filesize' || $fieldname == 'filestatus' || $fieldname == 'filetype')) { - $value = $adb->query_result($list_result,$i-1,$fieldname); - if($fieldname == 'filelocationtype') { - if($value == 'I') - $value = getTranslatedString('LBL_INTERNAL',$module); - elseif($value == 'E') - $value = getTranslatedString('LBL_EXTERNAL',$module); - else - $value = ' --'; - } - if($fieldname == 'filename') { - $downloadtype = $adb->query_result($list_result,$i-1,'filelocationtype'); - if($downloadtype == 'I') { - $fld_value = $value; - $ext_pos = strrpos($fld_value, "."); - $ext =substr($fld_value, $ext_pos + 1); - $ext = strtolower($ext); - if($value != ''){ - if($ext == 'bin' || $ext == 'exe' || $ext == 'rpm') - $fileicon=""; - elseif($ext == 'jpg' || $ext == 'gif' || $ext == 'bmp') - $fileicon=""; - elseif($ext == 'txt' || $ext == 'doc' || $ext == 'xls') - $fileicon=""; - elseif($ext == 'zip' || $ext == 'gz' || $ext == 'rar') - $fileicon=""; - else - $fileicon=""; - } - } elseif($downloadtype == 'E') { - if(trim($value) != '' ) { - $fld_value = $value; - $fileicon = "".getTranslatedString("; - } - else { - $fld_value = '--'; - $fileicon = ''; - } - } else { - $fld_value = ' --'; - $fileicon = ''; - } - - $file_name = $adb->query_result($list_result,$i-1,'filename'); - $notes_id = $adb->query_result($list_result,$i-1,'crmid'); - $folder_id = $adb->query_result($list_result,$i-1,'folderid'); - $download_type = $adb->query_result($list_result,$i-1,'filelocationtype'); - $file_status = $adb->query_result($list_result,$i-1,'filestatus'); - $fileidQuery = "select attachmentsid from vtiger_seattachmentsrel where crmid=?"; - $fileidres = $adb->pquery($fileidQuery,array($notes_id)); - $fileid = $adb->query_result($fileidres,0,'attachmentsid'); - if($file_name != '' && $file_status == 1) { - if($download_type == 'I' ) { - $fld_value = "".$fld_value.""; - } elseif($download_type == 'E') { - $fld_value = "".$fld_value.""; - } else { - $fld_value = ' --'; - } - } - $value = $fileicon.$fld_value; - } - if($fieldname == 'filesize') { - $downloadtype = $adb->query_result($list_result,$i-1,'filelocationtype'); - if($downloadtype == 'I') { - $filesize = $value; - if($filesize < 1024) - $value=$filesize.' B'; - elseif($filesize > 1024 && $filesize < 1048576) - $value=round($filesize/1024,2).' KB'; - else if($filesize > 1048576) - $value=round($filesize/(1024*1024),2).' MB'; - } else { - $value = ' --'; - } - } - if($fieldname == 'filestatus') { - $filestatus = $value; - if($filestatus == 1) - $value=getTranslatedString('yes',$module); - elseif($filestatus == 0) - $value=getTranslatedString('no',$module); - else - $value=' --'; - } - if($fieldname == 'filetype') { - $downloadtype = $adb->query_result($list_result,$i-1,'filelocationtype'); - $filetype = $adb->query_result($list_result,$i-1,'filetype'); - if($downloadtype == 'E' || $downloadtype != 'I') { - $value = ' --'; - } else - $value = $filetype; - } - if($fieldname == 'notecontent') { - $value = decode_html($value); - $value = textlength_check($value); - } - } elseif($module == "Products" && $name == "Related to") { - $value=getRelatedTo($module,$list_result,$i-1); - } elseif($name=='Contact Name' && ($module =='SalesOrder' || $module == 'Quotes' || $module == 'PurchaseOrder')) { - if($name == 'Contact Name') { - $contact_id = $adb->query_result($list_result,$i-1,"contactid"); - $contact_name = getFullNameFromQResult($list_result, $i-1,"Contacts"); - $value=""; - if(($contact_name != "") && ($contact_id !='NULL')) - $value ="".$contact_name.""; - } - } elseif($name == 'Product') { - $product_id = textlength_check($adb->query_result($list_result,$i-1,"productname")); - $value = $product_id; - } elseif($name=='Account Name') { - //modified for vtiger_customview 27/5 - if($module == 'Accounts') { - $account_id = $adb->query_result($list_result,$i-1,"crmid"); - //$account_name = getAccountName($account_id); - $account_name = textlength_check($adb->query_result($list_result,$i-1,"accountname")); - // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 - $value = ''.$account_name.''; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" - } elseif($module == 'Potentials' || $module == 'Contacts' || $module == 'Invoice' || $module == 'SalesOrder' || $module == 'Quotes') { //Potential,Contacts,Invoice,SalesOrder & Quotes records sort by Account Name - $accountname = textlength_check($adb->query_result($list_result,$i-1,"accountname")); - $accountid = $adb->query_result($list_result,$i-1,"accountid"); - $value = ''.$accountname.''; - } else { - $account_id = $adb->query_result($list_result,$i-1,"accountid"); - $account_name = getAccountName($account_id); - $acc_name = textlength_check($account_name); - // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 - $value = ''.$acc_name.''; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" - } - } elseif(( $module == 'HelpDesk' || $module == 'PriceBook' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'Faq') && $name == 'Product Name') { - if($module == 'HelpDesk' || $module == 'Faq') - $product_id = $adb->query_result($list_result,$i-1,"product_id"); - else - $product_id = $adb->query_result($list_result,$i-1,"productid"); - - if($product_id != '') - $product_name = getProductName($product_id); - else - $product_name = ''; - - $value = ''.textlength_check($product_name).''; - } elseif(($module == 'Quotes' && $name == 'Potential Name') || ($module == 'SalesOrder' && $name == 'Potential Name')) { - $potential_id = $adb->query_result($list_result,$i-1,"potentialid"); - $potential_name = getPotentialName($potential_id); - $value = ''.textlength_check($potential_name).''; - } elseif($module =='Emails' && $relatedlist != '' && ($name=='Subject' || $name=='Date Sent' || $name == 'To')) { - $list_result_count = $i-1; - $tmp_value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); - $value = ''.textlength_check($tmp_value).''; - if($name == 'Date Sent') { - $sql="select email_flag from vtiger_emaildetails where emailid=?"; - $result=$adb->pquery($sql, array($entity_id)); - $email_flag=$adb->query_result($result,0,"email_flag"); - if($email_flag != 'SAVED') - $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); - else - $value = ''; - } - } elseif($module == 'Calendar' && ($fieldname!='taskstatus' && $fieldname!='eventstatus')) { - if($activitytype == 'Task' ) { - if(getFieldVisibilityPermission('Calendar',$current_user->id,$fieldname) == '0'){ - $list_result_count = $i-1; - $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); - } else { - $value = ''; - } - } else { - if(getFieldVisibilityPermission('Events',$current_user->id,$fieldname) == '0'){ - $list_result_count = $i-1; - $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); - } else { - $value = ''; - } - } - } else { - $list_result_count = $i-1; - $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); - } - } - - // vtlib customization: For listview javascript triggers - $value = "$value "; - // END - - if($module == "Calendar" && $name == $app_strings['Close']) - { - if(isPermitted("Calendar","EditView") == 'yes') - { - if((getFieldVisibilityPermission('Events',$current_user->id,'eventstatus') == '0') || (getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0')) - { - array_push($list_header,$value); - } - } - } - else - $list_header[] = $value; - - } - - } - $varreturnset = ''; - if($returnset=='') - $varreturnset = '&return_module='.$module.'&return_action=index'; - else - $varreturnset = $returnset; - - - if($module == 'Calendar') - { - $actvity_type = $adb->query_result($list_result,$list_result_count,'activitytype'); - if($actvity_type == 'Task') - $varreturnset .= '&activity_mode=Task'; - else - $varreturnset .= '&activity_mode=Events'; - } - - //Added for Actions ie., edit and delete links in listview - $links_info = ""; - if(!(is_array($selectedfields) && $selectedfields != '')) - { - if(isPermitted($module,"EditView","") == 'yes'){ - $edit_link = getListViewEditLink($module,$entity_id,$relatedlist,$varreturnset,$list_result,$list_result_count); - if(isset($_REQUEST['start']) && $_REQUEST['start'] > 1 && $module != 'Emails') - $links_info .= "".$app_strings["LNK_EDIT"]." "; - else - $links_info .= "".$app_strings["LNK_EDIT"]." "; - } - - - if(isPermitted($module,"Delete","") == 'yes'){ - $del_link = getListViewDeleteLink($module,$entity_id,$relatedlist,$varreturnset); - if($links_info != "" && $del_link != "") - $links_info .= " | "; - if($del_link != "") - $links_info .= "".$app_strings["LNK_DELETE"].""; - } - } - // Record Change Notification - if(method_exists($focus, 'isViewed') && PerformancePrefs::getBoolean('LISTVIEW_RECORD_CHANGE_INDICATOR', true)) { - if(!$focus->isViewed($entity_id)) { - $links_info .= " | "; - } - } - // END - if($links_info != "" && !$skipActions) - $list_header[] = $links_info; - $list_block[$entity_id] = $list_header; - - } - $log->debug("Exiting getListViewEntries method ..."); - return $list_block; - -} - -/**This function generates the List view entries in a popup list view -*Param $focus - module object -*Param $list_result - resultset of a listview query -*Param $navigation_array - navigation values in an array -*Param $relatedlist - check for related list flag -*Param $returnset - list query parameters in url string -*Param $edit_action - Edit action value -*Param $del_action - delete action value -*Param $oCv - vtiger_customview object -*Returns an array type -*/ - - -function getSearchListViewEntries($focus, $module,$list_result,$navigation_array,$form='') -{ - global $log; - $log->debug("Entering getSearchListViewEntries(".get_class($focus).",". $module.",".$list_result.",".$navigation_array.") method ..."); - - global $adb,$app_strings,$theme,$current_user,$list_max_entries_per_page; - $noofrows = $adb->num_rows($list_result); - - $list_header = ''; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $list_block = Array(); - - //getting the vtiger_fieldtable entries from database - $tabid = getTabid($module); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - //Added to reduce the no. of queries logging for non-admin user -- by Minnie-start - $field_list = array(); - $j=0; - foreach($focus->search_fields as $name=>$tableinfo) - { - $fieldname = $focus->search_fields_name[$name]; - array_push($field_list, $fieldname); - $j++; - } - - $field=Array(); - if($is_admin==false && $module != 'Users') - { - if($module == 'Emails') - { - $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; - $params = array($tabid); - } - else - { - $profileList = getCurrentUserProfileList(); - $query = "SELECT DISTINCT vtiger_field.fieldname - FROM vtiger_field - INNER JOIN vtiger_profile2field - ON vtiger_profile2field.fieldid = vtiger_field.fieldid - INNER JOIN vtiger_def_org_field - ON vtiger_def_org_field.fieldid = vtiger_field.fieldid - WHERE vtiger_field.tabid = ? - AND vtiger_profile2field.visible = 0 - AND vtiger_def_org_field.visible = 0 - AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") - AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2)"; - $params = array($tabid, $profileList, $field_list); - } - - $result = $adb->pquery($query, $params); - - for($k=0;$k < $adb->num_rows($result);$k++) - { - $field[]=$adb->query_result($result,$k,"fieldname"); - } - } - //constructing the uitype and columnname array - $ui_col_array=Array(); - - $query = "SELECT uitype, columnname, fieldname - FROM vtiger_field - WHERE tabid=? - AND fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2)"; - $result = $adb->pquery($query, array($tabid, $field_list)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $tempArr=array(); - $uitype=$adb->query_result($result,$i,'uitype'); - $columnname=$adb->query_result($result,$i,'columnname'); - $field_name=$adb->query_result($result,$i,'fieldname'); - $tempArr[$uitype]=$columnname; - $ui_col_array[$field_name]=$tempArr; - } - - //end - if($navigation_array['end_val'] > 0) - { - for ($i=1; $i<=$noofrows; $i++) - { - - //Getting the entityid - if($module != 'Users') - { - $entity_id = $adb->query_result($list_result,$i-1,"crmid"); - }else - { - $entity_id = $adb->query_result($list_result,$i-1,"id"); - } - - $list_header=Array(); - - foreach($focus->search_fields as $name=>$tableinfo) - { - $fieldname = $focus->search_fields_name[$name]; - - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $module == 'Users') - { - if($fieldname == '') - { - $table_name = ''; - $column_name = ''; - foreach($tableinfo as $tablename=>$colname) - { - $table_name=$tablename; - $column_name = $colname; - } - $value = $adb->query_result($list_result,$i-1,$colname); - } - else - { - if(($module == 'Calls' || $module == 'Tasks' || $module == 'Meetings' || $module == 'Emails') && (($name=='Related to') || ($name=='Contact Name') || ($name=='Vendor Name'))) - { - if ($name=='Related to') - $value=getRelatedTo($module,$list_result,$i-1); - if($name=='Contact Name') - { - $contact_id = $adb->query_result($list_result,$i-1,"contactid"); - $contact_name = getFullNameFromQResult($list_result,$i-1,"Contacts"); - $value=""; - if(($contact_name != "") && ($contact_id !='NULL')) - $value = "".$contact_name.""; - } - } - elseif(($module == 'Faq' || $module == 'Documents') && $name=='Related to') - { - $value=getRelatedToEntity($module,$list_result,$i-1); - } - elseif($name=='Account Name' && ($module == 'Potentials' || $module == 'SalesOrder' || $module == 'Quotes')) - { - $account_id = $adb->query_result($list_result,$i-1,"accountid"); - $account_name = getAccountName($account_id); - $value = textlength_check($account_name); - } - elseif($name=='Quote Name' && $module == 'SalesOrder') - { - $quote_id = $adb->query_result($list_result,$i-1,"quoteid"); - $quotename = getQuoteName($quote_id); - $value = textlength_check($quotename); - } - elseif($name == 'Account Name' && $module=='Contacts' ) - { - $account_id = $adb->query_result($list_result,$i-1,"accountid"); - $account_name = getAccountName($account_id); - $value = textlength_check($account_name); - } - // vtlib customization: Generic popup handling - elseif(isset($focus->popup_fields) && in_array($fieldname, $focus->popup_fields)) { - global $default_charset; - $forfield = htmlspecialchars($_REQUEST['forfield'], ENT_QUOTES, $default_charset); - $list_result_count = $i-1; - $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"search",$focus->popup_type); - if(isset($forfield) && $forfield != '' && $focus->popup_type != 'detailview') { - $value = strip_tags($value); // Remove any previous html conversion - $value = "$value"; - } - } - // END - else - { - $list_result_count = $i-1; - $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"search",$focus->popup_type, $form); - } - - } - $list_header[]=$value; - } - } - - if($module=='Products' && ($focus->popup_type=='inventory_prod' || $focus->popup_type=='inventory_prod_po')) - { - global $default_charset; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - $row_id = $_REQUEST['curr_row']; - - //To get all the tax types and values and pass it to product details - $tax_str = ''; - $tax_details = getAllTaxes(); - for($tax_count=0;$tax_countid,'unit_price') == '0') { - $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); - if($_REQUEST['currencyid'] != null) { - $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id)); - $unitprice = $prod_prices[$entity_id]; - } - } else { - $unit_price = ''; - } - $sub_products = ''; - $sub_prod = ''; - $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'",array($entity_id)); - for($k=0;$k<$adb->num_rows($sub_prod_query);$k++){ - //$sub_prod=array(); - $id = $adb->query_result($sub_prod_query,$k,"productid"); - $str_sep=''; - if($k>0) $str_sep = ":"; - $sub_products .= $str_sep.$id; - $sub_prod .= $str_sep." - ".$adb->query_result($sub_prod_query,$k,"productname"); - } - - $sub_det = $sub_products."::".str_replace(":","
",$sub_prod); - $qty_stock=$adb->query_result($list_result,$list_result_count,'qtyinstock'); - - $slashes_temp_val = popup_from_html(getProductName($entity_id)); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $description=$adb->query_result($list_result,$list_result_count,'description'); - $slashes_desc = htmlspecialchars($description,ENT_QUOTES,$default_charset); - - $sub_products_link = ' Sub Products'; - - if(!isset($_REQUEST['record_id'])){ - $sub_products_query = $adb->pquery("SELECT * from vtiger_seproductsrel WHERE productid=? AND setype='Products'",array($entity_id)); - if($adb->num_rows($sub_products_query)>0) - $list_header[]=$sub_products_link; - else - $list_header[]= $app_strings['LBL_NO_SUB_PRODUCTS']; - } - } - - if($module=='Services' && $focus->popup_type=='inventory_service') - { - global $default_charset; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - $row_id = $_REQUEST['curr_row']; - - //To get all the tax types and values and pass it to product details - $tax_str = ''; - $tax_details = getAllTaxes(); - for($tax_count=0;$tax_countid,'unit_price') == '0') { - $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); - if($_REQUEST['currencyid'] != null) { - $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module); - $unitprice = $prod_prices[$entity_id]; - } - } else { - $unit_price = ''; - } - - $slashes_temp_val = popup_from_html($adb->query_result($list_result,$list_result_count,'servicename')); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $description=$adb->query_result($list_result,$list_result_count,'description'); - $slashes_desc = htmlspecialchars($description,ENT_QUOTES,$default_charset); - } - $list_block[$entity_id]=$list_header; - } - } - $list = $list_block; - $log->debug("Exiting getSearchListViewEntries method ..."); - return $list; -} - - -/**This function generates the value for a given vtiger_field namee -*Param $field_result - vtiger_field result in array -*Param $list_result - resultset of a listview query -*Param $fieldname - vtiger_field name -*Param $focus - module object -*Param $module - module name -*Param $entity_id - entity id -*Param $list_result_count - list result count -*Param $mode - mode type -*Param $popuptype - popup type -*Param $returnset - list query parameters in url string -*Param $viewid - custom view id -*Returns an string value -*/ - - -function getValue($field_result, $list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,$mode,$popuptype,$returnset='',$viewid='') -{ - global $log, $listview_max_textlength, $app_strings, $current_language,$currentModule; - $log->debug("Entering getValue(".$field_result.",". $list_result.",".$fieldname.",".get_class($focus).",".$module.",".$entity_id.",".$list_result_count.",".$mode.",".$popuptype.",".$returnset.",".$viewid.") method ..."); - global $adb, $current_user, $default_charset; - - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - $tabname = getParentTab(); - $tabid = getTabid($module); - $current_module_strings = return_module_language($current_language, $module); - $uicolarr=$field_result[$fieldname]; - foreach($uicolarr as $key=>$value) - { - $uitype = $key; - $colname = $value; - } - //added for getting event status in Custom view - Jaguar - if($module == 'Calendar' && ($colname == "status" || $colname == "eventstatus")) - { - $colname="activitystatus"; - } - //Ends - $field_val = $adb->query_result($list_result,$list_result_count,$colname); - if(stristr(html_entity_decode($field_val), "$value){ - $displayValue = $value; - } - } - $value = "$displayValue"; - } else { - $value = ''; - } - } // END - else if($uitype == 53) - { - $value = textlength_check($adb->query_result($list_result,$list_result_count,'user_name')); - } - elseif($uitype == 52) - { - $value = getUserName($adb->query_result($list_result,$list_result_count,'handler')); - } - elseif($uitype == 51)//Accounts - Member Of - { - $parentid = $adb->query_result($list_result,$list_result_count,"parentid"); - if($module=='Accounts') - $entity_name = textlength_check(getAccountName($parentid)); - elseif($module == 'Products') - $entity_name = textlength_check(getProductName($parentid)); - $value = ''.$entity_name.''; - - } - elseif($uitype == 77) - { - $value = getUserName($adb->query_result($list_result,$list_result_count,'inventorymanager')); - } - elseif($uitype == 5 || $uitype == 6 || $uitype == 23 || $uitype == 70) - { - if($temp_val != '' && $temp_val != '0000-00-00') - { - $value = getDisplayDate($temp_val); - } - elseif($temp_val == '0000-00-00') - { - $value = ''; - } - else - { - $value = $temp_val; - } - - - } - elseif($uitype == 15 || ($uitype == 55 && $fieldname =="salutationtype")) - { - $temp_val = decode_html($adb->query_result($list_result,$list_result_count,$colname)); - if(($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) && $temp_val != '') - { - $temp_acttype = $adb->query_result($list_result,$list_result_count,'activitytype'); - if(($temp_acttype == 'Meeting' || $temp_acttype == 'Call') && $fieldname =="taskstatus") - $temptable = "eventstatus"; - else - $temptable = $fieldname; - $roleid=$current_user->roleid; - $roleids = Array(); - $subrole = getRoleSubordinates($roleid); - if(count($subrole)> 0) - $roleids = $subrole; - array_push($roleids, $roleid); - - //here we are checking wheather the table contains the sortorder column .If sortorder is present in the main picklist table, then the role2picklist will be applicable for this table... - - $sql="select * from vtiger_$temptable where $temptable=?"; - $res = $adb->pquery($sql,array(decode_html($temp_val))); - $picklistvalueid = $adb->query_result($res,0,'picklist_valueid'); - if ($picklistvalueid != null) { - $pick_query="select * from vtiger_role2picklist where picklistvalueid=$picklistvalueid and roleid in (". generateQuestionMarks($roleids) .")"; - $res_val=$adb->pquery($pick_query,array($roleids)); - $num_val = $adb->num_rows($res_val); - } - if($num_val > 0 || ($temp_acttype == 'Task' && $fieldname == 'activitytype')) - $temp_val = $temp_val; - else - $temp_val = "".$app_strings['LBL_NOT_ACCESSIBLE'].""; - } - $value = ($current_module_strings[$temp_val] != '') ? $current_module_strings[$temp_val] : (($app_strings[$temp_val] != '') ? ($app_strings[$temp_val]) : $temp_val); - if($value != "".$app_strings['LBL_NOT_ACCESSIBLE']."") - { - $value = textlength_check($value); - } - } - elseif($uitype == 71 || $uitype == 72) - { - if($temp_val != '') - { - if($fieldname == 'unit_price') { - $currency_id = getProductBaseCurrency($entity_id,$module); - $cursym_convrate = getCurrencySymbolandCRate($currency_id); - $value = "".$cursym_convrate['symbol']." ". $temp_val; - } else { - $rate = $user_info['conv_rate']; - //changes made to remove vtiger_currency symbol infront of each vtiger_potential amount - if ($temp_val != 0) $value = convertFromDollar($temp_val,$rate); - else $value = $temp_val; - } - } - else - { - $value = ''; - } - - } - elseif($uitype == 17) - { - $value = ''.$temp_val.''; - } - elseif($uitype == 13 || $uitype == 104 && ($_REQUEST['action'] != 'Popup' && $_REQUEST['file'] != 'Popup')) - { - if($_SESSION['internal_mailer'] == 1) - { - //check added for email link in user detailview - if($module == 'Calendar') { - if(getActivityType($entity_id) == 'Task') { - $tabid = 9; - } else { - $tabid = 16; - } - } else { - $tabid = getTabid($module); - } - $fieldid = getFieldid($tabid, $fieldname); - if(empty($popuptype)){ - $value = ''.$temp_val.''; - } else { - $value = $temp_val; - } - } - else - $value = ''.$temp_val.''; - } - elseif($uitype == 56) - { - if($temp_val == 1) - { - $value = $app_strings['yes']; - } - elseif($temp_val == 0) - { - $value = $app_strings['no']; - } - else { - $value = ''; - } - } - elseif($uitype == 57) - { - if($temp_val != '') - { - $sql="SELECT * FROM vtiger_contactdetails WHERE contactid=?"; - $result=$adb->pquery($sql, array($temp_val)); - $value = ''; - if($adb->num_rows($result)) { - $name=getFullNameFromQResult($result,0,"Contacts"); - $value= ''.$name.''; - } - } - else - $value=''; - } - //Added by Minnie to get Campaign Source - elseif($uitype == 58) - { - if($temp_val != '') - { - $sql="SELECT * FROM vtiger_campaign WHERE campaignid=?"; - $result=$adb->pquery($sql, array($temp_val)); - $campaignname=$adb->query_result($result,0,"campaignname"); - $value= ''.$campaignname.''; - } - else - $value=''; - } - //End - //Added By *Raj* for the Issue ProductName not displayed in CustomView of HelpDesk - elseif($uitype == 59) - { - if($temp_val != '') - { - $value = getProductName($temp_val); - } - else - { - $value = ''; - } - } - //End - elseif($uitype == 61) - { - $attachmentid=$adb->query_result($adb->pquery("SELECT * FROM vtiger_seattachmentsrel WHERE crmid = ?", array($entity_id)),0,'attachmentsid'); - $value = ''.$temp_val.''; - } - elseif($uitype == 62) - { - $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); - $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); - - if($parenttype == "Leads") - { - $tablename = "vtiger_leaddetails"; $fieldname = "lastname"; $idname="leadid"; - } - if($parenttype == "Accounts") - { - $tablename = "vtiger_account"; $fieldname = "accountname"; $idname="accountid"; - } - if($parenttype == "Products") - { - $tablename = "vtiger_products"; $fieldname = "productname"; $idname="productid"; - } - if($parenttype == "HelpDesk") - { - $tablename = "vtiger_troubletickets"; $fieldname = "title"; $idname="ticketid"; - } - if($parenttype == "Invoice") - { - $tablename = "vtiger_invoice"; $fieldname = "subject"; $idname="invoiceid"; - } - - - if($parentid != '') - { - $sql="SELECT * FROM $tablename WHERE $idname = ?"; - $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); - - $value=''.$fieldvalue.''; - } - else - $value=''; - } - elseif($uitype == 66) - { - $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); - $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); - - if($parenttype == "Leads") - { - $tablename = "vtiger_leaddetails"; $fieldname = "lastname"; $idname="leadid"; - } - if($parenttype == "Accounts") - { - $tablename = "vtiger_account"; $fieldname = "accountname"; $idname="accountid"; - } - if($parenttype == "HelpDesk") - { - $tablename = "vtiger_troubletickets"; $fieldname = "title"; $idname="ticketid"; - } - if($parentid != '') - { - $sql="SELECT * FROM $tablename WHERE $idname = ?"; - $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); - - $value=''.$fieldvalue.''; - } - else - $value=''; - } - elseif($uitype == 67) - { - $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); - $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); - - if($parenttype == "Leads") - { - $tablename = "vtiger_leaddetails"; $fieldname = "lastname"; $idname="leadid"; - } - if($parenttype == "Contacts") - { - $tablename = "vtiger_contactdetails"; $fieldname = "contactname"; $idname="contactid"; - } - if($parentid != '') - { - $sql="SELECT * FROM $tablename WHERE $idname = ?"; - $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); - - $value=''.$fieldvalue.''; - } - else - $value=''; - } - elseif($uitype == 68) - { - $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); - $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); - - if($parenttype == '' && $parentid != '') - $parenttype = getSalesEntityType($parentid); - - if($parenttype == "Contacts") - { - $tablename = "vtiger_contactdetails"; $fieldname = "contactname"; $idname="contactid"; - } - if($parenttype == "Accounts") - { - $tablename = "vtiger_account"; $fieldname = "accountname"; $idname="accountid"; - } - if($parentid != '') - { - $sql="SELECT * FROM $tablename WHERE $idname = ?"; - $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); - - $value=''.$fieldvalue.''; - } - else - $value=''; - } - elseif($uitype == 78) - { - if($temp_val != '') - { - - $quote_name = getQuoteName($temp_val); - $value= ''.textlength_check($quote_name).''; - } - else - $value=''; - } - elseif($uitype == 79) - { - if($temp_val != '') - { - - $purchaseorder_name = getPoName($temp_val); - $value= ''.textlength_check($purchaseorder_name).''; - } - else - $value=''; - } - elseif($uitype == 80) - { - if($temp_val != '') - { - - $salesorder_name = getSoName($temp_val); - $value= "".textlength_check($salesorder_name).''; - } - else - $value=''; - } - elseif($uitype == 75 || $uitype == 81) - { - - if($temp_val != '') - { - - $vendor_name = getVendorName($temp_val); - $value= ''.textlength_check($vendor_name).''; - } - else - $value=''; - } - elseif($uitype == 98) - { - $value = ''.textlength_check(getRoleName($temp_val)).''; - } - elseif($uitype == 33) - { - $value = ($temp_val != "") ? str_ireplace(' |##| ',', ',$temp_val) : ""; - if(!$is_admin && $value != '') - { - $value = ($field_val != "") ? str_ireplace(' |##| ',', ',$field_val) : ""; - if($value != '') - { - $value_arr=explode(',',trim($value)); - $roleid=$current_user->roleid; - $subrole = getRoleSubordinates($roleid); - if(count($subrole)> 0) - { - $roleids = $subrole; - array_push($roleids, $roleid); - } - else - { - $roleids = $roleid; - } - - if (count($roleids) > 0) { - $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_$fieldname) order by $fieldname asc"; - $params = array($roleids); - } else { - $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where picklistid in (select picklistid from vtiger_$fieldname) order by $fieldname asc"; - $params = array(); - } - $pickListResult = $adb->pquery($pick_query, $params); - $picklistval = Array(); - for($i=0;$i<$adb->num_rows($pickListResult);$i++) - { - $picklistarr[]=$adb->query_result($pickListResult,$i,$fieldname); - } - $value_temp = Array(); - $string_temp = ''; - $str_c = 0; - foreach($value_arr as $ind => $val) - { - $notaccess = ''.$app_strings['LBL_NOT_ACCESSIBLE'].""; - if(!$listview_max_textlength || !(strlen(preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$string_temp)) > $listview_max_textlength)) - { - $value_temp1 = (in_array(trim($val),$picklistarr))?$val:$notaccess; - if($str_c!=0) - $string_temp .= ' , '; - $string_temp .= $value_temp1; - $str_c++; - } - else - $string_temp .='...'; - - } - $value=$string_temp; - } - } - } - elseif($uitype == 85) - { - $value = ($temp_val != "") ? "{$temp_val}" : ""; - } - elseif($uitype == 116) - { - $value = ($temp_val != "") ? getCurrencyName($temp_val) : ""; - } - elseif($uitype == 117) - { - // NOTE: Without symbol the value could be used for filtering/lookup hence avoiding the translation - $value = ($temp_val != "") ? getCurrencyName($temp_val,false) : ""; - } - elseif($uitype == 26){ - $sql ="select foldername from vtiger_attachmentsfolder where folderid = ?"; - $res = $adb->pquery($sql,array($temp_val)); - $foldername = $adb->query_result($res,0,'foldername'); - $value = $foldername; - } - //added for asterisk integration - elseif($uitype == 11){ - $value = "".$temp_val.""; - } - //asterisk changes end here - //Added for email status tracking - elseif($uitype == 25) - { - $contactid=$_REQUEST['record']; - $emailid=$adb->query_result($list_result,$list_result_count,"activityid"); - $result = $adb->pquery("SELECT access_count FROM vtiger_email_track WHERE crmid=? AND mailid=?", array($contactid,$emailid)); - $value=$adb->query_result($result,0,"access_count"); - if(!$value) { - $value = 0; - } - }elseif($uitype == 8){ - if(!empty($temp_val)){ - $temp_val = html_entity_decode($temp_val,ENT_QUOTES,$default_charset); - $json = new Zend_Json(); - $value = vt_suppressHTMLTags(implode(',',$json->decode($temp_val))); - } - } - //end email status tracking - else - { - if($fieldname == $focus->list_link_field) - { - if($mode == "search") - { - if($popuptype == "specific" || $popuptype=="toDospecific") - { - // Added for get the first name of contact in Popup window - if($colname == "lastname" && $module == 'Contacts') - { - $temp_val = getFullNameFromQResult($list_result,$list_result_count,"Contacts"); - } - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - //Added to avoid the error when select SO from Invoice through AjaxEdit - if($module == 'SalesOrder') - $value = ''.$temp_val.''; - - elseif($module =='Contacts'){ - require_once('modules/Contacts/Contacts.php'); - $cntct_focus = new Contacts(); - $cntct_focus->retrieve_entity_info($entity_id,"Contacts"); - $slashes_temp_val = popup_from_html($temp_val); - //ADDED TO CHECK THE FIELD PERMISSIONS FOR - $xyz=array('mailingstreet','mailingcity','mailingzip','mailingpobox','mailingcountry','mailingstate','otherstreet','othercity','otherzip','otherpobox','othercountry','otherstate'); - for($i=0;$i<12;$i++){ - if (getFieldVisibilityPermission($module, $current_user->id,$xyz[$i]) == '0'){ - $cntct_focus->column_fields[$xyz[$i]] = $cntct_focus->column_fields[$xyz[$i]]; - } - else - $cntct_focus->column_fields[$xyz[$i]] = ''; - } - // For ToDo creation the underlying form is not named as EditView - $form = !empty($_REQUEST['form']) ? $_REQUEST['form'] : ''; - if(!empty($form)) $form = htmlspecialchars($form,ENT_QUOTES,$default_charset); - $value = 'column_fields['mailingstreet']).'", "'.popup_decode_html($cntct_focus->column_fields['otherstreet']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingcity']).'", "'.popup_decode_html($cntct_focus->column_fields['othercity']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingstate']).'", "'.popup_decode_html($cntct_focus->column_fields['otherstate']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingzip']).'", "'.popup_decode_html($cntct_focus->column_fields['otherzip']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingcountry']).'", "'.popup_decode_html($cntct_focus->column_fields['othercountry']).'","'.popup_decode_html($cntct_focus->column_fields['mailingpobox']).'", "'.popup_decode_html($cntct_focus->column_fields['otherpobox']).'","'.$form.'");\'>'.$temp_val.''; - } - - else - if($popuptype=='toDospecific') - $value = ''.$temp_val.''; - else - $value = ''.$temp_val.''; - } - elseif($popuptype == "detailview") - { - if($colname == "lastname" && ($module == 'Contacts' || $module == 'Leads')) { - $temp_val = getFullNameFromQResult($list_result,$list_result_count,$module); - } - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - $focus->record_id = $_REQUEST['recordid']; - if($_REQUEST['return_module'] == "Calendar") - { - $value = ''.$temp_val.''; - } - else - $value = 'record_id.'","'.$module.'");\'>'.$temp_val.''; - } - elseif($popuptype == "formname_specific") - { - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - $value = ''.$temp_val.''; - } - elseif($popuptype == "inventory_prod") - { - $row_id = $_REQUEST['curr_row']; - - //To get all the tax types and values and pass it to product details - $tax_str = ''; - $tax_details = getAllTaxes(); - for($tax_count=0;$tax_countid,'unit_price') == '0') { - $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); - if($_REQUEST['currencyid'] != null) { - $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id)); - $unitprice = $prod_prices[$entity_id]; - } - } else { - $unit_price = ''; - } - $sub_products = ''; - $sub_prod = ''; - $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname,vtiger_products.qtyinstock,vtiger_crmentity.description from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'",array($entity_id)); - for($i=0;$i<$adb->num_rows($sub_prod_query);$i++){ - //$sub_prod=array(); - $id = $adb->query_result($sub_prod_query,$i,"productid"); - $str_sep=''; - if($i>0) $str_sep = ":"; - $sub_products .= $str_sep.$id; - $sub_prod .= $str_sep." - ".$adb->query_result($sub_prod_query,$i,"productname"); - } - - $sub_det = $sub_products."::".str_replace(":","
",$sub_prod); - $qty_stock=$adb->query_result($list_result,$list_result_count,'qtyinstock'); - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $description=decode_html_force($adb->query_result($list_result,$list_result_count,'description')); - $slashes_desc = addslashes(htmlspecialchars($description,ENT_QUOTES,$default_charset)); - - $slashes_desc = str_replace(array("\r","\n"),array('\r','\n'), $slashes_desc); - $tmp_arr = array("entityid"=>$entity_id,"prodname"=>"".stripslashes(nl2br($slashes_temp_val))."","unitprice" => "$unitprice", "qtyinstk"=>"$qty_stock","taxstring"=>"$tax_str","rowid"=>"$row_id","desc"=>"$slashes_desc","subprod_ids"=>"$sub_det"); - require_once('include/Zend/Json.php'); - $prod_arr = Zend_Json::encode($tmp_arr); - $value = ''.$temp_val.''; - } - elseif($popuptype == "inventory_prod_po") - { - $row_id = $_REQUEST['curr_row']; - - //To get all the tax types and values and pass it to product details - $tax_str = ''; - $tax_details = getAllTaxes(); - for($tax_count=0;$tax_countid,'unit_price') == '0') { - $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); - if($_REQUEST['currencyid'] != null) { - $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module); - $unitprice = $prod_prices[$entity_id]; - } - } else { - $unit_price = ''; - } - $sub_products = ''; - $sub_prod = ''; - $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname,vtiger_products.qtyinstock,vtiger_crmentity.description from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'",array($entity_id)); - for($i=0;$i<$adb->num_rows($sub_prod_query);$i++){ - //$sub_prod=array(); - $id = $adb->query_result($sub_prod_query,$i,"productid"); - $str_sep=''; - if($i>0) $str_sep = ":"; - $sub_products .= $str_sep.$id; - $sub_prod .= $str_sep." - $id.".$adb->query_result($sub_prod_query,$i,"productname"); - } - - $sub_det = $sub_products."::".str_replace(":","
",$sub_prod); - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $description=$adb->query_result($list_result,$list_result_count,'description'); - $slashes_desc = htmlspecialchars($description,ENT_QUOTES,$default_charset); - - $slashes_desc = str_replace(array("\r","\n"),array('\r','\n'), $slashes_desc); - $tmp_arr = array("entityid"=>$entity_id,"prodname"=>"".stripslashes(nl2br($slashes_temp_val))."","unitprice" => "$unitprice", "taxstring"=>"$tax_str","rowid"=>"$row_id","desc"=>"$slashes_desc","subprod_ids"=>"$sub_det"); - require_once('include/Zend/Json.php'); - $prod_arr = Zend_Json::encode($tmp_arr); - - $value = ''.$temp_val.''; - } - elseif($popuptype == "inventory_service") - { - $row_id = $_REQUEST['curr_row']; - - //To get all the tax types and values and pass it to product details - $tax_str = ''; - $tax_details = getAllTaxes(); - for($tax_count=0;$tax_countid,'unit_price') == '0') { - $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); - if($_REQUEST['currencyid'] != null) { - $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module); - $unitprice = $prod_prices[$entity_id]; - } - } else { - $unit_price = ''; - } - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $description=decode_html_force($adb->query_result($list_result,$list_result_count,'description')); - $slashes_desc = htmlspecialchars($description,ENT_QUOTES,$default_charset); - - $slashes_desc = str_replace(array("\r","\n"),array('\r','\n'), $slashes_desc); - $tmp_arr = array("entityid"=>$entity_id,"prodname"=>"".stripslashes(nl2br($slashes_temp_val))."","unitprice" => "$unitprice","taxstring"=>"$tax_str","rowid"=>"$row_id","desc"=>"$slashes_desc"); - require_once('include/Zend/Json.php'); - $prod_arr = Zend_Json::encode($tmp_arr); - - $value = ''.$temp_val.''; - } - elseif($popuptype == "inventory_pb") - { - - $prod_id = $_REQUEST['productid']; - $flname = $_REQUEST['fldname']; - $listprice=getListPrice($prod_id,$entity_id); - - $temp_val = popup_from_html($temp_val); - $value = ''.$temp_val.''; - } - elseif($popuptype == "specific_account_address") - { - require_once('modules/Accounts/Accounts.php'); - $acct_focus = new Accounts(); - $acct_focus->retrieve_entity_info($entity_id,"Accounts"); - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); - for($i=0;$i<12;$i++){ - if (getFieldVisibilityPermission($module, $current_user->id,$xyz[$i]) == '0'){ - $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]]; - } - else - $acct_focus->column_fields[$xyz[$i]] = ''; - } - $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['bill_street'])); - $ship_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['ship_street'])); - - $value = 'column_fields['bill_city']).'", "'.popup_decode_html($acct_focus->column_fields['ship_city']).'", "'.popup_decode_html($acct_focus->column_fields['bill_state']).'", "'.popup_decode_html($acct_focus->column_fields['ship_state']).'", "'.popup_decode_html($acct_focus->column_fields['bill_code']).'", "'.popup_decode_html($acct_focus->column_fields['ship_code']).'", "'.popup_decode_html($acct_focus->column_fields['bill_country']).'", "'.popup_decode_html($acct_focus->column_fields['ship_country']).'","'.popup_decode_html($acct_focus->column_fields['bill_pobox']).'", "'.popup_decode_html($acct_focus->column_fields['ship_pobox']).'");\'>'.$temp_val.''; - - } - elseif($popuptype == "specific_contact_account_address") - { - require_once('modules/Accounts/Accounts.php'); - $acct_focus = new Accounts(); - $acct_focus->retrieve_entity_info($entity_id,"Accounts"); - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['bill_street'])); - $ship_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['ship_street'])); - - $value = 'column_fields['bill_city']).'", "'.popup_decode_html($acct_focus->column_fields['ship_city']).'", "'.popup_decode_html($acct_focus->column_fields['bill_state']).'", "'.popup_decode_html($acct_focus->column_fields['ship_state']).'", "'.popup_decode_html($acct_focus->column_fields['bill_code']).'", "'.popup_decode_html($acct_focus->column_fields['ship_code']).'", "'.popup_decode_html($acct_focus->column_fields['bill_country']).'", "'.popup_decode_html($acct_focus->column_fields['ship_country']).'","'.popup_decode_html($acct_focus->column_fields['bill_pobox']).'", "'.popup_decode_html($acct_focus->column_fields['ship_pobox']).'");\'>'.$temp_val.''; - - } - elseif($popuptype == "specific_potential_account_address") - { - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - // For B2C support, Potential was enabled to be linked to Contacts also. - // Hence we need case handling for it. - $relatedid = $adb->query_result($list_result,$list_result_count,"related_to"); - $relatedentity = getSalesEntityType($relatedid); - if($relatedentity == 'Accounts') { - require_once('modules/Accounts/Accounts.php'); - $acct_focus = new Accounts(); - $acct_focus->retrieve_entity_info($relatedid,"Accounts"); - $account_name = getAccountName($relatedid); - - $slashes_account_name = popup_from_html($account_name); - $slashes_account_name = htmlspecialchars($slashes_account_name,ENT_QUOTES,$default_charset); - - $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); - for($i=0;$i<12;$i++){ - if (getFieldVisibilityPermission('Accounts', $current_user->id,$xyz[$i]) == '0'){ - $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]]; - } - else - $acct_focus->column_fields[$xyz[$i]] = ''; - } - $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['bill_street'])); - $ship_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['ship_street'])); - - $value = 'column_fields['bill_city']).'", "'.popup_decode_html($acct_focus->column_fields['ship_city']).'", "'.popup_decode_html($acct_focus->column_fields['bill_state']).'", "'.popup_decode_html($acct_focus->column_fields['ship_state']).'", "'.popup_decode_html($acct_focus->column_fields['bill_code']).'", "'.popup_decode_html($acct_focus->column_fields['ship_code']).'", "'.popup_decode_html($acct_focus->column_fields['bill_country']).'", "'.popup_decode_html($acct_focus->column_fields['ship_country']).'","'.popup_decode_html($acct_focus->column_fields['bill_pobox']).'", "'.popup_decode_html($acct_focus->column_fields['ship_pobox']).'");\'>'.$temp_val.''; - } else if($relatedentity == 'Contacts') { - - require_once('modules/Contacts/Contacts.php'); - $contact_name = getContactName($relatedid); - - $slashes_contact_name = popup_from_html($contact_name); - $slashes_contact_name = htmlspecialchars($slashes_contact_name,ENT_QUOTES,$default_charset); - - $value = ''.$temp_val.''; - - } else { - $value = $temp_val; - } - } - //added by rdhital/Raju for better emails - elseif($popuptype == "set_return_emails") - { - if ($module=='Accounts') - { - $name = $adb->query_result($list_result,$list_result_count,'accountname'); - $accid =$adb->query_result($list_result,$list_result_count,'accountid'); - if(CheckFieldPermission('email1',$module) == "true") - { - $emailaddress=$adb->query_result($list_result,$list_result_count,"email1"); - $email_check = 1; - } - else - $email_check = 0; - if($emailaddress == '') - { - if(CheckFieldPermission('email2',$module) == 'true') - { - $emailaddress2=$adb->query_result($list_result,$list_result_count,"email2"); - $email_check = 2; - } - else - { - if($email_check == 1) - $email_check = 4; - else - $email_check = 3; - } - } - $querystr="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; - $queryres = $adb->pquery($querystr, array(getTabid($module))); - //Change this index 0 - to get the vtiger_fieldid based on email1 or email2 - $fieldid = $adb->query_result($queryres,0,'fieldid'); - - $slashes_name = popup_from_html($name); - $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); - - $value = ''.textlength_check($name).''; - - }elseif ($module=='Vendors') - { - $name = $adb->query_result($list_result,$list_result_count,'vendorname'); - $venid =$adb->query_result($list_result,$list_result_count,'vendorid'); - if(CheckFieldPermission('email',$module) == "true") - { - $emailaddress=$adb->query_result($list_result,$list_result_count,"email"); - $email_check = 1; - } - else - $email_check = 0; - $querystr="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; - $queryres = $adb->pquery($querystr, array(getTabid($module))); - //Change this index 0 - to get the vtiger_fieldid based on email1 or email2 - $fieldid = $adb->query_result($queryres,0,'fieldid'); - - $slashes_name = popup_from_html($name); - $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); - - $value = ''.textlength_check($name).''; - - }elseif ($module=='Contacts' || $module=='Leads') - { - $name=getFullNameFromQResult($list_result,$list_result_count,$module); - if(CheckFieldPermission('email',$module) == "true") - { - $emailaddress=$adb->query_result($list_result,$list_result_count,"email"); - $email_check = 1; - } - else - $email_check = 0; - if($emailaddress == '') - { - if(CheckFieldPermission('yahooid',$module) == 'true') - { - $emailaddress2=$adb->query_result($list_result,$list_result_count,"yahooid"); - $email_check = 2; - } - else{ - if($email_check == 1) - $email_check = 4; - else - $email_check = 3; - } - } - - $querystr="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; - $queryres = $adb->pquery($querystr, array(getTabid($module))); - //Change this index 0 - to get the vtiger_fieldid based on email or yahooid - $fieldid = $adb->query_result($queryres,0,'fieldid'); - - $slashes_name = popup_from_html($name); - $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); - - $value = ''.$name.''; - - }else - { - $firstname=$adb->query_result($list_result,$list_result_count,"first_name"); - $lastname=$adb->query_result($list_result,$list_result_count,"last_name"); - $name=$lastname.' '.$firstname; - $emailaddress=$adb->query_result($list_result,$list_result_count,"email1"); - - $slashes_name = popup_from_html($name); - $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); - $email_check = 1; - $value = ''.textlength_check($name) .''; - - } - - } - elseif($popuptype == "specific_vendor_address") - { - require_once('modules/Vendors/Vendors.php'); - $acct_focus = new Vendors(); - $acct_focus->retrieve_entity_info($entity_id,"Vendors"); - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - $xyz=array('street','city','postalcode','pobox','country','state'); - for($i=0;$i<6;$i++){ - if (getFieldVisibilityPermission($module, $current_user->id,$xyz[$i]) == '0'){ - $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]]; - } - else - $acct_focus->column_fields[$xyz[$i]] = ''; - } - $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['street'])); - - $value = 'column_fields['city']).'", "'.popup_decode_html($acct_focus->column_fields['state']).'", "'.popup_decode_html($acct_focus->column_fields['postalcode']).'", "'.popup_decode_html($acct_focus->column_fields['country']).'","'.popup_decode_html($acct_focus->column_fields['pobox']).'");\'>'.$temp_val.''; - - } - elseif($popuptype == "specific_campaign") - { - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - $value = ''.$temp_val.''; - } - else - { - if($colname == "lastname") - $temp_val = getFullNameFromQResult($list_result,$list_result_count,$module); - - $slashes_temp_val = popup_from_html($temp_val); - $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); - - $log->debug("Exiting getValue method ..."); - if($_REQUEST['maintab'] == 'Calendar') - $value = ''.$temp_val.''; - else - $value = ''.$temp_val.''; - } - } - else - { - if(($module == "Leads" && $colname == "lastname") || ($module == "Contacts" && $colname == "lastname")) - { - $value = ''.$temp_val.''; - } - elseif($module == "Calendar") - { - $actvity_type = $adb->query_result($list_result,$list_result_count,'activitytype'); - $actvity_type = ($actvity_type != '') ? $actvity_type : $adb->query_result($list_result,$list_result_count,'type'); - if($actvity_type == "Task") - { - $value = ''.$temp_val.''; - } - else - { - $value = ''.$temp_val.''; - } - } - elseif($module == "Vendors") - { - - $value = ''.$temp_val.''; - } - elseif($module == "PriceBooks") - { - - $value = ''.$temp_val.''; - } - elseif($module == "SalesOrder") - { - - $value = ''.$temp_val.''; - } - elseif($module == 'Emails') - { - $value = $temp_val; - } - else - { - $value = ''.$temp_val.''; - } - } - } - elseif($fieldname == 'expectedroi' || $fieldname == 'actualroi' || $fieldname == 'actualcost' || $fieldname == 'budgetcost' || $fieldname == 'expectedrevenue') - { - $rate = $user_info['conv_rate']; - $value = convertFromDollar($temp_val,$rate); - } - elseif(($module == 'Invoice' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder') - && ($fieldname == 'hdnGrandTotal' || $fieldname == 'hdnSubTotal' || $fieldname == 'txtAdjustment' - || $fieldname == 'hdnDiscountAmount' || $fieldname == 'hdnS_H_Amount')) - { - $currency_info = getInventoryCurrencyInfo($module, $entity_id); - $currency_id = $currency_info['currency_id']; - $currency_symbol = $currency_info['currency_symbol']; - $value = $currency_symbol.$temp_val; - } - else - { - $value = $temp_val; - } - } - - // Mike Crowe Mod --------------------------------------------------------Make right justified and vtiger_currency value - if ( in_array($uitype,array(71,72,7,9,90)) ) - { - $value = ''.$value.''; - } - $log->debug("Exiting getValue method ..."); - return $value; -} - -/** Function to get the list query for a module - * @param $module -- module name:: Type string - * @param $where -- where:: Type string - * @returns $query -- query:: Type query - */ -function getListQuery($module,$where='') -{ - global $log; - $log->debug("Entering getListQuery(".$module.",".$where.") method ..."); - - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - $tab_id = getTabid($module); - switch($module) - { - Case "HelpDesk": - $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, - vtiger_troubletickets.title, vtiger_troubletickets.status, - vtiger_troubletickets.priority, vtiger_troubletickets.parent_id, - vtiger_contactdetails.contactid, vtiger_contactdetails.firstname, - vtiger_contactdetails.lastname, vtiger_account.accountid, - vtiger_account.accountname, vtiger_ticketcf.*, vtiger_troubletickets.ticket_no - FROM vtiger_troubletickets - INNER JOIN vtiger_ticketcf - ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_contactdetails - ON vtiger_troubletickets.parent_id = vtiger_contactdetails.contactid - LEFT JOIN vtiger_account - ON vtiger_account.accountid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_users - ON vtiger_crmentity.smownerid = vtiger_users.id - LEFT JOIN vtiger_products - ON vtiger_products.productid = vtiger_troubletickets.product_id - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - - } - break; - - Case "Accounts": - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, - vtiger_account.accountname, vtiger_account.email1, - vtiger_account.email2, vtiger_account.website, vtiger_account.phone, - vtiger_accountbillads.bill_city, - vtiger_accountscf.* - FROM vtiger_account - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_account.accountid - INNER JOIN vtiger_accountbillads - ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid - INNER JOIN vtiger_accountshipads - ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid - INNER JOIN vtiger_accountscf - ON vtiger_account.accountid = vtiger_accountscf.accountid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_account vtiger_account2 - ON vtiger_account.parentid = vtiger_account2.accountid - WHERE vtiger_crmentity.deleted = 0 ".$where; - - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $query .= " AND (vtiger_crmentity.smownerid IN (".$current_user->id.") - OR vtiger_crmentity.smownerid IN ( - SELECT vtiger_user2role.userid - FROM vtiger_user2role - INNER JOIN vtiger_users - ON vtiger_users.id = vtiger_user2role.userid - INNER JOIN vtiger_role - ON vtiger_role.roleid = vtiger_user2role.roleid - WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%') - OR vtiger_crmentity.smownerid IN ( - SELECT shareduserid - FROM vtiger_tmp_read_user_sharing_per - WHERE userid=".$current_user->id." - AND tabid=".$tab_id.") - OR ("; - - if(sizeof($current_user_groups) > 0) - { - $query .= " vtiger_groups.groupid IN (". implode(",", getCurrentUserGroupList()) .") - OR "; - } - $query .= " vtiger_groups.groupid IN ( - SELECT vtiger_tmp_read_group_sharing_per.sharedgroupid - FROM vtiger_tmp_read_group_sharing_per - WHERE userid=".$current_user->id." - AND tabid=".$tab_id."))) "; - } - break; - - Case "Potentials": - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, - vtiger_account.accountname, - vtiger_potential.related_to, vtiger_potential.potentialname, - vtiger_potential.sales_stage, vtiger_potential.amount, - vtiger_potential.currency, vtiger_potential.closingdate, - vtiger_potential.typeofrevenue, - vtiger_potentialscf.* - FROM vtiger_potential - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_potential.potentialid - INNER JOIN vtiger_potentialscf - ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid - LEFT JOIN vtiger_account - ON vtiger_potential.related_to = vtiger_account.accountid - LEFT JOIN vtiger_contactdetails - ON vtiger_potential.related_to = vtiger_contactdetails.contactid - LEFT JOIN vtiger_campaign - ON vtiger_campaign.campaignid = vtiger_potential.campaignid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - - break; - - Case "Leads": - $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, - vtiger_leaddetails.firstname, vtiger_leaddetails.lastname, - vtiger_leaddetails.company, vtiger_leadaddress.phone, - vtiger_leadsubdetails.website, vtiger_leaddetails.email, - vtiger_leadscf.* - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadsubdetails - ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadaddress - ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid - INNER JOIN vtiger_leadscf - ON vtiger_leaddetails.leadid = vtiger_leadscf.leadid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 - AND vtiger_leaddetails.converted = 0 ".$where; - - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Products": - $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.description, vtiger_products.*, vtiger_productcf.* - FROM vtiger_products - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_products.productid - INNER JOIN vtiger_productcf - ON vtiger_products.productid = vtiger_productcf.productid - LEFT JOIN vtiger_vendor - ON vtiger_vendor.vendorid = vtiger_products.vendor_id - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_products.handler"; - if((isset($_REQUEST["from_dashboard"]) && $_REQUEST["from_dashboard"] == true) && (isset($_REQUEST["type"]) && $_REQUEST["type"] =="dbrd")) - $query .= " INNER JOIN vtiger_inventoryproductrel on vtiger_inventoryproductrel.productid = vtiger_products.productid"; - $query .= " WHERE vtiger_crmentity.deleted = 0 ".$where; - break; - Case "Documents": - $query = "SELECT case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name,vtiger_crmentity.crmid, vtiger_crmentity.modifiedtime, - vtiger_crmentity.smownerid,vtiger_attachmentsfolder.*,vtiger_notes.* - FROM vtiger_notes - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_notes.notesid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_attachmentsfolder - ON vtiger_notes.folderid = vtiger_attachmentsfolder.folderid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Contacts": - //Query modified to sort by assigned to - $query = "SELECT vtiger_contactdetails.firstname, vtiger_contactdetails.lastname, - vtiger_contactdetails.title, vtiger_contactdetails.accountid, - vtiger_contactdetails.email, vtiger_contactdetails.phone, - vtiger_crmentity.smownerid, vtiger_crmentity.crmid - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid - INNER JOIN vtiger_contactaddress - ON vtiger_contactaddress.contactaddressid = vtiger_contactdetails.contactid - INNER JOIN vtiger_contactsubdetails - ON vtiger_contactsubdetails.contactsubscriptionid = vtiger_contactdetails.contactid - INNER JOIN vtiger_contactscf - ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_account - ON vtiger_account.accountid = vtiger_contactdetails.accountid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_contactdetails vtiger_contactdetails2 - ON vtiger_contactdetails.reportsto = vtiger_contactdetails2.contactid - LEFT JOIN vtiger_customerdetails - ON vtiger_customerdetails.customerid = vtiger_contactdetails.contactid"; - if((isset($_REQUEST["from_dashboard"]) && $_REQUEST["from_dashboard"] == true) && (isset($_REQUEST["type"]) && $_REQUEST["type"] =="dbrd")) - $query .= " INNER JOIN vtiger_campaigncontrel on vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid"; - $query .= " WHERE vtiger_crmentity.deleted = 0 ".$where; - - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Calendar": - - $query="SELECT vtiger_activity.activityid as act_id,vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.setype, - vtiger_activity.*, - vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, - vtiger_contactdetails.contactid, - vtiger_account.accountid, vtiger_account.accountname - FROM vtiger_activity - LEFT JOIN vtiger_activitycf - ON vtiger_activitycf.activityid = vtiger_activity.activityid - LEFT JOIN vtiger_cntactivityrel - ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid - LEFT JOIN vtiger_contactdetails - ON vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid - LEFT JOIN vtiger_seactivityrel - ON vtiger_seactivityrel.activityid = vtiger_activity.activityid - LEFT OUTER JOIN vtiger_activity_reminder - ON vtiger_activity_reminder.activity_id = vtiger_activity.activityid - LEFT JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_activity.activityid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT OUTER JOIN vtiger_account - ON vtiger_account.accountid = vtiger_contactdetails.accountid - LEFT OUTER JOIN vtiger_leaddetails - ON vtiger_leaddetails.leadid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_account vtiger_account2 - ON vtiger_account2.accountid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_potential - ON vtiger_potential.potentialid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_troubletickets - ON vtiger_troubletickets.ticketid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_salesorder - ON vtiger_salesorder.salesorderid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_purchaseorder - ON vtiger_purchaseorder.purchaseorderid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_quotes - ON vtiger_quotes.quoteid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_invoice - ON vtiger_invoice.invoiceid = vtiger_seactivityrel.crmid - LEFT OUTER JOIN vtiger_campaign - ON vtiger_campaign.campaignid = vtiger_seactivityrel.crmid"; - - //added to fix #5135 - if(isset($_REQUEST['from_homepage']) && ($_REQUEST['from_homepage'] == "upcoming_activities" || $_REQUEST['from_homepage'] == "pending_activities")) - { - $query.=" LEFT OUTER JOIN vtiger_recurringevents - ON vtiger_recurringevents.activityid=vtiger_activity.activityid"; - } - //end - - $query.=" WHERE vtiger_crmentity.deleted = 0 AND activitytype != 'Emails' ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - - } - break; - Case "Emails": - $query = "SELECT DISTINCT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, - vtiger_activity.activityid, vtiger_activity.subject, - vtiger_activity.date_start, - vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, - vtiger_contactdetails.contactid - FROM vtiger_activity - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_activity.activityid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_seactivityrel - ON vtiger_seactivityrel.activityid = vtiger_activity.activityid - LEFT JOIN vtiger_contactdetails - ON vtiger_contactdetails.contactid = vtiger_seactivityrel.crmid - LEFT JOIN vtiger_cntactivityrel - ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid - AND vtiger_cntactivityrel.contactid = vtiger_cntactivityrel.contactid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_salesmanactivityrel - ON vtiger_salesmanactivityrel.activityid = vtiger_activity.activityid - LEFT JOIN vtiger_emaildetails - ON vtiger_emaildetails.emailid = vtiger_activity.activityid - WHERE vtiger_activity.activitytype = 'Emails' - AND vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Faq": - $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.createdtime, vtiger_crmentity.modifiedtime, - vtiger_faq.* - FROM vtiger_faq - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_faq.id - LEFT JOIN vtiger_products - ON vtiger_faq.product_id = vtiger_products.productid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - - Case "Vendors": - $query = "SELECT vtiger_crmentity.crmid, vtiger_vendor.* - FROM vtiger_vendor - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_vendor.vendorid - INNER JOIN vtiger_vendorcf - ON vtiger_vendor.vendorid = vtiger_vendorcf.vendorid - WHERE vtiger_crmentity.deleted = 0 ".$where; - break; - Case "PriceBooks": - $query = "SELECT vtiger_crmentity.crmid, vtiger_pricebook.*, vtiger_currency_info.currency_name - FROM vtiger_pricebook - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_pricebook.pricebookid - INNER JOIN vtiger_pricebookcf - ON vtiger_pricebook.pricebookid = vtiger_pricebookcf.pricebookid - LEFT JOIN vtiger_currency_info - ON vtiger_pricebook.currency_id = vtiger_currency_info.id - WHERE vtiger_crmentity.deleted = 0 ".$where; - break; - Case "Quotes": - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.*, - vtiger_quotes.*, - vtiger_quotesbillads.*, - vtiger_quotesshipads.*, - vtiger_potential.potentialname, - vtiger_account.accountname, - vtiger_currency_info.currency_name - FROM vtiger_quotes - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_quotes.quoteid - INNER JOIN vtiger_quotesbillads - ON vtiger_quotes.quoteid = vtiger_quotesbillads.quotebilladdressid - INNER JOIN vtiger_quotesshipads - ON vtiger_quotes.quoteid = vtiger_quotesshipads.quoteshipaddressid - LEFT JOIN vtiger_quotescf - ON vtiger_quotes.quoteid = vtiger_quotescf.quoteid - LEFT JOIN vtiger_currency_info - ON vtiger_quotes.currency_id = vtiger_currency_info.id - LEFT OUTER JOIN vtiger_account - ON vtiger_account.accountid = vtiger_quotes.accountid - LEFT OUTER JOIN vtiger_potential - ON vtiger_potential.potentialid = vtiger_quotes.potentialid - LEFT JOIN vtiger_contactdetails - ON vtiger_contactdetails.contactid = vtiger_quotes.contactid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users as vtiger_usersQuotes - ON vtiger_usersQuotes.id = vtiger_quotes.inventorymanager - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "PurchaseOrder": - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.*, - vtiger_purchaseorder.*, - vtiger_pobillads.*, - vtiger_poshipads.*, - vtiger_vendor.vendorname, - vtiger_currency_info.currency_name - FROM vtiger_purchaseorder - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_purchaseorder.purchaseorderid - LEFT OUTER JOIN vtiger_vendor - ON vtiger_purchaseorder.vendorid = vtiger_vendor.vendorid - LEFT JOIN vtiger_contactdetails - ON vtiger_purchaseorder.contactid = vtiger_contactdetails.contactid - INNER JOIN vtiger_pobillads - ON vtiger_purchaseorder.purchaseorderid = vtiger_pobillads.pobilladdressid - INNER JOIN vtiger_poshipads - ON vtiger_purchaseorder.purchaseorderid = vtiger_poshipads.poshipaddressid - LEFT JOIN vtiger_purchaseordercf - ON vtiger_purchaseordercf.purchaseorderid = vtiger_purchaseorder.purchaseorderid - LEFT JOIN vtiger_currency_info - ON vtiger_purchaseorder.currency_id = vtiger_currency_info.id - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "SalesOrder": - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.*, - vtiger_salesorder.*, - vtiger_sobillads.*, - vtiger_soshipads.*, - vtiger_quotes.subject AS quotename, - vtiger_account.accountname, - vtiger_currency_info.currency_name - FROM vtiger_salesorder - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_salesorder.salesorderid - INNER JOIN vtiger_sobillads - ON vtiger_salesorder.salesorderid = vtiger_sobillads.sobilladdressid - INNER JOIN vtiger_soshipads - ON vtiger_salesorder.salesorderid = vtiger_soshipads.soshipaddressid - LEFT JOIN vtiger_salesordercf - ON vtiger_salesordercf.salesorderid = vtiger_salesorder.salesorderid - LEFT JOIN vtiger_currency_info - ON vtiger_salesorder.currency_id = vtiger_currency_info.id - LEFT OUTER JOIN vtiger_quotes - ON vtiger_quotes.quoteid = vtiger_salesorder.quoteid - LEFT OUTER JOIN vtiger_account - ON vtiger_account.accountid = vtiger_salesorder.accountid - LEFT JOIN vtiger_contactdetails - ON vtiger_salesorder.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_potential - ON vtiger_potential.potentialid = vtiger_salesorder.potentialid - LEFT JOIN vtiger_invoice_recurring_info - ON vtiger_invoice_recurring_info.salesorderid = vtiger_salesorder.salesorderid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Invoice": - //Query modified to sort by assigned to - //query modified -Code contribute by Geoff(http://forums.vtiger.com/viewtopic.php?t=3376) - $query = "SELECT vtiger_crmentity.*, - vtiger_invoice.*, - vtiger_invoicebillads.*, - vtiger_invoiceshipads.*, - vtiger_salesorder.subject AS salessubject, - vtiger_account.accountname, - vtiger_currency_info.currency_name - FROM vtiger_invoice - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_invoice.invoiceid - INNER JOIN vtiger_invoicebillads - ON vtiger_invoice.invoiceid = vtiger_invoicebillads.invoicebilladdressid - INNER JOIN vtiger_invoiceshipads - ON vtiger_invoice.invoiceid = vtiger_invoiceshipads.invoiceshipaddressid - LEFT JOIN vtiger_currency_info - ON vtiger_invoice.currency_id = vtiger_currency_info.id - LEFT OUTER JOIN vtiger_salesorder - ON vtiger_salesorder.salesorderid = vtiger_invoice.salesorderid - LEFT OUTER JOIN vtiger_account - ON vtiger_account.accountid = vtiger_invoice.accountid - LEFT JOIN vtiger_contactdetails - ON vtiger_contactdetails.contactid = vtiger_invoice.contactid - INNER JOIN vtiger_invoicecf - ON vtiger_invoice.invoiceid = vtiger_invoicecf.invoiceid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Campaigns": - //Query modified to sort by assigned to - //query modified -Code contribute by Geoff(http://forums.vtiger.com/viewtopic.php?t=3376) - $query = "SELECT vtiger_crmentity.*, - vtiger_campaign.* - FROM vtiger_campaign - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_campaign.campaignid - INNER JOIN vtiger_campaignscf - ON vtiger_campaign.campaignid = vtiger_campaignscf.campaignid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users - ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_products - ON vtiger_products.productid = vtiger_campaign.product_id - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - break; - Case "Users": - $query = "select id,user_name,roleid,first_name,last_name,email1,phone_mobile,phone_work,is_admin,status from vtiger_users inner join vtiger_user2role on vtiger_user2role.userid=vtiger_users.id where deleted=0 ".$where ; - break; - default: - // vtlib customization: Include the module file - $focus = CRMEntity::getInstance($module); - $query = $focus->getListQuery($module, $where); - // END - } - - $log->debug("Exiting getListQuery method ..."); - return $query; -} - -/**Function returns the list of records which an user is entiled to view -*Param $module - module name -*Returns a database query - type string -*/ - -function getReadEntityIds($module) -{ - global $log; - $log->debug("Entering getReadEntityIds(".$module.") method ..."); - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - $tab_id = getTabid($module); - - if($module == "Leads") - { - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 - AND vtiger_leaddetails.converted = 0 "; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - if($module == "Accounts") - { - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_account - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_account.accountid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 "; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - - - } - - if ($module == "Potentials") - { - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_potential - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_potential.potentialid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 "; - - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - - - } - - if($module == "Contacts") - { - //Query modified to sort by assigned to - - $query="SELECT vtiger_crmentity.crmid - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 "; - - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - if($module == "Products") - { - $query = "SELECT DISTINCT vtiger_crmentity.crmid - FROM vtiger_products - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_products.productid - LEFT JOIN vtiger_seproductsrel - ON vtiger_seproductsrel.productid = vtiger_products.productid - WHERE vtiger_crmentity.deleted = 0 - AND (vtiger_seproductsrel.crmid IS NULL - OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Leads').") - OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Accounts').") - OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Potentials').") - OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Contacts').")) "; - } - - if($module == "PurchaseOrder") - { - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_purchaseorder - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_purchaseorder.purchaseorderid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 "; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - if($module == "SalesOrder") - { - //Query modified to sort by assigned to - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_salesorder - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_salesorder.salesorderid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - if($module == "Invoice") - { - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_invoice - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_invoice.invoiceid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - if($module == "Quotes") - { - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_quotes - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_quotes.quoteid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - if($module == "HelpDesk") - { - $query = "SELECT vtiger_crmentity.crmid - FROM vtiger_troubletickets - INNER JOIN vtiger_crmentity - ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted = 0 ".$where; - if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - $sec_parameter=getListViewSecurityParameter($module); - $query .= $sec_parameter; - } - } - - $log->debug("Exiting getReadEntityIds method ..."); - return $query; - -} - -/** Function to get alphabetical search links -*Param $module - module name -*Param $action - action -*Param $fieldname - vtiger_field name -*Param $query - query -*Param $type - search type -*Param $popuptype - popup type -*Param $recordid - record id -*Param $return_module - return module -*Param $append_url - url string to be appended -*Param $viewid - custom view id -*Param $groupid - group id -*Returns an string value - */ -function AlphabeticalSearch($module,$action,$fieldname,$query,$type,$popuptype='',$recordid='',$return_module='',$append_url='',$viewid='',$groupid='') -{ - global $log; - $log->debug("Entering AlphabeticalSearch(".$module.",".$action.",".$fieldname.",".$query.",".$type.",".$popuptype.",".$recordid.",".$return_module.",".$append_url.",".$viewid.",".$groupid.") method ..."); - if($type=='advanced') - $flag='&advanced=true'; - - if($popuptype != '') - $popuptypevalue = "&popuptype=".$popuptype; - - if($recordid != '') - $returnvalue = '&recordid='.$recordid; - if($return_module != '') - $returnvalue .= '&return_module='.$return_module; - - // vtlib Customization : For uitype 10 popup during paging - if($_REQUEST['form'] == 'vtlibPopupView') { - $returnvalue .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); - } - // END - - for($var='A',$i =1;$i<=26;$i++,$var++) - // Mike Crowe Mod --------------------------------------------------------added groupid to url - $list .= ''.$var.''; - - $log->debug("Exiting AlphabeticalSearch method ..."); - return $list; -} - -/**Function to get parent name for a given parent id -*Param $module - module name -*Param $list_result- result set -*Param $rset - result set index -*Returns an string value -*/ -function getRelatedToEntity($module,$list_result,$rset) -{ - global $log; - $log->debug("Entering getRelatedToEntity(".$module.",".$list_result.",".$rset.") method ..."); - - global $adb; - $seid = $adb->query_result($list_result,$rset,"relatedto"); - $action = "DetailView"; - - if(isset($seid) && $seid != '') - { - $parent_module = $parent_module = getSalesEntityType($seid); - if($parent_module == 'Accounts') - { - $numrows= $adb->num_rows($evt_result); - - $parent_module = $adb->query_result($evt_result,0,'setype'); - $parent_id = $adb->query_result($evt_result,0,'crmid'); - - if ($numrows>1){ - $parent_module ='Multiple'; - $parent_name=$app_strings['LBL_MULTIPLE']; - } - //Raju -- Ends - $parent_query = "SELECT accountname FROM vtiger_account WHERE accountid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = $adb->query_result($parent_result,0,"accountname"); - } - if($parent_module == 'Leads') - { - $parent_query = "SELECT firstname,lastname FROM vtiger_leaddetails WHERE leadid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = getFullNameFromQResult($parent_result,0,"Leads"); - } - if($parent_module == 'Potentials') - { - $parent_query = "SELECT potentialname FROM vtiger_potential WHERE potentialid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = $adb->query_result($parent_result,0,"potentialname"); - } - if($parent_module == 'Products') - { - $parent_query = "SELECT productname FROM vtiger_products WHERE productid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = $adb->query_result($parent_result,0,"productname"); - } - if($parent_module == 'PurchaseOrder') - { - $parent_query = "SELECT subject FROM vtiger_purchaseorder WHERE purchaseorderid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - if($parent_module == 'SalesOrder') - { - $parent_query = "SELECT subject FROM vtiger_salesorder WHERE salesorderid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - if($parent_module == 'Invoice') - { - $parent_query = "SELECT subject FROM vtiger_invoice WHERE invoiceid=?"; - $parent_result = $adb->pquery($parent_query, array($seid)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - - $parent_value = "".$parent_name.""; - } - else - { - $parent_value = ''; - } - $log->debug("Exiting getRelatedToEntity method ..."); - return $parent_value; - -} - -/**Function to get parent name for a given parent id -*Param $module - module name -*Param $list_result- result set -*Param $rset - result set index -*Returns an string value -*/ - -//used in home page listTop vtiger_files -function getRelatedTo($module,$list_result,$rset) -{ - global $adb,$log,$app_strings; - $log->debug("Entering getRelatedTo(".$module.",".$list_result.",".$rset.") method ..."); - $tabname = getParentTab(); - if($module == "Documents") - { - $notesid = $adb->query_result($list_result,$rset,"notesid"); - $action = "DetailView"; - $evt_query="SELECT vtiger_senotesrel.crmid, vtiger_crmentity.setype - FROM vtiger_senotesrel - INNER JOIN vtiger_crmentity - ON vtiger_senotesrel.crmid = vtiger_crmentity.crmid - WHERE vtiger_senotesrel.notesid = ?"; - $params = array($notesid); - }else if($module == "Products") - { - $productid = $adb->query_result($list_result,$rset,"productid"); - $action = "DetailView"; - $evt_query="SELECT vtiger_seproductsrel.crmid, vtiger_crmentity.setype - FROM vtiger_seproductsrel - INNER JOIN vtiger_crmentity - ON vtiger_seproductsrel.crmid = vtiger_crmentity.crmid - WHERE vtiger_seproductsrel.productid =?"; - $params = array($productid); - }else - { - $activity_id = $adb->query_result($list_result,$rset,"activityid"); - $action = "DetailView"; - $evt_query="SELECT vtiger_seactivityrel.crmid, vtiger_crmentity.setype - FROM vtiger_seactivityrel - INNER JOIN vtiger_crmentity - ON vtiger_seactivityrel.crmid = vtiger_crmentity.crmid - WHERE vtiger_seactivityrel.activityid=?"; - $params = array($activity_id); - - if($module == 'HelpDesk') - { - $activity_id = $adb->query_result($list_result,$rset,"parent_id"); - if($activity_id != '') { - $evt_query = "SELECT crmid, setype FROM vtiger_crmentity WHERE crmid=?"; - $params = array($activity_id); - } - } - } - //added by raju to change the related to in emails inot multiple if email is for more than one contact - $evt_result = $adb->pquery($evt_query, $params); - $numrows= $adb->num_rows($evt_result); - - $parent_module = $adb->query_result($evt_result,0,'setype'); - $parent_id = $adb->query_result($evt_result,0,'crmid'); - - - - if ($numrows>1){ - $parent_module ='Multiple'; - $parent_name=$app_strings['LBL_MULTIPLE']; - } - //Raju -- Ends - if($module == 'HelpDesk' && ($parent_module == 'Accounts' || $parent_module == 'Contacts')) - { - global $theme; - $module_icon = ''.$app_strings[$parent_module].' '; - } - - $action = "DetailView"; - if($parent_module == 'Accounts') - { - $parent_query = "SELECT accountname FROM vtiger_account WHERE accountid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = textlength_check($adb->query_result($parent_result,0,"accountname")); - } - if($parent_module == 'Leads') - { - $parent_query = "SELECT firstname,lastname FROM vtiger_leaddetails WHERE leadid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = getFullNameFromQResult($parent_result,0,"Leads"); - } - if($parent_module == 'Potentials') - { - $parent_query = "SELECT potentialname FROM vtiger_potential WHERE potentialid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = textlength_check($adb->query_result($parent_result,0,"potentialname")); - } - if($parent_module == 'Products') - { - $parent_query = "SELECT productname FROM vtiger_products WHERE productid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"productname"); - } - if($parent_module == 'Quotes') - { - $parent_query = "SELECT subject FROM vtiger_quotes WHERE quoteid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - if($parent_module == 'PurchaseOrder') - { - $parent_query = "SELECT subject FROM vtiger_purchaseorder WHERE purchaseorderid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - if($parent_module == 'Invoice') - { - $parent_query = "SELECT subject FROM vtiger_invoice WHERE invoiceid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - if($parent_module == 'SalesOrder') - { - $parent_query = "SELECT subject FROM vtiger_salesorder WHERE salesorderid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"subject"); - } - if($parent_module == 'Contacts' && ($module == 'Emails' || $module == 'HelpDesk')) - { - $parent_query = "SELECT firstname,lastname FROM vtiger_contactdetails WHERE contactid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = getFullNameFromQResult($parent_result,0,"Contacts"); - } - if($parent_module == 'Vendors' && ($module == 'Emails')) - { - $parent_query = "SELECT vendorname FROM vtiger_vendor WHERE vendorid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"vendorname"); - } - if($parent_module == 'HelpDesk') - { - $parent_query = "SELECT title FROM vtiger_troubletickets WHERE ticketid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"title"); - //if(strlen($parent_name) > 25) - //{ - $parent_name = textlength_check($parent_name); - //} - } - if($parent_module == 'Campaigns') - { - $parent_query = "SELECT campaignname FROM vtiger_campaign WHERE campaignid=?"; - $parent_result = $adb->pquery($parent_query, array($parent_id)); - $parent_name = $adb->query_result($parent_result,0,"campaignname"); - //if(strlen($parent_name) > 25) - //{ - $parent_name = textlength_check($parent_name); - //} - } - - //added by rdhital for better emails - Raju - if ($parent_module == 'Multiple') - { - $parent_value = $parent_name; - } - else - { - $parent_value = $module_icon."".textlength_check($parent_name).""; - } - //code added by raju ends - $log->debug("Exiting getRelatedTo method ..."); - return $parent_value; - - - -} - -/**Function to get the table headers for a listview -*Param $navigation_arrray - navigation values in array -*Param $url_qry - url string -*Param $module - module name -*Param $action- action file name -*Param $viewid - view id -*Returns an string value -*/ - -function getTableHeaderNavigation($navigation_array, $url_qry,$module='',$action_val='index',$viewid='') -{ - global $log,$app_strings; - $log->debug("Entering getTableHeaderNavigation(".$navigation_array.",". $url_qry.",".$module.",".$action_val.",".$viewid.") method ..."); - global $theme,$current_user; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - if($module == 'Documents') { - $output = ''; - } else { - $output = ''; - } - $tabname = getParentTab(); - - $url_string = ''; - - // vtlib Customization : For uitype 10 popup during paging - if($_REQUEST['form'] == 'vtlibPopupView') { - $url_string .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); - } - // END - - if($module == 'Calendar' && $action_val == 'index') - { - if($_REQUEST['view'] == ''){ - if($current_user->activity_view == "This Year"){ - $mysel = 'year'; - }else if($current_user->activity_view == "This Month"){ - $mysel = 'month'; - }else if($current_user->activity_view == "This Week"){ - $mysel = 'week'; - }else{ - $mysel = 'day'; - } - } - $data_value=date('Y-m-d H:i:s'); - preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$data_value,$value); - $date_data = Array( - 'day'=>$value[3], - 'month'=>$value[2], - 'year'=>$value[1], - 'hour'=>$value[4], - 'min'=>$value[5], - ); - $tab_type = ($_REQUEST['subtab'] == '')?'event':vtlib_purify($_REQUEST['subtab']); - $url_string .= isset($_REQUEST['view'])?"&view=".vtlib_purify($_REQUEST['view']):"&view=".$mysel; - $url_string .= isset($_REQUEST['subtab'])?"&subtab=".vtlib_purify($_REQUEST['subtab']):''; - $url_string .= isset($_REQUEST['viewOption'])?"&viewOption=".vtlib_purify($_REQUEST['viewOption']):'&viewOption=listview'; - $url_string .= isset($_REQUEST['day'])?"&day=".vtlib_purify($_REQUEST['day']):'&day='.$date_data['day']; - $url_string .= isset($_REQUEST['week'])?"&week=".vtlib_purify($_REQUEST['week']):''; - $url_string .= isset($_REQUEST['month'])?"&month=".vtlib_purify($_REQUEST['month']):'&month='.$date_data['month']; - $url_string .= isset($_REQUEST['year'])?"&year=".vtlib_purify($_REQUEST['year']):"&year=".$date_data['year']; - $url_string .= isset($_REQUEST['n_type'])?"&n_type=".vtlib_purify($_REQUEST['n_type']):''; - $url_string .= isset($_REQUEST['search_option'])?"&search_option=".vtlib_purify($_REQUEST['search_option']):''; - } - if($module == 'Calendar' && $action_val != 'index') //added for the All link from the homepage -- ticket 5211 - $url_string .= isset($_REQUEST['from_homepage'])?"&from_homepage=".vtlib_purify($_REQUEST['from_homepage']):''; - - if(($navigation_array['prev']) != 0) - { - if($module == 'Calendar' && $action_val == 'index') - { - //$output .= ' '; - $output .= ' '; - //$output .= ' '; - $output .= ' '; - } - else if($action_val == "FindDuplicate") - { - $output .= ' '; - $output .= ' '; - }elseif($action_val == 'UnifiedSearch'){ - $output .= ' '; - $output .= ' '; - } - elseif($module == 'Documents') - { - $output .= ' '; - $output .= ' '; - } - else{ - $output .= ' '; - $output .= ' '; - } - } - else - { - $output .= ' '; - $output .= ' '; - } - - if($module == 'Calendar' && $action_val == 'index'){ - $jsNavigate = "cal_navigation('$tab_type','$url_string','&start='+this.value);"; - }else if($action_val == "FindDuplicate"){ - $jsNavigate = "getDuplicateListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; - }elseif($action_val == 'UnifiedSearch'){ - $jsNavigate = "getUnifiedSearchEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; - }elseif($module == 'Documents'){ - $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string&folderid=$action_val');"; - }else{ - $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; - } - if($module == 'Documents'){ - $url = '&folderid='.$action_val; - }else{ - $url = ''; - } - $jsHandler = "return VT_disableFormSubmit(event);"; - $output .= ""; - $output .= ""; - $output .= $app_strings['LBL_LIST_OF'].' '.$navigation_array['verylast'].''; - - if(($navigation_array['next']) !=0) - { - if($module == 'Calendar' && $action_val == 'index') - { - //$output .= ' '; - $output .= ' '; - //$output .= ' '; - $output .= ' '; - } - else if($action_val == "FindDuplicate") - { - $output .= ' '; - $output .= ' '; - }elseif($action_val == 'UnifiedSearch'){ - $output .= ' '; - $output .= ' '; - } - elseif($module == 'Documents') - { - $output .= ' '; - $output .= ' '; - } - else - { - $output .= ' '; - $output .= ' '; - } - } - else - { - $output .= ' '; - $output .= ' '; - } - $output .= ''; - $log->debug("Exiting getTableHeaderNavigation method ..."); - if($navigation_array['first']=='') - return; - else - return $output; -} - -function getPopupCheckquery($current_module,$relmodule,$relmod_recordid) -{ - global $log,$adb; - $log->debug("Entering getPopupCheckquery(".$current_module.",".$relmodule.",".$relmod_recordid.") method ..."); - if($current_module == "Contacts") - { - if($relmodule == "Accounts" && $relmod_recordid != '') - $condition = "and vtiger_account.accountid= ".$relmod_recordid; - - elseif($relmodule == "Potentials") - { - $query = "select contactid from vtiger_contpotentialrel where potentialid=?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $contact_id = $adb->query_result($result,0,"contactid"); - if($contact_id != '' && $contact_id != 0) - $condition = "and vtiger_contactdetails.contactid= ".$contact_id; - else - { - $query = "select related_to from vtiger_potential where potentialid=?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $acc_id = $adb->query_result($result,0,"related_to"); - if($acc_id != ''){ - $condition = "and vtiger_contactdetails.accountid= ".$acc_id; - } - } - } - elseif($relmodule == "Quotes") - { - - $query = "select accountid,contactid from vtiger_quotes where quoteid=?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $contactid = $adb->query_result($result,0,"contactid"); - if($contactid != '' && $contactid != 0) - $condition = "and vtiger_contactdetails.contactid= ".$contactid; - else - { - $account_id = $adb->query_result($result,0,"accountid"); - if($account_id != '') - $condition = "and vtiger_contactdetails.accountid= ".$account_id; - } - } - elseif($relmodule == "PurchaseOrder") - { - $query = "select contactid from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $contact_id = $adb->query_result($result,0,"contactid"); - if($contact_id != '') - $condition = "and vtiger_contactdetails.contactid= ".$contact_id; - else - $condition = "and vtiger_contactdetails.contactid= 0"; - } - elseif($relmodule == "SalesOrder") - { - $query = "select accountid,contactid from vtiger_salesorder where salesorderid=?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $contact_id = $adb->query_result($result,0,"contactid"); - if($contact_id != 0 && $contact_id != '') - $condition = "and vtiger_contactdetails.contactid=".$contact_id; - else - { - $account_id = $adb->query_result($result,0,"accountid"); - if($account_id != '') - $condition = "and vtiger_contactdetails.accountid= ".$account_id; - } - } - elseif($relmodule == "Invoice") - { - $query = "select accountid,contactid from vtiger_invoice where invoiceid=?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $contact_id = $adb->query_result($result,0,"contactid"); - if($contact_id != '' && $contact_id != 0) - $condition = " and vtiger_contactdetails.contactid=".$contact_id; - else - { - $account_id = $adb->query_result($result,0,"accountid"); - if($account_id != '') - $condition = " and vtiger_contactdetails.accountid=".$account_id; - } - } - elseif($relmodule == "Campaigns") - { - $query = "select contactid from vtiger_campaigncontrel where campaignid =?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $rows = $adb->num_rows($result); - if($rows != 0) - { - $j = 0; - $contactid_comma = "("; - for($k=0; $k < $rows; $k++) - { - $contactid = $adb->query_result($result,$k,'contactid'); - $contactid_comma.=$contactid; - if($k < ($rows-1)) - $contactid_comma.=', '; - } - $contactid_comma.= ")"; - } - else - $contactid_comma = "(0)"; - $condition = "and vtiger_contactdetails.contactid in ".$contactid_comma; - } - elseif($relmodule == "Products") - { - $query = "select crmid from vtiger_seproductsrel where productid=? and setype=?"; - $result = $adb->pquery($query, array($relmod_recordid,"Contacts")); - $rows = $adb->num_rows($result); - if($rows != 0) - { - $j = 0; - $contactid_comma = "("; - for($k=0; $k < $rows; $k++) - { - $contactid = $adb->query_result($result,$k,'crmid'); - $contactid_comma.=$contactid; - if($k < ($rows-1)) - $contactid_comma.=', '; - } - $contactid_comma.= ")"; - } - else - $contactid_comma = "(0)"; - $condition = "and vtiger_contactdetails.contactid in ".$contactid_comma; - } - elseif($relmodule == "HelpDesk" || $relmodule == "Trouble Tickets") - { - $query = "select parent_id from vtiger_troubletickets where ticketid =?"; - $result = $adb->pquery($query, array($relmod_recordid)); - $parent_id = $adb->query_result($result,0,"parent_id"); - if($parent_id != ""){ - $crmquery = "select setype from vtiger_crmentity where crmid=?"; - $parentmodule_id = $adb->pquery($crmquery, array($parent_id)); - $parent_modname = $adb->query_result($parentmodule_id,0,"setype"); - if($parent_modname == "Accounts") - $condition = "and vtiger_contactdetails.accountid= ".$parent_id; - if($parent_modname == "Contacts") - $condition = "and vtiger_contactdetails.contactid= ".$parent_id; - } - else - $condition = " and vtiger_contactdetails.contactid=0"; - - } - } - elseif($current_module == "Potentials") - { - if($relmodule == 'Accounts' || $relmodule == 'Contacts') - { - if($relmodule == 'Contacts') { - $pot_query = "select vtiger_crmentity.crmid,vtiger_contactdetails.contactid,vtiger_potential.potentialid from vtiger_potential inner join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_potential.related_to inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid where vtiger_crmentity.deleted=0 and vtiger_potential.related_to=?"; - } else { - $pot_query = "select vtiger_crmentity.crmid,vtiger_account.accountid,vtiger_potential.potentialid from vtiger_potential inner join vtiger_account on vtiger_account.accountid=vtiger_potential.related_to inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid where vtiger_crmentity.deleted=0 and vtiger_potential.related_to=?"; - } - $pot_result = $result = $adb->pquery($pot_query, array($relmod_recordid)); - $rows = $adb->num_rows($pot_result); - $potids_comma = ""; - if($rows != 0) - { - $j = 0; - $potids_comma .= "("; - for($k=0; $k < $rows; $k++) - { - $potential_ids = $adb->query_result($pot_result,$k,'potentialid'); - $potids_comma.=$potential_ids; - if($k < ($rows-1)) - $potids_comma.=','; - } - $potids_comma.= ")"; - } - else - $potids_comma = "(0)"; - $condition ="and vtiger_potential.potentialid in ".$potids_comma; - } - - } - else if($current_module == "Products") - { - if($relmodule == 'Accounts') - { - $pro_query = "select productid from vtiger_seproductsrel where setype='Accounts' and crmid=?"; - $pro_result = $result = $adb->pquery($pro_query, array($relmod_recordid)); - $rows = $adb->num_rows($pro_result); - if($rows != 0) - { - $proids_comma = "("; - for($k=0; $k < $rows; $k++) - { - $product_ids = $adb->query_result($pro_result,$k,'productid'); - $proids_comma .= $product_ids; - if($k < ($rows-1)) - $proids_comma.=','; - } - $proids_comma.= ")"; - } - else - $proids_comma = "(0)"; - $condition ="and vtiger_products.productid in ".$proids_comma; - } - } - else if($current_module == 'Quotes') - { - if($relmodule == 'Accounts') - { - $quote_query = "select quoteid from vtiger_quotes where accountid=?"; - $quote_result = $result = $adb->pquery($quote_query, array($relmod_recordid)); - $rows = $adb->num_rows($quote_result); - if($rows != 0) - { - $j = 0; - $qtids_comma = "("; - for($k=0; $k < $rows; $k++) - { - $quote_ids = $adb->query_result($quote_result,$k,'quoteid'); - $qtids_comma.=$quote_ids; - if($k < ($rows-1)) - $qtids_comma.=','; - } - $qtids_comma.= ")"; - } - else - $qtids_comma = "(0)"; - $condition ="and vtiger_quotes.quoteid in ".$qtids_comma; - } - - } - else if($current_module == 'SalesOrder') - { - if($relmodule == 'Accounts') - { - $SO_query = "select salesorderid from vtiger_salesorder where accountid=?"; - $SO_result = $result = $adb->pquery($SO_query, array($relmod_recordid)); - $rows = $adb->num_rows($SO_result); - if($rows != 0) - { - $SOids_comma = "("; - for($k=0; $k < $rows; $k++) - { - $SO_ids = $adb->query_result($SO_result,$k,'salesorderid'); - $SOids_comma.=$SO_ids; - if($k < ($rows-1)) - $SOids_comma.=','; - } - $SOids_comma.= ")"; - } - else - $SOids_comma = "(0)"; - $condition ="and vtiger_salesorder.salesorderid in ".$SOids_comma; - } - - } - else - $condition = ''; - $where = $condition; - $log->debug("Exiting getPopupCheckquery method ..."); - return $where; - - -} - -/**This function return the entity ids that need to be excluded in popup listview for a given record -Param $currentmodule - modulename of the entity to be selected -Param $returnmodule - modulename for which the entity is assingned -Param $recordid - the record id for which the entity is assigned -Return type string. -*/ - -function getRelCheckquery($currentmodule,$returnmodule,$recordid) -{ - global $log,$adb; - $log->debug("Entering getRelCheckquery(".$currentmodule.",".$returnmodule.",".$recordid.") method ..."); - $skip_id = Array(); - $where_relquery = ""; - $params = array(); - if($currentmodule=="Contacts" && $returnmodule == "Potentials") - { - $reltable = 'vtiger_contpotentialrel'; - $condition = 'WHERE potentialid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'contactid'; - $table = 'vtiger_contactdetails'; - } - elseif($currentmodule=="Contacts" && $returnmodule == "Vendors") - { - $reltable = 'vtiger_vendorcontactrel'; - $condition = 'WHERE vendorid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'contactid'; - $table = 'vtiger_contactdetails'; - } - elseif($currentmodule=="Contacts" && $returnmodule == "Campaigns") - { - $reltable = 'vtiger_campaigncontrel'; - $condition = 'WHERE campaignid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'contactid'; - $table = 'vtiger_contactdetails'; - } - elseif($currentmodule=="Contacts" && $returnmodule == "Calendar") - { - $reltable = 'vtiger_cntactivityrel'; - $condition = 'WHERE activityid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'contactid'; - $table = 'vtiger_contactdetails'; - } - elseif($currentmodule=="Leads" && $returnmodule == "Campaigns") - { - $reltable = 'vtiger_campaignleadrel'; - $condition = 'WHERE campaignid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'leadid'; - $table = 'vtiger_leaddetails'; - } - elseif($currentmodule=="Users" && $returnmodule == "Calendar") - { - $reltable = 'vtiger_salesmanactivityrel'; - $condition = 'WHERE activityid = ?'; - array_push($params, $recordid); - $selectfield = 'smid'; - $field = 'id'; - $table = 'vtiger_users'; - } - elseif($currentmodule=="Campaigns" && $returnmodule == "Leads") - { - $reltable = 'vtiger_campaignleadrel'; - $condition = 'WHERE leadid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'campaignid'; - $table = 'vtiger_campaign'; - } - elseif($currentmodule=="Campaigns" && $returnmodule == "Contacts") - { - $reltable = 'vtiger_campaigncontrel'; - $condition = 'WHERE contactid = ?'; - array_push($params, $recordid); - $field = $selectfield = 'campaignid'; - $table = 'vtiger_campaign'; - } - elseif($currentmodule == "Products" && ($returnmodule == "Potentials" || $returnmodule == "Accounts" || $returnmodule == "Contacts" || $returnmodule == "Leads")) - { - $reltable = 'vtiger_seproductsrel'; - $condition = 'WHERE crmid = ? and setype = ?'; - array_push($params, $recordid, $returnmodule); - $field = $selectfield ='productid'; - $table = 'vtiger_products'; - } - elseif(($currentmodule == "Leads" || $currentmodule == "Accounts" || $currentmodule == "Potentials" || $currentmodule == "Contacts") && $returnmodule == "Products")//added to fix the issues(ticket 4001,4002 and 4003) - { - $reltable = 'vtiger_seproductsrel'; - $condition = 'WHERE productid = ? and setype = ?'; - array_push($params, $recordid, $currentmodule); - $selectfield ='crmid'; - if($currentmodule == "Leads") - { - $field = 'leadid'; - $table = 'vtiger_leaddetails'; - } - elseif($currentmodule == "Accounts") - { - $field = 'accountid'; - $table = 'vtiger_account'; - } - elseif($currentmodule == "Contacts") - { - $field = 'contactid'; - $table = 'vtiger_contactdetails'; - } - elseif($currentmodule == "Potentials") - { - $field = 'potentialid'; - $table = 'vtiger_potential'; - } - } - elseif($currentmodule == "Products" && $returnmodule =="Vendors") - { - $reltable = 'vtiger_products'; - $condition = 'WHERE vendor_id = ?'; - array_push($params, $recordid); - $field = $selectfield ='productid'; - $table = 'vtiger_products'; - } - elseif($currentmodule == "Documents") - { - $reltable = "vtiger_senotesrel"; - $selectfield = "notesid"; - $condition = "where crmid = ?"; - array_push($params, $recordid); - $table = "vtiger_notes"; - $field = "notesid"; - } - //end - if($reltable != null) { - $query = "SELECT ".$selectfield." FROM ".$reltable." ".$condition; - } elseif($currentmodule != $returnmodule && $returnmodule!="") { // If none of the above relation matches, then the relation is assumed to be stored in vtiger_crmentityrel - $query = "SELECT relcrmid AS relatedid FROM vtiger_crmentityrel WHERE crmid = ? and module = ? and relmodule = ? - UNION SELECT crmid AS relatedid FROM vtiger_crmentityrel WHERE relcrmid = ? and relmodule = ? and module = ?"; - array_push($params, $recordid, $returnmodule, $currentmodule, $recordid, $returnmodule, $currentmodule); - - $focus_obj = CRMEntity::getInstance($currentmodule); - $field = $focus_obj->table_index; - $table = $focus_obj->table_name; - $selectfield = 'relatedid'; - } - - if($query !='') - { - $result = $adb->pquery($query, $params); - if($adb->num_rows($result)!=0) - { - for($k=0;$k < $adb->num_rows($result);$k++) - { - $skip_id[]=$adb->query_result($result,$k,$selectfield); - } - $skipids = implode(",", constructList($skip_id,'INTEGER')); - if (count($skipids) > 0) { - $where_relquery = "and ".$table.".".$field." not in (". $skipids .")"; - } - } - } - $log->debug("Exiting getRelCheckquery method ..."); - return $where_relquery; -} - -/**This function stores the variables in session sent in list view url string. -*Param $lv_array - list view session array -*Param $noofrows - no of rows -*Param $max_ent - maximum entires -*Param $module - module name -*Param $related - related module -*Return type void. -*/ - -function setSessionVar($lv_array,$noofrows,$max_ent,$module='',$related='') -{ - $start = ''; - if($noofrows>=1) - { - $lv_array['start']=1; - $start = 1; - } - elseif($related!='' && $noofrows == 0) - { - $lv_array['start']=1; - $start = 1; - } - else - { - $lv_array['start']=0; - $start = 0; - } - - if(isset($_REQUEST['start']) && $_REQUEST['start'] !='') - { - $lv_array['start']=ListViewSession::getRequestStartPage(); - $start = ListViewSession::getRequestStartPage(); - }elseif($_SESSION['rlvs'][$module][$related]['start'] != '') - { - - if($related!='') - { - $lv_array['start']=$_SESSION['rlvs'][$module][$related]['start']; - $start = $_SESSION['rlvs'][$module][$related]['start']; - } - } - if(isset($_REQUEST['viewname']) && $_REQUEST['viewname'] !='') - $lv_array['viewname']=vtlib_purify($_REQUEST['viewname']); - - if($related=='') - $_SESSION['lvs'][$_REQUEST['module']]=$lv_array; - else - $_SESSION['rlvs'][$module][$related] = $lv_array; - - if ($start < ceil ($noofrows / $max_ent) && $start !='') - { - $start = ceil ($noofrows / $max_ent); - if($related=='') - $_SESSION['lvs'][$currentModule]['start'] = $start; - } -} - -/**Function to get the table headers for related listview -*Param $navigation_arrray - navigation values in array -*Param $url_qry - url string -*Param $module - module name -*Param $action- action file name -*Param $viewid - view id -*Returns an string value -*/ - -//Temp function to be be deleted -function getRelatedTableHeaderNavigation($navigation_array, $url_qry,$module='',$action_val='',$viewid='') -{ - global $log, $singlepane_view,$app_strings; - $log->debug("Entering getTableHeaderNavigation(".$navigation_array.",". $url_qry.",".$module.",".$action_val.",".$viewid.") method ..."); - global $theme; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $tabid = getTabid($module); - $tabname = getParentTab(); - $url_qry .= '&parenttab='.$tabname; - $output = ''; - if($singlepane_view == 'true') - $action_val = 'DetailView'; - else - $action_val = 'CallRelatedList'; - if(($navigation_array['prev']) != 0) - { - $output .= ' '; - $output .= ' '; - - } - else - { - $output .= ' '; - $output .= ' '; - } - - $jsNavigate = "index.php?module=$module&action=$action_val$url_qry&start='+this.value+'&viewname=$viewid"; - $jsHandler = "return VT_disableFormSubmit(event);"; - $output .= ""; - $output .= ""; - $output .= $app_strings['LBL_LIST_OF'].' '.$navigation_array['verylast'].''; - - if(($navigation_array['next']) !=0) - { - $output .= ' '; - $output .= ' '; - } - else - { - $output .= ' '; - $output .= ' '; - } - $output .= ''; - $log->debug("Exiting getTableHeaderNavigation method ..."); - if($navigation_array['first']=='') - return; - else - return $output; -} - -/** Function to get the Edit link details for ListView and RelatedListView - * @param string $module - module name - * @param int $entity_id - record id - * @param string $relatedlist - string "relatedlist" or may be empty. if empty means ListView else relatedlist - * @param string $returnset - may be empty in case of ListView. For relatedlists, return_module, return_action and return_id values will be passed like &return_module=Accounts&return_action=CallRelatedList&return_id=10 - * return string $edit_link - url string which cotains the editlink details (module, action, record, etc.,) like index.php?module=Accounts&action=EditView&record=10 - */ -function getListViewEditLink($module,$entity_id,$relatedlist,$returnset,$result,$count) -{ - global $adb; - $return_action = "index"; - $edit_link = "index.php?module=$module&action=EditView&record=$entity_id"; - $tabname = getParentTab(); - //Added to fix 4600 - $url = getBasic_Advance_SearchURL(); - - //This is relatedlist listview - if($relatedlist == 'relatedlist') - { - $edit_link .= $returnset; - } - else - { - if($module == 'Calendar') - { - $return_action = "ListView"; - $actvity_type = $adb->query_result($result,$count,'type'); - if($actvity_type == 'Task') - $edit_link .= '&activity_mode=Task'; - else - $edit_link .= '&activity_mode=Events'; - } - $edit_link .= "&return_module=$module&return_action=$return_action"; - } - - $edit_link .= "&parenttab=".$tabname.$url; - //Appending view name while editing from ListView - $edit_link .= "&return_viewname=".$_SESSION['lvs'][$module]["viewname"]; - if($module == 'Emails') - $edit_link = 'javascript:;" onclick="OpenCompose(\''.$entity_id.'\',\'edit\');'; - return $edit_link; -} - -/** Function to get the Del link details for ListView and RelatedListView - * @param string $module - module name - * @param int $entity_id - record id - * @param string $relatedlist - string "relatedlist" or may be empty. if empty means ListView else relatedlist - * @param string $returnset - may be empty in case of ListView. For relatedlists, return_module, return_action and return_id values will be passed like &return_module=Accounts&return_action=CallRelatedList&return_id=10 - * return string $del_link - url string which cotains the editlink details (module, action, record, etc.,) like index.php?module=Accounts&action=Delete&record=10 - */ -function getListViewDeleteLink($module,$entity_id,$relatedlist,$returnset) -{ - $tabname = getParentTab(); - $current_module = vtlib_purify($_REQUEST['module']); - $viewname = $_SESSION['lvs'][$current_module]['viewname']; - - //Added to fix 4600 - $url = getBasic_Advance_SearchURL(); - - if($module == "Calendar") - $return_action = "ListView"; - else - $return_action = "index"; - - //This is added to avoid the del link in Product related list for the following modules - $avoid_del_links = Array("PurchaseOrder","SalesOrder","Quotes","Invoice"); - - if(($current_module == 'Products' || $current_module == 'Services') && in_array($module,$avoid_del_links)) - { - return ''; - } - - $del_link = "index.php?module=$module&action=Delete&record=$entity_id"; - - //This is added for relatedlist listview - if($relatedlist == 'relatedlist') - { - $del_link .= $returnset; - } - else - { - $del_link .= "&return_module=$module&return_action=$return_action"; - } - - $del_link .= "&parenttab=".$tabname."&return_viewname=".$viewname.$url; - - // vtlib customization: override default delete link for custom modules - $requestModule = vtlib_purify($_REQUEST['module']); - $requestRecord = vtlib_purify($_REQUEST['record']); - $requestAction = vtlib_purify($_REQUEST['action']); - $parenttab = vtlib_purify($_REQUEST['parenttab']); - $isCustomModule = vtlib_isCustomModule($requestModule); - if($isCustomModule && !in_array($requestAction, Array('index','ListView'))) { - $del_link = "index.php?module=$requestModule&action=updateRelations&parentid=$requestRecord"; - $del_link .= "&destination_module=$module&idlist=$entity_id&mode=delete&parenttab=$parenttab"; - } - // END - - return $del_link; -} - -/* Function to get the Entity Id of a given Entity Name */ -function getEntityId($module, $entityName) { - global $log, $adb; - $log->info("in getEntityId ".$entityName); - - $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?"; - $result = $adb->pquery($query, array($module)); - $fieldsname = $adb->query_result($result,0,'fieldname'); - $tablename = $adb->query_result($result,0,'tablename'); - $entityidfield = $adb->query_result($result,0,'entityidfield'); - if(!(strpos($fieldsname,',') === false)) { - $fieldlists = explode(',',$fieldsname); - $fieldsname = "concat("; - $fieldsname = $fieldsname.implode(",' ',",$fieldlists); - $fieldsname = $fieldsname.")"; - } - - if($entityName != '') { - $sql = "select $entityidfield from $tablename INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $tablename.$entityidfield " . - " WHERE vtiger_crmentity.deleted = 0 and $fieldsname=?"; - $result = $adb->pquery($sql, array($entityName)); - if($adb->num_rows($result) > 0) { - $entityId = $adb->query_result($result,0,$entityidfield); - } - } - if(!empty($entityId)) - return $entityId; - else - return 0; -} - -/** function used to get the parent id for the given input parent name --Pavani **/ -function getParentId($parent_name) -{ - global $adb; - if($parent_name == '' || $parent_name == NULL) - $parent_id = 0; - //For now it have conditions only for accounts and contacts, if needed can add more - $relatedTo = explode(':',$parent_name); - $parent_module = $relatedTo[0]; $parent_module = trim($parent_module," "); - $parent_name = $relatedTo[3]; $parent_name = trim($parent_name," "); - $num_rows = 0; - if($parent_module == 'Contacts') - { - $query ="select crmid from vtiger_contactdetails, vtiger_crmentity WHERE concat(lastname,' ',firstname)=? and vtiger_crmentity.crmid =vtiger_contactdetails.contactid and vtiger_crmentity.deleted=0"; - $result = $adb->pquery($query, array($parent_name)); - $num_rows=$adb->num_rows($result); - } - else if($parent_module == 'Accounts') - { - $query = "select crmid from vtiger_account, vtiger_crmentity WHERE accountname=? and vtiger_crmentity.crmid =vtiger_account.accountid and vtiger_crmentity.deleted=0"; - $result = $adb->pquery($query, array($parent_name)); - $num_rows = $adb->num_rows($result); - } - else $num_rows=0; - if($num_rows == 0) $parent_id = 0; - else $parent_id = $adb->query_result($result,0,"crmid"); - return $parent_id; -} - -function decode_html($str) -{ - global $default_charset; - // Direct Popup action or Ajax Popup action should be treated the same. - if($_REQUEST['action'] == 'Popup' || $_REQUEST['file'] == 'Popup') - return html_entity_decode($str); - else - return html_entity_decode($str,ENT_QUOTES,$default_charset); -} - -/** - * Alternative decoding function which coverts irrespective of $_REQUEST values. - * Useful incase of Popup (Listview etc...) where if decode_html will not work as expected - */ -function decode_html_force($str) { - global $default_charset; - return html_entity_decode($str,ENT_QUOTES,$default_charset); -} - -function popup_decode_html($str) -{ - global $default_charset; - $slashes_str = popup_from_html($str); - $slashes_str = htmlspecialchars($slashes_str,ENT_QUOTES,$default_charset); - return decode_html(br2nl($slashes_str)); -} - -//function added to check the text length in the listview. -function textlength_check($field_val) -{ - global $listview_max_textlength; - if($listview_max_textlength) { - $temp_val = preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$field_val); - if(strlen($field_val) > $listview_max_textlength) - { - $temp_val = substr(preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$field_val),0,$listview_max_textlength).'...'; - } - } else { - $temp_val = $field_val; - } - return $temp_val; -} - -/** Function to get permitted fields of current user of a particular module to find duplicate records --Pavani*/ -function getMergeFields($module,$str){ - global $adb,$current_user; - $tabid = getTabid($module); - if($str == "available_fields"){ - $result = getFieldsResultForMerge($tabid); - } - else { //if($str == fileds_to_merge) - $sql="select * from vtiger_user2mergefields where tabid=? and userid=? and visible=1"; - $result = $adb->pquery($sql, array($tabid,$current_user->id)); - } - - $num_rows=$adb->num_rows($result); - - $user_profileid = fetchUserProfileId($current_user->id); - $permitted_list = getProfile2FieldPermissionList($module, $user_profileid); - - $sql_def_org="select fieldid from vtiger_def_org_field where tabid=? and visible=0"; - $result_def_org=$adb->pquery($sql_def_org,array($tabid)); - $num_rows_org=$adb->num_rows($result_def_org); - $permitted_org_list = Array(); - for($i=0; $i<$num_rows_org; $i++) - $permitted_org_list[$i] = $adb->query_result($result_def_org,$i,"fieldid"); - - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - for($i=0; $i<$num_rows;$i++) - { - $field_id = $adb->query_result($result,$i,"fieldid"); - foreach($permitted_list as $field=>$data) - if($data[4] == $field_id and $data[1] == 0) - { - if($is_admin == 'true' || (in_array($field_id,$permitted_org_list))) - { - $field=""; - $fields.=$field; - break; - } - } - } - return $fields; -} - - -/** - * this function accepts a modulename and a fieldname and returns the first related module for it - * it expects the uitype of the field to be 10 - * @param string $module - the modulename - * @param string $fieldname - the field name - * @return string $data - the first related module - */ -function getFirstModule($module, $fieldname){ - global $adb; - $sql = "select fieldid, uitype from vtiger_field where tabid=? and fieldname=?"; - $result = $adb->pquery($sql, array(getTabid($module), $fieldname)); - - if($adb->num_rows($result)>0){ - $uitype = $adb->query_result($result, 0, "uitype"); - - if($uitype == 10){ - $fieldid = $adb->query_result($result, 0, "fieldid"); - $sql = "select * from vtiger_fieldmodulerel where fieldid=?"; - $result = $adb->pquery($sql, array($fieldid)); - $count = $adb->num_rows($result); - - if($count > 0){ - $data = $adb->query_result($result, 0, "relmodule"); - } - } - } - return $data; -} - -function VT_getSimpleNavigationValues($start,$size,$total){ - $prev = $start -1; - if($prev < 0){ - $prev = 0; - } - if($total === null){ - return array('start'=>$start,'first'=>$start,'current'=>$start,'end'=>$start,'end_val'=>$size,'allflag'=>'All', - 'prev'=>$prev,'next'=>$start+1,'verylast'=>'last'); - } - if(empty($total)){ - $lastPage = 1; - }else{ - $lastPage = ceil($total/$size); - } - - $next = $start+1; - if($next > $lastPage){ - $next = 0; - } - return array('start'=>$start,'first'=>$start,'current'=>$start,'end'=>$start,'end_val'=>$size,'allflag'=>'All', - 'prev'=>$prev,'next'=>$next,'verylast'=>$lastPage); -} - -/**Function to get the simplified table headers for a listview -*Param $navigation_arrray - navigation values in array -*Param $url_qry - url string -*Param $module - module name -*Param $action- action file name -*Param $viewid - view id -*Returns an string value -*/ - -function getTableHeaderSimpleNavigation($navigation_array, $url_qry,$module='',$action_val='index',$viewid=''){ - global $log,$app_strings; - global $theme,$current_user; - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - if($module == 'Documents') { - $output = ''; - } else { - $output = ''; - } - $tabname = getParentTab(); - - $url_string = ''; - - // vtlib Customization : For uitype 10 popup during paging - if($_REQUEST['form'] == 'vtlibPopupView') { - $url_string .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); - } - // END - - if($module == 'Calendar' && $action_val == 'index') - { - if($_REQUEST['view'] == ''){ - if($current_user->activity_view == "This Year"){ - $mysel = 'year'; - }else if($current_user->activity_view == "This Month"){ - $mysel = 'month'; - }else if($current_user->activity_view == "This Week"){ - $mysel = 'week'; - }else{ - $mysel = 'day'; - } - } - $data_value=date('Y-m-d H:i:s'); - preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$data_value,$value); - $date_data = Array( - 'day'=>$value[3], - 'month'=>$value[2], - 'year'=>$value[1], - 'hour'=>$value[4], - 'min'=>$value[5], - ); - $tab_type = ($_REQUEST['subtab'] == '')?'event':vtlib_purify($_REQUEST['subtab']); - $url_string .= isset($_REQUEST['view'])?"&view=".vtlib_purify($_REQUEST['view']):"&view=".$mysel; - $url_string .= isset($_REQUEST['subtab'])?"&subtab=".vtlib_purify($_REQUEST['subtab']):''; - $url_string .= isset($_REQUEST['viewOption'])?"&viewOption=".vtlib_purify($_REQUEST['viewOption']):'&viewOption=listview'; - $url_string .= isset($_REQUEST['day'])?"&day=".vtlib_purify($_REQUEST['day']):'&day='.$date_data['day']; - $url_string .= isset($_REQUEST['week'])?"&week=".vtlib_purify($_REQUEST['week']):''; - $url_string .= isset($_REQUEST['month'])?"&month=".vtlib_purify($_REQUEST['month']):'&month='.$date_data['month']; - $url_string .= isset($_REQUEST['year'])?"&year=".vtlib_purify($_REQUEST['year']):"&year=".$date_data['year']; - $url_string .= isset($_REQUEST['n_type'])?"&n_type=".vtlib_purify($_REQUEST['n_type']):''; - $url_string .= isset($_REQUEST['search_option'])?"&search_option=".vtlib_purify($_REQUEST['search_option']):''; - } - if($module == 'Calendar' && $action_val != 'index') //added for the All link from the homepage -- ticket 5211 - $url_string .= isset($_REQUEST['from_homepage'])?"&from_homepage=".vtlib_purify($_REQUEST['from_homepage']):''; - - if(($navigation_array['prev']) != 0){ - if($module == 'Calendar' && $action_val == 'index'){ - $output .= ' '; - $output .= ' '; - }else if($action_val == "FindDuplicate"){ - $output .= ' '; - $output .= ' '; - }elseif($action_val == 'UnifiedSearch'){ - $output .= ' '; - $output .= ' '; - }elseif($module == 'Documents'){ - $output .= ' '; - $output .= ' '; - }else{ - $output .= ' '; - $output .= ' '; - } - }else{ - $output .= ' '; - $output .= ' '; - } - if($module == 'Calendar' && $action_val == 'index'){ - $jsNavigate = "cal_navigation('$tab_type','$url_string','&start='+this.value+');"; - }else if($action_val == "FindDuplicate"){ - $jsNavigate = "getDuplicateListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; - }elseif($action_val == 'UnifiedSearch'){ - $jsNavigate = "getUnifiedSearchEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; - }elseif($module == 'Documents'){ - $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string&folderid=$action_val');"; - }else{ - $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; - } - if($module == 'Documents' && $action_val != 'UnifiedSearch'){ - $url = '&folderid='.$action_val; - }else{ - $url = ''; - } - $jsHandler = "return VT_disableFormSubmit(event);"; - $output .= ""; - $output .= ""; - if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true){ - $output .= $app_strings['LBL_LIST_OF'].' '.$navigation_array['verylast']; - }else{ - $output .= "".$app_strings[ - ".$app_strings["; - } - $output .=''; - - if(($navigation_array['next']) !=0){ - if($module == 'Calendar' && $action_val == 'index'){ - $output .= ' '; - $output .= ' '; - }else if($action_val == "FindDuplicate"){ - $output .= ' '; - $output .= ' '; - }elseif($action_val == 'UnifiedSearch'){ - $output .= ' '; - $output .= ' '; - }elseif($module == 'Documents'){ - $output .= ' '; - $output .= ' '; - }else{ - $output .= ' '; - $output .= ' '; - } - }else{ - $output .= ' '; - $output .= ' '; - } - $output .= ''; - if($navigation_array['first']=='') - return; - else - return $output; -} - -function getRecordRangeMessage($listResult, $limitStartRecord) { - global $adb, $app_strings; - $numRows = $adb->num_rows($listResult); - $recordListRangeMsg = ''; - if ($numRows > 0) { - $recordListRangeMsg = $app_strings['LBL_SHOWING'].' '.$app_strings['LBL_RECORDS']. - ' '.($limitStartRecord+1).' - '.($limitStartRecord+$numRows); - } - return $recordListRangeMsg; -} - -?> \ No newline at end of file +debug("Entering getListViewHeader(". $module.",".$sort_qry.",".$sorder.",".$order_by.",".$relatedlist.",".(is_object($oCv)? get_class($oCv) : $oCv).") method ..."); + global $adb; + global $theme; + global $app_strings; + global $mod_strings; + + $arrow=''; + $qry = getURLstring($focus); + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + $list_header = Array(); + + //Get the vtiger_tabid of the module + $tabid = getTabid($module); + $tabname = getParentTab(); + global $current_user; + //added for vtiger_customview 27/5 + if($oCv) + { + if(isset($oCv->list_fields)) + { + $focus->list_fields = $oCv->list_fields; + } + } + + // Remove fields which are made inactive + $focus->filterInactiveFields($module); + + //Added to reduce the no. of queries logging for non-admin user -- by Minnie-start + $field_list = array(); + $j=0; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + foreach($focus->list_fields as $name=>$tableinfo) + { + $fieldname = $focus->list_fields_name[$name]; + if($oCv) + { + if(isset($oCv->list_fields_name)) + { + $fieldname = $oCv->list_fields_name[$name]; + } + } + if($fieldname == 'accountname' && $module != 'Accounts') + { + $fieldname = 'account_id'; + } + if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'||$module == 'Calendar' )) + { + $fieldname = 'contact_id'; + } + if($fieldname == 'productname' && $module != 'Products') + { + $fieldname = 'product_id'; + } + array_push($field_list, $fieldname); + $j++; + } + $field=Array(); + if($is_admin==false) + { + if($module == 'Emails') + { + $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; + $params = array($tabid); + } + else + { + $profileList = getCurrentUserProfileList(); + $params = array(); + + $query = "SELECT DISTINCT vtiger_field.fieldname + FROM vtiger_field + INNER JOIN vtiger_profile2field + ON vtiger_profile2field.fieldid = vtiger_field.fieldid + INNER JOIN vtiger_def_org_field + ON vtiger_def_org_field.fieldid = vtiger_field.fieldid"; + if($module == "Calendar") { + $query .=" WHERE vtiger_field.tabid in (9,16) and vtiger_field.presence in (0,2)"; + } else { + $query .=" WHERE vtiger_field.tabid = ? and vtiger_field.presence in (0,2)"; + array_push($params, $tabid); + } + + $query.=" AND vtiger_profile2field.visible = 0 + AND vtiger_def_org_field.visible = 0 + AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") + AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .")"; + + array_push($params, $profileList, $field_list); + } + $result = $adb->pquery($query, $params); + for($k=0;$k < $adb->num_rows($result);$k++) + { + $field[]=$adb->query_result($result,$k,"fieldname"); + } + } + //end + //modified for vtiger_customview 27/5 - $app_strings change to $mod_strings + foreach($focus->list_fields as $name=>$tableinfo) + { + //added for vtiger_customview 27/5 + if($oCv) + { + if(isset($oCv->list_fields_name)) + { + $fieldname = $oCv->list_fields_name[$name]; + if($fieldname == 'accountname' && $module != 'Accounts') + { + $fieldname = 'account_id'; + } + if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'|| $module == 'Calendar') ) + { + $fieldname = 'contact_id'; + } + if($fieldname == 'productname' && $module != 'Products') + { + $fieldname = 'product_id'; + } + }else + { + $fieldname = $focus->list_fields_name[$name]; + } + }else + { + $fieldname = $focus->list_fields_name[$name]; + if($fieldname == 'accountname' && $module != 'Accounts') + { + $fieldname = 'account_id'; + } + if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'|| $module == 'Calendar')) + { + $fieldname = 'contact_id'; + } + if($fieldname == 'productname' && $module != 'Products') + { + $fieldname = 'product_id'; + } + + } + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $fieldname == '' || ($name=='Close' && $module=='Calendar')) + { + if(isset($focus->sortby_fields) && $focus->sortby_fields !='') + { + //Added on 14-12-2005 to avoid if and else check for every list vtiger_field for arrow image and change order + $change_sorder = array('ASC'=>'DESC','DESC'=>'ASC'); + $arrow_gif = array('ASC'=>'arrow_down.gif','DESC'=>'arrow_up.gif'); + foreach($focus->list_fields[$name] as $tab=>$col) + { + if(in_array($col,$focus->sortby_fields)) + { + if($order_by == $col) + { + $temp_sorder = $change_sorder[$sorder]; + $arrow = " "; + } + else + { + $temp_sorder = 'ASC'; + } + $lbl_name = getTranslatedString($name, $module); + //added to display vtiger_currency symbol in listview header + if($lbl_name =='Amount') + { + $lbl_name .=' ('.$app_strings['LBL_IN'].' '.$user_info['currency_symbol'].')'; + } + if($relatedlist !='' && $relatedlist != 'global'){ + $relationURL = ''; + if(!empty($_REQUEST['relation_id'])){ + $relationURL = '&relation_id='.vtlib_purify( + $_REQUEST['relation_id']); + } + $actionsURL = ''; + if(!empty($_REQUEST['actions'])){ + $actionsURL = '&actions='.vtlib_purify($_REQUEST['actions']); + } + if(empty($_REQUEST['header'])){ + $moduleLabel = getTranslatedString($module,$module); + }else{ + $moduleLabel = $_REQUEST['header']; + } + $moduleLabel = str_replace(' ','',$moduleLabel); + $name = "".$lbl_name."".$arrow.""; + } elseif($module == 'Users' && $name == 'User Name') + $name = "".getTranslatedString('LBL_LIST_USER_NAME_ROLE',$module)."".$arrow.""; + elseif($relatedlist == "global") + $name = $lbl_name; + else + $name = "".$lbl_name."".$arrow.""; + $arrow = ''; + } + else + { + if(stripos($col, 'cf_') === 0) { + $tablenameArray = array_keys($tableinfo,$col); + $tablename = $tablenameArray[0]; + $cf_columns = $adb->getColumnNames($tablename); + if (array_search($col, $cf_columns) != null) { + $pquery = "select fieldlabel,typeofdata from vtiger_field where tablename = ? and fieldname = ? and vtiger_field.presence in (0,2)"; + $cf_res = $adb->pquery($pquery, array($tablename, $col)); + if (count($cf_res) > 0){ + $cf_fld_label = $adb->query_result($cf_res, 0, "fieldlabel"); + $typeofdata = explode("~",$adb->query_result($cf_res, 0, "typeofdata")); + $new_field_label = $tablename. ":" . $col .":". $col .":". $module . "_" . str_replace(" ","_",$cf_fld_label) .":". $typeofdata[0]; + $name = $cf_fld_label; + + // Update the existing field name in the database with new field name. + $upd_query = "update vtiger_cvcolumnlist set columnname = ? where columnname like '" .$tablename. ":" . $col .":". $col ."%'"; + $upd_params = array($new_field_label); + $adb->pquery($upd_query, $upd_params); + + } + } + } else { + $name = getTranslatedString($name, $module); + } + } + } + } + //added to display vtiger_currency symbol in related listview header + if($name =='Amount' && $relatedlist !='' ) + { + $name .=' ('.$app_strings['LBL_IN'].' '.$user_info['currency_symbol'].')'; + } + + if($module == "Calendar" && $name == $app_strings['Close']) + { + if(isPermitted("Calendar","EditView") == 'yes') + { + if((getFieldVisibilityPermission('Events',$current_user->id,'eventstatus') == '0') || (getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0')) + { + array_push($list_header,$name); + } + } + } + else + { + $list_header[]=$name; + } + } + } + + //Added for Action - edit and delete link header in listview + if(!$skipActions && (isPermitted($module,"EditView","") == 'yes' || isPermitted($module,"Delete","") == 'yes')) + $list_header[] = $app_strings["LBL_ACTION"]; + + $log->debug("Exiting getListViewHeader method ..."); + return $list_header; +} + +/**This function is used to get the list view header in popup +*Param $focus - module object +*Param $module - module name +*Param $sort_qry - sort by value +*Param $sorder - sorting order (asc/desc) +*Param $order_by - order by +*Returns the listview header values in an array +*/ + +function getSearchListViewHeader($focus, $module,$sort_qry='',$sorder='',$order_by='') +{ + global $log; + $log->debug("Entering getSearchListViewHeader(".get_class($focus).",". $module.",".$sort_qry.",".$sorder.",".$order_by.") method ..."); + global $adb; + global $theme; + global $app_strings; + global $mod_strings,$current_user; + $arrow=''; + $list_header = Array(); + $tabid = getTabid($module); + if(isset($_REQUEST['task_relmod_id'])) + { + $task_relmod_id=vtlib_purify($_REQUEST['task_relmod_id']); + $pass_url .="&task_relmod_id=".$task_relmod_id; + } + if(isset($_REQUEST['relmod_id'])) + { + $relmod_id=vtlib_purify($_REQUEST['relmod_id']); + $pass_url .="&relmod_id=".$relmod_id; + } + if(isset($_REQUEST['task_parent_module'])) + { + $task_parent_module=vtlib_purify($_REQUEST['task_parent_module']); + $pass_url .="&task_parent_module=".$task_parent_module; + } + if(isset($_REQUEST['parent_module'])) + { + $parent_module=vtlib_purify($_REQUEST['parent_module']); + $pass_url .="&parent_module=".$parent_module; + } + if(isset($_REQUEST['fromPotential']) && (isset($_REQUEST['acc_id']) && $_REQUEST['acc_id']!= '')) + { + $pass_url .="&parent_module=Accounts&relmod_id=".vtlib_purify($_REQUEST['acc_id']); + } + + // vtlib Customization : For uitype 10 popup during paging + if($_REQUEST['form'] == 'vtlibPopupView') { + $pass_url .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); + } + // END + + //Added to reduce the no. of queries logging for non-admin user -- by Minnie-start + $field_list = array(); + $j=0; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + foreach($focus->search_fields as $name=>$tableinfo) + { + $fieldname = $focus->search_fields_name[$name]; + array_push($field_list, $fieldname); + $j++; + } + $field=Array(); + if($is_admin==false && $module != 'Users') + { + if($module == 'Emails') + { + $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; + $params = array($tabid); + } + else + { + $profileList = getCurrentUserProfileList(); + $query = "SELECT DISTINCT vtiger_field.fieldname + FROM vtiger_field + INNER JOIN vtiger_profile2field + ON vtiger_profile2field.fieldid = vtiger_field.fieldid + INNER JOIN vtiger_def_org_field + ON vtiger_def_org_field.fieldid = vtiger_field.fieldid + WHERE vtiger_field.tabid = ? + AND vtiger_profile2field.visible=0 + AND vtiger_def_org_field.visible=0 + AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") + AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2)"; + + $params = array($tabid, $profileList, $field_list); + } + + $result = $adb->pquery($query, $params); + for($k=0;$k < $adb->num_rows($result);$k++) + { + $field[]=$adb->query_result($result,$k,"fieldname"); + } + } + //end + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + + $focus->filterInactiveFields($module); + + foreach($focus->search_fields as $name=>$tableinfo) + { + $fieldname = $focus->search_fields_name[$name]; + $tabid = getTabid($module); + + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $module == 'Users') + { + + if(isset($focus->sortby_fields) && $focus->sortby_fields !='') + { + foreach($focus->search_fields[$name] as $tab=>$col) + { + if(in_array($col,$focus->sortby_fields)) + { + if($order_by == $col) + { + if($sorder == 'ASC') + { + $sorder = "DESC"; + $arrow = ""; + } + else + { + $sorder = 'ASC'; + $arrow = ""; + } + } + // vtlib customization: If translation is not available use the given name + $tr_name = getTranslatedString($name, $module); + $name = "".$tr_name." ".$arrow.""; + // END + $arrow = ''; + } + else { + // vtlib customization: If translation is not available use the given name + $tr_name = getTranslatedString($name, $module); + $name = $tr_name; + // END + } + } + } + $list_header[]=$name; + } + } + $log->debug("Exiting getSearchListViewHeader method ..."); + return $list_header; + +} + +/**This function generates the navigation array in a listview +*Param $display - start value of the navigation +*Param $noofrows - no of records +*Param $limit - no of entries per page +*Returns an array type +*/ + +//code contributed by raju for improved pagination +function getNavigationValues($display, $noofrows, $limit) +{ + global $log; + $log->debug("Entering getNavigationValues(".$display.",".$noofrows.",".$limit.") method ..."); + $navigation_array = Array(); + global $limitpage_navigation; + if(isset($_REQUEST['allflag']) && $_REQUEST['allflag'] == 'All'){ + $navigation_array['start'] =1; + $navigation_array['first'] = 1; + $navigation_array['end'] = 1; + $navigation_array['prev'] =0; + $navigation_array['next'] =0; + $navigation_array['end_val'] =$noofrows; + $navigation_array['current'] =1; + $navigation_array['allflag'] ='Normal'; + $navigation_array['verylast'] =1; + $log->debug("Exiting getNavigationValues method ..."); + return $navigation_array; + } + if($noofrows != 0) + { + if(((($display * $limit)-$limit)+1) > $noofrows) + { + $display =floor($noofrows / $limit); + } + $start = ((($display * $limit) - $limit)+1); + } + else + { + $start = 0; + } + + $end = $start + ($limit-1); + if($end > $noofrows) + { + $end = $noofrows; + } + $paging = ceil ($noofrows / $limit); + // Display the navigation + if ($display > 1) { + $previous = $display - 1; + } + else { + $previous=0; + } + if($noofrows < $limit) + { + $first = ''; + } + elseif ($noofrows != $limit) { + $last = $paging; + $first = 1; + if ($paging > $limitpage_navigation) { + $first = $display-floor(($limitpage_navigation/2)); + if ($first<1) $first=1; + $last = ($limitpage_navigation - 1) + $first; + } + if ($last > $paging ) { + $first = $paging - ($limitpage_navigation - 1); + $last = $paging; + } + } + if ($display < $paging) { + $next = $display + 1; + } + else { + $next=0; + } + $navigation_array['start'] = $start; + $navigation_array['first'] = $first; + $navigation_array['end'] = $last; + $navigation_array['prev'] = $previous; + $navigation_array['next'] = $next; + $navigation_array['end_val'] = $end; + $navigation_array['current'] = $display; + $navigation_array['allflag'] ='All'; + $navigation_array['verylast'] =$paging; + $log->debug("Exiting getNavigationValues method ..."); + return $navigation_array; + +} + + +//End of code contributed by raju for improved pagination + +/**This function generates the List view entries in a list view +*Param $focus - module object +*Param $list_result - resultset of a listview query +*Param $navigation_array - navigation values in an array +*Param $relatedlist - check for related list flag +*Param $returnset - list query parameters in url string +*Param $edit_action - Edit action value +*Param $del_action - delete action value +*Param $oCv - vtiger_customview object +*Returns an array type +*/ + +//parameter added for vtiger_customview $oCv 27/5 +function getListViewEntries($focus, $module,$list_result,$navigation_array,$relatedlist='',$returnset='',$edit_action='EditView',$del_action='Delete',$oCv='',$page='',$selectedfields='',$contRelatedfields='',$skipActions=false) +{ + global $log; + global $mod_strings; + $log->debug("Entering getListViewEntries(".get_class($focus).",". $module.",".$list_result.",".$navigation_array.",".$relatedlist.",".$returnset.",".$edit_action.",".$del_action.",".(is_object($oCv)? get_class($oCv) : $oCv).") method ..."); + $tabname = getParentTab(); + global $adb,$current_user; + global $app_strings; + $noofrows = $adb->num_rows($list_result); + $list_block = Array(); + global $theme; + $evt_status = ''; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + //getting the vtiger_fieldtable entries from database + $tabid = getTabid($module); + + //added for vtiger_customview 27/5 + if($oCv) + { + if(isset($oCv->list_fields)) + { + $focus->list_fields = $oCv->list_fields; + } + } + if(is_array($selectedfields) && $selectedfields != '') + { + $focus->list_fields = $selectedfields; + } + + // Remove fields which are made inactive + $focus->filterInactiveFields($module); + + //Added to reduce the no. of queries logging for non-admin user -- by minnie-start + $field_list = array(); + $j=0; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + foreach($focus->list_fields as $name=>$tableinfo) + { + $fieldname = $focus->list_fields_name[$name]; + if($oCv) + { + if(isset($oCv->list_fields_name)) + { + $fieldname = $oCv->list_fields_name[$name]; + } + } + if($fieldname == 'accountname' && $module != 'Accounts') + { + $fieldname = 'account_id'; + } + if($fieldname == 'lastname' &&($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'||$module == 'Calendar')) + $fieldname = 'contact_id'; + + if($fieldname == 'productname' && $module != 'Products') + { + $fieldname = 'product_id'; + } + + array_push($field_list, $fieldname); + $j++; + } + $field=Array(); + if($is_admin==false) + { + if($module == 'Emails') + { + $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; + $params = array($tabid); + } + else + { + $profileList = getCurrentUserProfileList(); + $params = array(); + $query = "SELECT DISTINCT vtiger_field.fieldname + FROM vtiger_field + INNER JOIN vtiger_profile2field + ON vtiger_profile2field.fieldid = vtiger_field.fieldid + INNER JOIN vtiger_def_org_field + ON vtiger_def_org_field.fieldid = vtiger_field.fieldid"; + + if($module == "Calendar") + $query .=" WHERE vtiger_field.tabid in (9,16) and vtiger_field.presence in (0,2)"; + else { + $query .=" WHERE vtiger_field.tabid = ? and vtiger_field.presence in (0,2)"; + array_push($params, $tabid); + } + + $query .=" AND vtiger_profile2field.visible = 0 + AND vtiger_profile2field.visible = 0 + AND vtiger_def_org_field.visible = 0 + AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") + AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .")"; + + array_push($params, $profileList, $field_list); + } + + $result = $adb->pquery($query, $params); + for($k=0;$k < $adb->num_rows($result);$k++) + { + $field[]=$adb->query_result($result,$k,"fieldname"); + } + } + //constructing the uitype and columnname array + $ui_col_array=Array(); + + $params = array(); + $query = "SELECT uitype, columnname, fieldname FROM vtiger_field "; + + if($module == "Calendar") + $query .=" WHERE vtiger_field.tabid in (9,16) and vtiger_field.presence in (0,2)"; + else { + $query .=" WHERE vtiger_field.tabid = ? and vtiger_field.presence in (0,2)"; + array_push($params, $tabid); + } + $query .= " AND fieldname IN (". generateQuestionMarks($field_list).") "; + array_push($params, $field_list); + + $result = $adb->pquery($query, $params); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $tempArr=array(); + $uitype=$adb->query_result($result,$i,'uitype'); + $columnname=$adb->query_result($result,$i,'columnname'); + $field_name=$adb->query_result($result,$i,'fieldname'); + $tempArr[$uitype]=$columnname; + $ui_col_array[$field_name]=$tempArr; + } + //end + if($navigation_array['start'] !=0) + for ($i=1; $i<=$noofrows; $i++) + { + $list_header =Array(); + //Getting the entityid + if($module != 'Users') + { + $entity_id = $adb->query_result($list_result,$i-1,"crmid"); + $owner_id = $adb->query_result($list_result,$i-1,"smownerid"); + }else + { + $entity_id = $adb->query_result($list_result,$i-1,"id"); + } + // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 + // begin: Armando Lüscher 05.07.2005 -> §priority + // Code contri buted by fredy Desc: Set Priority color + $priority = $adb->query_result($list_result,$i-1,"priority"); + + $font_color_high = "color:#00DD00;"; + $font_color_medium = "color:#DD00DD;"; + $P_FONT_COLOR = ""; + switch ($priority) + { + case 'High': + $P_FONT_COLOR = $font_color_high; + break; + case 'Medium': + $P_FONT_COLOR = $font_color_medium; + break; + default: + $P_FONT_COLOR = ""; + } + //end: Armando Lüscher 05.07.2005 -> §priority + foreach($focus->list_fields as $name=>$tableinfo) + { + $fieldname = $focus->list_fields_name[$name]; + + //added for vtiger_customview 27/5 + if($oCv) { + if(isset($oCv->list_fields_name)) { + $fieldname = $oCv->list_fields_name[$name]; + if($fieldname == 'accountname' && $module != 'Accounts') { + $fieldname = 'account_id'; + } + if($fieldname == 'lastname' &&($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'||$module == 'Calendar' )) { + $fieldname = 'contact_id'; + } + if($fieldname == 'productname' && $module != 'Products') { + $fieldname = 'product_id'; + } + } else { + $fieldname = $focus->list_fields_name[$name]; + } + } else { + $fieldname = $focus->list_fields_name[$name]; + if($fieldname == 'accountname' && $module != 'Accounts') { + $fieldname = 'account_id'; + } + if($fieldname == 'lastname' && ($module == 'SalesOrder'|| $module == 'PurchaseOrder' || $module == 'Invoice' || $module == 'Quotes'|| $module == 'Calendar')) { + $fieldname = 'contact_id'; + } + if($fieldname == 'productname' && $module != 'Products') { + $fieldname = 'product_id'; + } + } + if($is_admin==true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $fieldname == '' || ($name=='Close' && $module=='Calendar')) { + if($fieldname == '') { + $table_name = ''; + $column_name = ''; + foreach($tableinfo as $tablename=>$colname) { + $table_name=$tablename; + $column_name = $colname; + } + $value = $adb->query_result($list_result,$i-1,$colname); + } + else { + if($module == 'Calendar') { + $act_id = $adb->query_result($list_result,$i-1,"activityid"); + + $cal_sql = "select activitytype from vtiger_activity where activityid=?"; + $cal_res = $adb->pquery($cal_sql,array($act_id)); + if($adb->num_rows($cal_res)>=0) + $activitytype = $adb->query_result($cal_res,0,"activitytype"); + } + if(($module == 'Calendar' || $module == 'Emails' || $module == 'HelpDesk' || $module == 'Invoice' || $module == 'Leads' || $module == 'Contacts') && (($fieldname=='parent_id') || ($name=='Contact Name') || ($name=='Close') || ($fieldname == 'firstname'))) { + if($module == 'Calendar'){ + if($fieldname=='status'){ + if($activitytype == 'Task'){ + $fieldname='taskstatus'; + } else { + $fieldname='eventstatus'; + } + } + if($activitytype == 'Task' ) { + if(getFieldVisibilityPermission('Calendar',$current_user->id,$fieldname) == '0'){ + $has_permission = 'yes'; + } else { + $has_permission = 'no'; + } + } else { + if(getFieldVisibilityPermission('Events',$current_user->id,$fieldname) == '0'){ + $has_permission = 'yes'; + } else { + $has_permission = 'no'; + } + } + } + if($module != 'Calendar' || ($module == 'Calendar' && $has_permission == 'yes')) { + if ($fieldname=='parent_id') { + $value=getRelatedTo($module,$list_result,$i-1); + } + if($name=='Contact Name') { + $contact_id = $adb->query_result($list_result,$i-1,"contactid"); + $contact_name = getFullNameFromQResult($list_result,$i-1,"Contacts"); + $value=""; + //Added to get the contactname for activities custom view - t=2190 + if($contact_id != '' && !empty($contact_name)) { + $contact_name = getContactName($contact_id); + } + if(($contact_name != "") && ($contact_id !='NULL')) { + // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 + $value = "".$contact_name.""; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" + } + } + if($fieldname == "firstname") { + $first_name = textlength_check($adb->query_result($list_result,$i-1,"firstname")); + + $value = ''.$first_name.''; + } + + if ($name == 'Close') { + $status = $adb->query_result($list_result,$i-1,"status"); + $activityid = $adb->query_result($list_result,$i-1,"activityid"); + if(empty($activityid)){ + $activityid = $adb->query_result($list_result, $i-1, "tmp_activity_id"); + } + $activitytype = $adb->query_result($list_result,$i-1,"activitytype"); + // TODO - Picking activitytype when it is not present in the Custom View. + // Going forward, this column should be added to the select list if not already present as a performance improvement. + if (empty($activitytype)) { + $activitytypeRes = $adb->pquery('SELECT activitytype FROM vtiger_activity WHERE activityid=?', array($activityid)); + if ($adb->num_rows($activitytypeRes) > 0) { + $activitytype = $adb->query_result($activitytypeRes, 0, 'activitytype'); + } + } + if ($activitytype != 'Task' && $activitytype != 'Emails') { + $eventstatus = $adb->query_result($list_result,$i-1,"eventstatus"); + if(isset($eventstatus)) { + $status = $eventstatus; + } + } + if($status =='Deferred' || $status == 'Completed' || $status == 'Held' || $status == '') { + $value=""; + } else { + if($activitytype=='Task') + $evt_status='&status=Completed'; + else + $evt_status='&eventstatus=Held'; + if(isPermitted("Calendar",'EditView',$activityid) == 'yes') { + if ($returnset == '') { + $returnset = '&return_module=Calendar&return_action=ListView&return_id='.$activityid.'&return_viewname='.$oCv->setdefaultviewid; + } + // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 + $value = "X"; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" + } else { + $value = ""; + } + } + } + + } else { + $value = ""; + } + } elseif($module == "Documents" && ($fieldname == 'filelocationtype' || $fieldname == 'filename' || $fieldname == 'filesize' || $fieldname == 'filestatus' || $fieldname == 'filetype')) { + $value = $adb->query_result($list_result,$i-1,$fieldname); + if($fieldname == 'filelocationtype') { + if($value == 'I') + $value = getTranslatedString('LBL_INTERNAL',$module); + elseif($value == 'E') + $value = getTranslatedString('LBL_EXTERNAL',$module); + else + $value = ' --'; + } + if($fieldname == 'filename') { + $downloadtype = $adb->query_result($list_result,$i-1,'filelocationtype'); + if($downloadtype == 'I') { + $fld_value = $value; + $ext_pos = strrpos($fld_value, "."); + $ext =substr($fld_value, $ext_pos + 1); + $ext = strtolower($ext); + if($value != ''){ + if($ext == 'bin' || $ext == 'exe' || $ext == 'rpm') + $fileicon=""; + elseif($ext == 'jpg' || $ext == 'gif' || $ext == 'bmp') + $fileicon=""; + elseif($ext == 'txt' || $ext == 'doc' || $ext == 'xls') + $fileicon=""; + elseif($ext == 'zip' || $ext == 'gz' || $ext == 'rar') + $fileicon=""; + else + $fileicon=""; + } + } elseif($downloadtype == 'E') { + if(trim($value) != '' ) { + $fld_value = $value; + $fileicon = "".getTranslatedString("; + } + else { + $fld_value = '--'; + $fileicon = ''; + } + } else { + $fld_value = ' --'; + $fileicon = ''; + } + + $file_name = $adb->query_result($list_result,$i-1,'filename'); + $notes_id = $adb->query_result($list_result,$i-1,'crmid'); + $folder_id = $adb->query_result($list_result,$i-1,'folderid'); + $download_type = $adb->query_result($list_result,$i-1,'filelocationtype'); + $file_status = $adb->query_result($list_result,$i-1,'filestatus'); + $fileidQuery = "select attachmentsid from vtiger_seattachmentsrel where crmid=?"; + $fileidres = $adb->pquery($fileidQuery,array($notes_id)); + $fileid = $adb->query_result($fileidres,0,'attachmentsid'); + if($file_name != '' && $file_status == 1) { + if($download_type == 'I' ) { + $fld_value = "".$fld_value.""; + } elseif($download_type == 'E') { + $fld_value = "".$fld_value.""; + } else { + $fld_value = ' --'; + } + } + $value = $fileicon.$fld_value; + } + if($fieldname == 'filesize') { + $downloadtype = $adb->query_result($list_result,$i-1,'filelocationtype'); + if($downloadtype == 'I') { + $filesize = $value; + if($filesize < 1024) + $value=$filesize.' B'; + elseif($filesize > 1024 && $filesize < 1048576) + $value=round($filesize/1024,2).' KB'; + else if($filesize > 1048576) + $value=round($filesize/(1024*1024),2).' MB'; + } else { + $value = ' --'; + } + } + if($fieldname == 'filestatus') { + $filestatus = $value; + if($filestatus == 1) + $value=getTranslatedString('yes',$module); + elseif($filestatus == 0) + $value=getTranslatedString('no',$module); + else + $value=' --'; + } + if($fieldname == 'filetype') { + $downloadtype = $adb->query_result($list_result,$i-1,'filelocationtype'); + $filetype = $adb->query_result($list_result,$i-1,'filetype'); + if($downloadtype == 'E' || $downloadtype != 'I') { + $value = ' --'; + } else + $value = $filetype; + } + if($fieldname == 'notecontent') { + $value = decode_html($value); + $value = textlength_check($value); + } + } elseif($module == "Products" && $name == "Related to") { + $value=getRelatedTo($module,$list_result,$i-1); + } elseif($name=='Contact Name' && ($module =='SalesOrder' || $module == 'Quotes' || $module == 'PurchaseOrder')) { + if($name == 'Contact Name') { + $contact_id = $adb->query_result($list_result,$i-1,"contactid"); + $contact_name = getFullNameFromQResult($list_result, $i-1,"Contacts"); + $value=""; + if(($contact_name != "") && ($contact_id !='NULL')) + $value ="".$contact_name.""; + } + } elseif($name == 'Product') { + $product_id = textlength_check($adb->query_result($list_result,$i-1,"productname")); + $value = $product_id; + } elseif($name=='Account Name') { + //modified for vtiger_customview 27/5 + if($module == 'Accounts') { + $account_id = $adb->query_result($list_result,$i-1,"crmid"); + //$account_name = getAccountName($account_id); + $account_name = textlength_check($adb->query_result($list_result,$i-1,"accountname")); + // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 + $value = ''.$account_name.''; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" + } elseif($module == 'Potentials' || $module == 'Contacts' || $module == 'Invoice' || $module == 'SalesOrder' || $module == 'Quotes') { //Potential,Contacts,Invoice,SalesOrder & Quotes records sort by Account Name + $accountname = textlength_check($adb->query_result($list_result,$i-1,"accountname")); + $accountid = $adb->query_result($list_result,$i-1,"accountid"); + $value = ''.$accountname.''; + } else { + $account_id = $adb->query_result($list_result,$i-1,"accountid"); + $account_name = getAccountName($account_id); + $acc_name = textlength_check($account_name); + // Fredy Klammsteiner, 4.8.2005: changes from 4.0.1 migrated to 4.2 + $value = ''.$acc_name.''; // Armando Lüscher 05.07.2005 -> §priority -> Desc: inserted style="$P_FONT_COLOR" + } + } elseif(( $module == 'HelpDesk' || $module == 'PriceBook' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'Faq') && $name == 'Product Name') { + if($module == 'HelpDesk' || $module == 'Faq') + $product_id = $adb->query_result($list_result,$i-1,"product_id"); + else + $product_id = $adb->query_result($list_result,$i-1,"productid"); + + if($product_id != '') + $product_name = getProductName($product_id); + else + $product_name = ''; + + $value = ''.textlength_check($product_name).''; + } elseif(($module == 'Quotes' && $name == 'Potential Name') || ($module == 'SalesOrder' && $name == 'Potential Name')) { + $potential_id = $adb->query_result($list_result,$i-1,"potentialid"); + $potential_name = getPotentialName($potential_id); + $value = ''.textlength_check($potential_name).''; + } elseif($module =='Emails' && $relatedlist != '' && ($name=='Subject' || $name=='Date Sent' || $name == 'To')) { + $list_result_count = $i-1; + $tmp_value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); + $value = ''.textlength_check($tmp_value).''; + if($name == 'Date Sent') { + $sql="select email_flag from vtiger_emaildetails where emailid=?"; + $result=$adb->pquery($sql, array($entity_id)); + $email_flag=$adb->query_result($result,0,"email_flag"); + if($email_flag != 'SAVED') + $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); + else + $value = ''; + } + } elseif($module == 'Calendar' && ($fieldname!='taskstatus' && $fieldname!='eventstatus')) { + if($activitytype == 'Task' ) { + if(getFieldVisibilityPermission('Calendar',$current_user->id,$fieldname) == '0'){ + $list_result_count = $i-1; + $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); + } else { + $value = ''; + } + } else { + if(getFieldVisibilityPermission('Events',$current_user->id,$fieldname) == '0'){ + $list_result_count = $i-1; + $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); + } else { + $value = ''; + } + } + } else { + $list_result_count = $i-1; + $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset,$oCv->setdefaultviewid); + } + } + + // vtlib customization: For listview javascript triggers + $value = "$value "; + // END + + if($module == "Calendar" && $name == $app_strings['Close']) + { + if(isPermitted("Calendar","EditView") == 'yes') + { + if((getFieldVisibilityPermission('Events',$current_user->id,'eventstatus') == '0') || (getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0')) + { + array_push($list_header,$value); + } + } + } + else + $list_header[] = $value; + + } + + } + $varreturnset = ''; + if($returnset=='') + $varreturnset = '&return_module='.$module.'&return_action=index'; + else + $varreturnset = $returnset; + + + if($module == 'Calendar') + { + $actvity_type = $adb->query_result($list_result,$list_result_count,'activitytype'); + if($actvity_type == 'Task') + $varreturnset .= '&activity_mode=Task'; + else + $varreturnset .= '&activity_mode=Events'; + } + + //Added for Actions ie., edit and delete links in listview + $links_info = ""; + if(!(is_array($selectedfields) && $selectedfields != '')) + { + if(isPermitted($module,"EditView","") == 'yes'){ + $edit_link = getListViewEditLink($module,$entity_id,$relatedlist,$varreturnset,$list_result,$list_result_count); + if(isset($_REQUEST['start']) && $_REQUEST['start'] > 1 && $module != 'Emails') + $links_info .= "".$app_strings["LNK_EDIT"]." "; + else + $links_info .= "".$app_strings["LNK_EDIT"]." "; + } + + + if(isPermitted($module,"Delete","") == 'yes'){ + $del_link = getListViewDeleteLink($module,$entity_id,$relatedlist,$varreturnset); + if($links_info != "" && $del_link != "") + $links_info .= " | "; + if($del_link != "") + $links_info .= "".$app_strings["LNK_DELETE"].""; + } + } + // Record Change Notification + if(method_exists($focus, 'isViewed') && PerformancePrefs::getBoolean('LISTVIEW_RECORD_CHANGE_INDICATOR', true)) { + if(!$focus->isViewed($entity_id)) { + $links_info .= " | "; + } + } + // END + if($links_info != "" && !$skipActions) + $list_header[] = $links_info; + $list_block[$entity_id] = $list_header; + + } + $log->debug("Exiting getListViewEntries method ..."); + return $list_block; + +} + +/**This function generates the List view entries in a popup list view +*Param $focus - module object +*Param $list_result - resultset of a listview query +*Param $navigation_array - navigation values in an array +*Param $relatedlist - check for related list flag +*Param $returnset - list query parameters in url string +*Param $edit_action - Edit action value +*Param $del_action - delete action value +*Param $oCv - vtiger_customview object +*Returns an array type +*/ + + +function getSearchListViewEntries($focus, $module,$list_result,$navigation_array,$form='') +{ + global $log; + $log->debug("Entering getSearchListViewEntries(".get_class($focus).",". $module.",".$list_result.",".$navigation_array.") method ..."); + + global $adb,$app_strings,$theme,$current_user,$list_max_entries_per_page; + $noofrows = $adb->num_rows($list_result); + + $list_header = ''; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + $list_block = Array(); + + //getting the vtiger_fieldtable entries from database + $tabid = getTabid($module); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + //Added to reduce the no. of queries logging for non-admin user -- by Minnie-start + $field_list = array(); + $j=0; + foreach($focus->search_fields as $name=>$tableinfo) + { + $fieldname = $focus->search_fields_name[$name]; + array_push($field_list, $fieldname); + $j++; + } + + $field=Array(); + if($is_admin==false && $module != 'Users') + { + if($module == 'Emails') + { + $query = "SELECT fieldname FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; + $params = array($tabid); + } + else + { + $profileList = getCurrentUserProfileList(); + $query = "SELECT DISTINCT vtiger_field.fieldname + FROM vtiger_field + INNER JOIN vtiger_profile2field + ON vtiger_profile2field.fieldid = vtiger_field.fieldid + INNER JOIN vtiger_def_org_field + ON vtiger_def_org_field.fieldid = vtiger_field.fieldid + WHERE vtiger_field.tabid = ? + AND vtiger_profile2field.visible = 0 + AND vtiger_def_org_field.visible = 0 + AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") + AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2)"; + $params = array($tabid, $profileList, $field_list); + } + + $result = $adb->pquery($query, $params); + + for($k=0;$k < $adb->num_rows($result);$k++) + { + $field[]=$adb->query_result($result,$k,"fieldname"); + } + } + //constructing the uitype and columnname array + $ui_col_array=Array(); + + $query = "SELECT uitype, columnname, fieldname + FROM vtiger_field + WHERE tabid=? + AND fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($query, array($tabid, $field_list)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $tempArr=array(); + $uitype=$adb->query_result($result,$i,'uitype'); + $columnname=$adb->query_result($result,$i,'columnname'); + $field_name=$adb->query_result($result,$i,'fieldname'); + $tempArr[$uitype]=$columnname; + $ui_col_array[$field_name]=$tempArr; + } + + //end + if($navigation_array['end_val'] > 0) + { + for ($i=1; $i<=$noofrows; $i++) + { + + //Getting the entityid + if($module != 'Users') + { + $entity_id = $adb->query_result($list_result,$i-1,"crmid"); + }else + { + $entity_id = $adb->query_result($list_result,$i-1,"id"); + } + + $list_header=Array(); + + foreach($focus->search_fields as $name=>$tableinfo) + { + $fieldname = $focus->search_fields_name[$name]; + + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field) || $module == 'Users') + { + if($fieldname == '') + { + $table_name = ''; + $column_name = ''; + foreach($tableinfo as $tablename=>$colname) + { + $table_name=$tablename; + $column_name = $colname; + } + $value = $adb->query_result($list_result,$i-1,$colname); + } + else + { + if(($module == 'Calls' || $module == 'Tasks' || $module == 'Meetings' || $module == 'Emails') && (($name=='Related to') || ($name=='Contact Name') || ($name=='Vendor Name'))) + { + if ($name=='Related to') + $value=getRelatedTo($module,$list_result,$i-1); + if($name=='Contact Name') + { + $contact_id = $adb->query_result($list_result,$i-1,"contactid"); + $contact_name = getFullNameFromQResult($list_result,$i-1,"Contacts"); + $value=""; + if(($contact_name != "") && ($contact_id !='NULL')) + $value = "".$contact_name.""; + } + } + elseif(($module == 'Faq' || $module == 'Documents') && $name=='Related to') + { + $value=getRelatedToEntity($module,$list_result,$i-1); + } + elseif($name=='Account Name' && ($module == 'Potentials' || $module == 'SalesOrder' || $module == 'Quotes')) + { + $account_id = $adb->query_result($list_result,$i-1,"accountid"); + $account_name = getAccountName($account_id); + $value = textlength_check($account_name); + } + elseif($name=='Quote Name' && $module == 'SalesOrder') + { + $quote_id = $adb->query_result($list_result,$i-1,"quoteid"); + $quotename = getQuoteName($quote_id); + $value = textlength_check($quotename); + } + elseif($name == 'Account Name' && $module=='Contacts' ) + { + $account_id = $adb->query_result($list_result,$i-1,"accountid"); + $account_name = getAccountName($account_id); + $value = textlength_check($account_name); + } + // vtlib customization: Generic popup handling + elseif(isset($focus->popup_fields) && in_array($fieldname, $focus->popup_fields)) { + global $default_charset; + $forfield = htmlspecialchars($_REQUEST['forfield'], ENT_QUOTES, $default_charset); + $list_result_count = $i-1; + $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"search",$focus->popup_type); + if(isset($forfield) && $forfield != '' && $focus->popup_type != 'detailview') { + $value = strip_tags($value); // Remove any previous html conversion + $value = "$value"; + } + } + // END + else + { + $list_result_count = $i-1; + $value = getValue($ui_col_array,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"search",$focus->popup_type, $form); + } + + } + $list_header[]=$value; + } + } + + if($module=='Products' && ($focus->popup_type=='inventory_prod' || $focus->popup_type=='inventory_prod_po')) + { + global $default_charset; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $row_id = $_REQUEST['curr_row']; + + //To get all the tax types and values and pass it to product details + $tax_str = ''; + $tax_details = getAllTaxes(); + for($tax_count=0;$tax_countid,'unit_price') == '0') { + $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); + if($_REQUEST['currencyid'] != null) { + $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id)); + $unitprice = $prod_prices[$entity_id]; + } + } else { + $unit_price = ''; + } + $sub_products = ''; + $sub_prod = ''; + $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'",array($entity_id)); + for($k=0;$k<$adb->num_rows($sub_prod_query);$k++){ + //$sub_prod=array(); + $id = $adb->query_result($sub_prod_query,$k,"productid"); + $str_sep=''; + if($k>0) $str_sep = ":"; + $sub_products .= $str_sep.$id; + $sub_prod .= $str_sep." - ".$adb->query_result($sub_prod_query,$k,"productname"); + } + + $sub_det = $sub_products."::".str_replace(":","
",$sub_prod); + $qty_stock=$adb->query_result($list_result,$list_result_count,'qtyinstock'); + + $slashes_temp_val = popup_from_html(getProductName($entity_id)); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $description=$adb->query_result($list_result,$list_result_count,'description'); + $slashes_desc = htmlspecialchars($description,ENT_QUOTES,$default_charset); + + $sub_products_link = ' Sub Products'; + + if(!isset($_REQUEST['record_id'])){ + $sub_products_query = $adb->pquery("SELECT * from vtiger_seproductsrel WHERE productid=? AND setype='Products'",array($entity_id)); + if($adb->num_rows($sub_products_query)>0) + $list_header[]=$sub_products_link; + else + $list_header[]= $app_strings['LBL_NO_SUB_PRODUCTS']; + } + } + + if($module=='Services' && $focus->popup_type=='inventory_service') + { + global $default_charset; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $row_id = $_REQUEST['curr_row']; + + //To get all the tax types and values and pass it to product details + $tax_str = ''; + $tax_details = getAllTaxes(); + for($tax_count=0;$tax_countid,'unit_price') == '0') { + $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); + if($_REQUEST['currencyid'] != null) { + $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module); + $unitprice = $prod_prices[$entity_id]; + } + } else { + $unit_price = ''; + } + + $slashes_temp_val = popup_from_html($adb->query_result($list_result,$list_result_count,'servicename')); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $description=$adb->query_result($list_result,$list_result_count,'description'); + $slashes_desc = htmlspecialchars($description,ENT_QUOTES,$default_charset); + } + $list_block[$entity_id]=$list_header; + } + } + $list = $list_block; + $log->debug("Exiting getSearchListViewEntries method ..."); + return $list; +} + + +/**This function generates the value for a given vtiger_field namee +*Param $field_result - vtiger_field result in array +*Param $list_result - resultset of a listview query +*Param $fieldname - vtiger_field name +*Param $focus - module object +*Param $module - module name +*Param $entity_id - entity id +*Param $list_result_count - list result count +*Param $mode - mode type +*Param $popuptype - popup type +*Param $returnset - list query parameters in url string +*Param $viewid - custom view id +*Returns an string value +*/ + + +function getValue($field_result, $list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,$mode,$popuptype,$returnset='',$viewid='') +{ + global $log, $listview_max_textlength, $app_strings, $current_language,$currentModule; + $log->debug("Entering getValue(".$field_result.",". $list_result.",".$fieldname.",".get_class($focus).",".$module.",".$entity_id.",".$list_result_count.",".$mode.",".$popuptype.",".$returnset.",".$viewid.") method ..."); + global $adb, $current_user, $default_charset; + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $tabname = getParentTab(); + $tabid = getTabid($module); + $current_module_strings = return_module_language($current_language, $module); + $uicolarr=$field_result[$fieldname]; + foreach($uicolarr as $key=>$value) + { + $uitype = $key; + $colname = $value; + } + //added for getting event status in Custom view - Jaguar + if($module == 'Calendar' && ($colname == "status" || $colname == "eventstatus")) + { + $colname="activitystatus"; + } + //Ends + $field_val = $adb->query_result($list_result,$list_result_count,$colname); + if(stristr(html_entity_decode($field_val), "$value){ + $displayValue = $value; + } + } + $value = "$displayValue"; + } else { + $value = ''; + } + } // END + else if($uitype == 53) + { + $value = textlength_check($adb->query_result($list_result,$list_result_count,'user_name')); + // When Assigned To field is used in Popup window + if($value == '' ) { + $user_id = $adb->query_result($list_result,$list_result_count,'smownerid'); + if ($user_id != null && $user_id != '') { + $value = getOwnerName($user_id); + } + } + } + elseif($uitype == 52) + { + $value = getUserName($adb->query_result($list_result,$list_result_count,$colname)); + } + elseif($uitype == 51)//Accounts - Member Of + { + $parentid = $adb->query_result($list_result,$list_result_count,"parentid"); + if($module=='Accounts') + $entity_name = textlength_check(getAccountName($parentid)); + elseif($module == 'Products') + $entity_name = textlength_check(getProductName($parentid)); + $value = ''.$entity_name.''; + + } + elseif($uitype == 77) + { + $value = getUserName($adb->query_result($list_result,$list_result_count,'inventorymanager')); + } + elseif($uitype == 5 || $uitype == 6 || $uitype == 23 || $uitype == 70) + { + if($temp_val != '' && $temp_val != '0000-00-00') + { + $value = getDisplayDate($temp_val); + } + elseif($temp_val == '0000-00-00') + { + $value = ''; + } + else + { + $value = $temp_val; + } + + + } + elseif($uitype == 15 || ($uitype == 55 && $fieldname =="salutationtype")) + { + $temp_val = decode_html($adb->query_result($list_result,$list_result_count,$colname)); + if(($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) && $temp_val != '') + { + $temp_acttype = $adb->query_result($list_result,$list_result_count,'activitytype'); + if(($temp_acttype != 'Task') && $fieldname =="taskstatus") + $temptable = "eventstatus"; + else + $temptable = $fieldname; + $roleid=$current_user->roleid; + $roleids = Array(); + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + $roleids = $subrole; + array_push($roleids, $roleid); + + //here we are checking wheather the table contains the sortorder column .If sortorder is present in the main picklist table, then the role2picklist will be applicable for this table... + + $sql="select * from vtiger_$temptable where $temptable=?"; + $res = $adb->pquery($sql,array(decode_html($temp_val))); + $picklistvalueid = $adb->query_result($res,0,'picklist_valueid'); + if ($picklistvalueid != null) { + $pick_query="select * from vtiger_role2picklist where picklistvalueid=$picklistvalueid and roleid in (". generateQuestionMarks($roleids) .")"; + $res_val=$adb->pquery($pick_query,array($roleids)); + $num_val = $adb->num_rows($res_val); + } + if($num_val > 0 || ($temp_acttype == 'Task' && $fieldname == 'activitytype')) + $temp_val = $temp_val; + else + $temp_val = "".$app_strings['LBL_NOT_ACCESSIBLE'].""; + } + $value = ($current_module_strings[$temp_val] != '') ? $current_module_strings[$temp_val] : (($app_strings[$temp_val] != '') ? ($app_strings[$temp_val]) : $temp_val); + if($value != "".$app_strings['LBL_NOT_ACCESSIBLE']."") + { + $value = textlength_check($value); + } + } + elseif ($uitype == 16) + { + $value = getTranslatedString($temp_val,$currentModule); + } + elseif($uitype == 71 || $uitype == 72) + { + if($temp_val != '') + { + if($fieldname == 'unit_price') { + $currency_id = getProductBaseCurrency($entity_id,$module); + $cursym_convrate = getCurrencySymbolandCRate($currency_id); + $value = "".$cursym_convrate['symbol']." ". $temp_val; + } else { + $rate = $user_info['conv_rate']; + //changes made to remove vtiger_currency symbol infront of each vtiger_potential amount + if ($temp_val != 0) $value = convertFromDollar($temp_val,$rate); + else $value = $temp_val; + } + } + else + { + $value = ''; + } + + } + elseif($uitype == 17) + { + $value = ''.$temp_val.''; + } + elseif($uitype == 13 || $uitype == 104 && ($_REQUEST['action'] != 'Popup' && $_REQUEST['file'] != 'Popup')) + { + if($_SESSION['internal_mailer'] == 1) + { + //check added for email link in user detailview + if($module == 'Calendar') { + if(getActivityType($entity_id) == 'Task') { + $tabid = 9; + } else { + $tabid = 16; + } + } else { + $tabid = getTabid($module); + } + $fieldid = getFieldid($tabid, $fieldname); + if(empty($popuptype)){ + $value = ''.$temp_val.''; + } else { + $value = $temp_val; + } + } + else + $value = ''.$temp_val.''; + } + elseif($uitype == 56) + { + if($temp_val == 1) + { + $value = $app_strings['yes']; + } + elseif($temp_val == 0) + { + $value = $app_strings['no']; + } + else { + $value = ''; + } + } + elseif($uitype == 57) + { + if($temp_val != '') + { + $sql="SELECT * FROM vtiger_contactdetails WHERE contactid=?"; + $result=$adb->pquery($sql, array($temp_val)); + $value = ''; + if($adb->num_rows($result)) { + $name=getFullNameFromQResult($result,0,"Contacts"); + $value= ''.$name.''; + } + } + else + $value=''; + } + //Added by Minnie to get Campaign Source + elseif($uitype == 58) + { + if($temp_val != '') + { + $sql="SELECT * FROM vtiger_campaign WHERE campaignid=?"; + $result=$adb->pquery($sql, array($temp_val)); + $campaignname=$adb->query_result($result,0,"campaignname"); + $value= ''.$campaignname.''; + } + else + $value=''; + } + //End + //Added By *Raj* for the Issue ProductName not displayed in CustomView of HelpDesk + elseif($uitype == 59) + { + if($temp_val != '') + { + $value = getProductName($temp_val); + } + else + { + $value = ''; + } + } + //End + elseif($uitype == 61) + { + $attachmentid=$adb->query_result($adb->pquery("SELECT * FROM vtiger_seattachmentsrel WHERE crmid = ?", array($entity_id)),0,'attachmentsid'); + $value = ''.$temp_val.''; + } + elseif($uitype == 62) + { + $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); + $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); + + if($parenttype == "Leads") + { + $tablename = "vtiger_leaddetails"; $fieldname = "lastname"; $idname="leadid"; + } + if($parenttype == "Accounts") + { + $tablename = "vtiger_account"; $fieldname = "accountname"; $idname="accountid"; + } + if($parenttype == "Products") + { + $tablename = "vtiger_products"; $fieldname = "productname"; $idname="productid"; + } + if($parenttype == "HelpDesk") + { + $tablename = "vtiger_troubletickets"; $fieldname = "title"; $idname="ticketid"; + } + if($parenttype == "Invoice") + { + $tablename = "vtiger_invoice"; $fieldname = "subject"; $idname="invoiceid"; + } + + + if($parentid != '') + { + $sql="SELECT * FROM $tablename WHERE $idname = ?"; + $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); + + $value=''.$fieldvalue.''; + } + else + $value=''; + } + elseif($uitype == 66) + { + $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); + $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); + + if($parenttype == "Leads") + { + $tablename = "vtiger_leaddetails"; $fieldname = "lastname"; $idname="leadid"; + } + if($parenttype == "Accounts") + { + $tablename = "vtiger_account"; $fieldname = "accountname"; $idname="accountid"; + } + if($parenttype == "HelpDesk") + { + $tablename = "vtiger_troubletickets"; $fieldname = "title"; $idname="ticketid"; + } + if($parentid != '') + { + $sql="SELECT * FROM $tablename WHERE $idname = ?"; + $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); + + $value=''.$fieldvalue.''; + } + else + $value=''; + } + elseif($uitype == 67) + { + $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); + $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); + + if($parenttype == "Leads") + { + $tablename = "vtiger_leaddetails"; $fieldname = "lastname"; $idname="leadid"; + } + if($parenttype == "Contacts") + { + $tablename = "vtiger_contactdetails"; $fieldname = "contactname"; $idname="contactid"; + } + if($parentid != '') + { + $sql="SELECT * FROM $tablename WHERE $idname = ?"; + $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); + + $value=''.$fieldvalue.''; + } + else + $value=''; + } + elseif($uitype == 68) + { + $parentid = $adb->query_result($list_result,$list_result_count,"parent_id"); + $parenttype = $adb->query_result($list_result,$list_result_count,"parent_type"); + + if($parenttype == '' && $parentid != '') + $parenttype = getSalesEntityType($parentid); + + if($parenttype == "Contacts") + { + $tablename = "vtiger_contactdetails"; $fieldname = "contactname"; $idname="contactid"; + } + if($parenttype == "Accounts") + { + $tablename = "vtiger_account"; $fieldname = "accountname"; $idname="accountid"; + } + if($parentid != '') + { + $sql="SELECT * FROM $tablename WHERE $idname = ?"; + $fieldvalue=$adb->query_result($adb->pquery($sql, array($parentid)),0,$fieldname); + + $value=''.$fieldvalue.''; + } + else + $value=''; + } + elseif($uitype == 78) + { + if($temp_val != '') + { + + $quote_name = getQuoteName($temp_val); + $value= ''.textlength_check($quote_name).''; + } + else + $value=''; + } + elseif($uitype == 79) + { + if($temp_val != '') + { + + $purchaseorder_name = getPoName($temp_val); + $value= ''.textlength_check($purchaseorder_name).''; + } + else + $value=''; + } + elseif($uitype == 80) + { + if($temp_val != '') + { + + $salesorder_name = getSoName($temp_val); + $value= "".textlength_check($salesorder_name).''; + } + else + $value=''; + } + elseif($uitype == 75 || $uitype == 81) + { + + if($temp_val != '') + { + + $vendor_name = getVendorName($temp_val); + $value= ''.textlength_check($vendor_name).''; + } + else + $value=''; + } + elseif($uitype == 98) + { + $value = ''.textlength_check(getRoleName($temp_val)).''; + } + elseif($uitype == 33) + { + $value = ($temp_val != "") ? str_ireplace(' |##| ',', ',$temp_val) : ""; + if(!$is_admin && $value != '') + { + $value = ($field_val != "") ? str_ireplace(' |##| ',', ',$field_val) : ""; + if($value != '') + { + $value_arr=explode(',',trim($value)); + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + + if (count($roleids) > 0) { + $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_$fieldname) order by $fieldname asc"; + $params = array($roleids); + } else { + $pick_query="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where picklistid in (select picklistid from vtiger_$fieldname) order by $fieldname asc"; + $params = array(); + } + $pickListResult = $adb->pquery($pick_query, $params); + $picklistval = Array(); + for($i=0;$i<$adb->num_rows($pickListResult);$i++) + { + $picklistarr[]=$adb->query_result($pickListResult,$i,$fieldname); + } + $value_temp = Array(); + $string_temp = ''; + $str_c = 0; + foreach($value_arr as $ind => $val) + { + $notaccess = ''.$app_strings['LBL_NOT_ACCESSIBLE'].""; + if(!$listview_max_textlength || !(strlen(preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$string_temp)) > $listview_max_textlength)) + { + $value_temp1 = (in_array(trim($val),$picklistarr))?$val:$notaccess; + if($str_c!=0) + $string_temp .= ' , '; + $string_temp .= $value_temp1; + $str_c++; + } + else + $string_temp .='...'; + + } + $value=$string_temp; + } + } + } + elseif($uitype == 85) + { + $value = ($temp_val != "") ? "{$temp_val}" : ""; + } + elseif($uitype == 116) + { + $value = ($temp_val != "") ? getCurrencyName($temp_val) : ""; + } + elseif($uitype == 117) + { + // NOTE: Without symbol the value could be used for filtering/lookup hence avoiding the translation + $value = ($temp_val != "") ? getCurrencyName($temp_val,false) : ""; + } + elseif($uitype == 26){ + $sql ="select foldername from vtiger_attachmentsfolder where folderid = ?"; + $res = $adb->pquery($sql,array($temp_val)); + $foldername = $adb->query_result($res,0,'foldername'); + $value = $foldername; + } + //added for asterisk integration + elseif($uitype == 11){ + // Fix added for Trac Id: 6139 + if(vtlib_isModuleActive('PBXManager')) { + $value = "".$temp_val.""; + } else { + $value = $temp_val; + } + } + //asterisk changes end here + //Added for email status tracking + elseif($uitype == 25) + { + $contactid=$_REQUEST['record']; + $emailid=$adb->query_result($list_result,$list_result_count,"activityid"); + $result = $adb->pquery("SELECT access_count FROM vtiger_email_track WHERE crmid=? AND mailid=?", array($contactid,$emailid)); + $value=$adb->query_result($result,0,"access_count"); + if(!$value) { + $value = 0; + } + }elseif($uitype == 8){ + if(!empty($temp_val)){ + $temp_val = html_entity_decode($temp_val,ENT_QUOTES,$default_charset); + $json = new Zend_Json(); + $value = vt_suppressHTMLTags(implode(',',$json->decode($temp_val))); + } + } + //end email status tracking + else + { + if($fieldname == $focus->list_link_field) + { + if($mode == "search") + { + if($popuptype == "specific" || $popuptype=="toDospecific") + { + // Added for get the first name of contact in Popup window + if($colname == "lastname" && $module == 'Contacts') + { + $temp_val = getFullNameFromQResult($list_result,$list_result_count,"Contacts"); + } + + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + //Added to avoid the error when select SO from Invoice through AjaxEdit + if($module == 'SalesOrder') + $value = ''.$temp_val.''; + + elseif($module =='Contacts'){ + require_once('modules/Contacts/Contacts.php'); + $cntct_focus = new Contacts(); + $cntct_focus->retrieve_entity_info($entity_id,"Contacts"); + $slashes_temp_val = popup_from_html($temp_val); + //ADDED TO CHECK THE FIELD PERMISSIONS FOR + $xyz=array('mailingstreet','mailingcity','mailingzip','mailingpobox','mailingcountry','mailingstate','otherstreet','othercity','otherzip','otherpobox','othercountry','otherstate'); + for($i=0;$i<12;$i++){ + if (getFieldVisibilityPermission($module, $current_user->id,$xyz[$i]) == '0'){ + $cntct_focus->column_fields[$xyz[$i]] = $cntct_focus->column_fields[$xyz[$i]]; + } + else + $cntct_focus->column_fields[$xyz[$i]] = ''; + } + // For ToDo creation the underlying form is not named as EditView + $form = !empty($_REQUEST['form']) ? $_REQUEST['form'] : ''; + if(!empty($form)) $form = htmlspecialchars($form,ENT_QUOTES,$default_charset); + $value = 'column_fields['mailingstreet']).'", "'.popup_decode_html($cntct_focus->column_fields['otherstreet']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingcity']).'", "'.popup_decode_html($cntct_focus->column_fields['othercity']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingstate']).'", "'.popup_decode_html($cntct_focus->column_fields['otherstate']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingzip']).'", "'.popup_decode_html($cntct_focus->column_fields['otherzip']).'", "'.popup_decode_html($cntct_focus->column_fields['mailingcountry']).'", "'.popup_decode_html($cntct_focus->column_fields['othercountry']).'","'.popup_decode_html($cntct_focus->column_fields['mailingpobox']).'", "'.popup_decode_html($cntct_focus->column_fields['otherpobox']).'","'.$form.'");\'>'.$temp_val.''; + } + + else + if($popuptype=='toDospecific') + $value = ''.$temp_val.''; + else + $value = ''.$temp_val.''; + } + elseif($popuptype == "detailview") + { + if($colname == "lastname" && ($module == 'Contacts' || $module == 'Leads')) { + $temp_val = getFullNameFromQResult($list_result,$list_result_count,$module); + } + + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + $focus->record_id = $_REQUEST['recordid']; + if($_REQUEST['return_module'] == "Calendar") + { + $value = ''.$temp_val.''; + } + else + $value = 'record_id.'","'.$module.'");\'>'.$temp_val.''; + } + elseif($popuptype == "formname_specific") + { + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + $value = ''.$temp_val.''; + } + elseif($popuptype == "inventory_prod") + { + $row_id = $_REQUEST['curr_row']; + + //To get all the tax types and values and pass it to product details + $tax_str = ''; + $tax_details = getAllTaxes(); + for($tax_count=0;$tax_countid,'unit_price') == '0') { + $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); + if($_REQUEST['currencyid'] != null) { + $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id)); + $unitprice = $prod_prices[$entity_id]; + } + } else { + $unit_price = ''; + } + $sub_products = ''; + $sub_prod = ''; + $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname,vtiger_products.qtyinstock,vtiger_crmentity.description from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'",array($entity_id)); + for($i=0;$i<$adb->num_rows($sub_prod_query);$i++){ + //$sub_prod=array(); + $id = $adb->query_result($sub_prod_query,$i,"productid"); + $str_sep=''; + if($i>0) $str_sep = ":"; + $sub_products .= $str_sep.$id; + $sub_prod .= $str_sep." - ".$adb->query_result($sub_prod_query,$i,"productname"); + } + + $sub_det = $sub_products."::".str_replace(":","
",$sub_prod); + $qty_stock=$adb->query_result($list_result,$list_result_count,'qtyinstock'); + + //fix for T6943 + + $slashes_temp_val = popup_from_html($field_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $description = popup_from_html($adb->query_result($list_result,$list_result_count,'description')); + $slashes_temp_desc = decode_html(nl2br(htmlspecialchars($description,ENT_QUOTES,$default_charset))); + $slashes_desc = stripslashes($slashes_temp_desc); + + $slashes_desc = str_replace(array("\r","\n"),array('\r','\n'), $slashes_desc); + $tmp_arr = array("entityid"=>$entity_id,"prodname"=>"".stripslashes(decode_html(nl2br($slashes_temp_val)))."","unitprice" => "$unitprice", "qtyinstk"=>"$qty_stock","taxstring"=>"$tax_str","rowid"=>"$row_id","desc"=>"$slashes_desc","subprod_ids"=>"$sub_det"); + require_once('include/Zend/Json.php'); + $prod_arr = Zend_Json::encode($tmp_arr); + $value = ''.$temp_val.''; + } + elseif($popuptype == "inventory_prod_po") + { + $row_id = $_REQUEST['curr_row']; + + //To get all the tax types and values and pass it to product details + $tax_str = ''; + $tax_details = getAllTaxes(); + for($tax_count=0;$tax_countid,'unit_price') == '0') { + $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); + if($_REQUEST['currencyid'] != null) { + $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module); + $unitprice = $prod_prices[$entity_id]; + } + } else { + $unit_price = ''; + } + $sub_products = ''; + $sub_prod = ''; + $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname,vtiger_products.qtyinstock,vtiger_crmentity.description from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'",array($entity_id)); + for($i=0;$i<$adb->num_rows($sub_prod_query);$i++){ + //$sub_prod=array(); + $id = $adb->query_result($sub_prod_query,$i,"productid"); + $str_sep=''; + if($i>0) $str_sep = ":"; + $sub_products .= $str_sep.$id; + $sub_prod .= $str_sep." - $id.".$adb->query_result($sub_prod_query,$i,"productname"); + } + + $sub_det = $sub_products."::".str_replace(":","
",$sub_prod); + + $slashes_temp_val = popup_from_html($field_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $description = popup_from_html($adb->query_result($list_result,$list_result_count,'description')); + $slashes_temp_desc = decode_html(nl2br(htmlspecialchars($description,ENT_QUOTES,$default_charset))); + $slashes_desc = stripslashes($slashes_temp_desc); + + $slashes_desc = str_replace(array("\r","\n"),array('\r','\n'), $slashes_desc); + $tmp_arr = array("entityid"=>$entity_id,"prodname"=>"".stripslashes(decode_html(nl2br($slashes_temp_val)))."","unitprice" => "$unitprice", "qtyinstk"=>"$qty_stock","taxstring"=>"$tax_str","rowid"=>"$row_id","desc"=>"$slashes_desc","subprod_ids"=>"$sub_det"); + require_once('include/Zend/Json.php'); + $prod_arr = Zend_Json::encode($tmp_arr); + $value = ''.$temp_val.''; + } + elseif($popuptype == "inventory_service") + { + $row_id = $_REQUEST['curr_row']; + + //To get all the tax types and values and pass it to product details + $tax_str = ''; + $tax_details = getAllTaxes(); + for($tax_count=0;$tax_countid,'unit_price') == '0') { + $unitprice=$adb->query_result($list_result,$list_result_count,'unit_price'); + if($_REQUEST['currencyid'] != null) { + $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module); + $unitprice = $prod_prices[$entity_id]; + } + } else { + $unit_price = ''; + } + + $slashes_temp_val = popup_from_html($field_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $description = popup_from_html($adb->query_result($list_result,$list_result_count,'description')); + $slashes_temp_desc = decode_html(nl2br(htmlspecialchars($description,ENT_QUOTES,$default_charset))); + $slashes_desc = stripslashes($slashes_temp_desc); + + $slashes_desc = str_replace(array("\r","\n"),array('\r','\n'), $slashes_desc); + $tmp_arr = array("entityid"=>$entity_id,"prodname"=>"".stripslashes(decode_html(nl2br($slashes_temp_val)))."","unitprice" => "$unitprice","taxstring"=>"$tax_str","rowid"=>"$row_id","desc"=>"$slashes_desc"); + require_once('include/Zend/Json.php'); + $prod_arr = Zend_Json::encode($tmp_arr); + + $value = ''.$temp_val.''; + } + elseif($popuptype == "inventory_pb") + { + + $prod_id = $_REQUEST['productid']; + $flname = $_REQUEST['fldname']; + $listprice=getListPrice($prod_id,$entity_id); + + $temp_val = popup_from_html($temp_val); + $value = ''.$temp_val.''; + } + elseif($popuptype == "specific_account_address") + { + require_once('modules/Accounts/Accounts.php'); + $acct_focus = new Accounts(); + $acct_focus->retrieve_entity_info($entity_id,"Accounts"); + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); + for($i=0;$i<12;$i++){ + if (getFieldVisibilityPermission($module, $current_user->id,$xyz[$i]) == '0'){ + $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]]; + } + else + $acct_focus->column_fields[$xyz[$i]] = ''; + } + $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['bill_street'])); + $ship_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['ship_street'])); + + $value = 'column_fields['bill_city']).'", "'.popup_decode_html($acct_focus->column_fields['ship_city']).'", "'.popup_decode_html($acct_focus->column_fields['bill_state']).'", "'.popup_decode_html($acct_focus->column_fields['ship_state']).'", "'.popup_decode_html($acct_focus->column_fields['bill_code']).'", "'.popup_decode_html($acct_focus->column_fields['ship_code']).'", "'.popup_decode_html($acct_focus->column_fields['bill_country']).'", "'.popup_decode_html($acct_focus->column_fields['ship_country']).'","'.popup_decode_html($acct_focus->column_fields['bill_pobox']).'", "'.popup_decode_html($acct_focus->column_fields['ship_pobox']).'");\'>'.$temp_val.''; + + } + elseif($popuptype == "specific_contact_account_address") + { + require_once('modules/Accounts/Accounts.php'); + $acct_focus = new Accounts(); + $acct_focus->retrieve_entity_info($entity_id,"Accounts"); + + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['bill_street'])); + $ship_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['ship_street'])); + + $value = 'column_fields['bill_city']).'", "'.popup_decode_html($acct_focus->column_fields['ship_city']).'", "'.popup_decode_html($acct_focus->column_fields['bill_state']).'", "'.popup_decode_html($acct_focus->column_fields['ship_state']).'", "'.popup_decode_html($acct_focus->column_fields['bill_code']).'", "'.popup_decode_html($acct_focus->column_fields['ship_code']).'", "'.popup_decode_html($acct_focus->column_fields['bill_country']).'", "'.popup_decode_html($acct_focus->column_fields['ship_country']).'","'.popup_decode_html($acct_focus->column_fields['bill_pobox']).'", "'.popup_decode_html($acct_focus->column_fields['ship_pobox']).'");\'>'.$temp_val.''; + + } + elseif($popuptype == "specific_potential_account_address") + { + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + // For B2C support, Potential was enabled to be linked to Contacts also. + // Hence we need case handling for it. + $relatedid = $adb->query_result($list_result,$list_result_count,"related_to"); + $relatedentity = getSalesEntityType($relatedid); + if($relatedentity == 'Accounts') { + require_once('modules/Accounts/Accounts.php'); + $acct_focus = new Accounts(); + $acct_focus->retrieve_entity_info($relatedid,"Accounts"); + $account_name = getAccountName($relatedid); + + $slashes_account_name = popup_from_html($account_name); + $slashes_account_name = htmlspecialchars($slashes_account_name,ENT_QUOTES,$default_charset); + + $xyz=array('bill_street','bill_city','bill_code','bill_pobox','bill_country','bill_state','ship_street','ship_city','ship_code','ship_pobox','ship_country','ship_state'); + for($i=0;$i<12;$i++){ + if (getFieldVisibilityPermission('Accounts', $current_user->id,$xyz[$i]) == '0'){ + $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]]; + } + else + $acct_focus->column_fields[$xyz[$i]] = ''; + } + $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['bill_street'])); + $ship_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['ship_street'])); + + $value = 'column_fields['bill_city']).'", "'.popup_decode_html($acct_focus->column_fields['ship_city']).'", "'.popup_decode_html($acct_focus->column_fields['bill_state']).'", "'.popup_decode_html($acct_focus->column_fields['ship_state']).'", "'.popup_decode_html($acct_focus->column_fields['bill_code']).'", "'.popup_decode_html($acct_focus->column_fields['ship_code']).'", "'.popup_decode_html($acct_focus->column_fields['bill_country']).'", "'.popup_decode_html($acct_focus->column_fields['ship_country']).'","'.popup_decode_html($acct_focus->column_fields['bill_pobox']).'", "'.popup_decode_html($acct_focus->column_fields['ship_pobox']).'");\'>'.$temp_val.''; + } else if($relatedentity == 'Contacts') { + + require_once('modules/Contacts/Contacts.php'); + $contact_name = getContactName($relatedid); + + $slashes_contact_name = popup_from_html($contact_name); + $slashes_contact_name = htmlspecialchars($slashes_contact_name,ENT_QUOTES,$default_charset); + + $value = ''.$temp_val.''; + + } else { + $value = $temp_val; + } + } + //added by rdhital/Raju for better emails + elseif($popuptype == "set_return_emails") + { + if ($module=='Accounts') + { + $name = $adb->query_result($list_result,$list_result_count,'accountname'); + $accid =$adb->query_result($list_result,$list_result_count,'accountid'); + if(CheckFieldPermission('email1',$module) == "true") + { + $emailaddress=$adb->query_result($list_result,$list_result_count,"email1"); + $email_check = 1; + } + else + $email_check = 0; + if($emailaddress == '') + { + if(CheckFieldPermission('email2',$module) == 'true') + { + $emailaddress2=$adb->query_result($list_result,$list_result_count,"email2"); + $email_check = 2; + } + else + { + if($email_check == 1) + $email_check = 4; + else + $email_check = 3; + } + } + $querystr="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; + $queryres = $adb->pquery($querystr, array(getTabid($module))); + //Change this index 0 - to get the vtiger_fieldid based on email1 or email2 + $fieldid = $adb->query_result($queryres,0,'fieldid'); + + $slashes_name = popup_from_html($name); + $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); + + $value = ''.textlength_check($name).''; + + }elseif ($module=='Vendors') + { + $name = $adb->query_result($list_result,$list_result_count,'vendorname'); + $venid =$adb->query_result($list_result,$list_result_count,'vendorid'); + if(CheckFieldPermission('email',$module) == "true") + { + $emailaddress=$adb->query_result($list_result,$list_result_count,"email"); + $email_check = 1; + } + else + $email_check = 0; + $querystr="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; + $queryres = $adb->pquery($querystr, array(getTabid($module))); + //Change this index 0 - to get the vtiger_fieldid based on email1 or email2 + $fieldid = $adb->query_result($queryres,0,'fieldid'); + + $slashes_name = popup_from_html($name); + $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); + + $value = ''.textlength_check($name).''; + + }elseif ($module=='Contacts' || $module=='Leads') + { + $name=getFullNameFromQResult($list_result,$list_result_count,$module); + if(CheckFieldPermission('email',$module) == "true") + { + $emailaddress=$adb->query_result($list_result,$list_result_count,"email"); + $email_check = 1; + } + else + $email_check = 0; + if($emailaddress == '') + { + if(CheckFieldPermission('yahooid',$module) == 'true') + { + $emailaddress2=$adb->query_result($list_result,$list_result_count,"yahooid"); + $email_check = 2; + } + else{ + if($email_check == 1) + $email_check = 4; + else + $email_check = 3; + } + } + + $querystr="SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; + $queryres = $adb->pquery($querystr, array(getTabid($module))); + //Change this index 0 - to get the vtiger_fieldid based on email or yahooid + $fieldid = $adb->query_result($queryres,0,'fieldid'); + + $slashes_name = popup_from_html($name); + $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); + + $value = ''.$name.''; + + }else + { + $firstname=$adb->query_result($list_result,$list_result_count,"first_name"); + $lastname=$adb->query_result($list_result,$list_result_count,"last_name"); + $name=$lastname.' '.$firstname; + $emailaddress=$adb->query_result($list_result,$list_result_count,"email1"); + + $slashes_name = popup_from_html($name); + $slashes_name = htmlspecialchars($slashes_name,ENT_QUOTES,$default_charset); + $email_check = 1; + $value = ''.textlength_check($name) .''; + + } + + } + elseif($popuptype == "specific_vendor_address") + { + require_once('modules/Vendors/Vendors.php'); + $acct_focus = new Vendors(); + $acct_focus->retrieve_entity_info($entity_id,"Vendors"); + + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + $xyz=array('street','city','postalcode','pobox','country','state'); + for($i=0;$i<6;$i++){ + if (getFieldVisibilityPermission($module, $current_user->id,$xyz[$i]) == '0'){ + $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]]; + } + else + $acct_focus->column_fields[$xyz[$i]] = ''; + } + $bill_street = str_replace(array("\r","\n"),array('\r','\n'), popup_decode_html($acct_focus->column_fields['street'])); + + $value = 'column_fields['city']).'", "'.popup_decode_html($acct_focus->column_fields['state']).'", "'.popup_decode_html($acct_focus->column_fields['postalcode']).'", "'.popup_decode_html($acct_focus->column_fields['country']).'","'.popup_decode_html($acct_focus->column_fields['pobox']).'");\'>'.$temp_val.''; + + } + elseif($popuptype == "specific_campaign") + { + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + $value = ''.$temp_val.''; + } + else + { + if($colname == "lastname") + $temp_val = getFullNameFromQResult($list_result,$list_result_count,$module); + + $slashes_temp_val = popup_from_html($temp_val); + $slashes_temp_val = htmlspecialchars($slashes_temp_val,ENT_QUOTES,$default_charset); + + $log->debug("Exiting getValue method ..."); + if($_REQUEST['maintab'] == 'Calendar') + $value = ''.$temp_val.''; + else + $value = ''.$temp_val.''; + } + } + else + { + if(($module == "Leads" && $colname == "lastname") || ($module == "Contacts" && $colname == "lastname")) + { + $value = ''.$temp_val.''; + } + elseif($module == "Calendar") + { + $actvity_type = $adb->query_result($list_result,$list_result_count,'activitytype'); + $actvity_type = ($actvity_type != '') ? $actvity_type : $adb->query_result($list_result,$list_result_count,'type'); + if($actvity_type == "Task") + { + $value = ''.$temp_val.''; + } + else + { + $value = ''.$temp_val.''; + } + } + elseif($module == "Vendors") + { + + $value = ''.$temp_val.''; + } + elseif($module == "PriceBooks") + { + + $value = ''.$temp_val.''; + } + elseif($module == "SalesOrder") + { + + $value = ''.$temp_val.''; + } + elseif($module == 'Emails') + { + $value = $temp_val; + } + else + { + $value = ''.$temp_val.''; + } + } + } + elseif($fieldname == 'expectedroi' || $fieldname == 'actualroi' || $fieldname == 'actualcost' || $fieldname == 'budgetcost' || $fieldname == 'expectedrevenue') + { + $rate = $user_info['conv_rate']; + $value = convertFromDollar($temp_val,$rate); + } + elseif(($module == 'Invoice' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder') + && ($fieldname == 'hdnGrandTotal' || $fieldname == 'hdnSubTotal' || $fieldname == 'txtAdjustment' + || $fieldname == 'hdnDiscountAmount' || $fieldname == 'hdnS_H_Amount')) + { + $currency_info = getInventoryCurrencyInfo($module, $entity_id); + $currency_id = $currency_info['currency_id']; + $currency_symbol = $currency_info['currency_symbol']; + $value = $currency_symbol.$temp_val; + } + else + { + $value = $temp_val; + } + } + + // Mike Crowe Mod --------------------------------------------------------Make right justified and vtiger_currency value + if ( in_array($uitype,array(71,72,7,9,90)) ) + { + $value = ''.$value.''; + } + $log->debug("Exiting getValue method ..."); + return $value; +} + +/** Function to get the list query for a module + * @param $module -- module name:: Type string + * @param $where -- where:: Type string + * @returns $query -- query:: Type query + */ +function getListQuery($module,$where='') +{ + global $log; + $log->debug("Entering getListQuery(".$module.",".$where.") method ..."); + + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $tab_id = getTabid($module); + switch($module) + { + Case "HelpDesk": + $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_troubletickets.title, vtiger_troubletickets.status, + vtiger_troubletickets.priority, vtiger_troubletickets.parent_id, + vtiger_contactdetails.contactid, vtiger_contactdetails.firstname, + vtiger_contactdetails.lastname, vtiger_account.accountid, + vtiger_account.accountname, vtiger_ticketcf.*, vtiger_troubletickets.ticket_no + FROM vtiger_troubletickets + INNER JOIN vtiger_ticketcf + ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_contactdetails + ON vtiger_troubletickets.parent_id = vtiger_contactdetails.contactid + LEFT JOIN vtiger_account + ON vtiger_account.accountid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_users + ON vtiger_crmentity.smownerid = vtiger_users.id + LEFT JOIN vtiger_products + ON vtiger_products.productid = vtiger_troubletickets.product_id"; + $query .= ' '.getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + + Case "Accounts": + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_account.accountname, vtiger_account.email1, + vtiger_account.email2, vtiger_account.website, vtiger_account.phone, + vtiger_accountbillads.bill_city, + vtiger_accountscf.* + FROM vtiger_account + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_account.accountid + INNER JOIN vtiger_accountbillads + ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads + ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + INNER JOIN vtiger_accountscf + ON vtiger_account.accountid = vtiger_accountscf.accountid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_account vtiger_account2 + ON vtiger_account.parentid = vtiger_account2.accountid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + + Case "Potentials": + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_account.accountname, + vtiger_potential.related_to, vtiger_potential.potentialname, + vtiger_potential.sales_stage, vtiger_potential.amount, + vtiger_potential.currency, vtiger_potential.closingdate, + vtiger_potential.typeofrevenue, + vtiger_potentialscf.* + FROM vtiger_potential + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_potential.potentialid + INNER JOIN vtiger_potentialscf + ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid + LEFT JOIN vtiger_account + ON vtiger_potential.related_to = vtiger_account.accountid + LEFT JOIN vtiger_contactdetails + ON vtiger_potential.related_to = vtiger_contactdetails.contactid + LEFT JOIN vtiger_campaign + ON vtiger_campaign.campaignid = vtiger_potential.campaignid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + + Case "Leads": + $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_leaddetails.firstname, vtiger_leaddetails.lastname, + vtiger_leaddetails.company, vtiger_leadaddress.phone, + vtiger_leadsubdetails.website, vtiger_leaddetails.email, + vtiger_leadscf.* + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails + ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress + ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + INNER JOIN vtiger_leadscf + ON vtiger_leaddetails.leadid = vtiger_leadscf.leadid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 AND vtiger_leaddetails.converted = 0 ". + $where; + break; + Case "Products": + $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.description, vtiger_products.*, vtiger_productcf.* + FROM vtiger_products + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_products.productid + INNER JOIN vtiger_productcf + ON vtiger_products.productid = vtiger_productcf.productid + LEFT JOIN vtiger_vendor + ON vtiger_vendor.vendorid = vtiger_products.vendor_id + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_products.handler"; + if((isset($_REQUEST["from_dashboard"]) && $_REQUEST["from_dashboard"] == true) && (isset($_REQUEST["type"]) && $_REQUEST["type"] =="dbrd")) + $query .= " INNER JOIN vtiger_inventoryproductrel on vtiger_inventoryproductrel.productid = vtiger_products.productid"; + $query .= " WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Documents": + $query = "SELECT case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name,vtiger_crmentity.crmid, vtiger_crmentity.modifiedtime, + vtiger_crmentity.smownerid,vtiger_attachmentsfolder.*,vtiger_notes.* + FROM vtiger_notes + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_notes.notesid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_attachmentsfolder + ON vtiger_notes.folderid = vtiger_attachmentsfolder.folderid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Contacts": + //Query modified to sort by assigned to + $query = "SELECT vtiger_contactdetails.firstname, vtiger_contactdetails.lastname, + vtiger_contactdetails.title, vtiger_contactdetails.accountid, + vtiger_contactdetails.email, vtiger_contactdetails.phone, + vtiger_crmentity.smownerid, vtiger_crmentity.crmid + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress + ON vtiger_contactaddress.contactaddressid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactsubdetails + ON vtiger_contactsubdetails.contactsubscriptionid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactscf + ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_account + ON vtiger_account.accountid = vtiger_contactdetails.accountid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_contactdetails vtiger_contactdetails2 + ON vtiger_contactdetails.reportsto = vtiger_contactdetails2.contactid + LEFT JOIN vtiger_customerdetails + ON vtiger_customerdetails.customerid = vtiger_contactdetails.contactid"; + if((isset($_REQUEST["from_dashboard"]) && $_REQUEST["from_dashboard"] == true) && + (isset($_REQUEST["type"]) && $_REQUEST["type"] =="dbrd")) { + $query .= " INNER JOIN vtiger_campaigncontrel on vtiger_campaigncontrel.contactid = ". + "vtiger_contactdetails.contactid"; + } + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Calendar": + + $query="SELECT vtiger_activity.activityid as act_id,vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.setype, + vtiger_activity.*, + vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, + vtiger_contactdetails.contactid, + vtiger_account.accountid, vtiger_account.accountname + FROM vtiger_activity + LEFT JOIN vtiger_activitycf + ON vtiger_activitycf.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_cntactivityrel + ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_contactdetails + ON vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid + LEFT JOIN vtiger_seactivityrel + ON vtiger_seactivityrel.activityid = vtiger_activity.activityid + LEFT OUTER JOIN vtiger_activity_reminder + ON vtiger_activity_reminder.activity_id = vtiger_activity.activityid + LEFT JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_activity.activityid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT OUTER JOIN vtiger_account + ON vtiger_account.accountid = vtiger_contactdetails.accountid + LEFT OUTER JOIN vtiger_leaddetails + ON vtiger_leaddetails.leadid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_account vtiger_account2 + ON vtiger_account2.accountid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_potential + ON vtiger_potential.potentialid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_troubletickets + ON vtiger_troubletickets.ticketid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_salesorder + ON vtiger_salesorder.salesorderid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_purchaseorder + ON vtiger_purchaseorder.purchaseorderid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_quotes + ON vtiger_quotes.quoteid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_invoice + ON vtiger_invoice.invoiceid = vtiger_seactivityrel.crmid + LEFT OUTER JOIN vtiger_campaign + ON vtiger_campaign.campaignid = vtiger_seactivityrel.crmid"; + + //added to fix #5135 + if(isset($_REQUEST['from_homepage']) && ($_REQUEST['from_homepage'] == + "upcoming_activities" || $_REQUEST['from_homepage'] == "pending_activities")) { + $query.=" LEFT OUTER JOIN vtiger_recurringevents + ON vtiger_recurringevents.activityid=vtiger_activity.activityid"; + } + //end + + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query.=" WHERE vtiger_crmentity.deleted = 0 AND activitytype != 'Emails' ".$where; + break; + Case "Emails": + $query = "SELECT DISTINCT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_activity.activityid, vtiger_activity.subject, + vtiger_activity.date_start, + vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, + vtiger_contactdetails.contactid + FROM vtiger_activity + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_activity.activityid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_seactivityrel + ON vtiger_seactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_contactdetails + ON vtiger_contactdetails.contactid = vtiger_seactivityrel.crmid + LEFT JOIN vtiger_cntactivityrel + ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid + AND vtiger_cntactivityrel.contactid = vtiger_cntactivityrel.contactid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_salesmanactivityrel + ON vtiger_salesmanactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_emaildetails + ON vtiger_emaildetails.emailid = vtiger_activity.activityid + WHERE vtiger_activity.activitytype = 'Emails'"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "AND vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Faq": + $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.createdtime, vtiger_crmentity.modifiedtime, + vtiger_faq.* + FROM vtiger_faq + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_faq.id + LEFT JOIN vtiger_products + ON vtiger_faq.product_id = vtiger_products.productid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + + Case "Vendors": + $query = "SELECT vtiger_crmentity.crmid, vtiger_vendor.* + FROM vtiger_vendor + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_vendor.vendorid + INNER JOIN vtiger_vendorcf + ON vtiger_vendor.vendorid = vtiger_vendorcf.vendorid + WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "PriceBooks": + $query = "SELECT vtiger_crmentity.crmid, vtiger_pricebook.*, vtiger_currency_info.currency_name + FROM vtiger_pricebook + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_pricebook.pricebookid + INNER JOIN vtiger_pricebookcf + ON vtiger_pricebook.pricebookid = vtiger_pricebookcf.pricebookid + LEFT JOIN vtiger_currency_info + ON vtiger_pricebook.currency_id = vtiger_currency_info.id + WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Quotes": + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.*, + vtiger_quotes.*, + vtiger_quotesbillads.*, + vtiger_quotesshipads.*, + vtiger_potential.potentialname, + vtiger_account.accountname, + vtiger_currency_info.currency_name + FROM vtiger_quotes + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_quotes.quoteid + INNER JOIN vtiger_quotesbillads + ON vtiger_quotes.quoteid = vtiger_quotesbillads.quotebilladdressid + INNER JOIN vtiger_quotesshipads + ON vtiger_quotes.quoteid = vtiger_quotesshipads.quoteshipaddressid + LEFT JOIN vtiger_quotescf + ON vtiger_quotes.quoteid = vtiger_quotescf.quoteid + LEFT JOIN vtiger_currency_info + ON vtiger_quotes.currency_id = vtiger_currency_info.id + LEFT OUTER JOIN vtiger_account + ON vtiger_account.accountid = vtiger_quotes.accountid + LEFT OUTER JOIN vtiger_potential + ON vtiger_potential.potentialid = vtiger_quotes.potentialid + LEFT JOIN vtiger_contactdetails + ON vtiger_contactdetails.contactid = vtiger_quotes.contactid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users as vtiger_usersQuotes + ON vtiger_usersQuotes.id = vtiger_quotes.inventorymanager"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "PurchaseOrder": + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.*, + vtiger_purchaseorder.*, + vtiger_pobillads.*, + vtiger_poshipads.*, + vtiger_vendor.vendorname, + vtiger_currency_info.currency_name + FROM vtiger_purchaseorder + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_purchaseorder.purchaseorderid + LEFT OUTER JOIN vtiger_vendor + ON vtiger_purchaseorder.vendorid = vtiger_vendor.vendorid + LEFT JOIN vtiger_contactdetails + ON vtiger_purchaseorder.contactid = vtiger_contactdetails.contactid + INNER JOIN vtiger_pobillads + ON vtiger_purchaseorder.purchaseorderid = vtiger_pobillads.pobilladdressid + INNER JOIN vtiger_poshipads + ON vtiger_purchaseorder.purchaseorderid = vtiger_poshipads.poshipaddressid + LEFT JOIN vtiger_purchaseordercf + ON vtiger_purchaseordercf.purchaseorderid = vtiger_purchaseorder.purchaseorderid + LEFT JOIN vtiger_currency_info + ON vtiger_purchaseorder.currency_id = vtiger_currency_info.id + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "SalesOrder": + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.*, + vtiger_salesorder.*, + vtiger_sobillads.*, + vtiger_soshipads.*, + vtiger_quotes.subject AS quotename, + vtiger_account.accountname, + vtiger_currency_info.currency_name + FROM vtiger_salesorder + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_salesorder.salesorderid + INNER JOIN vtiger_sobillads + ON vtiger_salesorder.salesorderid = vtiger_sobillads.sobilladdressid + INNER JOIN vtiger_soshipads + ON vtiger_salesorder.salesorderid = vtiger_soshipads.soshipaddressid + LEFT JOIN vtiger_salesordercf + ON vtiger_salesordercf.salesorderid = vtiger_salesorder.salesorderid + LEFT JOIN vtiger_currency_info + ON vtiger_salesorder.currency_id = vtiger_currency_info.id + LEFT OUTER JOIN vtiger_quotes + ON vtiger_quotes.quoteid = vtiger_salesorder.quoteid + LEFT OUTER JOIN vtiger_account + ON vtiger_account.accountid = vtiger_salesorder.accountid + LEFT JOIN vtiger_contactdetails + ON vtiger_salesorder.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_potential + ON vtiger_potential.potentialid = vtiger_salesorder.potentialid + LEFT JOIN vtiger_invoice_recurring_info + ON vtiger_invoice_recurring_info.salesorderid = vtiger_salesorder.salesorderid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Invoice": + //Query modified to sort by assigned to + //query modified -Code contribute by Geoff(http://forums.vtiger.com/viewtopic.php?t=3376) + $query = "SELECT vtiger_crmentity.*, + vtiger_invoice.*, + vtiger_invoicebillads.*, + vtiger_invoiceshipads.*, + vtiger_salesorder.subject AS salessubject, + vtiger_account.accountname, + vtiger_currency_info.currency_name + FROM vtiger_invoice + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_invoice.invoiceid + INNER JOIN vtiger_invoicebillads + ON vtiger_invoice.invoiceid = vtiger_invoicebillads.invoicebilladdressid + INNER JOIN vtiger_invoiceshipads + ON vtiger_invoice.invoiceid = vtiger_invoiceshipads.invoiceshipaddressid + LEFT JOIN vtiger_currency_info + ON vtiger_invoice.currency_id = vtiger_currency_info.id + LEFT OUTER JOIN vtiger_salesorder + ON vtiger_salesorder.salesorderid = vtiger_invoice.salesorderid + LEFT OUTER JOIN vtiger_account + ON vtiger_account.accountid = vtiger_invoice.accountid + LEFT JOIN vtiger_contactdetails + ON vtiger_contactdetails.contactid = vtiger_invoice.contactid + INNER JOIN vtiger_invoicecf + ON vtiger_invoice.invoiceid = vtiger_invoicecf.invoiceid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Campaigns": + //Query modified to sort by assigned to + //query modified -Code contribute by Geoff(http://forums.vtiger.com/viewtopic.php?t=3376) + $query = "SELECT vtiger_crmentity.*, + vtiger_campaign.* + FROM vtiger_campaign + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_campaign.campaignid + INNER JOIN vtiger_campaignscf + ON vtiger_campaign.campaignid = vtiger_campaignscf.campaignid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_products + ON vtiger_products.productid = vtiger_campaign.product_id"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 ".$where; + break; + Case "Users": + $query = "SELECT id,user_name,first_name,last_name,email1,phone_mobile,phone_work,is_admin,status, + vtiger_user2role.roleid as roleid,vtiger_role.depth as depth + FROM vtiger_users + INNER JOIN vtiger_user2role ON vtiger_users.id = vtiger_user2role.userid + INNER JOIN vtiger_role ON vtiger_user2role.roleid = vtiger_role.roleid + WHERE deleted=0 ".$where ; + break; + default: + // vtlib customization: Include the module file + $focus = CRMEntity::getInstance($module); + $query = $focus->getListQuery($module, $where); + // END + } + + if($module != 'Users') { + $query = listQueryNonAdminChange($query, $module); + } + $log->debug("Exiting getListQuery method ..."); + return $query; +} + +/**Function returns the list of records which an user is entiled to view +*Param $module - module name +*Returns a database query - type string +*/ + +function getReadEntityIds($module) +{ + global $log; + $log->debug("Entering getReadEntityIds(".$module.") method ..."); + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $tab_id = getTabid($module); + + if($module == "Leads") { + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 + AND vtiger_leaddetails.converted = 0 "; + }elseif($module == "Accounts") { + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_account + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_account.accountid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif ($module == "Potentials") { + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_potential + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_potential.potentialid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif($module == "Contacts") { + //Query modified to sort by assigned to + + $query="SELECT vtiger_crmentity.crmid + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif($module == "Products") { + $query = "SELECT DISTINCT vtiger_crmentity.crmid + FROM vtiger_products + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_products.productid + LEFT JOIN vtiger_seproductsrel + ON vtiger_seproductsrel.productid = vtiger_products.productid + WHERE vtiger_crmentity.deleted = 0 + AND (vtiger_seproductsrel.crmid IS NULL + OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Leads').") + OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Accounts').") + OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Potentials').") + OR vtiger_seproductsrel.crmid IN (".getReadEntityIds('Contacts').")) "; + }elseif($module == "PurchaseOrder") { + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_purchaseorder + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_purchaseorder.purchaseorderid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif($module == "SalesOrder") { + //Query modified to sort by assigned to + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_salesorder + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_salesorder.salesorderid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif($module == "Invoice") { + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_invoice + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_invoice.invoiceid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif($module == "Quotes") { + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_quotes + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_quotes.quoteid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + }elseif($module == "HelpDesk") { + $query = "SELECT vtiger_crmentity.crmid + FROM vtiger_troubletickets + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid"; + $query .= getNonAdminAccessControlQuery($module,$current_user); + $query .= "WHERE vtiger_crmentity.deleted = 0 "; + } + + $log->debug("Exiting getReadEntityIds method ..."); + return $query; + +} + +/** Function to get alphabetical search links +*Param $module - module name +*Param $action - action +*Param $fieldname - vtiger_field name +*Param $query - query +*Param $type - search type +*Param $popuptype - popup type +*Param $recordid - record id +*Param $return_module - return module +*Param $append_url - url string to be appended +*Param $viewid - custom view id +*Param $groupid - group id +*Returns an string value + */ +function AlphabeticalSearch($module,$action,$fieldname,$query,$type,$popuptype='',$recordid='',$return_module='',$append_url='',$viewid='',$groupid='') +{ + global $log; + $log->debug("Entering AlphabeticalSearch(".$module.",".$action.",".$fieldname.",".$query.",".$type.",".$popuptype.",".$recordid.",".$return_module.",".$append_url.",".$viewid.",".$groupid.") method ..."); + if($type=='advanced') + $flag='&advanced=true'; + + if($popuptype != '') + $popuptypevalue = "&popuptype=".$popuptype; + + if($recordid != '') + $returnvalue = '&recordid='.$recordid; + if($return_module != '') + $returnvalue .= '&return_module='.$return_module; + + // vtlib Customization : For uitype 10 popup during paging + if($_REQUEST['form'] == 'vtlibPopupView') { + $returnvalue .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); + } + // END + + for($var='A',$i =1;$i<=26;$i++,$var++) + // Mike Crowe Mod --------------------------------------------------------added groupid to url + $list .= ''.$var.''; + + $log->debug("Exiting AlphabeticalSearch method ..."); + return $list; +} + +/**Function to get parent name for a given parent id +*Param $module - module name +*Param $list_result- result set +*Param $rset - result set index +*Returns an string value +*/ +function getRelatedToEntity($module,$list_result,$rset) +{ + global $log; + $log->debug("Entering getRelatedToEntity(".$module.",".$list_result.",".$rset.") method ..."); + + global $adb; + $seid = $adb->query_result($list_result,$rset,"relatedto"); + $action = "DetailView"; + + if(isset($seid) && $seid != '') + { + $parent_module = $parent_module = getSalesEntityType($seid); + if($parent_module == 'Accounts') + { + $numrows= $adb->num_rows($evt_result); + + $parent_module = $adb->query_result($evt_result,0,'setype'); + $parent_id = $adb->query_result($evt_result,0,'crmid'); + + if ($numrows>1){ + $parent_module ='Multiple'; + $parent_name=$app_strings['LBL_MULTIPLE']; + } + //Raju -- Ends + $parent_query = "SELECT accountname FROM vtiger_account WHERE accountid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = $adb->query_result($parent_result,0,"accountname"); + } + if($parent_module == 'Leads') + { + $parent_query = "SELECT firstname,lastname FROM vtiger_leaddetails WHERE leadid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = getFullNameFromQResult($parent_result,0,"Leads"); + } + if($parent_module == 'Potentials') + { + $parent_query = "SELECT potentialname FROM vtiger_potential WHERE potentialid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = $adb->query_result($parent_result,0,"potentialname"); + } + if($parent_module == 'Products') + { + $parent_query = "SELECT productname FROM vtiger_products WHERE productid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = $adb->query_result($parent_result,0,"productname"); + } + if($parent_module == 'PurchaseOrder') + { + $parent_query = "SELECT subject FROM vtiger_purchaseorder WHERE purchaseorderid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + if($parent_module == 'SalesOrder') + { + $parent_query = "SELECT subject FROM vtiger_salesorder WHERE salesorderid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + if($parent_module == 'Invoice') + { + $parent_query = "SELECT subject FROM vtiger_invoice WHERE invoiceid=?"; + $parent_result = $adb->pquery($parent_query, array($seid)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + + $parent_value = "".$parent_name.""; + } + else + { + $parent_value = ''; + } + $log->debug("Exiting getRelatedToEntity method ..."); + return $parent_value; + +} + +/**Function to get parent name for a given parent id +*Param $module - module name +*Param $list_result- result set +*Param $rset - result set index +*Returns an string value +*/ + +//used in home page listTop vtiger_files +function getRelatedTo($module,$list_result,$rset) +{ + global $adb,$log,$app_strings; + $tabname = getParentTab(); + if($module == "Documents") + { + $notesid = $adb->query_result($list_result,$rset,"notesid"); + $action = "DetailView"; + $evt_query="SELECT vtiger_senotesrel.crmid, vtiger_crmentity.setype + FROM vtiger_senotesrel + INNER JOIN vtiger_crmentity + ON vtiger_senotesrel.crmid = vtiger_crmentity.crmid + WHERE vtiger_senotesrel.notesid = ?"; + $params = array($notesid); + }else if($module == "Products") + { + $productid = $adb->query_result($list_result,$rset,"productid"); + $action = "DetailView"; + $evt_query="SELECT vtiger_seproductsrel.crmid, vtiger_crmentity.setype + FROM vtiger_seproductsrel + INNER JOIN vtiger_crmentity + ON vtiger_seproductsrel.crmid = vtiger_crmentity.crmid + WHERE vtiger_seproductsrel.productid =?"; + $params = array($productid); + }else + { + $activity_id = $adb->query_result($list_result,$rset,"activityid"); + $action = "DetailView"; + $evt_query="SELECT vtiger_seactivityrel.crmid, vtiger_crmentity.setype + FROM vtiger_seactivityrel + INNER JOIN vtiger_crmentity + ON vtiger_seactivityrel.crmid = vtiger_crmentity.crmid + WHERE vtiger_seactivityrel.activityid=?"; + $params = array($activity_id); + + if($module == 'HelpDesk') + { + $activity_id = $adb->query_result($list_result,$rset,"parent_id"); + if($activity_id != '') { + $evt_query = "SELECT crmid, setype FROM vtiger_crmentity WHERE crmid=?"; + $params = array($activity_id); + } + } + } + //added by raju to change the related to in emails inot multiple if email is for more than one contact + $evt_result = $adb->pquery($evt_query, $params); + $numrows= $adb->num_rows($evt_result); + + $parent_module = $adb->query_result($evt_result,0,'setype'); + $parent_id = $adb->query_result($evt_result,0,'crmid'); + + + + if ($numrows>1){ + $parent_module ='Multiple'; + $parent_name=$app_strings['LBL_MULTIPLE']; + } + //Raju -- Ends + if($module == 'HelpDesk' && ($parent_module == 'Accounts' || $parent_module == 'Contacts')) + { + global $theme; + $module_icon = ''.$app_strings[$parent_module].' '; + } + + $action = "DetailView"; + if($parent_module == 'Accounts') + { + $parent_query = "SELECT accountname FROM vtiger_account WHERE accountid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = textlength_check($adb->query_result($parent_result,0,"accountname")); + } + if($parent_module == 'Leads') + { + $parent_query = "SELECT firstname,lastname FROM vtiger_leaddetails WHERE leadid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = getFullNameFromQResult($parent_result,0,"Leads"); + } + if($parent_module == 'Potentials') + { + $parent_query = "SELECT potentialname FROM vtiger_potential WHERE potentialid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = textlength_check($adb->query_result($parent_result,0,"potentialname")); + } + if($parent_module == 'Products') + { + $parent_query = "SELECT productname FROM vtiger_products WHERE productid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"productname"); + } + if($parent_module == 'Quotes') + { + $parent_query = "SELECT subject FROM vtiger_quotes WHERE quoteid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + if($parent_module == 'PurchaseOrder') + { + $parent_query = "SELECT subject FROM vtiger_purchaseorder WHERE purchaseorderid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + if($parent_module == 'Invoice') + { + $parent_query = "SELECT subject FROM vtiger_invoice WHERE invoiceid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + if($parent_module == 'SalesOrder') + { + $parent_query = "SELECT subject FROM vtiger_salesorder WHERE salesorderid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"subject"); + } + if($parent_module == 'Contacts' && ($module == 'Emails' || $module == 'HelpDesk')) + { + $parent_query = "SELECT firstname,lastname FROM vtiger_contactdetails WHERE contactid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = getFullNameFromQResult($parent_result,0,"Contacts"); + } + if($parent_module == 'Vendors' && ($module == 'Emails')) + { + $parent_query = "SELECT vendorname FROM vtiger_vendor WHERE vendorid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"vendorname"); + } + if($parent_module == 'HelpDesk') + { + $parent_query = "SELECT title FROM vtiger_troubletickets WHERE ticketid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"title"); + //if(strlen($parent_name) > 25) + //{ + $parent_name = textlength_check($parent_name); + //} + } + if($parent_module == 'Campaigns') + { + $parent_query = "SELECT campaignname FROM vtiger_campaign WHERE campaignid=?"; + $parent_result = $adb->pquery($parent_query, array($parent_id)); + $parent_name = $adb->query_result($parent_result,0,"campaignname"); + //if(strlen($parent_name) > 25) + //{ + $parent_name = textlength_check($parent_name); + //} + } + + //added by rdhital for better emails - Raju + if ($parent_module == 'Multiple') + { + $parent_value = $parent_name; + } + else + { + $parent_value = $module_icon."".textlength_check($parent_name).""; + } + //code added by raju ends + $log->debug("Exiting getRelatedTo method ..."); + return $parent_value; + + + +} + +/**Function to get the table headers for a listview +*Param $navigation_arrray - navigation values in array +*Param $url_qry - url string +*Param $module - module name +*Param $action- action file name +*Param $viewid - view id +*Returns an string value +*/ + +function getTableHeaderNavigation($navigation_array, $url_qry,$module='',$action_val='index',$viewid='') +{ + global $log,$app_strings; + $log->debug("Entering getTableHeaderNavigation(".$navigation_array.",". $url_qry.",".$module.",".$action_val.",".$viewid.") method ..."); + global $theme,$current_user; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + if($module == 'Documents') { + $output = ''; + } else { + $output = ''; + } + $tabname = getParentTab(); + + $url_string = ''; + + // vtlib Customization : For uitype 10 popup during paging + if($_REQUEST['form'] == 'vtlibPopupView') { + $url_string .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); + } + // END + + if($module == 'Calendar' && $action_val == 'index') + { + if($_REQUEST['view'] == ''){ + if($current_user->activity_view == "This Year"){ + $mysel = 'year'; + }else if($current_user->activity_view == "This Month"){ + $mysel = 'month'; + }else if($current_user->activity_view == "This Week"){ + $mysel = 'week'; + }else{ + $mysel = 'day'; + } + } + $data_value=date('Y-m-d H:i:s'); + preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$data_value,$value); + $date_data = Array( + 'day'=>$value[3], + 'month'=>$value[2], + 'year'=>$value[1], + 'hour'=>$value[4], + 'min'=>$value[5], + ); + $tab_type = ($_REQUEST['subtab'] == '')?'event':vtlib_purify($_REQUEST['subtab']); + $url_string .= isset($_REQUEST['view'])?"&view=".vtlib_purify($_REQUEST['view']):"&view=".$mysel; + $url_string .= isset($_REQUEST['subtab'])?"&subtab=".vtlib_purify($_REQUEST['subtab']):''; + $url_string .= isset($_REQUEST['viewOption'])?"&viewOption=".vtlib_purify($_REQUEST['viewOption']):'&viewOption=listview'; + $url_string .= isset($_REQUEST['day'])?"&day=".vtlib_purify($_REQUEST['day']):'&day='.$date_data['day']; + $url_string .= isset($_REQUEST['week'])?"&week=".vtlib_purify($_REQUEST['week']):''; + $url_string .= isset($_REQUEST['month'])?"&month=".vtlib_purify($_REQUEST['month']):'&month='.$date_data['month']; + $url_string .= isset($_REQUEST['year'])?"&year=".vtlib_purify($_REQUEST['year']):"&year=".$date_data['year']; + $url_string .= isset($_REQUEST['n_type'])?"&n_type=".vtlib_purify($_REQUEST['n_type']):''; + $url_string .= isset($_REQUEST['search_option'])?"&search_option=".vtlib_purify($_REQUEST['search_option']):''; + } + if($module == 'Calendar' && $action_val != 'index') //added for the All link from the homepage -- ticket 5211 + $url_string .= isset($_REQUEST['from_homepage'])?"&from_homepage=".vtlib_purify($_REQUEST['from_homepage']):''; + + if(($navigation_array['prev']) != 0) + { + if($module == 'Calendar' && $action_val == 'index') + { + //$output .= ' '; + $output .= ' '; + //$output .= ' '; + $output .= ' '; + } + else if($action_val == "FindDuplicate") + { + $output .= ' '; + $output .= ' '; + }elseif($action_val == 'UnifiedSearch'){ + $output .= ' '; + $output .= ' '; + } + elseif($module == 'Documents') + { + $output .= ' '; + $output .= ' '; + } + else{ + $output .= ' '; + $output .= ' '; + } + } + else + { + $output .= ' '; + $output .= ' '; + } + + if($module == 'Calendar' && $action_val == 'index'){ + $jsNavigate = "cal_navigation('$tab_type','$url_string','&start='+this.value);"; + }else if($action_val == "FindDuplicate"){ + $jsNavigate = "getDuplicateListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; + }elseif($action_val == 'UnifiedSearch'){ + $jsNavigate = "getUnifiedSearchEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; + }elseif($module == 'Documents'){ + $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string&folderid=$action_val');"; + }else{ + $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; + } + if($module == 'Documents'){ + $url = '&folderid='.$action_val; + }else{ + $url = ''; + } + $jsHandler = "return VT_disableFormSubmit(event);"; + $output .= ""; + $output .= ""; + $output .= $app_strings['LBL_LIST_OF'].' '.$navigation_array['verylast'].''; + + if(($navigation_array['next']) !=0) + { + if($module == 'Calendar' && $action_val == 'index') + { + //$output .= ' '; + $output .= ' '; + //$output .= ' '; + $output .= ' '; + } + else if($action_val == "FindDuplicate") + { + $output .= ' '; + $output .= ' '; + }elseif($action_val == 'UnifiedSearch'){ + $output .= ' '; + $output .= ' '; + } + elseif($module == 'Documents') + { + $output .= ' '; + $output .= ' '; + } + else + { + $output .= ' '; + $output .= ' '; + } + } + else + { + $output .= ' '; + $output .= ' '; + } + $output .= ''; + $log->debug("Exiting getTableHeaderNavigation method ..."); + if($navigation_array['first']=='') + return; + else + return $output; +} + +function getPopupCheckquery($current_module,$relmodule,$relmod_recordid) +{ + global $log,$adb; + $log->debug("Entering getPopupCheckquery(".$current_module.",".$relmodule.",".$relmod_recordid.") method ..."); + if($current_module == "Contacts") + { + if($relmodule == "Accounts" && $relmod_recordid != '') + $condition = "and vtiger_account.accountid= ".$relmod_recordid; + + elseif($relmodule == "Potentials") + { + $query = "select contactid from vtiger_contpotentialrel where potentialid=?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $contact_id = $adb->query_result($result,0,"contactid"); + if($contact_id != '' && $contact_id != 0) + $condition = "and vtiger_contactdetails.contactid= ".$contact_id; + else + { + $query = "select related_to from vtiger_potential where potentialid=?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $acc_id = $adb->query_result($result,0,"related_to"); + if($acc_id != ''){ + $condition = "and vtiger_contactdetails.accountid= ".$acc_id; + } + } + } + elseif($relmodule == "Quotes") + { + + $query = "select accountid,contactid from vtiger_quotes where quoteid=?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $contactid = $adb->query_result($result,0,"contactid"); + if($contactid != '' && $contactid != 0) + $condition = "and vtiger_contactdetails.contactid= ".$contactid; + else + { + $account_id = $adb->query_result($result,0,"accountid"); + if($account_id != '') + $condition = "and vtiger_contactdetails.accountid= ".$account_id; + } + } + elseif($relmodule == "PurchaseOrder") + { + $query = "select contactid from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $contact_id = $adb->query_result($result,0,"contactid"); + if($contact_id != '') + $condition = "and vtiger_contactdetails.contactid= ".$contact_id; + else + $condition = "and vtiger_contactdetails.contactid= 0"; + } + elseif($relmodule == "SalesOrder") + { + $query = "select accountid,contactid from vtiger_salesorder where salesorderid=?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $contact_id = $adb->query_result($result,0,"contactid"); + if($contact_id != 0 && $contact_id != '') + $condition = "and vtiger_contactdetails.contactid=".$contact_id; + else + { + $account_id = $adb->query_result($result,0,"accountid"); + if($account_id != '') + $condition = "and vtiger_contactdetails.accountid= ".$account_id; + } + } + elseif($relmodule == "Invoice") + { + $query = "select accountid,contactid from vtiger_invoice where invoiceid=?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $contact_id = $adb->query_result($result,0,"contactid"); + if($contact_id != '' && $contact_id != 0) + $condition = " and vtiger_contactdetails.contactid=".$contact_id; + else + { + $account_id = $adb->query_result($result,0,"accountid"); + if($account_id != '') + $condition = " and vtiger_contactdetails.accountid=".$account_id; + } + } + elseif($relmodule == "Campaigns") + { + $query = "select contactid from vtiger_campaigncontrel where campaignid =?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $rows = $adb->num_rows($result); + if($rows != 0) + { + $j = 0; + $contactid_comma = "("; + for($k=0; $k < $rows; $k++) + { + $contactid = $adb->query_result($result,$k,'contactid'); + $contactid_comma.=$contactid; + if($k < ($rows-1)) + $contactid_comma.=', '; + } + $contactid_comma.= ")"; + } + else + $contactid_comma = "(0)"; + $condition = "and vtiger_contactdetails.contactid in ".$contactid_comma; + } + elseif($relmodule == "Products") + { + $query = "select crmid from vtiger_seproductsrel where productid=? and setype=?"; + $result = $adb->pquery($query, array($relmod_recordid,"Contacts")); + $rows = $adb->num_rows($result); + if($rows != 0) + { + $j = 0; + $contactid_comma = "("; + for($k=0; $k < $rows; $k++) + { + $contactid = $adb->query_result($result,$k,'crmid'); + $contactid_comma.=$contactid; + if($k < ($rows-1)) + $contactid_comma.=', '; + } + $contactid_comma.= ")"; + } + else + $contactid_comma = "(0)"; + $condition = "and vtiger_contactdetails.contactid in ".$contactid_comma; + } + elseif($relmodule == "HelpDesk" || $relmodule == "Trouble Tickets") + { + $query = "select parent_id from vtiger_troubletickets where ticketid =?"; + $result = $adb->pquery($query, array($relmod_recordid)); + $parent_id = $adb->query_result($result,0,"parent_id"); + if($parent_id != ""){ + $crmquery = "select setype from vtiger_crmentity where crmid=?"; + $parentmodule_id = $adb->pquery($crmquery, array($parent_id)); + $parent_modname = $adb->query_result($parentmodule_id,0,"setype"); + if($parent_modname == "Accounts") + $condition = "and vtiger_contactdetails.accountid= ".$parent_id; + if($parent_modname == "Contacts") + $condition = "and vtiger_contactdetails.contactid= ".$parent_id; + } + else + $condition = " and vtiger_contactdetails.contactid=0"; + + } + } + elseif($current_module == "Potentials") + { + if($relmodule == 'Accounts' || $relmodule == 'Contacts') + { + if($relmodule == 'Contacts') { + $pot_query = "select vtiger_crmentity.crmid,vtiger_contactdetails.contactid,vtiger_potential.potentialid from vtiger_potential inner join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_potential.related_to inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid where vtiger_crmentity.deleted=0 and vtiger_potential.related_to=?"; + } else { + $pot_query = "select vtiger_crmentity.crmid,vtiger_account.accountid,vtiger_potential.potentialid from vtiger_potential inner join vtiger_account on vtiger_account.accountid=vtiger_potential.related_to inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid where vtiger_crmentity.deleted=0 and vtiger_potential.related_to=?"; + } + $pot_result = $result = $adb->pquery($pot_query, array($relmod_recordid)); + $rows = $adb->num_rows($pot_result); + $potids_comma = ""; + if($rows != 0) + { + $j = 0; + $potids_comma .= "("; + for($k=0; $k < $rows; $k++) + { + $potential_ids = $adb->query_result($pot_result,$k,'potentialid'); + $potids_comma.=$potential_ids; + if($k < ($rows-1)) + $potids_comma.=','; + } + $potids_comma.= ")"; + } + else + $potids_comma = "(0)"; + $condition ="and vtiger_potential.potentialid in ".$potids_comma; + } + + } + else if($current_module == "Products") + { + if($relmodule == 'Accounts') + { + $pro_query = "select productid from vtiger_seproductsrel where setype='Accounts' and crmid=?"; + $pro_result = $result = $adb->pquery($pro_query, array($relmod_recordid)); + $rows = $adb->num_rows($pro_result); + if($rows != 0) + { + $proids_comma = "("; + for($k=0; $k < $rows; $k++) + { + $product_ids = $adb->query_result($pro_result,$k,'productid'); + $proids_comma .= $product_ids; + if($k < ($rows-1)) + $proids_comma.=','; + } + $proids_comma.= ")"; + } + else + $proids_comma = "(0)"; + $condition ="and vtiger_products.productid in ".$proids_comma; + } + } + else if($current_module == 'Quotes') + { + if($relmodule == 'Accounts') + { + $quote_query = "select quoteid from vtiger_quotes where accountid=?"; + $quote_result = $result = $adb->pquery($quote_query, array($relmod_recordid)); + $rows = $adb->num_rows($quote_result); + if($rows != 0) + { + $j = 0; + $qtids_comma = "("; + for($k=0; $k < $rows; $k++) + { + $quote_ids = $adb->query_result($quote_result,$k,'quoteid'); + $qtids_comma.=$quote_ids; + if($k < ($rows-1)) + $qtids_comma.=','; + } + $qtids_comma.= ")"; + } + else + $qtids_comma = "(0)"; + $condition ="and vtiger_quotes.quoteid in ".$qtids_comma; + } + + } + else if($current_module == 'SalesOrder') + { + if($relmodule == 'Accounts') + { + $SO_query = "select salesorderid from vtiger_salesorder where accountid=?"; + $SO_result = $result = $adb->pquery($SO_query, array($relmod_recordid)); + $rows = $adb->num_rows($SO_result); + if($rows != 0) + { + $SOids_comma = "("; + for($k=0; $k < $rows; $k++) + { + $SO_ids = $adb->query_result($SO_result,$k,'salesorderid'); + $SOids_comma.=$SO_ids; + if($k < ($rows-1)) + $SOids_comma.=','; + } + $SOids_comma.= ")"; + } + else + $SOids_comma = "(0)"; + $condition ="and vtiger_salesorder.salesorderid in ".$SOids_comma; + } + + } + else + $condition = ''; + $where = $condition; + $log->debug("Exiting getPopupCheckquery method ..."); + return $where; + + +} + +/**This function return the entity ids that need to be excluded in popup listview for a given record +Param $currentmodule - modulename of the entity to be selected +Param $returnmodule - modulename for which the entity is assingned +Param $recordid - the record id for which the entity is assigned +Return type string. +*/ + +function getRelCheckquery($currentmodule,$returnmodule,$recordid) +{ + global $log,$adb; + $log->debug("Entering getRelCheckquery(".$currentmodule.",".$returnmodule.",".$recordid.") method ..."); + $skip_id = Array(); + $where_relquery = ""; + $params = array(); + if($currentmodule=="Contacts" && $returnmodule == "Potentials") + { + $reltable = 'vtiger_contpotentialrel'; + $condition = 'WHERE potentialid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'contactid'; + $table = 'vtiger_contactdetails'; + } + elseif($currentmodule=="Contacts" && $returnmodule == "Vendors") + { + $reltable = 'vtiger_vendorcontactrel'; + $condition = 'WHERE vendorid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'contactid'; + $table = 'vtiger_contactdetails'; + } + elseif($currentmodule=="Contacts" && $returnmodule == "Campaigns") + { + $reltable = 'vtiger_campaigncontrel'; + $condition = 'WHERE campaignid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'contactid'; + $table = 'vtiger_contactdetails'; + } + elseif($currentmodule=="Contacts" && $returnmodule == "Calendar") + { + $reltable = 'vtiger_cntactivityrel'; + $condition = 'WHERE activityid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'contactid'; + $table = 'vtiger_contactdetails'; + } + elseif($currentmodule=="Leads" && $returnmodule == "Campaigns") + { + $reltable = 'vtiger_campaignleadrel'; + $condition = 'WHERE campaignid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'leadid'; + $table = 'vtiger_leaddetails'; + } + elseif($currentmodule=="Users" && $returnmodule == "Calendar") + { + $reltable = 'vtiger_salesmanactivityrel'; + $condition = 'WHERE activityid = ?'; + array_push($params, $recordid); + $selectfield = 'smid'; + $field = 'id'; + $table = 'vtiger_users'; + } + elseif($currentmodule=="Campaigns" && $returnmodule == "Leads") + { + $reltable = 'vtiger_campaignleadrel'; + $condition = 'WHERE leadid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'campaignid'; + $table = 'vtiger_campaign'; + } + elseif($currentmodule=="Campaigns" && $returnmodule == "Contacts") + { + $reltable = 'vtiger_campaigncontrel'; + $condition = 'WHERE contactid = ?'; + array_push($params, $recordid); + $field = $selectfield = 'campaignid'; + $table = 'vtiger_campaign'; + } + elseif($currentmodule == "Products" && ($returnmodule == "Potentials" || $returnmodule == "Accounts" || $returnmodule == "Contacts" || $returnmodule == "Leads")) + { + $reltable = 'vtiger_seproductsrel'; + $condition = 'WHERE crmid = ? and setype = ?'; + array_push($params, $recordid, $returnmodule); + $field = $selectfield ='productid'; + $table = 'vtiger_products'; + } + elseif(($currentmodule == "Leads" || $currentmodule == "Accounts" || $currentmodule == "Potentials" || $currentmodule == "Contacts") && $returnmodule == "Products")//added to fix the issues(ticket 4001,4002 and 4003) + { + $reltable = 'vtiger_seproductsrel'; + $condition = 'WHERE productid = ? and setype = ?'; + array_push($params, $recordid, $currentmodule); + $selectfield ='crmid'; + if($currentmodule == "Leads") + { + $field = 'leadid'; + $table = 'vtiger_leaddetails'; + } + elseif($currentmodule == "Accounts") + { + $field = 'accountid'; + $table = 'vtiger_account'; + } + elseif($currentmodule == "Contacts") + { + $field = 'contactid'; + $table = 'vtiger_contactdetails'; + } + elseif($currentmodule == "Potentials") + { + $field = 'potentialid'; + $table = 'vtiger_potential'; + } + } + elseif($currentmodule == "Products" && $returnmodule =="Vendors") + { + $reltable = 'vtiger_products'; + $condition = 'WHERE vendor_id = ?'; + array_push($params, $recordid); + $field = $selectfield ='productid'; + $table = 'vtiger_products'; + } + elseif($currentmodule == "Documents") + { + $reltable = "vtiger_senotesrel"; + $selectfield = "notesid"; + $condition = "where crmid = ?"; + array_push($params, $recordid); + $table = "vtiger_notes"; + $field = "notesid"; + } + //end + if($reltable != null) { + $query = "SELECT ".$selectfield." FROM ".$reltable." ".$condition; + } elseif($currentmodule != $returnmodule && $returnmodule!="") { // If none of the above relation matches, then the relation is assumed to be stored in vtiger_crmentityrel + $query = "SELECT relcrmid AS relatedid FROM vtiger_crmentityrel WHERE crmid = ? and module = ? and relmodule = ? + UNION SELECT crmid AS relatedid FROM vtiger_crmentityrel WHERE relcrmid = ? and relmodule = ? and module = ?"; + array_push($params, $recordid, $returnmodule, $currentmodule, $recordid, $returnmodule, $currentmodule); + + $focus_obj = CRMEntity::getInstance($currentmodule); + $field = $focus_obj->table_index; + $table = $focus_obj->table_name; + $selectfield = 'relatedid'; + } + + if($query !='') + { + $result = $adb->pquery($query, $params); + if($adb->num_rows($result)!=0) + { + for($k=0;$k < $adb->num_rows($result);$k++) + { + $skip_id[]=$adb->query_result($result,$k,$selectfield); + } + $skipids = implode(",", constructList($skip_id,'INTEGER')); + if (count($skipids) > 0) { + $where_relquery = "and ".$table.".".$field." not in (". $skipids .")"; + } + } + } + $log->debug("Exiting getRelCheckquery method ..."); + return $where_relquery; +} + +/**This function stores the variables in session sent in list view url string. +*Param $lv_array - list view session array +*Param $noofrows - no of rows +*Param $max_ent - maximum entires +*Param $module - module name +*Param $related - related module +*Return type void. +*/ + +function setSessionVar($lv_array,$noofrows,$max_ent,$module='',$related='') +{ + $start = ''; + if($noofrows>=1) + { + $lv_array['start']=1; + $start = 1; + } + elseif($related!='' && $noofrows == 0) + { + $lv_array['start']=1; + $start = 1; + } + else + { + $lv_array['start']=0; + $start = 0; + } + + if(isset($_REQUEST['start']) && $_REQUEST['start'] !='') + { + $lv_array['start']=ListViewSession::getRequestStartPage(); + $start = ListViewSession::getRequestStartPage(); + }elseif($_SESSION['rlvs'][$module][$related]['start'] != '') + { + + if($related!='') + { + $lv_array['start']=$_SESSION['rlvs'][$module][$related]['start']; + $start = $_SESSION['rlvs'][$module][$related]['start']; + } + } + if(isset($_REQUEST['viewname']) && $_REQUEST['viewname'] !='') + $lv_array['viewname']=vtlib_purify($_REQUEST['viewname']); + + if($related=='') + $_SESSION['lvs'][$_REQUEST['module']]=$lv_array; + else + $_SESSION['rlvs'][$module][$related] = $lv_array; + + if ($start < ceil ($noofrows / $max_ent) && $start !='') + { + $start = ceil ($noofrows / $max_ent); + if($related=='') + $_SESSION['lvs'][$currentModule]['start'] = $start; + } +} + +/**Function to get the table headers for related listview +*Param $navigation_arrray - navigation values in array +*Param $url_qry - url string +*Param $module - module name +*Param $action- action file name +*Param $viewid - view id +*Returns an string value +*/ + +function getRelatedTableHeaderNavigation($navigation_array, $url_qry,$module,$related_module, + $recordid) { + global $log, $app_strings, $adb; + $log->debug("Entering getTableHeaderNavigation(".$navigation_array.",". $url_qry.",".$module.",".$action_val.",".$viewid.") method ..."); + global $theme; + $relatedTabId = getTabid($related_module); + $tabid = getTabid($module); + + $relatedListResult = $adb->pquery('SELECT * FROM vtiger_relatedlists WHERE tabid=? AND + related_tabid=?', array($tabid,$relatedTabId)); + if(empty($relatedListResult)) return; + $relatedListRow = $adb->fetch_row($relatedListResult); + $header = $relatedListRow['label']; + $actions = $relatedListRow['actions']; + $functionName = $relatedListRow['name']; + + $urldata = "module=$module&action={$module}Ajax&file=DetailViewAjax&record={$recordid}&". + "ajxaction=LOADRELATEDLIST&header={$header}&relation_id={$relatedListRow['relation_id']}". + "&actions={$actions}&{$url_qry}"; + + $formattedHeader = str_replace(' ','',$header); + $target = 'tbl_'.$module.'_'.$formattedHeader; + $imagesuffix = $module.'_'.$formattedHeader; + + $output = ''; + if(($navigation_array['prev']) != 0) { + $output .= ' '; + $output .= ' '; + } else { + $output .= ' '; + $output .= ' '; + } + + $jsHandler = "return VT_disableFormSubmit(event);"; + $output .= ""; + $output .= ""; + $computeCount = $_REQUEST['withCount']; + if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true + || ((boolean) $computeCount) == true){ + $output .= $app_strings['LBL_LIST_OF'].' '.$navigation_array['verylast']; + }else{ + $output .= "".$app_strings[ + ".$app_strings["; + } + $output .= ''; + + if(($navigation_array['next']) !=0) { + $output .= ' '; + $output .= ' '; + } else { + $output .= ' '; + $output .= ' '; + } + $output .= ''; + $log->debug("Exiting getTableHeaderNavigation method ..."); + if($navigation_array['first']=='') + return; + else + return $output; +} + +/** Function to get the Edit link details for ListView and RelatedListView + * @param string $module - module name + * @param int $entity_id - record id + * @param string $relatedlist - string "relatedlist" or may be empty. if empty means ListView else relatedlist + * @param string $returnset - may be empty in case of ListView. For relatedlists, return_module, return_action and return_id values will be passed like &return_module=Accounts&return_action=CallRelatedList&return_id=10 + * return string $edit_link - url string which cotains the editlink details (module, action, record, etc.,) like index.php?module=Accounts&action=EditView&record=10 + */ +function getListViewEditLink($module,$entity_id,$relatedlist,$returnset,$result,$count) +{ + global $adb; + $return_action = "index"; + $edit_link = "index.php?module=$module&action=EditView&record=$entity_id"; + $tabname = getParentTab(); + //Added to fix 4600 + $url = getBasic_Advance_SearchURL(); + + //This is relatedlist listview + if($relatedlist == 'relatedlist') + { + $edit_link .= $returnset; + } + else + { + if($module == 'Calendar') + { + $return_action = "ListView"; + $actvity_type = $adb->query_result($result,$count,'type'); + if($actvity_type == 'Task') + $edit_link .= '&activity_mode=Task'; + else + $edit_link .= '&activity_mode=Events'; + } + $edit_link .= "&return_module=$module&return_action=$return_action"; + } + + $edit_link .= "&parenttab=".$tabname.$url; + //Appending view name while editing from ListView + $edit_link .= "&return_viewname=".$_SESSION['lvs'][$module]["viewname"]; + if($module == 'Emails') + $edit_link = 'javascript:;" onclick="OpenCompose(\''.$entity_id.'\',\'edit\');'; + return $edit_link; +} + +/** Function to get the Del link details for ListView and RelatedListView + * @param string $module - module name + * @param int $entity_id - record id + * @param string $relatedlist - string "relatedlist" or may be empty. if empty means ListView else relatedlist + * @param string $returnset - may be empty in case of ListView. For relatedlists, return_module, return_action and return_id values will be passed like &return_module=Accounts&return_action=CallRelatedList&return_id=10 + * return string $del_link - url string which cotains the editlink details (module, action, record, etc.,) like index.php?module=Accounts&action=Delete&record=10 + */ +function getListViewDeleteLink($module,$entity_id,$relatedlist,$returnset) +{ + $tabname = getParentTab(); + $current_module = vtlib_purify($_REQUEST['module']); + $viewname = $_SESSION['lvs'][$current_module]['viewname']; + + //Added to fix 4600 + $url = getBasic_Advance_SearchURL(); + + if($module == "Calendar") + $return_action = "ListView"; + else + $return_action = "index"; + + //This is added to avoid the del link in Product related list for the following modules + $avoid_del_links = Array("PurchaseOrder","SalesOrder","Quotes","Invoice"); + + if(($current_module == 'Products' || $current_module == 'Services') && in_array($module,$avoid_del_links)) + { + return ''; + } + + $del_link = "index.php?module=$module&action=Delete&record=$entity_id"; + + //This is added for relatedlist listview + if($relatedlist == 'relatedlist') + { + $del_link .= $returnset; + } + else + { + $del_link .= "&return_module=$module&return_action=$return_action"; + } + + $del_link .= "&parenttab=".$tabname."&return_viewname=".$viewname.$url; + + // vtlib customization: override default delete link for custom modules + $requestModule = vtlib_purify($_REQUEST['module']); + $requestRecord = vtlib_purify($_REQUEST['record']); + $requestAction = vtlib_purify($_REQUEST['action']); + $parenttab = vtlib_purify($_REQUEST['parenttab']); + $isCustomModule = vtlib_isCustomModule($requestModule); + if($requestAction==$requestModule."Ajax"){ + $requestAction=vtlib_purify($_REQUEST['file']); + } + if($isCustomModule && !in_array($requestAction, Array('index','ListView'))) { + $del_link = "index.php?module=$requestModule&action=updateRelations&parentid=$requestRecord"; + $del_link .= "&destination_module=$module&idlist=$entity_id&mode=delete&parenttab=$parenttab"; + } + // END + + return $del_link; +} + +/* Function to get the Entity Id of a given Entity Name */ +function getEntityId($module, $entityName) { + global $log, $adb; + $log->info("in getEntityId ".$entityName); + + $query = "select fieldname,tablename,entityidfield from vtiger_entityname where modulename = ?"; + $result = $adb->pquery($query, array($module)); + $fieldsname = $adb->query_result($result,0,'fieldname'); + $tablename = $adb->query_result($result,0,'tablename'); + $entityidfield = $adb->query_result($result,0,'entityidfield'); + if(!(strpos($fieldsname,',') === false)) { + $fieldlists = explode(',',$fieldsname); + $fieldsname = "concat("; + $fieldsname = $fieldsname.implode(",' ',",$fieldlists); + $fieldsname = $fieldsname.")"; + } + + if($entityName != '') { + $sql = "select $entityidfield from $tablename INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $tablename.$entityidfield " . + " WHERE vtiger_crmentity.deleted = 0 and $fieldsname=?"; + $result = $adb->pquery($sql, array($entityName)); + if($adb->num_rows($result) > 0) { + $entityId = $adb->query_result($result,0,$entityidfield); + } + } + if(!empty($entityId)) + return $entityId; + else + return 0; +} + +/** function used to get the parent id for the given input parent name --Pavani **/ +function getParentId($parent_name) +{ + global $adb; + if($parent_name == '' || $parent_name == NULL) + $parent_id = 0; + //For now it have conditions only for accounts and contacts, if needed can add more + $relatedTo = explode(':',$parent_name); + $parent_module = $relatedTo[0]; $parent_module = trim($parent_module," "); + $parent_name = $relatedTo[3]; $parent_name = trim($parent_name," "); + $num_rows = 0; + if($parent_module == 'Contacts') + { + $query ="select crmid from vtiger_contactdetails, vtiger_crmentity WHERE concat(lastname,' ',firstname)=? and vtiger_crmentity.crmid =vtiger_contactdetails.contactid and vtiger_crmentity.deleted=0"; + $result = $adb->pquery($query, array($parent_name)); + $num_rows=$adb->num_rows($result); + } + else if($parent_module == 'Accounts') + { + $query = "select crmid from vtiger_account, vtiger_crmentity WHERE accountname=? and vtiger_crmentity.crmid =vtiger_account.accountid and vtiger_crmentity.deleted=0"; + $result = $adb->pquery($query, array($parent_name)); + $num_rows = $adb->num_rows($result); + } + else $num_rows=0; + if($num_rows == 0) $parent_id = 0; + else $parent_id = $adb->query_result($result,0,"crmid"); + return $parent_id; +} + +function decode_html($str) +{ + global $default_charset; + // Direct Popup action or Ajax Popup action should be treated the same. + if($_REQUEST['action'] == 'Popup' || $_REQUEST['file'] == 'Popup') + return html_entity_decode($str); + else + return html_entity_decode($str,ENT_QUOTES,$default_charset); +} + +/** + * Alternative decoding function which coverts irrespective of $_REQUEST values. + * Useful incase of Popup (Listview etc...) where if decode_html will not work as expected + */ +function decode_html_force($str) { + global $default_charset; + return html_entity_decode($str,ENT_QUOTES,$default_charset); +} + +function popup_decode_html($str) +{ + global $default_charset; + $slashes_str = popup_from_html($str); + $slashes_str = htmlspecialchars($slashes_str,ENT_QUOTES,$default_charset); + return decode_html(br2nl($slashes_str)); +} + +//function added to check the text length in the listview. +function textlength_check($field_val) +{ + global $listview_max_textlength, $default_charset; + if($listview_max_textlength) { + $temp_val = preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$field_val); + if(function_exists('mb_strlen')){ + if(mb_strlen($default_charset) > $listview_max_textlength) { + $temp_val = mb_substr(preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$field_val),0, + $listview_max_textlength,$default_charset).'...'; + } + }elseif(strlen($field_val) > $listview_max_textlength) { + $temp_val = substr(preg_replace("/(<\/?)(\w+)([^>]*>)/i","",$field_val),0,$listview_max_textlength).'...'; + } + } else { + $temp_val = $field_val; + } + return $temp_val; +} + +/** Function to get permitted fields of current user of a particular module to find duplicate records --Pavani*/ +function getMergeFields($module,$str){ + global $adb,$current_user; + $tabid = getTabid($module); + if($str == "available_fields"){ + $result = getFieldsResultForMerge($tabid); + } + else { //if($str == fileds_to_merge) + $sql="select * from vtiger_user2mergefields where tabid=? and userid=? and visible=1"; + $result = $adb->pquery($sql, array($tabid,$current_user->id)); + } + + $num_rows=$adb->num_rows($result); + + $user_profileid = fetchUserProfileId($current_user->id); + $permitted_list = getProfile2FieldPermissionList($module, $user_profileid); + + $sql_def_org="select fieldid from vtiger_def_org_field where tabid=? and visible=0"; + $result_def_org=$adb->pquery($sql_def_org,array($tabid)); + $num_rows_org=$adb->num_rows($result_def_org); + $permitted_org_list = Array(); + for($i=0; $i<$num_rows_org; $i++) + $permitted_org_list[$i] = $adb->query_result($result_def_org,$i,"fieldid"); + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + for($i=0; $i<$num_rows;$i++) + { + $field_id = $adb->query_result($result,$i,"fieldid"); + foreach($permitted_list as $field=>$data) + if($data[4] == $field_id and $data[1] == 0) + { + if($is_admin == 'true' || (in_array($field_id,$permitted_org_list))) + { + $field=""; + $fields.=$field; + break; + } + } + } + return $fields; +} + + +/** + * this function accepts a modulename and a fieldname and returns the first related module for it + * it expects the uitype of the field to be 10 + * @param string $module - the modulename + * @param string $fieldname - the field name + * @return string $data - the first related module + */ +function getFirstModule($module, $fieldname){ + global $adb; + $sql = "select fieldid, uitype from vtiger_field where tabid=? and fieldname=?"; + $result = $adb->pquery($sql, array(getTabid($module), $fieldname)); + + if($adb->num_rows($result)>0){ + $uitype = $adb->query_result($result, 0, "uitype"); + + if($uitype == 10){ + $fieldid = $adb->query_result($result, 0, "fieldid"); + $sql = "select * from vtiger_fieldmodulerel where fieldid=?"; + $result = $adb->pquery($sql, array($fieldid)); + $count = $adb->num_rows($result); + + if($count > 0){ + $data = $adb->query_result($result, 0, "relmodule"); + } + } + } + return $data; +} + +function VT_getSimpleNavigationValues($start,$size,$total){ + $prev = $start -1; + if($prev < 0){ + $prev = 0; + } + if($total === null){ + return array('start'=>$start,'first'=>$start,'current'=>$start,'end'=>$start,'end_val'=>$size,'allflag'=>'All', + 'prev'=>$prev,'next'=>$start+1,'verylast'=>'last'); + } + if(empty($total)){ + $lastPage = 1; + }else{ + $lastPage = ceil($total/$size); + } + + $next = $start+1; + if($next > $lastPage){ + $next = 0; + } + return array('start'=>$start,'first'=>$start,'current'=>$start,'end'=>$start,'end_val'=>$size,'allflag'=>'All', + 'prev'=>$prev,'next'=>$next,'verylast'=>$lastPage); +} + +/**Function to get the simplified table headers for a listview +*Param $navigation_arrray - navigation values in array +*Param $url_qry - url string +*Param $module - module name +*Param $action- action file name +*Param $viewid - view id +*Returns an string value +*/ + +function getTableHeaderSimpleNavigation($navigation_array, $url_qry,$module='',$action_val='index',$viewid=''){ + global $log,$app_strings; + global $theme,$current_user; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + if($module == 'Documents') { + $output = ''; + } else { + $output = ''; + } + $tabname = getParentTab(); + + $url_string = ''; + + // vtlib Customization : For uitype 10 popup during paging + if($_REQUEST['form'] == 'vtlibPopupView') { + $url_string .= '&form=vtlibPopupView&forfield='.vtlib_purify($_REQUEST['forfield']).'&srcmodule='.vtlib_purify($_REQUEST['srcmodule']).'&forrecord='.vtlib_purify($_REQUEST['forrecord']); + } + // END + + if($module == 'Calendar' && $action_val == 'index') + { + if($_REQUEST['view'] == ''){ + if($current_user->activity_view == "This Year"){ + $mysel = 'year'; + }else if($current_user->activity_view == "This Month"){ + $mysel = 'month'; + }else if($current_user->activity_view == "This Week"){ + $mysel = 'week'; + }else{ + $mysel = 'day'; + } + } + $data_value=date('Y-m-d H:i:s'); + preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$data_value,$value); + $date_data = Array( + 'day'=>$value[3], + 'month'=>$value[2], + 'year'=>$value[1], + 'hour'=>$value[4], + 'min'=>$value[5], + ); + $tab_type = ($_REQUEST['subtab'] == '')?'event':vtlib_purify($_REQUEST['subtab']); + $url_string .= isset($_REQUEST['view'])?"&view=".vtlib_purify($_REQUEST['view']):"&view=".$mysel; + $url_string .= isset($_REQUEST['subtab'])?"&subtab=".vtlib_purify($_REQUEST['subtab']):''; + $url_string .= isset($_REQUEST['viewOption'])?"&viewOption=".vtlib_purify($_REQUEST['viewOption']):'&viewOption=listview'; + $url_string .= isset($_REQUEST['day'])?"&day=".vtlib_purify($_REQUEST['day']):'&day='.$date_data['day']; + $url_string .= isset($_REQUEST['week'])?"&week=".vtlib_purify($_REQUEST['week']):''; + $url_string .= isset($_REQUEST['month'])?"&month=".vtlib_purify($_REQUEST['month']):'&month='.$date_data['month']; + $url_string .= isset($_REQUEST['year'])?"&year=".vtlib_purify($_REQUEST['year']):"&year=".$date_data['year']; + $url_string .= isset($_REQUEST['n_type'])?"&n_type=".vtlib_purify($_REQUEST['n_type']):''; + $url_string .= isset($_REQUEST['search_option'])?"&search_option=".vtlib_purify($_REQUEST['search_option']):''; + } + if($module == 'Calendar' && $action_val != 'index') //added for the All link from the homepage -- ticket 5211 + $url_string .= isset($_REQUEST['from_homepage'])?"&from_homepage=".vtlib_purify($_REQUEST['from_homepage']):''; + + if(($navigation_array['prev']) != 0){ + if($module == 'Calendar' && $action_val == 'index'){ + $output .= ' '; + $output .= ' '; + }else if($action_val == "FindDuplicate"){ + $output .= ' '; + $output .= ' '; + }elseif($action_val == 'UnifiedSearch'){ + $output .= ' '; + $output .= ' '; + }elseif($module == 'Documents'){ + $output .= ' '; + $output .= ' '; + }else{ + $output .= ' '; + $output .= ' '; + } + }else{ + $output .= ' '; + $output .= ' '; + } + if($module == 'Calendar' && $action_val == 'index'){ + $jsNavigate = "cal_navigation('$tab_type','$url_string','&start='+this.value);"; + }else if($action_val == "FindDuplicate"){ + $jsNavigate = "getDuplicateListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; + }elseif($action_val == 'UnifiedSearch'){ + $jsNavigate = "getUnifiedSearchEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; + }elseif($module == 'Documents'){ + $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string&folderid=$action_val');"; + }else{ + $jsNavigate = "getListViewEntries_js('$module','parenttab=$tabname&start='+this.value+'$url_string');"; + } + if($module == 'Documents' && $action_val != 'UnifiedSearch'){ + $url = '&folderid='.$action_val; + }else{ + $url = ''; + } + $jsHandler = "return VT_disableFormSubmit(event);"; + $output .= ""; + $output .= ""; + if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true){ + $output .= $app_strings['LBL_LIST_OF'].' '.$navigation_array['verylast']; + }else{ + $output .= "".$app_strings[ + ".$app_strings["; + } + $output .=''; + + if(($navigation_array['next']) !=0){ + if($module == 'Calendar' && $action_val == 'index'){ + $output .= ' '; + $output .= ' '; + }else if($action_val == "FindDuplicate"){ + $output .= ' '; + $output .= ' '; + }elseif($action_val == 'UnifiedSearch'){ + $output .= ' '; + $output .= ' '; + }elseif($module == 'Documents'){ + $output .= ' '; + $output .= ' '; + }else{ + $output .= ' '; + $output .= ' '; + } + }else{ + $output .= ' '; + $output .= ' '; + } + $output .= ''; + if($navigation_array['first']=='') + return; + else + return $output; +} + +function getRecordRangeMessage($listResult, $limitStartRecord,$totalRows='') { + global $adb, $app_strings; + $numRows = $adb->num_rows($listResult); + $recordListRangeMsg = ''; + if ($numRows > 0) { + $recordListRangeMsg = $app_strings['LBL_SHOWING'].' '.$app_strings['LBL_RECORDS']. + ' '.($limitStartRecord+1).' - '.($limitStartRecord+$numRows); + if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true){ + $recordListRangeMsg .= ' '.$app_strings['LBL_LIST_OF']." $totalRows"; + } + } + return $recordListRangeMsg; +} + +function listQueryNonAdminChange($query, $module, $scope='') { + $instance = CRMEntity::getInstance($module); + return $instance->listQueryNonAdminChange($query, $scope); +} + +?> diff --git a/oss/vtiger/trunk/include/utils/RecurringType.php b/oss/vtiger/trunk/include/utils/RecurringType.php index f46a78e3..29402e2c 100644 --- a/oss/vtiger/trunk/include/utils/RecurringType.php +++ b/oss/vtiger/trunk/include/utils/RecurringType.php @@ -1,321 +1,321 @@ - $st_date[2], - 'month' => $st_date[1], - 'year' => $st_date[0] - ); - $end_date = Array( - 'day' => $end_date[2], - 'month' => $end_date[1], - 'year' => $end_date[0] - ); - $this->recur_type = $repeat_arr['type']; - $this->recur_freq = $repeat_arr['repeat_frequency']; - $this->startdate = new vt_DateTime($start_date,true); - $this->enddate = new vt_DateTime($end_date,true); - if($repeat_arr['sun_flag']) - { - $this->dayofweek_to_rpt[] = 0; - } - if($repeat_arr['mon_flag']) - { - $this->dayofweek_to_rpt[] = 1; - } - if($repeat_arr['tue_flag']) - { - $this->dayofweek_to_rpt[] = 2; - } - if($repeat_arr['wed_flag']) - { - $this->dayofweek_to_rpt[] = 3; - } - if($repeat_arr['thu_flag']) - { - $this->dayofweek_to_rpt[] = 4; - } - if($repeat_arr['fri_flag']) - { - $this->dayofweek_to_rpt[] = 5; - } - if($repeat_arr['sat_flag']) - { - $this->dayofweek_to_rpt[] = 6; - } - $this->repeat_monthby = $repeat_arr['repeatmonth_type']; - if(isset($repeat_arr['repeatmonth_date'])) - $this->rptmonth_datevalue = $repeat_arr['repeatmonth_date']; - $this->rptmonth_daytype = $repeat_arr['repeatmonth_daytype']; - $this->recurringdates = $this->getRecurringDates(); - } - - /** - * Function to get recurring dates depending on the recurring type - * return array $recurringDates - Recurring Dates in format - */ - - function getRecurringDates() - { - $startdate = $this->startdate->get_formatted_date(); - $recurringDates[] = $startdate; - $tempdate = $startdate; - $enddate = $this->enddate->get_formatted_date(); - while($tempdate <= $enddate) - { - if($this->recur_type == 'Daily') - { - $st_date = explode("-",$tempdate); - if(isset($this->recur_freq)) - $index = $st_date[2] + $this->recur_freq - 1; - else - $index = $st_date[2]; - $tempdateObj = $this->startdate->getThismonthDaysbyIndex($index,'',$st_date[1],$st_date[0]); - $tempdate = $tempdateObj->get_formatted_date(); - $recurringDates[] = $tempdate; - } - elseif($this->recur_type == 'Weekly') - { - $st_date = explode("-",$tempdate); - $date_arr = Array( - 'day' => $st_date[2], - 'month' => $st_date[1], - 'year' => $st_date[0] - ); - $tempdateObj = new vt_DateTime($date_arr,true); - if(count($this->dayofweek_to_rpt) == 0) - $this->dayofweek_to_rpt[] = $this->startdate->dayofweek; - for($i=0;$idayofweek_to_rpt);$i++) - { - - $repeatDay = $tempdateObj->getThisweekDaysbyIndex($this->dayofweek_to_rpt[$i]); - $repeatDate= $repeatDay->get_formatted_date(); - if($repeatDate > $startdate && $repeatDate <= $enddate) - $recurringDates[] = $repeatDate; - } - - if(isset($this->recur_freq)) - $index = $this->recur_freq * 7; - else - $index = 7; - $date_arr = Array( - 'day' => $st_date[2] + $index, - 'month' => $st_date[1], - 'year' => $st_date[0] - ); - $tempdateObj = new vt_DateTime($date_arr,true); - $tempdate = $tempdateObj->get_formatted_date(); - } - elseif($this->recur_type == 'Monthly') - { - $st_date = explode("-",$tempdate); - $date_arr = Array( - 'day' => $st_date[2], - 'month' => $st_date[1], - 'year' => $st_date[0] - ); - $startdateObj = new vt_DateTime($date_arr,true); - if($this->repeat_monthby == 'date') - { - if($this->rptmonth_datevalue <= $st_date[2]) - { - $index = $this->rptmonth_datevalue - 1; - $day = $this->rptmonth_datevalue; - if(isset($this->recur_freq)) - $month = $st_date[1] + $this->recur_freq; - else - $month = $st_date[1] + 1; - $year = $st_date[0]; - $tempdateObj = $startdateObj->getThismonthDaysbyIndex($index,$day,$month,$year); - } - else - { - $index = $this->rptmonth_datevalue - 1; - $day = $this->rptmonth_datevalue; - $month = $st_date[1]; - $year = $st_date[0]; - $tempdateObj = $startdateObj->getThismonthDaysbyIndex($index,$day,$month,$year); - } - } - elseif($this->repeat_monthby == 'day') - { - if($this->rptmonth_daytype == 'first') - { - $date_arr = Array( - 'day' => 1, - 'month' => $st_date[1], - 'year' => $st_date[0] - ); - $tempdateObj = new vt_DateTime($date_arr,true); - $firstdayofmonthObj = $this->getFistdayofmonth($this->dayofweek_to_rpt[0],$tempdateObj); - if($firstdayofmonthObj->get_formatted_date() <= $tempdate) - { - if(isset($this->recur_freq)) - $month = $firstdayofmonthObj->month + $this->recur_freq; - else - $month = $firstdayofmonthObj->month + 1; - $dateObj = $firstdayofmonthObj->getThismonthDaysbyIndex(0,1,$month,$firstdayofmonthObj->year); - $nextmonthObj = $this->getFistdayofmonth($this->dayofweek_to_rpt[0],$dateObj); - $tempdateObj = $nextmonthObj; - } - else - { - $tempdateObj = $firstdayofmonthObj; - } - - } - elseif($this->rptmonth_daytype == 'last') - { - $date_arr = Array( - 'day' => $startdateObj->daysinmonth, - 'month' => $startdateObj->month, - 'year' => $startdateObj->year - ); - $tempdateObj = new vt_DateTime($date_arr,true); - $lastdayofmonthObj = $this->getLastdayofmonth($this->dayofweek_to_rpt[0],$tempdateObj); - if($lastdayofmonthObj->get_formatted_date() <= $tempdate) - { - if(isset($this->recur_freq)) - $month = $lastdayofmonthObj->month + $this->recur_freq; - else - $month = $lastdayofmonthObj->month + 1; - $dateObj = $lastdayofmonthObj->getThismonthDaysbyIndex(0,1,$month,$lastdayofmonthObj->year); - $dateObj = $dateObj->getThismonthDaysbyIndex($dateObj->daysinmonth-1,$dateObj->daysinmonth,$month,$lastdayofmonthObj->year); - $nextmonthObj = $this->getLastdayofmonth($this->dayofweek_to_rpt[0],$dateObj); - $tempdateObj = $nextmonthObj; - } - else - { - $tempdateObj = $lastdayofmonthObj; - } - } - } - else - { - $date_arr = Array( - 'day' => $st_date[2], - 'month' => $st_date[1]+1, - 'year' => $st_date[0] - ); - $tempdateObj = new vt_DateTime($date_arr,true); - } - $tempdate = $tempdateObj->get_formatted_date(); - $recurringDates[] = $tempdate; - } - elseif($this->recur_type == 'Yearly') - { - $st_date = explode("-",$tempdate); - if(isset($this->recur_freq)) - $index = $st_date[0] + $this->recur_freq; - else - $index = $st_date[0] + 1; - if ($index > 2037 || $index < 1970) - { - print("".$app_strings['LBL_CAL_LIMIT_MSG'].""); - exit; - } - $date_arr = Array( - 'day' => $st_date[2], - 'month' => $st_date[1], - 'year' => $index - ); - $tempdateObj = new vt_DateTime($date_arr,true); - $tempdate = $tempdateObj->get_formatted_date(); - $recurringDates[] = $tempdate; - } - else - { - die("Recurring Type ".$this->recur_type." is not defined"); - } - } - return $recurringDates; - } - - /** Function to get first day of the month(like first Monday or Friday and etc.) - * @param $dayofweek -- day of the week to repeat the event :: Type string - * @param $dateObj -- date object :: Type vt_DateTime Object - * return $dateObj -- the date object on which the event repeats :: Type vt_DateTime Object - */ - function getFistdayofmonth($dayofweek,& $dateObj) - { - if($dayofweek < $dateObj->dayofweek) - { - $index = (7 - $dateObj->dayofweek) + $dayofweek; - $day = 1 + $index; - $month = $dateObj->month; - $year = $dateObj->year; - $dateObj = $dateObj->getThismonthDaysbyIndex($index,$day,$month,$year); - } - else - { - $index = $dayofweek - $dateObj->dayofweek; - $day = 1 + $index; - $month = $dateObj->month; - $year = $dateObj->year; - $dateObj = $dateObj->getThismonthDaysbyIndex($index,$day,$month,$year); - } - return $dateObj; - } - - /** Function to get last day of the month(like last Monday or Friday and etc.) - * @param $dayofweek -- day of the week to repeat the event :: Type string - * @param $dateObj -- date object :: Type vt_DateTime Object - * return $dateObj -- the date object on which the event repeats :: Type vt_DateTime Object - */ - - function getLastdayofmonth($dayofweek,& $dateObj) - { - if($dayofweek == $dateObj->dayofweek) - { - return $dateObj; - } - else - { - if($dayofweek > $dateObj->dayofweek) - $day = $dateObj->day - 7 + ($dayofweek - $dateObj->dayofweek); - else - $day = $dateObj->day - ($dateObj->dayofweek - $dayofweek); - $index = $day - 1; - $month = $dateObj->month; - $year = $dateObj->year; - $dateObj = $dateObj->getThismonthDaysbyIndex($index,$day,$month,$year); - return $dateObj; - } - - } - -} - -?> + $st_date[2], + 'month' => $st_date[1], + 'year' => $st_date[0] + ); + $end_date = Array( + 'day' => $end_date[2], + 'month' => $end_date[1], + 'year' => $end_date[0] + ); + $this->recur_type = $repeat_arr['type']; + $this->recur_freq = $repeat_arr['repeat_frequency']; + $this->startdate = new vt_DateTime($start_date,true); + $this->enddate = new vt_DateTime($end_date,true); + if($repeat_arr['sun_flag']) + { + $this->dayofweek_to_rpt[] = 0; + } + if($repeat_arr['mon_flag']) + { + $this->dayofweek_to_rpt[] = 1; + } + if($repeat_arr['tue_flag']) + { + $this->dayofweek_to_rpt[] = 2; + } + if($repeat_arr['wed_flag']) + { + $this->dayofweek_to_rpt[] = 3; + } + if($repeat_arr['thu_flag']) + { + $this->dayofweek_to_rpt[] = 4; + } + if($repeat_arr['fri_flag']) + { + $this->dayofweek_to_rpt[] = 5; + } + if($repeat_arr['sat_flag']) + { + $this->dayofweek_to_rpt[] = 6; + } + $this->repeat_monthby = $repeat_arr['repeatmonth_type']; + if(isset($repeat_arr['repeatmonth_date'])) + $this->rptmonth_datevalue = $repeat_arr['repeatmonth_date']; + $this->rptmonth_daytype = $repeat_arr['repeatmonth_daytype']; + $this->recurringdates = $this->getRecurringDates(); + } + + /** + * Function to get recurring dates depending on the recurring type + * return array $recurringDates - Recurring Dates in format + */ + + function getRecurringDates() + { + $startdate = $this->startdate->get_formatted_date(); + $recurringDates[] = $startdate; + $tempdate = $startdate; + $enddate = $this->enddate->get_formatted_date(); + while($tempdate <= $enddate) + { + if($this->recur_type == 'Daily') + { + $st_date = explode("-",$tempdate); + if(isset($this->recur_freq)) + $index = $st_date[2] + $this->recur_freq - 1; + else + $index = $st_date[2]; + $tempdateObj = $this->startdate->getThismonthDaysbyIndex($index,'',$st_date[1],$st_date[0]); + $tempdate = $tempdateObj->get_formatted_date(); + $recurringDates[] = $tempdate; + } + elseif($this->recur_type == 'Weekly') + { + $st_date = explode("-",$tempdate); + $date_arr = Array( + 'day' => $st_date[2], + 'month' => $st_date[1], + 'year' => $st_date[0] + ); + $tempdateObj = new vt_DateTime($date_arr,true); + if(count($this->dayofweek_to_rpt) == 0) + $this->dayofweek_to_rpt[] = $this->startdate->dayofweek; + for($i=0;$idayofweek_to_rpt);$i++) + { + + $repeatDay = $tempdateObj->getThisweekDaysbyIndex($this->dayofweek_to_rpt[$i]); + $repeatDate= $repeatDay->get_formatted_date(); + if($repeatDate > $startdate && $repeatDate <= $enddate) + $recurringDates[] = $repeatDate; + } + + if(isset($this->recur_freq)) + $index = $this->recur_freq * 7; + else + $index = 7; + $date_arr = Array( + 'day' => $st_date[2] + $index, + 'month' => $st_date[1], + 'year' => $st_date[0] + ); + $tempdateObj = new vt_DateTime($date_arr,true); + $tempdate = $tempdateObj->get_formatted_date(); + } + elseif($this->recur_type == 'Monthly') + { + $st_date = explode("-",$tempdate); + $date_arr = Array( + 'day' => $st_date[2], + 'month' => $st_date[1], + 'year' => $st_date[0] + ); + $startdateObj = new vt_DateTime($date_arr,true); + if($this->repeat_monthby == 'date') + { + if($this->rptmonth_datevalue <= $st_date[2]) + { + $index = $this->rptmonth_datevalue - 1; + $day = $this->rptmonth_datevalue; + if(isset($this->recur_freq)) + $month = $st_date[1] + $this->recur_freq; + else + $month = $st_date[1] + 1; + $year = $st_date[0]; + $tempdateObj = $startdateObj->getThismonthDaysbyIndex($index,$day,$month,$year); + } + else + { + $index = $this->rptmonth_datevalue - 1; + $day = $this->rptmonth_datevalue; + $month = $st_date[1]; + $year = $st_date[0]; + $tempdateObj = $startdateObj->getThismonthDaysbyIndex($index,$day,$month,$year); + } + } + elseif($this->repeat_monthby == 'day') + { + if($this->rptmonth_daytype == 'first') + { + $date_arr = Array( + 'day' => 1, + 'month' => $st_date[1], + 'year' => $st_date[0] + ); + $tempdateObj = new vt_DateTime($date_arr,true); + $firstdayofmonthObj = $this->getFistdayofmonth($this->dayofweek_to_rpt[0],$tempdateObj); + if($firstdayofmonthObj->get_formatted_date() <= $tempdate) + { + if(isset($this->recur_freq)) + $month = $firstdayofmonthObj->month + $this->recur_freq; + else + $month = $firstdayofmonthObj->month + 1; + $dateObj = $firstdayofmonthObj->getThismonthDaysbyIndex(0,1,$month,$firstdayofmonthObj->year); + $nextmonthObj = $this->getFistdayofmonth($this->dayofweek_to_rpt[0],$dateObj); + $tempdateObj = $nextmonthObj; + } + else + { + $tempdateObj = $firstdayofmonthObj; + } + + } + elseif($this->rptmonth_daytype == 'last') + { + $date_arr = Array( + 'day' => $startdateObj->daysinmonth, + 'month' => $startdateObj->month, + 'year' => $startdateObj->year + ); + $tempdateObj = new vt_DateTime($date_arr,true); + $lastdayofmonthObj = $this->getLastdayofmonth($this->dayofweek_to_rpt[0],$tempdateObj); + if($lastdayofmonthObj->get_formatted_date() <= $tempdate) + { + if(isset($this->recur_freq)) + $month = $lastdayofmonthObj->month + $this->recur_freq; + else + $month = $lastdayofmonthObj->month + 1; + $dateObj = $lastdayofmonthObj->getThismonthDaysbyIndex(0,1,$month,$lastdayofmonthObj->year); + $dateObj = $dateObj->getThismonthDaysbyIndex($dateObj->daysinmonth-1,$dateObj->daysinmonth,$month,$lastdayofmonthObj->year); + $nextmonthObj = $this->getLastdayofmonth($this->dayofweek_to_rpt[0],$dateObj); + $tempdateObj = $nextmonthObj; + } + else + { + $tempdateObj = $lastdayofmonthObj; + } + } + } + else + { + $date_arr = Array( + 'day' => $st_date[2], + 'month' => $st_date[1]+1, + 'year' => $st_date[0] + ); + $tempdateObj = new vt_DateTime($date_arr,true); + } + $tempdate = $tempdateObj->get_formatted_date(); + $recurringDates[] = $tempdate; + } + elseif($this->recur_type == 'Yearly') + { + $st_date = explode("-",$tempdate); + if(isset($this->recur_freq)) + $index = $st_date[0] + $this->recur_freq; + else + $index = $st_date[0] + 1; + if ($index > 2037 || $index < 1970) + { + print("".$app_strings['LBL_CAL_LIMIT_MSG'].""); + exit; + } + $date_arr = Array( + 'day' => $st_date[2], + 'month' => $st_date[1], + 'year' => $index + ); + $tempdateObj = new vt_DateTime($date_arr,true); + $tempdate = $tempdateObj->get_formatted_date(); + $recurringDates[] = $tempdate; + } + else + { + die("Recurring Type ".$this->recur_type." is not defined"); + } + } + return $recurringDates; + } + + /** Function to get first day of the month(like first Monday or Friday and etc.) + * @param $dayofweek -- day of the week to repeat the event :: Type string + * @param $dateObj -- date object :: Type vt_DateTime Object + * return $dateObj -- the date object on which the event repeats :: Type vt_DateTime Object + */ + function getFistdayofmonth($dayofweek,& $dateObj) + { + if($dayofweek < $dateObj->dayofweek) + { + $index = (7 - $dateObj->dayofweek) + $dayofweek; + $day = 1 + $index; + $month = $dateObj->month; + $year = $dateObj->year; + $dateObj = $dateObj->getThismonthDaysbyIndex($index,$day,$month,$year); + } + else + { + $index = $dayofweek - $dateObj->dayofweek; + $day = 1 + $index; + $month = $dateObj->month; + $year = $dateObj->year; + $dateObj = $dateObj->getThismonthDaysbyIndex($index,$day,$month,$year); + } + return $dateObj; + } + + /** Function to get last day of the month(like last Monday or Friday and etc.) + * @param $dayofweek -- day of the week to repeat the event :: Type string + * @param $dateObj -- date object :: Type vt_DateTime Object + * return $dateObj -- the date object on which the event repeats :: Type vt_DateTime Object + */ + + function getLastdayofmonth($dayofweek,& $dateObj) + { + if($dayofweek == $dateObj->dayofweek) + { + return $dateObj; + } + else + { + if($dayofweek > $dateObj->dayofweek) + $day = $dateObj->day - 7 + ($dayofweek - $dateObj->dayofweek); + else + $day = $dateObj->day - ($dateObj->dayofweek - $dayofweek); + $index = $day - 1; + $month = $dateObj->month; + $year = $dateObj->year; + $dateObj = $dateObj->getThismonthDaysbyIndex($index,$day,$month,$year); + return $dateObj; + } + + } + +} + +?> diff --git a/oss/vtiger/trunk/include/utils/SearchUtils.php b/oss/vtiger/trunk/include/utils/SearchUtils.php index 270edcfa..f52df225 100644 --- a/oss/vtiger/trunk/include/utils/SearchUtils.php +++ b/oss/vtiger/trunk/include/utils/SearchUtils.php @@ -1,1097 +1,1173 @@ -debug("Entering getSearchListHeaderValues(".get_class($focus).",". $module.",".$sort_qry.",".$sorder.",".$order_by.",".$relatedlist.",".get_class($oCv).") method ..."); - global $adb; - global $theme; - global $app_strings; - global $mod_strings,$current_user; - - $arrow=''; - $qry = getURLstring($focus); - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - $search_header = Array(); - - //Get the vtiger_tabid of the module - //require_once('include/utils/UserInfoUtil.php') - $tabid = getTabid($module); - //added for vtiger_customview 27/5 - if($oCv) - { - if(isset($oCv->list_fields)) - { - $focus->list_fields = $oCv->list_fields; - } - } - //Added to reduce the no. of queries logging for non-admin vtiger_users -- by Minnie-start - $field_list = array(); - $j=0; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - foreach($focus->list_fields as $name=>$tableinfo) - { - $fieldname = $focus->list_fields_name[$name]; - if($oCv) - { - if(isset($oCv->list_fields_name)) - { - $fieldname = $oCv->list_fields_name[$name]; - } - } - if($fieldname == "accountname" && $module !="Accounts") - $fieldname = "account_id"; - - if($fieldname == "productname" && $module =="Campaigns") - $fieldname = "product_id"; - - if($fieldname == "lastname" && $module !="Leads" && $module !="Contacts") - { - $fieldname = "contact_id"; - } - if($fieldname == 'folderid' && $module == 'Documents'){ - $fieldname = 'foldername'; - } - array_push($field_list, $fieldname); - $j++; - } - //Getting the Entries from Profile2 vtiger_field vtiger_table - if($is_admin == false) - { - $profileList = getCurrentUserProfileList(); - //changed to get vtiger_field.fieldname - $query = "SELECT vtiger_profile2field.*,vtiger_field.fieldname FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; - if( $adb->dbType == "pgsql") - $query = fixPostgresQuery( $query, $log, 0); - $result = $adb->pquery($query, array($tabid, $profileList, $field_list)); - $field=Array(); - for($k=0;$k < $adb->num_rows($result);$k++) - { - $field[]=$adb->query_result($result,$k,"fieldname"); - } - - //if this field array is empty and the user don't have any one of the admin, view all, edit all permissions then the search picklist options will be empty and we cannot navigate the users list - js error will thrown in function getListViewEntries_js in Smarty\templates\Popup.tpl - if($module == 'Users' && empty($field)) - $field = Array("last_name","email1"); - } - - // Remove fields which are made inactive - $focus->filterInactiveFields($module); - - //modified for vtiger_customview 27/5 - $app_strings change to $mod_strings - foreach($focus->list_fields as $name=>$tableinfo) - { - //added for vtiger_customview 27/5 - if($oCv) - { - if(isset($oCv->list_fields_name)) - { - if( $oCv->list_fields_name[$name] == '') - $fieldname = 'crmid'; - else - $fieldname = $oCv->list_fields_name[$name]; - - }else - { - if( $focus->list_fields_name[$name] == '') - $fieldname = 'crmid'; - else - $fieldname = $focus->list_fields_name[$name]; - - } - if($fieldname == "lastname" && $module !="Leads" && $module !="Contacts") - $fieldname = "contact_id"; - if($fieldname == "accountname" && $module !="Accounts") - $fieldname = "account_id"; - if($fieldname == "productname" && $module =="Campaigns") - $fieldname = "product_id"; - - - } - else - { - if( $focus->list_fields_name[$name] == '') - $fieldname = 'crmid'; - else - $fieldname = $focus->list_fields_name[$name]; - - if($fieldname == "lastname" && $module !="Leads" && $module !="Contacts") - $fieldname = "contact_id"; - } - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field)) - { - if($fieldname!='parent_id') - { - $fld_name=$fieldname; - if($fieldname == 'contact_id' && $module !="Contacts") - $name = $app_strings['LBL_CONTACT_LAST_NAME']; - elseif($fieldname == 'contact_id' && $module =="Contacts") - $name = $mod_strings['Reports To']." - ".$mod_strings['LBL_LIST_LAST_NAME']; - //assign the translated string - //added to fix #5205 - //Added condition to hide the close column in calendar search header - if($name != $app_strings['Close']) - $search_header[$fld_name] = getTranslatedString($name); - } - } - if($module == 'HelpDesk' && $fieldname == 'crmid') - { - $fld_name=$fieldname; - $search_header[$fld_name] = getTranslatedString($name); - } - } - $log->debug("Exiting getSearchListHeaderValues method ..."); - return $search_header; - -} - -/**This function is used to get the where condition for search listview query along with url_string -*Param $module - module name -*Returns the where conditions and url_string values in string format -*/ - -function Search($module) -{ - global $log,$default_charset; - $log->debug("Entering Search(".$module.") method ..."); - $url_string=''; - if(isset($_REQUEST['search_field']) && $_REQUEST['search_field'] !="") { - $search_column=vtlib_purify($_REQUEST['search_field']); - } - if(isset($_REQUEST['search_text']) && $_REQUEST['search_text']!="") { - // search other characters like "|, ?, ?" by jagi - $search_string = $_REQUEST['search_text']; - $stringConvert = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$search_string) : $search_string; - $search_string=trim($stringConvert); - } - if(isset($_REQUEST['searchtype']) && $_REQUEST['searchtype']!="") { - $search_type=vtlib_purify($_REQUEST['searchtype']); - if($search_type == "BasicSearch") { - $where=BasicSearch($module,$search_column,$search_string); - } else if ($search_type == "AdvanceSearch") { - } else { //Global Search - } - $url_string = "&search_field=".$search_column."&search_text=".urlencode($search_string)."&searchtype=BasicSearch"; - if(isset($_REQUEST['type']) && $_REQUEST['type'] != '') - $url_string .= "&type=".vtlib_purify($_REQUEST['type']); - $log->debug("Exiting Search method ..."); - return $where."#@@#".$url_string; - } -} - -/**This function is used to get user_id's for a given user_name during search -*Param $table_name - vtiger_tablename -*Param $column_name - columnname -*Param $search_string - searchstring value (username) -*Returns the where conditions for list query in string format -*/ - -function get_usersid($table_name,$column_name,$search_string) -{ - - global $log; - $log->debug("Entering get_usersid(".$table_name.",".$column_name.",".$search_string.") method ..."); - global $adb; - $user_qry="select distinct(vtiger_users.id)from vtiger_users inner join vtiger_crmentity on vtiger_crmentity.smownerid=vtiger_users.id where vtiger_users.user_name like '" . formatForSqlLike($search_string) . "'"; - $user_result=$adb->pquery($user_qry, array()); - $noofuser_rows=$adb->num_rows($user_result); - $x=$noofuser_rows-1; - if($noofuser_rows!=0) - { - $where="("; - for($i=0;$i<$noofuser_rows;$i++) - { - $user_id=$adb->query_result($user_result,$i,'id'); - $where .= "$table_name.$column_name =".$user_id; - if($i != $x) - { - $where .= " or "; - } - } - $where.=" or vtiger_groups.groupname like '". formatForSqlLike($search_string) ."')"; - } - else - { - $where=" vtiger_groups.groupname like '". formatForSqlLike($search_string) ."' "; - } - $log->debug("Exiting get_usersid method ..."); - return $where; -} - -/**This function is used to get where conditions for a given vtiger_accountid or contactid during search for their respective names -*Param $column_name - columnname -*Param $search_string - searchstring value (username) -*Returns the where conditions for list query in string format -*/ - - -function getValuesforColumns($column_name,$search_string,$criteria='cts') -{ - global $log, $current_user; - $log->debug("Entering getValuesforColumns(".$column_name.",".$search_string.") method ..."); - global $column_array,$table_col_array; - - if($_REQUEST['type'] == "entchar") - $criteria = "is"; - - for($i=0; $iid,'firstname') == '0') { - $where = "concat(vtiger_contactdetails.lastname, ' ', vtiger_contactdetails.firstname) = '$search_string'"; - } else { - $where = "vtiger_contactdetails.lastname = '$search_string'"; - } - } - else { - $where="("; - for($j=0;$jdebug("Exiting getValuesforColumns method ..."); - return $where; -} - -/**This function is used to get where conditions in Basic Search -*Param $module - module name -*Param $search_field - columnname/field name in which the string has be searched -*Param $search_string - searchstring value (username) -*Returns the where conditions for list query in string format -*/ - -function BasicSearch($module,$search_field,$search_string){ - global $log,$mod_strings,$current_user; - $log->debug("Entering BasicSearch(".$module.",".$search_field.",".$search_string.") method ..."); - global $adb; - $search_string = ltrim(rtrim($adb->sql_escape_string($search_string))); - global $column_array,$table_col_array; - if($search_field =='crmid'){ - $column_name='crmid'; - $table_name='vtiger_crmentity'; - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - }elseif($search_field =='currency_id' && ($module == 'PriceBooks' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice' || $module == 'Quotes')){ - $column_name='currency_name'; - $table_name='vtiger_currency_info'; - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - }elseif($search_field == 'folderid' && $module == 'Documents'){ - $column_name='foldername'; - $table_name='vtiger_attachmentsfolder'; - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - }else{ - //Check added for tickets by accounts/contacts in dashboard - $search_field_first = $search_field; - if($module=='HelpDesk'){ - if($search_field == 'contactid'){ - $where = "(vtiger_contactdetails.contact_no like '". formatForSqlLike($search_string) ."')"; - return $where; - }elseif($search_field == 'account_id'){ - $search_field = "parent_id"; - } - } - //Check ends - - //Added to search contact name by lastname - if(($module == "Calendar" || $module == "Invoice" || $module == "Documents" || $module == "SalesOrder" || $module== "PurchaseOrder") && ($search_field == "contact_id")){ - $module = 'Contacts'; - $search_field = 'lastname'; - } - if($search_field == "accountname" && $module != "Accounts"){ - $search_field = "account_id"; - } - if($search_field == 'productname' && $module == 'Campaigns'){ - $search_field = "product_id"; - } - - $qry="select vtiger_field.columnname,tablename from vtiger_tab inner join vtiger_field on vtiger_field.tabid=vtiger_tab.tabid where vtiger_tab.name=? and (fieldname=? or columnname=?)"; - $result = $adb->pquery($qry, array($module, $search_field, $search_field)); - $noofrows = $adb->num_rows($result); - if($noofrows!=0) - { - $column_name=$adb->query_result($result,0,'columnname'); - - //Check added for tickets by accounts/contacts in dashboard - if ($column_name == 'parent_id') - { - if ($search_field_first == 'account_id') $search_field_first = 'accountid'; - if ($search_field_first == 'contactid') $search_field_first = 'contact_id'; - $column_name = $search_field_first; - } - - //Check ends - $table_name=$adb->query_result($result,0,'tablename'); - $uitype=getUItype($module,$column_name); - - //Added for Member of search in Accounts - if($column_name == "parentid" && $module == "Accounts") - { - $table_name = "vtiger_account2"; - $column_name = "accountname"; - } - if($column_name == "parentid" && $module == "Products") - { - $table_name = "vtiger_products2"; - $column_name = "productname"; - } - if($column_name == "reportsto" && $module == "Contacts") - { - $table_name = "vtiger_contactdetails2"; - $column_name = "lastname"; - } - if($column_name == "inventorymanager" && $module = "Quotes") - { - $table_name = "vtiger_usersQuotes"; - $column_name = "user_name"; - } - //Added to support user date format in basic search - if($uitype == 5 || $uitype == 6 || $uitype == 23 || $uitype == 70) - { - list($sdate,$stime) = split(" ",$search_string); - if($stime !='') - $search_string = getDBInsertDateValue($sdate)." ".$stime; - else - $search_string = getDBInsertDateValue($sdate); - } - // Added to fix errors while searching check box type fields(like product active. ie. they store 0 or 1. we search them as yes or no) in basic search. - if ($uitype == 56) - { - if(strtolower($search_string) == 'yes') - $where="$table_name.$column_name = '1'"; - elseif(strtolower($search_string) == 'no') - $where="$table_name.$column_name = '0'"; - else - $where="$table_name.$column_name = '-1'"; - - } - elseif ($uitype == 15 || $uitype == 16) - { - if(is_uitype($uitype, '_picklist_')) - { - // Get all the keys for the for the Picklist value - $mod_keys = array_keys($mod_strings, $search_string); - if(sizeof($mod_keys) >= 1) - { - // Iterate on the keys, to get the first key which doesn't start with LBL_ (assuming it is not used in PickList) - foreach($mod_keys as $mod_idx=>$mod_key) - { - $stridx = strpos($mod_key, 'LBL_'); - // Use strict type comparision, refer strpos for more details - if ($stridx !== 0) - { - $search_string = $mod_key; - if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($tab_col == "vtiger_activity.status" || $tab_col == "vtiger_activity.eventstatus")) - { - $where="(vtiger_activity.status like '". formatForSqlLike($search_string) ."' or vtiger_activity.eventstatus like '". formatForSqlLike($search_string) ."')"; - } - else - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - break; - } - else //if the mod strings cointains LBL , just return the original search string. Not the key - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - } - } - else - { - if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($table_name == "vtiger_activity" && ($column_name == "status" || $column_name == "eventstatus"))) - { - $where="(vtiger_activity.status like '". formatForSqlLike($search_string) ."' or vtiger_activity.eventstatus like '". formatForSqlLike($search_string) ."')"; - } - else - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - } - } - } - elseif($table_name == "vtiger_crmentity" && $column_name == "smownerid") - { - $where = get_usersid($table_name,$column_name,$search_string); - } - else if(in_array($column_name,$column_array)) - { - $where = getValuesforColumns($column_name,$search_string); - } - else if($_REQUEST['type'] == 'entchar') - { - $where="$table_name.$column_name = '". $search_string ."'"; - } - else - { - $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; - } - } - } - if(stristr($where,"like '%%'")) - { - $where_cond0=str_replace("like '%%'","like ''",$where); - $where_cond1=str_replace("like '%%'","is NULL",$where); - if($module == "Calendar") - $where = "(".$where_cond0." and ".$where_cond1.")"; - else - $where = "(".$where_cond0." or ".$where_cond1.")"; - } - // commented to support searching "%" with the search string. - if($_REQUEST['type'] == 'alpbt'){ - $where = str_replace_once("%", "", $where); - } - - //uitype 10 handling - if($uitype == 10){ - $where = array(); - $sql = "select fieldid from vtiger_field where tabid=? and fieldname=?"; - $result = $adb->pquery($sql, array(getTabid($module), $search_field)); - - if($adb->num_rows($result)>0){ - $fieldid = $adb->query_result($result, 0, "fieldid"); - $sql = "select * from vtiger_fieldmodulerel where fieldid=?"; - $result = $adb->pquery($sql, array($fieldid)); - $count = $adb->num_rows($result); - $searchString = formatForSqlLike($search_string); - - for($i=0;$i<$count;$i++){ - $relModule = $adb->query_result($result, $i, "relmodule"); - $relInfo = getEntityField($relModule); - $relTable = $relInfo["tablename"]; - $relField = $relInfo["fieldname"]; - - if(strpos($relField, 'concat') !== false){ - $where[] = "$relField like '$searchString'"; - }else{ - $where[] = "$relTable.$relField like '$searchString'"; - } - - } - $where = implode(" or ", $where); - } - $where = "($where) "; - } - - $log->debug("Exiting BasicSearch method ..."); - return $where; -} - -/**This function is used to get where conditions in Advance Search -*Param $module - module name -*Returns the where conditions for list query in string format -*/ - -function getAdvSearchfields($module) -{ - global $log; - $log->debug("Entering getAdvSearchfields(".$module.") method ..."); - global $adb; - global $current_user; - global $mod_strings,$app_strings; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - $tabid = getTabid($module); - if($tabid==9) - $tabid="9,16"; - - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) - { - $sql = "select * from vtiger_field "; - $sql.= " where vtiger_field.tabid in(?) and"; - $sql.= " vtiger_field.displaytype in (1,2,3) and vtiger_field.presence in (0,2)"; - if($tabid == 13 || $tabid == 15) - { - $sql.= " and vtiger_field.fieldlabel != 'Add Comment'"; - } - if($tabid == 14) - { - $sql.= " and vtiger_field.fieldlabel != 'Product Image'"; - } - if($tabid == 9 || $tabid==16) - { - $sql.= " and vtiger_field.fieldname not in('notime','duration_minutes','duration_hours')"; - } - if($tabid == 4) - { - $sql.= " and vtiger_field.fieldlabel != 'Contact Image'"; - } - if($tabid == 13 || $tabid == 10) - { - $sql.= " and vtiger_field.fieldlabel != 'Attachment'"; - } - $sql.= " group by vtiger_field.fieldlabel order by block,sequence"; - - $params = array($tabid); - } - else - { - $profileList = getCurrentUserProfileList(); - $sql = "select * from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid "; - $sql.= " where vtiger_field.tabid in(?) and"; - $sql.= " vtiger_field.displaytype in (1,2,3) and vtiger_field.presence in (0,2) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0"; - - $params = array($tabid); - - if (count($profileList) > 0) { - $sql.= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; - array_push($params, $profileList); - } - - if($tabid == 13 || $tabid == 15) - { - $sql.= " and vtiger_field.fieldlabel != 'Add Comment'"; - } - if($tabid == 14) - { - $sql.= " and vtiger_field.fieldlabel != 'Product Image'"; - } - if($tabid == 9 || $tabid==16) - { - $sql.= " and vtiger_field.fieldname not in('notime','duration_minutes','duration_hours')"; - } - if($tabid == 4) - { - $sql.= " and vtiger_field.fieldlabel != 'Contact Image'"; - } - if($tabid == 13 || $tabid == 10) - { - $sql.= " and vtiger_field.fieldlabel != 'Attachment'"; - } - $sql .= " group by vtiger_field.fieldlabel order by block,sequence"; - } - - $result = $adb->pquery($sql, $params); - $noofrows = $adb->num_rows($result); - $block = ''; - $select_flag = ''; - - for($i=0; $i<$noofrows; $i++) - { - $fieldtablename = $adb->query_result($result,$i,"tablename"); - $fieldcolname = $adb->query_result($result,$i,"columnname"); - $block = $adb->query_result($result,$i,"block"); - $fieldtype = $adb->query_result($result,$i,"typeofdata"); - $fieldtype = explode("~",$fieldtype); - $fieldtypeofdata = $fieldtype[0]; - if($fieldcolname == 'account_id' || $fieldcolname == 'accountid' || $fieldcolname == 'product_id' || $fieldcolname == 'vendor_id' || $fieldcolname == 'contact_id' || $fieldcolname == 'contactid' || $fieldcolname == 'vendorid' || $fieldcolname == 'potentialid' || $fieldcolname == 'salesorderid' || $fieldcolname == 'quoteid' || $fieldcolname == 'parentid' || $fieldcolname == "recurringtype" || $fieldcolname == "campaignid" || $fieldcolname == "inventorymanager" || $fieldcolname == "handler" || $fieldcolname == "currency_id") - $fieldtypeofdata = "V"; - if($fieldcolname == "discontinued" || $fieldcolname == "active") - $fieldtypeofdata = "C"; - $fieldlabel = $mod_strings[$adb->query_result($result,$i,"fieldlabel")]; - - // Added to display customfield label in search options - if($fieldlabel == "") - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - - if($fieldlabel == "Related To") - { - $fieldlabel = "Related to"; - } - if($fieldlabel == "Start Date & Time") - { - $fieldlabel = "Start Date"; - if($module == 'Activities' && $block == 19) - $module_columnlist['vtiger_activity:time_start::Activities_Start Time:I'] = 'Start Time'; - - } - //$fieldlabel1 = str_replace(" ","_",$fieldlabel); // Is not used anywhere - //Check added to search the lists by Inventory manager - if($fieldtablename == 'vtiger_quotes' && $fieldcolname == 'inventorymanager') - { - $fieldtablename = 'vtiger_usersQuotes'; - $fieldcolname = 'user_name'; - } - if($fieldtablename == 'vtiger_contactdetails' && $fieldcolname == 'reportsto') - { - $fieldtablename = 'vtiger_contactdetails2'; - $fieldcolname = 'lastname'; - } - if($fieldtablename == 'vtiger_notes' && $fieldcolname == 'folderid'){ - $fieldtablename = 'vtiger_attachmentsfolder'; - $fieldcolname = 'foldername'; - } - if($fieldlabel != 'Related to') - { - if ($i==0) - $select_flag = "selected"; - - $mod_fieldlabel = $mod_strings[$fieldlabel]; - if($mod_fieldlabel =="") $mod_fieldlabel = $fieldlabel; - - if($fieldlabel == "Product Code") - $OPTION_SET .= ""; - if($fieldlabel == "Reports To") - $OPTION_SET .= ""; - elseif($fieldcolname == "contactid" || $fieldcolname == "contact_id") - { - $OPTION_SET .= ""; - $OPTION_SET .= ""; - } - elseif($fieldcolname == "campaignid") - $OPTION_SET .= ""; - else - $OPTION_SET .= ""; - } - } - //Added to include Ticket ID in HelpDesk advance search - if($module == 'HelpDesk') - { - $mod_fieldlabel = $mod_strings['Ticket ID']; - if($mod_fieldlabel =="") $mod_fieldlabel = 'Ticket ID'; - - $OPTION_SET .= ""; - } - //Added to include activity type in activity advance search - if($module == 'Activities') - { - $mod_fieldlabel = $mod_strings['Activity Type']; - if($mod_fieldlabel =="") $mod_fieldlabel = 'Activity Type'; - - $OPTION_SET .= ""; - } - $log->debug("Exiting getAdvSearchfields method ..."); - return $OPTION_SET; -} - -/**This function is returns the search criteria options for Advance Search -*takes no parameter -*Returns the criteria option in html format -*/ - -function getcriteria_options() -{ - global $log,$app_strings; - $log->debug("Entering getcriteria_options() method ..."); - $CRIT_OPT = ""; - $log->debug("Exiting getcriteria_options method ..."); - return $CRIT_OPT; -} - -/**This function is returns the where conditions for each search criteria option in Advance Search -*Param $criteria - search criteria option -*Param $searchstring - search string -*Param $searchfield - vtiger_fieldname to be search for -*Returns the search criteria option (where condition) to be added in list query -*/ - -function getSearch_criteria($criteria,$searchstring,$searchfield) -{ - global $log; - $log->debug("Entering getSearch_criteria(".$criteria.",".$searchstring.",".$searchfield.") method ..."); - $searchstring = ltrim(rtrim($searchstring)); - if(($searchfield != "vtiger_troubletickets.update_log") && ($searchfield == "vtiger_crmentity.modifiedtime" || $searchfield == "vtiger_crmentity.createdtime" || stristr($searchfield,'date'))) - { - list($sdate,$stime) = split(" ",$searchstring); - if($stime !='') - $searchstring = getDBInsertDateValue($sdate)." ".$stime; - else - $searchstring = getDBInsertDateValue($sdate); - } - if($searchfield == "vtiger_account.parentid") - $searchfield = "vtiger_account2.accountname"; - if($searchfield == "vtiger_pricebook.currency_id" || $searchfield == "vtiger_quotes.currency_id" || $searchfield == "vtiger_invoice.currency_id" - || $searchfield == "vtiger_purchaseorder.currency_id" || $searchfield == "vtiger_salesorder.currency_id") - $searchfield = "vtiger_currency_info.currency_name"; - $where_string = ''; - switch($criteria) - { - case 'cts': - $where_string = $searchfield." like '". formatForSqlLike($searchstring) ."' "; - if($searchstring == NULL) - { - $where_string = "(".$searchfield." like '' or ".$searchfield." is NULL)"; - } - break; - - case 'dcts': - if($searchfield == "vtiger_users.user_name" || $searchfield =="vtiger_groups.groupname") - $where_string = "(".$searchfield." not like '". formatForSqlLike($searchstring) ."')"; - else - $where_string = "(".$searchfield." not like '". formatForSqlLike($searchstring) ."' or ".$searchfield." is null)"; - if($searchstring == NULL) - $where_string = "(".$searchfield." not like '' or ".$searchfield." is not NULL)"; - break; - - case 'is': - $where_string = $searchfield." = '".$searchstring."' "; - if($searchstring == NULL) - $where_string = "(".$searchfield." is NULL or ".$searchfield." = '')"; - break; - - case 'isn': - if($searchfield == "vtiger_users.user_name" || $searchfield =="vtiger_groups.groupname") - $where_string = "(".$searchfield." <> '".$searchstring."')"; - else - $where_string = "(".$searchfield." <> '".$searchstring."' or ".$searchfield." is null)"; - if($searchstring == NULL) - $where_string = "(".$searchfield." not like '' and ".$searchfield." is not NULL)"; - break; - - case 'bwt': - $where_string = $searchfield." like '". formatForSqlLike($searchstring, 2) ."' "; - break; - - case 'ewt': - $where_string = $searchfield." like '". formatForSqlLike($searchstring, 1) ."' "; - break; - - case 'grt': - $where_string = $searchfield." > '".$searchstring."' "; - break; - - case 'lst': - $where_string = $searchfield." < '".$searchstring."' "; - break; - - case 'grteq': - $where_string = $searchfield." >= '".$searchstring."' "; - break; - - case 'lsteq': - $where_string = $searchfield." <= '".$searchstring."' "; - break; - - - } - $log->debug("Exiting getSearch_criteria method ..."); - return $where_string; -} - -/**This function is returns the where conditions for search -*Param $currentModule - module name -*Returns the where condition to be added in list query in string format -*/ - -function getWhereCondition($currentModule) -{ - global $log,$default_charset,$adb; - global $column_array,$table_col_array,$mod_strings,$current_user; - - $log->debug("Entering getWhereCondition(".$currentModule.") method ..."); - - if($_REQUEST['searchtype']=='advance') - { - $adv_string=''; - $url_string=''; - if(isset($_REQUEST['search_cnt'])) - $tot_no_criteria = vtlib_purify($_REQUEST['search_cnt']); - if($_REQUEST['matchtype'] == 'all') - $matchtype = "and"; - else - $matchtype = "or"; - for($i=0; $i<$tot_no_criteria; $i++) - { - if($i == $tot_no_criteria-1) - $matchtype= ""; - - $table_colname = 'Fields'.$i; - $search_condition = 'Condition'.$i; - $search_value = 'Srch_value'.$i; - - list($tab_col_val,$typeofdata) = split("::::",$_REQUEST[$table_colname]); - $tab_col = str_replace('\'','',stripslashes($tab_col_val)); - $srch_cond = str_replace('\'','',stripslashes($_REQUEST[$search_condition])); - $srch_val = $_REQUEST[$search_value]; - $srch_val = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$srch_val) : $srch_val; - $url_string .="&Fields".$i."=".$tab_col."&Condition".$i."=".$srch_cond."&Srch_value".$i."=".urlencode($srch_val); - $srch_val = $adb->sql_escape_string($srch_val); - list($tab_name,$column_name) = split("[.]",$tab_col); - $uitype=getUItype($currentModule,$column_name); - //added to allow search in check box type fields(ex: product active. it will contain 0 or 1) using yes or no instead of 0 or 1 - if ($uitype == 56) - { - if(strtolower($srch_val) == 'yes') - $adv_string .= " ".getSearch_criteria($srch_cond,"1",$tab_name.'.'.$column_name)." ".$matchtype; - elseif(strtolower($srch_val) == 'no') - $adv_string .= " ".getSearch_criteria($srch_cond,"0",$tab_name.'.'.$column_name)." ".$matchtype; - else - $adv_string .= " ".getSearch_criteria($srch_cond,"-1",$tab_name.'.'.$column_name)." ".$matchtype; - } - elseif ($uitype == 15 || $uitype == 16) - { - if(is_uitype($uitype, '_picklist_')) { - // Get all the keys for the for the Picklist value - $mod_keys = array_keys($mod_strings, $srch_val); - if(sizeof($mod_keys) >= 1) - { - // Iterate on the keys, to get the first key which doesn't start with LBL_ (assuming it is not used in PickList) - foreach($mod_keys as $mod_idx=>$mod_key) { - $stridx = strpos($mod_key, 'LBL_'); - // Use strict type comparision, refer strpos for more details - if ($stridx !== 0) - { - $srch_val = $mod_key; - if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($tab_col == "vtiger_activity.status" || $tab_col == "vtiger_activity.eventstatus")) - { - if($srch_cond == 'dcts' || $srch_cond == 'isn' || $srch_cond == 'is') - $re_cond = "and"; - else - $re_cond = "or"; - if($srch_cond == 'is' && $srch_val !='') - $re_cond = "or"; - - $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.status')." ".$re_cond; - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.eventstatus')." )".$matchtype; - } - else - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_name.'.'.$column_name)." ".$matchtype; - break; - } - else //if the key contains the LBL, then return the original srch_val. - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_name.'.'.$column_name)." ".$matchtype; - - } - - } - else - { - if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($tab_col == "vtiger_activity.status" || $tab_col == "vtiger_activity.eventstatus")) - { - if($srch_cond == 'dcts' || $srch_cond == 'isn' || $srch_cond == 'is') - $re_cond = "and"; - else - $re_cond = "or"; - if($srch_cond == 'is' && $srch_val !='') - $re_cond = "or"; - - $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.status')." ".$re_cond; - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.eventstatus')." )".$matchtype; - } - else - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_col)." ".$matchtype; - } - } - } - - elseif($tab_col == "vtiger_crmentity.smownerid") - { - $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_users.user_name')." or"; - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_groups.groupname')." )".$matchtype; - } - elseif($tab_col == "vtiger_cntactivityrel.contactid") - { - $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_contactdetails.firstname')." or"; - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_contactdetails.lastname')." )".$matchtype; - } - elseif(in_array($column_name,$column_array)) - { - $adv_string .= " ".getValuesforColumns($column_name,$srch_val,$srch_cond)." ".$matchtype; - } - else - { - $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_col)." ".$matchtype; - } - } - $where="(".$adv_string.")#@@#".$url_string."&searchtype=advance&search_cnt=".$tot_no_criteria."&matchtype=".vtlib_purify($_REQUEST['matchtype']); - } - elseif($_REQUEST['type']=='dbrd') - { - $where = getdashboardcondition(); - } - else - { - $where=Search($currentModule); - } - $log->debug("Exiting getWhereCondition method ..."); - return $where; - -} - -/**This function is returns the where conditions for dashboard and shows the records when clicked on dashboard graph -*Takes no parameter, process the values got from the html request object -*Returns the search criteria option (where condition) to be added in list query -*/ - -function getdashboardcondition() -{ - global $adb; - $where_clauses = Array(); - $url_string = ""; - - if (isset($_REQUEST['leadsource'])) $lead_source = $_REQUEST['leadsource']; - if (isset($_REQUEST['date_closed'])) $date_closed = $_REQUEST['date_closed']; - if (isset($_REQUEST['sales_stage'])) $sales_stage = $_REQUEST['sales_stage']; - if (isset($_REQUEST['closingdate_start'])) $date_closed_start = $_REQUEST['closingdate_start']; - if (isset($_REQUEST['closingdate_end'])) $date_closed_end = $_REQUEST['closingdate_end']; - if(isset($_REQUEST['owner'])) $owner = vtlib_purify($_REQUEST['owner']); - if(isset($_REQUEST['campaignid'])) $campaign = vtlib_purify($_REQUEST['campaignid']); - if(isset($_REQUEST['quoteid'])) $quote = vtlib_purify($_REQUEST['quoteid']); - if(isset($_REQUEST['invoiceid'])) $invoice = vtlib_purify($_REQUEST['invoiceid']); - if(isset($_REQUEST['purchaseorderid'])) $po = vtlib_purify($_REQUEST['purchaseorderid']); - - if(isset($date_closed_start) && $date_closed_start != "" && isset($date_closed_end) && $date_closed_end != "") - { - array_push($where_clauses, "vtiger_potential.closingdate >= ".$adb->quote($date_closed_start)." and vtiger_potential.closingdate <= ".$adb->quote($date_closed_end)); - $url_string .= "&closingdate_start=".$date_closed_start."&closingdate_end=".$date_closed_end; - } - - if(isset($sales_stage) && $sales_stage!=''){ - if($sales_stage=='Other') - array_push($where_clauses, "(vtiger_potential.sales_stage <> 'Closed Won' and vtiger_potential.sales_stage <> 'Closed Lost')"); - else - array_push($where_clauses, "vtiger_potential.sales_stage = ".$adb->quote($sales_stage)); - $url_string .= "&sales_stage=".$sales_stage; - } - if(isset($lead_source) && $lead_source != "") { - array_push($where_clauses, "vtiger_potential.leadsource = ".$adb->quote($lead_source)); - $url_string .= "&leadsource=".$lead_source; - } - if(isset($date_closed) && $date_closed != "") { - array_push($where_clauses, $adb->getDBDateString("vtiger_potential.closingdate")." like ".$adb->quote($date_closed.'%').""); - $url_string .= "&date_closed=".$date_closed; - } - if(isset($owner) && $owner != ""){ - $user_qry="select vtiger_users.id from vtiger_users where vtiger_users.user_name = ?"; - $res = $adb->pquery($user_qry, array($owner)); - $uid = $adb->query_result($res,0,'id'); - array_push($where_clauses, "vtiger_crmentity.smownerid = ".$uid); - //$url_string .= "&assigned_user_id=".$uid; - $url_string .= "&owner=".$owner; - } - if(isset($campaign) && $campaign != "") - { - array_push($where_clauses, "vtiger_campaigncontrel.campaignid = ".$campaign); - $url_string .= "&campaignid=".$campaign; - } - if(isset($quote) && $quote != "") - { - array_push($where_clauses, "vtiger_inventoryproductrel.id = ".$quote); - $url_string .= ""eid=".$quote; - } - if(isset($invoice) && $invoice != "") - { - array_push($where_clauses, "vtiger_inventoryproductrel.id = ".$invoice); - $url_string .= "&invoiceid=".$invoice; - } - if(isset($po) && $po != "") - { - array_push($where_clauses, "vtiger_inventoryproductrel.id = ".$po); - $url_string .= "&purchaseorderid=".$po; - } - if(isset($_REQUEST['from_homepagedb']) && $_REQUEST['from_homepagedb'] != '') { - $url_string .= "&from_homepagedb=".vtlib_purify($_REQUEST['from_homepagedb']); - } - if(isset($_REQUEST['type']) && $_REQUEST['type'] != '') { - $url_string .= "&type=".vtlib_purify($_REQUEST['type']); - } - - $where = ""; - foreach($where_clauses as $clause) - { - if($where != "") - $where .= " and "; - $where .= $clause; - } - return $where."#@@#".$url_string; -} - -/**This function is used to replace only the first occurence of a given string -Param $needle - string to be replaced -Param $replace - string to be replaced with -Param $replace - given string -Return type is string -*/ -function str_replace_once($needle, $replace, $haystack) -{ - // Looks for the first occurence of $needle in $haystack - // and replaces it with $replace. - $pos = strpos($haystack, $needle); - if ($pos === false) { - // Nothing found - return $haystack; - } - return substr_replace($haystack, $replace, $pos, strlen($needle)); -} - -/** - * Function to get the where condition for a module based on the field table entries - * @param string $listquery -- ListView query for the module - * @param string $module -- module name - * @param string $search_val -- entered search string value - * @return string $where -- where condition for the module based on field table entries - */ -function getUnifiedWhere($listquery,$module,$search_val){ - global $adb, $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - $search_val = $adb->sql_escape_string($search_val); - if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0){ - $query = "SELECT columnname, tablename FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; - $qparams = array(getTabid($module)); - }else{ - $profileList = getCurrentUserProfileList(); - $query = "SELECT columnname, tablename FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid = vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid = vtiger_field.fieldid WHERE vtiger_field.tabid = ? AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) . ") AND vtiger_def_org_field.visible = 0 and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; - $qparams = array(getTabid($module), $profileList); - } - $result = $adb->pquery($query, $qparams); - $noofrows = $adb->num_rows($result); - - $where = ''; - for($i=0;$i<$noofrows;$i++){ - $columnname = $adb->query_result($result,$i,'columnname'); - $tablename = $adb->query_result($result,$i,'tablename'); - - // Search / Lookup customization - if($module == 'Contacts' && $columnname == 'accountid') { - $columnname = "accountname"; - $tablename = "vtiger_account"; - } - // END - - //Before form the where condition, check whether the table for the field has been added in the listview query - if(strstr($listquery,$tablename)){ - if($where != ''){ - $where .= " OR "; - } - $where .= $tablename.".".$columnname." LIKE '". formatForSqlLike($search_val) ."'"; - } - } - return $where; -} - +debug("Entering getSearchListHeaderValues(".(is_object($focus)? get_class($focus):'').",". $module.",".$sort_qry.",".$sorder.",".$order_by.",".$relatedlist.",".(is_object($oCV)? get_class($oCV):'').") method ..."); + global $adb; + global $theme; + global $app_strings; + global $mod_strings,$current_user; + + $arrow=''; + $qry = getURLstring($focus); + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + $search_header = Array(); + + //Get the vtiger_tabid of the module + //require_once('include/utils/UserInfoUtil.php') + $tabid = getTabid($module); + //added for vtiger_customview 27/5 + if($oCv) + { + if(isset($oCv->list_fields)) + { + $focus->list_fields = $oCv->list_fields; + } + } + //Added to reduce the no. of queries logging for non-admin vtiger_users -- by Minnie-start + $field_list = array(); + $j=0; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + foreach($focus->list_fields as $name=>$tableinfo) + { + $fieldname = $focus->list_fields_name[$name]; + if($oCv) + { + if(isset($oCv->list_fields_name)) + { + $fieldname = $oCv->list_fields_name[$name]; + } + } + if($fieldname == "accountname" && $module !="Accounts") + $fieldname = "account_id"; + + if($fieldname == "productname" && $module =="Campaigns") + $fieldname = "product_id"; + + if($fieldname == "lastname" && $module !="Leads" && $module !="Contacts") + { + $fieldname = "contact_id"; + } + if($fieldname == 'folderid' && $module == 'Documents'){ + $fieldname = 'foldername'; + } + array_push($field_list, $fieldname); + $j++; + } + //Getting the Entries from Profile2 vtiger_field vtiger_table + if($is_admin == false) + { + $profileList = getCurrentUserProfileList(); + //changed to get vtiger_field.fieldname + $query = "SELECT vtiger_profile2field.*,vtiger_field.fieldname FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") AND vtiger_field.fieldname IN (". generateQuestionMarks($field_list) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; + if( $adb->dbType == "pgsql") + $query = fixPostgresQuery( $query, $log, 0); + $result = $adb->pquery($query, array($tabid, $profileList, $field_list)); + $field=Array(); + for($k=0;$k < $adb->num_rows($result);$k++) + { + $field[]=$adb->query_result($result,$k,"fieldname"); + } + + //if this field array is empty and the user don't have any one of the admin, view all, edit all permissions then the search picklist options will be empty and we cannot navigate the users list - js error will thrown in function getListViewEntries_js in Smarty\templates\Popup.tpl + if($module == 'Users' && empty($field)) + $field = Array("last_name","email1"); + } + + // Remove fields which are made inactive + $focus->filterInactiveFields($module); + + //modified for vtiger_customview 27/5 - $app_strings change to $mod_strings + foreach($focus->list_fields as $name=>$tableinfo) + { + //added for vtiger_customview 27/5 + if($oCv) + { + if(isset($oCv->list_fields_name)) + { + if( $oCv->list_fields_name[$name] == '') + $fieldname = 'crmid'; + else + $fieldname = $oCv->list_fields_name[$name]; + + }else + { + if( $focus->list_fields_name[$name] == '') + $fieldname = 'crmid'; + else + $fieldname = $focus->list_fields_name[$name]; + + } + if($fieldname == "lastname" && $module !="Leads" && $module !="Contacts") + $fieldname = "contact_id"; + if($fieldname == "accountname" && $module !="Accounts") + $fieldname = "account_id"; + if($fieldname == "productname" && $module =="Campaigns") + $fieldname = "product_id"; + + + } + else + { + if( $focus->list_fields_name[$name] == '') + $fieldname = 'crmid'; + else + $fieldname = $focus->list_fields_name[$name]; + + if($fieldname == "lastname" && $module !="Leads" && $module !="Contacts") + $fieldname = "contact_id"; + } + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0 || in_array($fieldname,$field)) + { + if($fieldname!='parent_id') + { + $fld_name=$fieldname; + if($fieldname == 'contact_id' && $module !="Contacts") + $name = $app_strings['LBL_CONTACT_LAST_NAME']; + elseif($fieldname == 'contact_id' && $module =="Contacts") + $name = $mod_strings['Reports To']." - ".$mod_strings['LBL_LIST_LAST_NAME']; + //assign the translated string + //added to fix #5205 + //Added condition to hide the close column in calendar search header + if($name != $app_strings['Close']) + $search_header[$fld_name] = getTranslatedString($name); + } + } + if($module == 'HelpDesk' && $fieldname == 'crmid') + { + $fld_name=$fieldname; + $search_header[$fld_name] = getTranslatedString($name); + } + } + $log->debug("Exiting getSearchListHeaderValues method ..."); + return $search_header; + +} + +/**This function is used to get the where condition for search listview query along with url_string +*Param $module - module name +*Returns the where conditions and url_string values in string format +*/ + +function Search($module) +{ + global $log,$default_charset; + $log->debug("Entering Search(".$module.") method ..."); + $url_string=''; + if(isset($_REQUEST['search_field']) && $_REQUEST['search_field'] !="") { + $search_column=vtlib_purify($_REQUEST['search_field']); + } + if(isset($_REQUEST['search_text']) && $_REQUEST['search_text']!="") { + // search other characters like "|, ?, ?" by jagi + $search_string = $_REQUEST['search_text']; + $stringConvert = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$search_string) : $search_string; + $search_string=trim($stringConvert); + } + if(isset($_REQUEST['searchtype']) && $_REQUEST['searchtype']!="") { + $search_type=vtlib_purify($_REQUEST['searchtype']); + if($search_type == "BasicSearch") { + $where=BasicSearch($module,$search_column,$search_string); + } else if ($search_type == "AdvanceSearch") { + } else { //Global Search + } + $url_string = "&search_field=".$search_column."&search_text=".urlencode($search_string)."&searchtype=BasicSearch"; + if(isset($_REQUEST['type']) && $_REQUEST['type'] != '') + $url_string .= "&type=".vtlib_purify($_REQUEST['type']); + $log->debug("Exiting Search method ..."); + return $where."#@@#".$url_string; + } +} + +/**This function is used to get user_id's for a given user_name during search +*Param $table_name - vtiger_tablename +*Param $column_name - columnname +*Param $search_string - searchstring value (username) +*Returns the where conditions for list query in string format +*/ + +function get_usersid($table_name,$column_name,$search_string) +{ + + global $log; + $log->debug("Entering get_usersid(".$table_name.",".$column_name.",".$search_string.") method ..."); + global $adb; + $where.="(vtiger_users.user_name like '". formatForSqlLike($search_string) . + "' or vtiger_groups.groupname like '". formatForSqlLike($search_string) ."')"; + $log->debug("Exiting get_usersid method ..."); + return $where; +} + +/**This function is used to get where conditions for a given vtiger_accountid or contactid during search for their respective names +*Param $column_name - columnname +*Param $search_string - searchstring value (username) +*Returns the where conditions for list query in string format +*/ + + +function getValuesforColumns($column_name,$search_string,$criteria='cts') +{ + global $log, $current_user; + $log->debug("Entering getValuesforColumns(".$column_name.",".$search_string.") method ..."); + global $column_array,$table_col_array; + + if($_REQUEST['type'] == "entchar") + $criteria = "is"; + + for($i=0; $iid,'firstname') == '0') { + $where = "concat(vtiger_contactdetails.lastname, ' ', vtiger_contactdetails.firstname) = '$search_string'"; + } else { + $where = "vtiger_contactdetails.lastname = '$search_string'"; + } + } + else { + $where="("; + for($j=0;$jdebug("Exiting getValuesforColumns method ..."); + return $where; +} + +/**This function is used to get where conditions in Basic Search +*Param $module - module name +*Param $search_field - columnname/field name in which the string has be searched +*Param $search_string - searchstring value (username) +*Returns the where conditions for list query in string format +*/ + +function BasicSearch($module,$search_field,$search_string){ + global $log,$mod_strings,$current_user; + $log->debug("Entering BasicSearch(".$module.",".$search_field.",".$search_string.") method ..."); + global $adb; + $search_string = ltrim(rtrim($adb->sql_escape_string($search_string))); + global $column_array,$table_col_array; + if($search_field =='crmid'){ + $column_name='crmid'; + $table_name='vtiger_crmentity'; + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + }elseif($search_field =='currency_id' && ($module == 'PriceBooks' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice' || $module == 'Quotes')){ + $column_name='currency_name'; + $table_name='vtiger_currency_info'; + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + }elseif($search_field == 'folderid' && $module == 'Documents'){ + $column_name='foldername'; + $table_name='vtiger_attachmentsfolder'; + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + }else{ + //Check added for tickets by accounts/contacts in dashboard + $search_field_first = $search_field; + if($module=='HelpDesk'){ + if($search_field == 'contactid'){ + $where = "(vtiger_contactdetails.contact_no like '". formatForSqlLike($search_string) ."')"; + return $where; + }elseif($search_field == 'account_id'){ + $search_field = "parent_id"; + } + } + //Check ends + + //Added to search contact name by lastname + if(($module == "Calendar" || $module == "Invoice" || $module == "Documents" || $module == "SalesOrder" || $module== "PurchaseOrder") && ($search_field == "contact_id")){ + $module = 'Contacts'; + $search_field = 'lastname'; + } + if($search_field == "accountname" && $module != "Accounts"){ + $search_field = "account_id"; + } + if($search_field == 'productname' && $module == 'Campaigns'){ + $search_field = "product_id"; + } + + $qry="select vtiger_field.columnname,tablename from vtiger_tab inner join vtiger_field on vtiger_field.tabid=vtiger_tab.tabid where vtiger_tab.name=? and (fieldname=? or columnname=?)"; + $result = $adb->pquery($qry, array($module, $search_field, $search_field)); + $noofrows = $adb->num_rows($result); + if($noofrows!=0) + { + $column_name=$adb->query_result($result,0,'columnname'); + + //Check added for tickets by accounts/contacts in dashboard + if ($column_name == 'parent_id') + { + if ($search_field_first == 'account_id') $search_field_first = 'accountid'; + if ($search_field_first == 'contactid') $search_field_first = 'contact_id'; + $column_name = $search_field_first; + } + + //Check ends + $table_name=$adb->query_result($result,0,'tablename'); + $uitype=getUItype($module,$column_name); + + //Added for Member of search in Accounts + if($column_name == "parentid" && $module == "Accounts") + { + $table_name = "vtiger_account2"; + $column_name = "accountname"; + } + if($column_name == "parentid" && $module == "Products") + { + $table_name = "vtiger_products2"; + $column_name = "productname"; + } + if($column_name == "reportsto" && $module == "Contacts") + { + $table_name = "vtiger_contactdetails2"; + $column_name = "lastname"; + } + if($column_name == "inventorymanager" && $module = "Quotes") + { + $table_name = "vtiger_usersQuotes"; + $column_name = "user_name"; + } + //Added to support user date format in basic search + if($uitype == 5 || $uitype == 6 || $uitype == 23 || $uitype == 70) + { + list($sdate,$stime) = split(" ",$search_string); + if($stime !='') + $search_string = getDBInsertDateValue($sdate)." ".$stime; + else + $search_string = getDBInsertDateValue($sdate); + } + // Added to fix errors while searching check box type fields(like product active. ie. they store 0 or 1. we search them as yes or no) in basic search. + if ($uitype == 56) + { + if(strtolower($search_string) == 'yes') + $where="$table_name.$column_name = '1'"; + elseif(strtolower($search_string) == 'no') + $where="$table_name.$column_name = '0'"; + else + $where="$table_name.$column_name = '-1'"; + + } + elseif ($uitype == 15 || $uitype == 16) + { + if(is_uitype($uitype, '_picklist_')) + { + // Get all the keys for the for the Picklist value + $mod_keys = array_keys($mod_strings, $search_string); + if(sizeof($mod_keys) >= 1) + { + // Iterate on the keys, to get the first key which doesn't start with LBL_ (assuming it is not used in PickList) + foreach($mod_keys as $mod_idx=>$mod_key) + { + $stridx = strpos($mod_key, 'LBL_'); + // Use strict type comparision, refer strpos for more details + if ($stridx !== 0) + { + $search_string = $mod_key; + if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($column_name == "status" || $column_name == "eventstatus")) + { + $where="(vtiger_activity.status like '". formatForSqlLike($search_string) ."' or vtiger_activity.eventstatus like '". formatForSqlLike($search_string) ."')"; + } + else + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + break; + } + else //if the mod strings cointains LBL , just return the original search string. Not the key + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + } + } + else + { + if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($table_name == "vtiger_activity" && ($column_name == "status" || $column_name == "eventstatus"))) + { + $where="(vtiger_activity.status like '". formatForSqlLike($search_string) ."' or vtiger_activity.eventstatus like '". formatForSqlLike($search_string) ."')"; + } + else + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + } + } + } + elseif($table_name == "vtiger_crmentity" && $column_name == "smownerid") + { + $where = get_usersid($table_name,$column_name,$search_string); + } + else if(in_array($column_name,$column_array)) + { + $where = getValuesforColumns($column_name,$search_string); + } + else if($_REQUEST['type'] == 'entchar') + { + $where="$table_name.$column_name = '". $search_string ."'"; + } + else + { + $where="$table_name.$column_name like '". formatForSqlLike($search_string) ."'"; + } + } + } + if(stristr($where,"like '%%'")) + { + $where_cond0=str_replace("like '%%'","like ''",$where); + $where_cond1=str_replace("like '%%'","is NULL",$where); + if($module == "Calendar") + $where = "(".$where_cond0." and ".$where_cond1.")"; + else + $where = "(".$where_cond0." or ".$where_cond1.")"; + } + // commented to support searching "%" with the search string. + if($_REQUEST['type'] == 'alpbt'){ + $where = str_replace_once("%", "", $where); + } + + //uitype 10 handling + if($uitype == 10){ + $where = array(); + $sql = "select fieldid from vtiger_field where tabid=? and fieldname=?"; + $result = $adb->pquery($sql, array(getTabid($module), $search_field)); + + if($adb->num_rows($result)>0){ + $fieldid = $adb->query_result($result, 0, "fieldid"); + $sql = "select * from vtiger_fieldmodulerel where fieldid=?"; + $result = $adb->pquery($sql, array($fieldid)); + $count = $adb->num_rows($result); + $searchString = formatForSqlLike($search_string); + + for($i=0;$i<$count;$i++){ + $relModule = $adb->query_result($result, $i, "relmodule"); + $relInfo = getEntityField($relModule); + $relTable = $relInfo["tablename"]; + $relField = $relInfo["fieldname"]; + + if(strpos($relField, 'concat') !== false){ + $where[] = "$relField like '$searchString'"; + }else{ + $where[] = "$relTable.$relField like '$searchString'"; + } + + } + $where = implode(" or ", $where); + } + $where = "($where) "; + } + + $log->debug("Exiting BasicSearch method ..."); + return $where; +} + +/**This function is used to get where conditions in Advance Search +*Param $module - module name +*Returns the where conditions for list query in string format +*/ + +function getAdvSearchfields($module) +{ + global $log; + $log->debug("Entering getAdvSearchfields(".$module.") method ..."); + global $adb; + global $current_user; + global $mod_strings,$app_strings; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $tabid = getTabid($module); + if($tabid==9) + $tabid="9,16"; + + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $sql = "select * from vtiger_field "; + $sql.= " where vtiger_field.tabid in(?) and"; + $sql.= " vtiger_field.displaytype in (1,2,3) and vtiger_field.presence in (0,2)"; + if($tabid == 13 || $tabid == 15) + { + $sql.= " and vtiger_field.fieldlabel != 'Add Comment'"; + } + if($tabid == 14) + { + $sql.= " and vtiger_field.fieldlabel != 'Product Image'"; + } + if($tabid == 9 || $tabid==16) + { + $sql.= " and vtiger_field.fieldname not in('notime','duration_minutes','duration_hours')"; + } + if($tabid == 4) + { + $sql.= " and vtiger_field.fieldlabel != 'Contact Image'"; + } + if($tabid == 13 || $tabid == 10) + { + $sql.= " and vtiger_field.fieldlabel != 'Attachment'"; + } + $sql.= " group by vtiger_field.fieldlabel order by block,sequence"; + + $params = array($tabid); + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "select * from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid "; + $sql.= " where vtiger_field.tabid in(?) and"; + $sql.= " vtiger_field.displaytype in (1,2,3) and vtiger_field.presence in (0,2) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0"; + + $params = array($tabid); + + if (count($profileList) > 0) { + $sql.= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + + if($tabid == 13 || $tabid == 15) + { + $sql.= " and vtiger_field.fieldlabel != 'Add Comment'"; + } + if($tabid == 14) + { + $sql.= " and vtiger_field.fieldlabel != 'Product Image'"; + } + if($tabid == 9 || $tabid==16) + { + $sql.= " and vtiger_field.fieldname not in('notime','duration_minutes','duration_hours')"; + } + if($tabid == 4) + { + $sql.= " and vtiger_field.fieldlabel != 'Contact Image'"; + } + if($tabid == 13 || $tabid == 10) + { + $sql.= " and vtiger_field.fieldlabel != 'Attachment'"; + } + $sql .= " group by vtiger_field.fieldlabel order by block,sequence"; + } + + $result = $adb->pquery($sql, $params); + $noofrows = $adb->num_rows($result); + $block = ''; + $select_flag = ''; + + for($i=0; $i<$noofrows; $i++) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $block = $adb->query_result($result,$i,"block"); + $fieldtype = $adb->query_result($result,$i,"typeofdata"); + $fieldtype = explode("~",$fieldtype); + $fieldtypeofdata = $fieldtype[0]; + if($fieldcolname == 'account_id' || $fieldcolname == 'accountid' || $fieldcolname == 'product_id' || $fieldcolname == 'vendor_id' || $fieldcolname == 'contact_id' || $fieldcolname == 'contactid' || $fieldcolname == 'vendorid' || $fieldcolname == 'potentialid' || $fieldcolname == 'salesorderid' || $fieldcolname == 'quoteid' || $fieldcolname == 'parentid' || $fieldcolname == "recurringtype" || $fieldcolname == "campaignid" || $fieldcolname == "inventorymanager" || $fieldcolname == "handler" || $fieldcolname == "currency_id") + $fieldtypeofdata = "V"; + if($fieldcolname == "discontinued" || $fieldcolname == "active") + $fieldtypeofdata = "C"; + $fieldlabel = $mod_strings[$adb->query_result($result,$i,"fieldlabel")]; + + // Added to display customfield label in search options + if($fieldlabel == "") + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + + if($fieldlabel == "Related To") + { + $fieldlabel = "Related to"; + } + if($fieldlabel == "Start Date & Time") + { + $fieldlabel = "Start Date"; + if($module == 'Activities' && $block == 19) + $module_columnlist['vtiger_activity:time_start::Activities_Start Time:I'] = 'Start Time'; + + } + //$fieldlabel1 = str_replace(" ","_",$fieldlabel); // Is not used anywhere + //Check added to search the lists by Inventory manager + if($fieldtablename == 'vtiger_quotes' && $fieldcolname == 'inventorymanager') + { + $fieldtablename = 'vtiger_usersQuotes'; + $fieldcolname = 'user_name'; + } + if($fieldtablename == 'vtiger_contactdetails' && $fieldcolname == 'reportsto') + { + $fieldtablename = 'vtiger_contactdetails2'; + $fieldcolname = 'lastname'; + } + if($fieldtablename == 'vtiger_notes' && $fieldcolname == 'folderid'){ + $fieldtablename = 'vtiger_attachmentsfolder'; + $fieldcolname = 'foldername'; + } + if($fieldlabel != 'Related to') + { + if ($i==0) + $select_flag = "selected"; + + $mod_fieldlabel = $mod_strings[$fieldlabel]; + if($mod_fieldlabel =="") $mod_fieldlabel = $fieldlabel; + + if($fieldlabel == "Product Code") + $OPTION_SET .= ""; + if($fieldlabel == "Reports To") + $OPTION_SET .= ""; + elseif($fieldcolname == "contactid" || $fieldcolname == "contact_id") + { + $OPTION_SET .= ""; + $OPTION_SET .= ""; + } + elseif($fieldcolname == "campaignid") + $OPTION_SET .= ""; + else + $OPTION_SET .= ""; + } + } + //Added to include Ticket ID in HelpDesk advance search + if($module == 'HelpDesk') + { + $mod_fieldlabel = $mod_strings['Ticket ID']; + if($mod_fieldlabel =="") $mod_fieldlabel = 'Ticket ID'; + + $OPTION_SET .= ""; + } + //Added to include activity type in activity advance search + if($module == 'Activities') + { + $mod_fieldlabel = $mod_strings['Activity Type']; + if($mod_fieldlabel =="") $mod_fieldlabel = 'Activity Type'; + + $OPTION_SET .= ""; + } + $log->debug("Exiting getAdvSearchfields method ..."); + return $OPTION_SET; +} + +/**This function is returns the search criteria options for Advance Search +*takes no parameter +*Returns the criteria option in html format +*/ + +function getcriteria_options() +{ + global $log,$app_strings; + $log->debug("Entering getcriteria_options() method ..."); + $CRIT_OPT = ""; + $log->debug("Exiting getcriteria_options method ..."); + return $CRIT_OPT; +} + +/**This function is returns the where conditions for each search criteria option in Advance Search +*Param $criteria - search criteria option +*Param $searchstring - search string +*Param $searchfield - vtiger_fieldname to be search for +*Returns the search criteria option (where condition) to be added in list query +*/ + +function getSearch_criteria($criteria,$searchstring,$searchfield) +{ + global $log; + $log->debug("Entering getSearch_criteria(".$criteria.",".$searchstring.",".$searchfield.") method ..."); + $searchstring = ltrim(rtrim($searchstring)); + if(($searchfield != "vtiger_troubletickets.update_log") && ($searchfield == "vtiger_crmentity.modifiedtime" || $searchfield == "vtiger_crmentity.createdtime" || stristr($searchfield,'date'))) + { + list($sdate,$stime) = split(" ",$searchstring); + if($stime !='') + $searchstring = getDBInsertDateValue($sdate)." ".$stime; + else + $searchstring = getDBInsertDateValue($sdate); + } + if($searchfield == "vtiger_account.parentid") + $searchfield = "vtiger_account2.accountname"; + if($searchfield == "vtiger_pricebook.currency_id" || $searchfield == "vtiger_quotes.currency_id" || $searchfield == "vtiger_invoice.currency_id" + || $searchfield == "vtiger_purchaseorder.currency_id" || $searchfield == "vtiger_salesorder.currency_id") + $searchfield = "vtiger_currency_info.currency_name"; + $where_string = ''; + switch($criteria) + { + case 'cts': + $where_string = $searchfield." like '". formatForSqlLike($searchstring) ."' "; + if($searchstring == NULL) + { + $where_string = "(".$searchfield." like '' or ".$searchfield." is NULL)"; + } + break; + + case 'dcts': + if($searchfield == "vtiger_users.user_name" || $searchfield =="vtiger_groups.groupname") + $where_string = "(".$searchfield." not like '". formatForSqlLike($searchstring) ."')"; + else + $where_string = "(".$searchfield." not like '". formatForSqlLike($searchstring) ."' or ".$searchfield." is null)"; + if($searchstring == NULL) + $where_string = "(".$searchfield." not like '' or ".$searchfield." is not NULL)"; + break; + + case 'is': + $where_string = $searchfield." = '".$searchstring."' "; + if($searchstring == NULL) + $where_string = "(".$searchfield." is NULL or ".$searchfield." = '')"; + break; + + case 'isn': + if($searchfield == "vtiger_users.user_name" || $searchfield =="vtiger_groups.groupname") + $where_string = "(".$searchfield." <> '".$searchstring."')"; + else + $where_string = "(".$searchfield." <> '".$searchstring."' or ".$searchfield." is null)"; + if($searchstring == NULL) + $where_string = "(".$searchfield." not like '' and ".$searchfield." is not NULL)"; + break; + + case 'bwt': + $where_string = $searchfield." like '". formatForSqlLike($searchstring, 2) ."' "; + break; + + case 'ewt': + $where_string = $searchfield." like '". formatForSqlLike($searchstring, 1) ."' "; + break; + + case 'grt': + $where_string = $searchfield." > '".$searchstring."' "; + break; + + case 'lst': + $where_string = $searchfield." < '".$searchstring."' "; + break; + + case 'grteq': + $where_string = $searchfield." >= '".$searchstring."' "; + break; + + case 'lsteq': + $where_string = $searchfield." <= '".$searchstring."' "; + break; + + + } + $log->debug("Exiting getSearch_criteria method ..."); + return $where_string; +} + +/**This function is returns the where conditions for search +*Param $currentModule - module name +*Returns the where condition to be added in list query in string format +*/ + +function getWhereCondition($currentModule) +{ + global $log,$default_charset,$adb; + global $column_array,$table_col_array,$mod_strings,$current_user; + + $log->debug("Entering getWhereCondition(".$currentModule.") method ..."); + + if($_REQUEST['searchtype']=='advance') + { + $adv_string=''; + $url_string=''; + if(isset($_REQUEST['search_cnt'])) + $tot_no_criteria = vtlib_purify($_REQUEST['search_cnt']); + if($_REQUEST['matchtype'] == 'all') + $matchtype = "and"; + else + $matchtype = "or"; + for($i=0; $i<$tot_no_criteria; $i++) + { + if($i == $tot_no_criteria-1) + $matchtype= ""; + + $table_colname = 'Fields'.$i; + $search_condition = 'Condition'.$i; + $search_value = 'Srch_value'.$i; + + list($tab_col_val,$typeofdata) = split("::::",$_REQUEST[$table_colname]); + $tab_col = str_replace('\'','',stripslashes($tab_col_val)); + $srch_cond = str_replace('\'','',stripslashes($_REQUEST[$search_condition])); + $srch_val = $_REQUEST[$search_value]; + $srch_val = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$srch_val) : $srch_val; + $url_string .="&Fields".$i."=".$tab_col."&Condition".$i."=".$srch_cond."&Srch_value".$i."=".urlencode($srch_val); + $srch_val = $adb->sql_escape_string($srch_val); + list($tab_name,$column_name) = split("[.]",$tab_col); + $uitype=getUItype($currentModule,$column_name); + //added to allow search in check box type fields(ex: product active. it will contain 0 or 1) using yes or no instead of 0 or 1 + if ($uitype == 56) + { + if(strtolower($srch_val) == 'yes') + $adv_string .= " ".getSearch_criteria($srch_cond,"1",$tab_name.'.'.$column_name)." ".$matchtype; + elseif(strtolower($srch_val) == 'no') + $adv_string .= " ".getSearch_criteria($srch_cond,"0",$tab_name.'.'.$column_name)." ".$matchtype; + else + $adv_string .= " ".getSearch_criteria($srch_cond,"-1",$tab_name.'.'.$column_name)." ".$matchtype; + } + elseif ($uitype == 15 || $uitype == 16) + { + if(is_uitype($uitype, '_picklist_')) { + // Get all the keys for the for the Picklist value + $mod_keys = array_keys($mod_strings, $srch_val); + if(sizeof($mod_keys) >= 1) + { + // Iterate on the keys, to get the first key which doesn't start with LBL_ (assuming it is not used in PickList) + foreach($mod_keys as $mod_idx=>$mod_key) { + $stridx = strpos($mod_key, 'LBL_'); + // Use strict type comparision, refer strpos for more details + if ($stridx !== 0) + { + $srch_val = $mod_key; + if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($tab_col == "vtiger_activity.status" || $tab_col == "vtiger_activity.eventstatus")) + { + if($srch_cond == 'dcts' || $srch_cond == 'isn' || $srch_cond == 'is') + $re_cond = "and"; + else + $re_cond = "or"; + if($srch_cond == 'is' && $srch_val !='') + $re_cond = "or"; + + $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.status')." ".$re_cond; + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.eventstatus')." )".$matchtype; + } + else + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_name.'.'.$column_name)." ".$matchtype; + break; + } + else //if the key contains the LBL, then return the original srch_val. + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_name.'.'.$column_name)." ".$matchtype; + + } + + } + else + { + if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0' && ($tab_col == "vtiger_activity.status" || $tab_col == "vtiger_activity.eventstatus")) + { + if($srch_cond == 'dcts' || $srch_cond == 'isn' || $srch_cond == 'is') + $re_cond = "and"; + else + $re_cond = "or"; + if($srch_cond == 'is' && $srch_val !='') + $re_cond = "or"; + + $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.status')." ".$re_cond; + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_activity.eventstatus')." )".$matchtype; + } + else + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_col)." ".$matchtype; + } + } + } + + elseif($tab_col == "vtiger_crmentity.smownerid") + { + $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_users.user_name')." or"; + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_groups.groupname')." )".$matchtype; + } + elseif($tab_col == "vtiger_cntactivityrel.contactid") + { + $adv_string .= " (".getSearch_criteria($srch_cond,$srch_val,'vtiger_contactdetails.firstname')." or"; + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,'vtiger_contactdetails.lastname')." )".$matchtype; + } + elseif(in_array($column_name,$column_array)) + { + $adv_string .= " ".getValuesforColumns($column_name,$srch_val,$srch_cond)." ".$matchtype; + } + else + { + $adv_string .= " ".getSearch_criteria($srch_cond,$srch_val,$tab_col)." ".$matchtype; + } + } + $where="(".$adv_string.")#@@#".$url_string."&searchtype=advance&search_cnt=".$tot_no_criteria."&matchtype=".vtlib_purify($_REQUEST['matchtype']); + } + elseif($_REQUEST['type']=='dbrd') + { + $where = getdashboardcondition(); + } + else + { + $where=Search($currentModule); + } + $log->debug("Exiting getWhereCondition method ..."); + return $where; + +} + +function getSearchURL($input) { + global $log,$default_charset; + $urlString=''; + if($input['searchtype']=='advance') { + if(empty($input['search_cnt'])) { + return $urlString; + } + $noOfConditions = vtlib_purify($input['search_cnt']); + for($i=0; $i<$noOfConditions; $i++) { + $fieldInfo = 'Fields'.$i; + $condition = 'Condition'.$i; + $value = 'Srch_value'.$i; + + list($fieldName,$typeOfData) = split("::::",str_replace('\'','', + stripslashes($input[$fieldInfo]))); + $operator = str_replace('\'','',stripslashes($input[$condition])); + $searchValue = $input[$value]; + $searchValue = function_exists(iconv) ? @iconv("UTF-8",$default_charset, + $searchValue) : $searchValue; + $urlString .="&Fields$i=$fieldName&Condition$i=$operator&Srch_value$i=". + urlencode($searchValue); + } + $urlString .= "&searchtype=advance&search_cnt=$noOfConditions&matchtype=". + vtlib_purify($input['matchtype']); + } elseif($input['type']=='dbrd'){ + if(isset($input['leadsource'])) { + $leadSource = $input['leadsource']; + $urlString .= "&leadsource=".$leadSource; + } + if(isset($input['date_closed'])) { + $dateClosed = $input['date_closed']; + $urlString .= "&date_closed=".$dateClosed; + } + if(isset($input['sales_stage'])) { + $salesStage = $input['sales_stage']; + $urlString .= "&sales_stage=".$salesStage; + } + if(!empty($input['closingdate_start']) && !empty($input['closingdate_end'])) { + $dateClosedStart = $input['closingdate_start']; + $dateClosedEnd = $input['closingdate_end']; + $urlString .= "&closingdate_start=$dateClosedStart&closingdate_end=".$dateClosedEnd; + } + if(isset($input['owner'])) { + $owner = vtlib_purify($input['owner']); + $urlString .= "&owner=".$owner; + } + if(isset($input['campaignid'])) { + $campaignId = vtlib_purify($input['campaignid']); + $urlString .= "&campaignid=".$campaignId; + } + if(isset($input['quoteid'])) { + $quoteId = vtlib_purify($input['quoteid']); + $urlString .= ""eid=".$quoteId; + } + if(isset($input['invoiceid'])) { + $invoiceId = vtlib_purify($input['invoiceid']); + $urlString .= "&invoiceid=".$invoiceId; + } + if(isset($input['purchaseorderid'])) { + $purchaseOrderId = vtlib_purify($input['purchaseorderid']); + $urlString .= "&purchaseorderid=".$purchaseOrderId; + } + + if(isset($input['from_homepagedb']) && $input['from_homepagedb'] != '') { + $url_string .= "&from_homepagedb=".vtlib_purify($input['from_homepagedb']); + } + if(isset($input['type']) && $input['type'] != '') { + $url_string .= "&type=".vtlib_purify($input['type']); + } + } else { + $value = $input['search_text']; + $stringConvert = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$value) : + $value; + $value=trim($stringConvert); + $field=vtlib_purify($input['search_field']); + $urlString = "&search_field=$field&search_text=".urlencode($value)."&searchtype=BasicSearch"; + if(!empty($input['type'])) { + $urlString .= "&type=".vtlib_purify($input['type']); + } + if(!empty($input['operator'])) { + $urlString .= "&operator=".$input['operator']; + } + } + return $urlString; +} + +/**This function is returns the where conditions for dashboard and shows the records when clicked on dashboard graph +*Takes no parameter, process the values got from the html request object +*Returns the search criteria option (where condition) to be added in list query +*/ + +function getdashboardcondition() +{ + global $adb; + $where_clauses = Array(); + $url_string = ""; + + if (isset($_REQUEST['leadsource'])) $lead_source = $_REQUEST['leadsource']; + if (isset($_REQUEST['date_closed'])) $date_closed = $_REQUEST['date_closed']; + if (isset($_REQUEST['sales_stage'])) $sales_stage = $_REQUEST['sales_stage']; + if (isset($_REQUEST['closingdate_start'])) $date_closed_start = $_REQUEST['closingdate_start']; + if (isset($_REQUEST['closingdate_end'])) $date_closed_end = $_REQUEST['closingdate_end']; + if(isset($_REQUEST['owner'])) $owner = vtlib_purify($_REQUEST['owner']); + if(isset($_REQUEST['campaignid'])) $campaign = vtlib_purify($_REQUEST['campaignid']); + if(isset($_REQUEST['quoteid'])) $quote = vtlib_purify($_REQUEST['quoteid']); + if(isset($_REQUEST['invoiceid'])) $invoice = vtlib_purify($_REQUEST['invoiceid']); + if(isset($_REQUEST['purchaseorderid'])) $po = vtlib_purify($_REQUEST['purchaseorderid']); + + if(isset($date_closed_start) && $date_closed_start != "" && isset($date_closed_end) && $date_closed_end != "") + { + array_push($where_clauses, "vtiger_potential.closingdate >= ".$adb->quote($date_closed_start)." and vtiger_potential.closingdate <= ".$adb->quote($date_closed_end)); + $url_string .= "&closingdate_start=".$date_closed_start."&closingdate_end=".$date_closed_end; + } + + if(isset($sales_stage) && $sales_stage!=''){ + if($sales_stage=='Other') + array_push($where_clauses, "(vtiger_potential.sales_stage <> 'Closed Won' and vtiger_potential.sales_stage <> 'Closed Lost')"); + else + array_push($where_clauses, "vtiger_potential.sales_stage = ".$adb->quote($sales_stage)); + $url_string .= "&sales_stage=".$sales_stage; + } + if(isset($lead_source) && $lead_source != "") { + array_push($where_clauses, "vtiger_potential.leadsource = ".$adb->quote($lead_source)); + $url_string .= "&leadsource=".$lead_source; + } + if(isset($date_closed) && $date_closed != "") { + array_push($where_clauses, $adb->getDBDateString("vtiger_potential.closingdate")." like ".$adb->quote($date_closed.'%').""); + $url_string .= "&date_closed=".$date_closed; + } + if(isset($owner) && $owner != ""){ + $user_qry="select vtiger_users.id from vtiger_users where vtiger_users.user_name = ?"; + $res = $adb->pquery($user_qry, array($owner)); + $uid = $adb->query_result($res,0,'id'); + array_push($where_clauses, "vtiger_crmentity.smownerid = ".$uid); + //$url_string .= "&assigned_user_id=".$uid; + $url_string .= "&owner=".$owner; + } + if(isset($campaign) && $campaign != "") + { + array_push($where_clauses, "vtiger_campaigncontrel.campaignid = ".$campaign); + $url_string .= "&campaignid=".$campaign; + } + if(isset($quote) && $quote != "") + { + array_push($where_clauses, "vtiger_inventoryproductrel.id = ".$quote); + $url_string .= ""eid=".$quote; + } + if(isset($invoice) && $invoice != "") + { + array_push($where_clauses, "vtiger_inventoryproductrel.id = ".$invoice); + $url_string .= "&invoiceid=".$invoice; + } + if(isset($po) && $po != "") + { + array_push($where_clauses, "vtiger_inventoryproductrel.id = ".$po); + $url_string .= "&purchaseorderid=".$po; + } + if(isset($_REQUEST['from_homepagedb']) && $_REQUEST['from_homepagedb'] != '') { + $url_string .= "&from_homepagedb=".vtlib_purify($_REQUEST['from_homepagedb']); + } + if(isset($_REQUEST['type']) && $_REQUEST['type'] != '') { + $url_string .= "&type=".vtlib_purify($_REQUEST['type']); + } + + $where = ""; + foreach($where_clauses as $clause) + { + if($where != "") + $where .= " and "; + $where .= $clause; + } + return $where."#@@#".$url_string; +} + +/**This function is used to replace only the first occurence of a given string +Param $needle - string to be replaced +Param $replace - string to be replaced with +Param $replace - given string +Return type is string +*/ +function str_replace_once($needle, $replace, $haystack) +{ + // Looks for the first occurence of $needle in $haystack + // and replaces it with $replace. + $pos = strpos($haystack, $needle); + if ($pos === false) { + // Nothing found + return $haystack; + } + return substr_replace($haystack, $replace, $pos, strlen($needle)); +} + +/** + * Function to get the where condition for a module based on the field table entries + * @param string $listquery -- ListView query for the module + * @param string $module -- module name + * @param string $search_val -- entered search string value + * @return string $where -- where condition for the module based on field table entries + */ +function getUnifiedWhere($listquery,$module,$search_val){ + global $adb, $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $search_val = $adb->sql_escape_string($search_val); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0){ + $query = "SELECT columnname, tablename FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2)"; + $qparams = array(getTabid($module)); + }else{ + $profileList = getCurrentUserProfileList(); + $query = "SELECT columnname, tablename FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid = vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid = vtiger_field.fieldid WHERE vtiger_field.tabid = ? AND vtiger_profile2field.visible = 0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) . ") AND vtiger_def_org_field.visible = 0 and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; + $qparams = array(getTabid($module), $profileList); + } + $result = $adb->pquery($query, $qparams); + $noofrows = $adb->num_rows($result); + + $where = ''; + for($i=0;$i<$noofrows;$i++){ + $columnname = $adb->query_result($result,$i,'columnname'); + $tablename = $adb->query_result($result,$i,'tablename'); + + // Search / Lookup customization + if($module == 'Contacts' && $columnname == 'accountid') { + $columnname = "accountname"; + $tablename = "vtiger_account"; + } + // END + + //Before form the where condition, check whether the table for the field has been added in the listview query + if(strstr($listquery,$tablename)){ + if($where != ''){ + $where .= " OR "; + } + $where .= $tablename.".".$columnname." LIKE '". formatForSqlLike($search_val) ."'"; + } + } + return $where; +} + ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/UserInfoUtil.php b/oss/vtiger/trunk/include/utils/UserInfoUtil.php index 7f70814a..a4d8e20c 100644 --- a/oss/vtiger/trunk/include/utils/UserInfoUtil.php +++ b/oss/vtiger/trunk/include/utils/UserInfoUtil.php @@ -1,4406 +1,4409 @@ -debug("Entering getMailServerInfo(".$user->user_name.") method ..."); - global $adb; - $sql = "select * from vtiger_mail_accounts where status=1 and user_id=?"; - $result = $adb->pquery($sql, array($user->id)); - $log->debug("Exiting getMailServerInfo method ..."); - return $result; -} - -/** To get the Role of the specified user - * @param $userid -- The user Id:: Type integer - * @returns vtiger_roleid :: Type String - */ -function fetchUserRole($userid) -{ - global $log; - $log->debug("Entering fetchUserRole(".$userid.") method ..."); - global $adb; - $sql = "select roleid from vtiger_user2role where userid=?"; - $result = $adb->pquery($sql, array($userid)); - $roleid= $adb->query_result($result,0,"roleid"); - $log->debug("Exiting fetchUserRole method ..."); - return $roleid; -} - -/** Depricated. Function to be replaced by getUserProfile() - * Should be done accross the product - * - */ -function fetchUserProfileId($userid) -{ - global $log; - $log->debug("Entering fetchUserProfileId(".$userid.") method ..."); - - // Look up information in cache first - $profileid = VTCacheUtils::lookupUserProfileId($userid); - - if($profileid === false) { - global $adb; - - $query = "SELECT profileid FROM vtiger_role2profile WHERE roleid=(SELECT roleid FROM vtiger_user2role WHERE userid=?)"; - $result = $adb->pquery($query, array($userid)); - - if($result && $adb->num_rows($result)) { - $profileid = $adb->query_result($result, 0, 'profileid'); - // TODO: What if there are multiple profile to one role? - } - - // Update information to cache for re-use - VTCacheUtils::updateUserProfileId($userid, $profileid); - } - - $log->debug("Exiting fetchUserProfileId method ..."); - return $profileid; -} - -/** Function to get the lists of groupids releated with an user - * This function accepts the user id as arguments and - * returns the groupids related with the user id - * as a comma seperated string -*/ -function fetchUserGroupids($userid) -{ - global $log; - $log->debug("Entering fetchUserGroupids(".$userid.") method ..."); - global $adb; - $focus = new GetUserGroups(); - $focus->getAllUserGroups($userid); - //Asha: Remove implode if not required and if so, also remove explode functions used at the recieving end of this function - $groupidlists = implode(",",$focus->user_groups); - $log->debug("Exiting fetchUserGroupids method ..."); - return $groupidlists; - -} - -/** Function to load all the permissions - * - */ -function loadAllPerms() - { - global $log; - $log->debug("Entering loadAllPerms() method ..."); - global $adb,$MAX_TAB_PER; - global $persistPermArray; - - $persistPermArray = Array(); - $profiles = Array(); - $sql = "select distinct profileid from vtiger_profile2tab"; - $result = $adb->pquery($sql, array()); - $num_rows = $adb->num_rows($result); - for ( $i=0; $i < $num_rows; $i++ ) - $profiles[] = $adb->query_result($result,$i,'profileid'); - - $persistPermArray = Array(); - foreach ( $profiles as $profileid ) - { - $sql = "select * from vtiger_profile2tab where profileid=?"; - $result = $adb->pquery($sql, array($profileid)); - if($MAX_TAB_PER !='') - { - $persistPermArray[$profileid] = array_fill(0,$MAX_TAB_PER,0); - } - $num_rows = $adb->num_rows($result); - for($i=0; $i<$num_rows; $i++) - { - $tabid= $adb->query_result($result,$i,'tabid'); - $tab_per= $adb->query_result($result,$i,'permissions'); - $persistPermArray[$profileid][$tabid] = $tab_per; - } - } - $log->debug("Exiting loadAllPerms method ..."); -} - -/** Function to get all the vtiger_tab permission for the specified vtiger_profile - * @param $profileid -- Profile Id:: Type integer - * @returns TabPermission Array in the following format: - * $tabPermission = Array($tabid1=>permission, - * $tabid2=>permission, - * | - * $tabidn=>permission) - * - */ -function getAllTabsPermission($profileid) -{ - global $log; - $log->debug("Entering getAllTabsPermission(".$profileid.") method ..."); - global $persistPermArray; - global $adb,$MAX_TAB_PER; - // Mike Crowe Mod -------------------------------------------------------- - if ( $cache_tab_perms ) - { - if ( count($persistPermArray) == 0 ) - loadAllPerms(); - $log->debug("Exiting getAllTabsPermission method ..."); - return $persistPermArray[$profileid]; - } - else - { - $sql = "select * from vtiger_profile2tab where profileid=?"; - $result = $adb->pquery($sql, array($profileid)); - $tab_perr_array = Array(); - if($MAX_TAB_PER !='') - { - $tab_perr_array = array_fill(0,$MAX_TAB_PER,0); - } - $num_rows = $adb->num_rows($result); - for($i=0; $i<$num_rows; $i++) - { - $tabid= $adb->query_result($result,$i,'tabid'); - $tab_per= $adb->query_result($result,$i,'permissions'); - $tab_perr_array[$tabid] = $tab_per; - } - $log->debug("Exiting getAllTabsPermission method ..."); - return $tab_perr_array; - } - // Mike Crowe Mod ---------------------------------------------------------------- - -} - -/** Function to get all the vtiger_tab permission for the specified vtiger_profile other than tabid 15 - * @param $profileid -- Profile Id:: Type integer - * @returns TabPermission Array in the following format: - * $tabPermission = Array($tabid1=>permission, - * $tabid2=>permission, - * | - * $tabidn=>permission) - * - */ -function getTabsPermission($profileid) -{ - global $log; - $log->debug("Entering getTabsPermission(".$profileid.") method ..."); - global $persistPermArray; - global $adb; - // Mike Crowe Mod ------------------------------------------------------- - if ( $cache_tab_perms ) - { - if ( count($persistPermArray) == 0 ) - loadAllPerms(); - $tab_perr_array = $persistPermArray; - foreach( array(1,3,16,15) as $tabid ) - $tab_perr_array[$tabid] = 0; - $log->debug("Exiting getTabsPermission method ..."); - return $tab_perr_array; - } - else - { - $sql = "select * from vtiger_profile2tab where profileid=?"; - $result = $adb->pquery($sql, array($profileid)); - $tab_perr_array = Array(); - $num_rows = $adb->num_rows($result); - for($i=0; $i<$num_rows; $i++) - { - $tabid= $adb->query_result($result,$i,'tabid'); - $tab_per= $adb->query_result($result,$i,'permissions'); - if($tabid != 3 && $tabid != 16) - { - $tab_perr_array[$tabid] = $tab_per; - } - } - $log->debug("Exiting getTabsPermission method ..."); - return $tab_perr_array; - } - -} - -/** Function to get all the vtiger_tab standard action permission for the specified vtiger_profile - * @param $profileid -- Profile Id:: Type integer - * @returns Tab Action Permission Array in the following format: - * $tabPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * | - * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) - * - */ -function getTabsActionPermission($profileid) -{ - global $log; - $log->debug("Entering getTabsActionPermission(".$profileid.") method ..."); - global $adb; - $check = Array(); - $temp_tabid = Array(); - $sql1 = "select * from vtiger_profile2standardpermissions where profileid=? and tabid not in(16) order by(tabid)"; - $result1 = $adb->pquery($sql1, array($profileid)); - $num_rows1 = $adb->num_rows($result1); - for($i=0; $i<$num_rows1; $i++) - { - $tab_id = $adb->query_result($result1,$i,'tabid'); - if(! in_array($tab_id,$temp_tabid)) - { - $temp_tabid[] = $tab_id; - $access = Array(); - } - - $action_id = $adb->query_result($result1,$i,'operation'); - $per_id = $adb->query_result($result1,$i,'permissions'); - $access[$action_id] = $per_id; - $check[$tab_id] = $access; - } - $log->debug("Exiting getTabsActionPermission method ..."); - return $check; -} - -/** Function to get all the vtiger_tab utility action permission for the specified vtiger_profile - * @param $profileid -- Profile Id:: Type integer - * @returns Tab Utility Action Permission Array in the following format: - * $tabPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * | - * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) - * - */ - -function getTabsUtilityActionPermission($profileid) -{ - global $log; - $log->debug("Entering getTabsUtilityActionPermission(".$profileid.") method ..."); - - global $adb; - $check = Array(); - $temp_tabid = Array(); - $sql1 = "select * from vtiger_profile2utility where profileid=? order by(tabid)"; - $result1 = $adb->pquery($sql1, array($profileid)); - $num_rows1 = $adb->num_rows($result1); - for($i=0; $i<$num_rows1; $i++) - { - $tab_id = $adb->query_result($result1,$i,'tabid'); - if(! in_array($tab_id,$temp_tabid)) - { - $temp_tabid[] = $tab_id; - $access = Array(); - } - - $action_id = $adb->query_result($result1,$i,'activityid'); - $per_id = $adb->query_result($result1,$i,'permission'); - $access[$action_id] = $per_id; - $check[$tab_id] = $access; - - - } - - $log->debug("Exiting getTabsUtilityActionPermission method ..."); - return $check; - -} -/**This Function returns the Default Organisation Sharing Action Array for all modules whose sharing actions are editable - * The result array will be in the following format: - * Arr=(tabid1=>Sharing Action Id, - * tabid2=>SharingAction Id, - * | - * | - * | - * tabid3=>SharingAcion Id) - */ - -function getDefaultSharingEditAction() -{ - global $log; - $log->debug("Entering getDefaultSharingEditAction() method ..."); - global $adb; - //retreiving the standard permissions - $sql= "select * from vtiger_def_org_share where editstatus=0"; - $result = $adb->pquery($sql, array()); - $permissionRow=$adb->fetch_array($result); - do - { - for($j=0;$jfetch_array($result)); - - $log->debug("Exiting getDefaultSharingEditAction method ..."); - return $copy; - -} -/**This Function returns the Default Organisation Sharing Action Array for modules with edit status in (0,1) - * The result array will be in the following format: - * Arr=(tabid1=>Sharing Action Id, - * tabid2=>SharingAction Id, - * | - * | - * | - * tabid3=>SharingAcion Id) - */ -function getDefaultSharingAction() -{ - global $log; - $log->debug("Entering getDefaultSharingAction() method ..."); - global $adb; - //retreivin the standard permissions - $sql= "select * from vtiger_def_org_share where editstatus in(0,1)"; - $result = $adb->pquery($sql, array()); - $permissionRow=$adb->fetch_array($result); - do - { - for($j=0;$jfetch_array($result)); - $log->debug("Exiting getDefaultSharingAction method ..."); - return $copy; - -} - - -/**This Function returns the Default Organisation Sharing Action Array for all modules - * The result array will be in the following format: - * Arr=(tabid1=>Sharing Action Id, - * tabid2=>SharingAction Id, - * | - * | - * | - * tabid3=>SharingAcion Id) - */ -function getAllDefaultSharingAction() -{ - global $log; - $log->debug("Entering getAllDefaultSharingAction() method ..."); - global $adb; - $copy=Array(); - //retreiving the standard permissions - $sql= "select * from vtiger_def_org_share"; - $result = $adb->pquery($sql, array()); - $num_rows=$adb->num_rows($result); - - for($i=0;$i<$num_rows;$i++) - { - $tabid=$adb->query_result($result,$i,'tabid'); - $permission=$adb->query_result($result,$i,'permission'); - $copy[$tabid]=$permission; - - } - - $log->debug("Exiting getAllDefaultSharingAction method ..."); - return $copy; - -} - - -/** Function to create the vtiger_role - * @param $roleName -- Role Name:: Type varchar - * @param $parentRoleId -- Parent Role Id:: Type varchar - * @param $roleProfileArray -- Profile to be associated with this vtiger_role:: Type Array - * @returns the Rold Id :: Type varchar - * - */ - -function createRole($roleName,$parentRoleId,$roleProfileArray) -{ - global $log; - $log->debug("Entering createRole(".$roleName.",".$parentRoleId.",".$roleProfileArray.") method ..."); - global $adb; - $parentRoleDetails=getRoleInformation($parentRoleId); - $parentRoleInfo=$parentRoleDetails[$parentRoleId]; - $roleid_no=$adb->getUniqueId("vtiger_role"); - $roleId='H'.$roleid_no; - $parentRoleHr=$parentRoleInfo[1]; - $parentRoleDepth=$parentRoleInfo[2]; - $nowParentRoleHr=$parentRoleHr.'::'.$roleId; - $nowRoleDepth=$parentRoleDepth + 1; - - // Invalidate any cached information - VTCacheUtils::clearRoleSubordinates($roleId); - - //Inserting vtiger_role into db - $query="insert into vtiger_role values(?,?,?,?)"; - $qparams = array($roleId,$roleName,$nowParentRoleHr,$nowRoleDepth); - $adb->pquery($query,$qparams); - - //Inserting into vtiger_role2profile vtiger_table - foreach($roleProfileArray as $profileId) - { - if($profileId != '') - { - insertRole2ProfileRelation($roleId,$profileId); - } - } - - $log->debug("Exiting createRole method ..."); - return $roleId; - -} - -/** Function to update the vtiger_role - * @param $roleName -- Role Name:: Type varchar - * @param $roleId -- Role Id:: Type varchar - * @param $roleProfileArray -- Profile to be associated with this vtiger_role:: Type Array - * - */ -function updateRole($roleId,$roleName,$roleProfileArray) -{ - global $log; - $log->debug("Entering updateRole(".$roleId.",".$roleName.",".$roleProfileArray.") method ..."); - - // Invalidate any cached information - VTCacheUtils::clearRoleSubordinates($roleId); - - global $adb; - $sql1 = "update vtiger_role set rolename=? where roleid=?"; - $adb->pquery($sql1, array($roleName, $roleId)); - //Updating the Role2Profile relation - $sql2 = "delete from vtiger_role2profile where roleId=?"; - $adb->pquery($sql2, array($roleId)); - - foreach($roleProfileArray as $profileId) - { - if($profileId != '') - { - insertRole2ProfileRelation($roleId,$profileId); - } - } - $log->debug("Exiting updateRole method ..."); - -} - -/** Function to add the vtiger_role to vtiger_profile relation - * @param $profileId -- Profile Id:: Type integer - * @param $roleId -- Role Id:: Type varchar - * - */ -function insertRole2ProfileRelation($roleId,$profileId) -{ - global $log; - $log->debug("Entering insertRole2ProfileRelation(".$roleId.",".$profileId.") method ..."); - global $adb; - $query="insert into vtiger_role2profile values(?,?)"; - $qparams = array($roleId,$profileId); - $adb->pquery($query, $qparams); - $log->debug("Exiting insertRole2ProfileRelation method ..."); - -} - - -/** Function to get the vtiger_roleid from vtiger_rolename - * @param $rolename -- Role Name:: Type varchar - * @returns Role Id:: Type varchar - * - */ -function fetchRoleId($rolename) -{ -global $log; -$log->debug("Entering fetchRoleId(".$rolename.") method ..."); - - global $adb; - $sqlfetchroleid = "select roleid from vtiger_role where rolename=?"; - $resultroleid = $adb->pquery($sqlfetchroleid, array($rolename)); - $role_id = $adb->query_result($resultroleid,0,"roleid"); -$log->debug("Exiting fetchRoleId method ..."); - return $role_id; -} - -/** Function to update user to vtiger_role mapping based on the userid - * @param $roleid -- Role Id:: Type varchar - * @param $userid User Id:: Type integer - * - */ -function updateUser2RoleMapping($roleid,$userid) -{ -global $log; -$log->debug("Entering updateUser2RoleMapping(".$roleid.",".$userid.") method ..."); - global $adb; - //Check if row already exists - $sqlcheck = "select * from vtiger_user2role where userid=?"; - $resultcheck = $adb->pquery($sqlcheck, array($userid)); - if($adb->num_rows($resultcheck) == 1) - { - $sqldelete = "delete from vtiger_user2role where userid=?"; - $delparams = array($userid); - $result_delete = $adb->pquery($sqldelete, $delparams); - } - $sql = "insert into vtiger_user2role(userid,roleid) values(?,?)"; - $params = array($userid, $roleid); - $result = $adb->pquery($sql, $params); - $log->debug("Exiting updateUser2RoleMapping method ..."); - -} - - -/** Function to update user to group mapping based on the userid - * @param $groupname -- Group Name:: Type varchar - * @param $userid User Id:: Type integer - * - */ -function updateUsers2GroupMapping($groupname,$userid) -{ -global $log; -$log->debug("Entering updateUsers2GroupMapping(".$groupname.",".$userid.") method ..."); - global $adb; - $sqldelete = "delete from vtiger_users2group where userid = ?"; - $delparams = array($userid); - $result_delete = $adb->pquery($sqldelete, $delparams); - - $sql = "insert into vtiger_users2group(groupname,userid) values(?,?)"; - $params = array($groupname,$userid); - $result = $adb->pquery($sql, $params); - $log->debug("Exiting updateUsers2GroupMapping method ..."); -} - -/** Function to add user to vtiger_role mapping - * @param $roleid -- Role Id:: Type varchar - * @param $userid User Id:: Type integer - * - */ -function insertUser2RoleMapping($roleid,$userid) -{ -global $log; -$log->debug("Entering insertUser2RoleMapping(".$roleid.",".$userid.") method ..."); - - global $adb; - $sql = "insert into vtiger_user2role(userid,roleid) values(?,?)"; - $params = array($userid, $roleid); - $adb->pquery($sql, $params); -$log->debug("Exiting insertUser2RoleMapping method ..."); - -} - -/** Function to add user to group mapping - * @param $groupname -- Group Name:: Type varchar - * @param $userid User Id:: Type integer - * - */ -function insertUsers2GroupMapping($groupname,$userid) -{ -global $log; -$log->debug("Entering insertUsers2GroupMapping(".$groupname.",".$userid.") method ..."); - global $adb; - $sql = "insert into vtiger_users2group(groupname,userid) values(?,?)"; - $params = array($groupname, $userid); - $adb->pquery($sql, $params); -$log->debug("Exiting insertUsers2GroupMapping method ..."); -} - -/** Function to get the word template resultset - * @param $module -- Module Name:: Type varchar - * @returns Type:: resultset - * - */ -function fetchWordTemplateList($module) -{ - global $log; - $log->debug("Entering fetchWordTemplateList(".$module.") method ..."); - global $adb; - $sql_word = "select templateid, filename from vtiger_wordtemplates where module =?" ; - $result=$adb->pquery($sql_word, array($module)); - $log->debug("Exiting fetchWordTemplateList method ..."); - return $result; -} - - - -/** Function to get the email template iformation - * @param $templateName -- Template Name:: Type varchar - * @returns Type:: resultset - * - */ -function fetchEmailTemplateInfo($templateName) -{ - global $log; - $log->debug("Entering fetchEmailTemplateInfo(".$templateName.") method ..."); - global $adb; - $sql= "select * from vtiger_emailtemplates where templatename=?"; - $result = $adb->pquery($sql, array($templateName)); - $log->debug("Exiting fetchEmailTemplateInfo method ..."); - return $result; -} - -/** Function to substitute the tokens in the specified file - * @param $templateName -- Template Name:: Type varchar - * @param $globals - * - */ -function substituteTokens($filename,$globals) -{ -global $log; -$log->debug("Entering substituteTokens(".$filename.",".$globals.") method ..."); - $log->debug("in substituteTokens method with filename ".$filename.' and content globals as '.$globals); - - global $root_directory; - - if (!$filename) - { - - $log->debug("filename is not set in substituteTokens"); - $filename = $this->filename; - $log->debug("filename is not set in substituteTokens so taking default filename"); - } - - if (!$dump = file ($filename)) - { - $log->debug("not able to create the file or get access to the file with filename ".$filename." so returning 0"); - $log->debug("Exiting substituteTokens method ..."); - return 0; - } - - $log->debug("about to start replacing the tokens"); - require_once($root_directory .'/modules/Emails/templates/testemailtemplateusage.php'); - eval ("global $globals; "); - while (list($key,$val) = each($dump)) - { - $replacedString ; - if (ereg( "\$",$val)) - { - $log->debug("token is ".$val); - eval( "\$val = \"$val\";"); - $val = stripslashes ($val); - $replacedString .= $val; - } - } - - $log->debug("the replacedString is ".$replacedString); - $log->debug("Exiting substituteTokens method ..."); - return $replacedString; -} - -/** Function to get the vtiger_role name from the vtiger_roleid - * @param $roleid -- Role Id:: Type varchar - * @returns $rolename -- Role Name:: Type varchar - * - */ -function getRoleName($roleid) -{ - global $log; - $log->debug("Entering getRoleName(".$roleid.") method ..."); - global $adb; - $sql1 = "select * from vtiger_role where roleid=?"; - $result = $adb->pquery($sql1, array($roleid)); - $rolename = $adb->query_result($result,0,"rolename"); - $log->debug("Exiting getRoleName method ..."); - return $rolename; -} - -/** Function to get the vtiger_profile name from the vtiger_profileid - * @param $profileid -- Profile Id:: Type integer - * @returns $rolename -- Role Name:: Type varchar - * - */ -function getProfileName($profileid) -{ - global $log; - $log->debug("Entering getProfileName(".$profileid.") method ..."); - global $adb; - $sql1 = "select * from vtiger_profile where profileid=?"; - $result = $adb->pquery($sql1, array($profileid)); - $profilename = $adb->query_result($result,0,"profilename"); - $log->debug("Exiting getProfileName method ..."); - return $profilename; -} -/** Function to get the vtiger_profile Description from the vtiger_profileid - * @param $profileid -- Profile Id:: Type integer - * @returns $rolename -- Role Name:: Type varchar - * - */ -function getProfileDescription($profileid) -{ - global $log; - $log->debug("Entering getProfileDescription(".$profileid.") method ..."); - global $adb; - $sql1 = "select description from vtiger_profile where profileid=?"; - $result = $adb->pquery($sql1, array($profileid)); - $profileDescription = $adb->query_result($result,0,"description"); - $log->debug("Exiting getProfileDescription method ..."); - return $profileDescription; -} - - -/** Function to check if the currently logged in user is permitted to perform the specified action - * @param $module -- Module Name:: Type varchar - * @param $actionname -- Action Name:: Type varchar - * @param $recordid -- Record Id:: Type integer - * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user - * - */ -function isPermitted($module,$actionname,$record_id='') -{ - global $log; - $log->debug("Entering isPermitted(".$module.",".$actionname.",".$record_id.") method ..."); - - global $adb; - global $current_user; - global $seclog; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - $permission = "no"; - if($module == 'Users' || $module == 'Home' || $module == 'uploads') - { - //These modules dont have security right now - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - - } - - //Checking the Access for the Settings Module - if($module == 'Settings' || $module == 'Administration' || $module == 'System' || $_REQUEST['parenttab'] == 'Settings') - { - if(! $is_admin) - { - $permission = "no"; - } - else - { - $permission = "yes"; - } - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - - //Checking whether the user is admin - if($is_admin) - { - $permission ="yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - //Retreiving the Tabid and Action Id - $tabid = getTabid($module); - $actionid=getActionid($actionname); - //If no actionid, then allow action is vtiger_tab permission is available - if($actionid == '') - { - if($profileTabsPermission[$tabid] ==0) - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - } - else - { - $permission ="no"; - } - return $permission; - - } - - $action = getActionname($actionid); - //Checking for view all permission - if($profileGlobalPermission[1] ==0 || $profileGlobalPermission[2] ==0) - { - if($actionid == 3 || $actionid == 4) - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - - } - } - //Checking for edit all permission - if($profileGlobalPermission[2] ==0) - { - if($actionid == 3 || $actionid == 4 || $actionid ==0 || $actionid ==1) - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - - } - } - //Checking for vtiger_tab permission - if($profileTabsPermission[$tabid] !=0) - { - $permission = "no"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - //Checking for Action Permission - if(strlen($profileActionPermission[$tabid][$actionid]) < 1 && $profileActionPermission[$tabid][$actionid] == '') - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - - if($profileActionPermission[$tabid][$actionid] != 0 && $profileActionPermission[$tabid][$actionid] != '') - { - $permission = "no"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - //Checking and returning true if recorid is null - if($record_id == '') - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - - //If modules is Products,Vendors,Faq,PriceBook then no sharing - if($record_id != '') - { - if(getTabOwnedBy($module) == 1) - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - } - - //Retreiving the RecordOwnerId - $recOwnType=''; - $recOwnId=''; - $recordOwnerArr=getRecordOwnerId($record_id); - foreach($recordOwnerArr as $type=>$id) - { - $recOwnType=$type; - $recOwnId=$id; - } - //Retreiving the default Organisation sharing Access - $others_permission_id = $defaultOrgSharingPermission[$tabid]; - - if($recOwnType == 'Users') - { - //Checking if the Record Owner is the current User - if($current_user->id == $recOwnId) - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - //Checking if the Record Owner is the Subordinate User - foreach($subordinate_roles_users as $roleid=>$userids) - { - if(in_array($recOwnId,$userids)) - { - $permission='yes'; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - - } - - - } - elseif($recOwnType == 'Groups') - { - //Checking if the record owner is the current user's group - if(in_array($recOwnId,$current_user_groups)) - { - $permission='yes'; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - } - - //Checking for Default Org Sharing permission - if($others_permission_id == 0) - { - if($actionid == 1 || $actionid == 0) - { - - if($module == 'Calendar') - { - if($recOwnType == 'Users') - { - $permission = isCalendarPermittedBySharing($record_id); - } - else - { - $permission='no'; - } - } - else - { - $permission = isReadWritePermittedBySharing($module,$tabid,$actionid,$record_id); - } - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - elseif($actionid == 2) - { - $permission = "no"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - else - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - } - elseif($others_permission_id == 1) - { - if($actionid == 2) - { - $permission = "no"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - else - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - } - elseif($others_permission_id == 2) - { - - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - elseif($others_permission_id == 3) - { - - if($actionid == 3 || $actionid == 4) - { - if($module == 'Calendar') - { - if($recOwnType == 'Users') - { - $permission = isCalendarPermittedBySharing($record_id); - } - else - { - $permission='no'; - } - } - else - { - $permission = isReadPermittedBySharing($module,$tabid,$actionid,$record_id); - } - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - elseif($actionid ==0 || $actionid ==1) - { - if($module == 'Calendar') - { - $permission='no'; - } - else - { - $permission = isReadWritePermittedBySharing($module,$tabid,$actionid,$record_id); - } - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - elseif($actionid ==2) - { - $permission ="no"; - return $permission; - } - else - { - $permission = "yes"; - $log->debug("Exiting isPermitted method ..."); - return $permission; - } - } - else - { - $permission = "yes"; - } - - $log->debug("Exiting isPermitted method ..."); - return $permission; - -} - -/** Function to check if the currently logged in user has Read Access due to Sharing for the specified record - * @param $module -- Module Name:: Type varchar - * @param $actionid -- Action Id:: Type integer - * @param $recordid -- Record Id:: Type integer - * @param $tabid -- Tab Id:: Type integer - * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user - */ -function isReadPermittedBySharing($module,$tabid,$actionid,$record_id) -{ - global $log; - $log->debug("Entering isReadPermittedBySharing(".$module.",".$tabid.",".$actionid.",".$record_id.") method ..."); - global $adb; - global $current_user; - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - $ownertype=''; - $ownerid=''; - $sharePer='no'; - - $sharingModuleList=getSharingModuleList(); - if(! in_array($module,$sharingModuleList)) - { - $sharePer='no'; - return $sharePer; - } - - $recordOwnerArr=getRecordOwnerId($record_id); - foreach($recordOwnerArr as $type=>$id) - { - $ownertype=$type; - $ownerid=$id; - } - - $varname=$module."_share_read_permission"; - $read_per_arr=$$varname; - if($ownertype == 'Users') - { - //Checking the Read Sharing Permission Array in Role Users - $read_role_per=$read_per_arr['ROLE']; - foreach($read_role_per as $roleid=>$userids) - { - if(in_array($ownerid,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; - } - - } - - //Checking the Read Sharing Permission Array in Groups Users - $read_grp_per=$read_per_arr['GROUP']; - foreach($read_grp_per as $grpid=>$userids) - { - if(in_array($ownerid,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; - } - - } - - } - elseif($ownertype == 'Groups') - { - $read_grp_per=$read_per_arr['GROUP']; - if(array_key_exists($ownerid,$read_grp_per)) - { - $sharePer='yes'; - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; - } - } - - //Checking for the Related Sharing Permission - $relatedModuleArray=$related_module_share[$tabid]; - if(is_array($relatedModuleArray)) - { - foreach($relatedModuleArray as $parModId) - { - $parRecordOwner=getParentRecordOwner($tabid,$parModId,$record_id); - if(sizeof($parRecordOwner) > 0) - { - $parModName=getTabname($parModId); - $rel_var=$parModName."_".$module."_share_read_permission"; - $read_related_per_arr=$$rel_var; - $rel_owner_type=''; - $rel_owner_id=''; - foreach($parRecordOwner as $rel_type=>$rel_id) - { - $rel_owner_type=$rel_type; - $rel_owner_id=$rel_id; - } - if($rel_owner_type=='Users') - { - //Checking in Role Users - $read_related_role_per=$read_related_per_arr['ROLE']; - foreach($read_related_role_per as $roleid=>$userids) - { - if(in_array($rel_owner_id,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; - } - - } - //Checking in Group Users - $read_related_grp_per=$read_related_per_arr['GROUP']; - foreach($read_related_grp_per as $grpid=>$userids) - { - if(in_array($rel_owner_id,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; - } - - } - - } - elseif($rel_owner_type=='Groups') - { - $read_related_grp_per=$read_related_per_arr['GROUP']; - if(array_key_exists($rel_owner_id,$read_related_grp_per)) - { - $sharePer='yes'; - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; - } - - } - } - } - } - $log->debug("Exiting isReadPermittedBySharing method ..."); - return $sharePer; -} - - - -/** Function to check if the currently logged in user has Write Access due to Sharing for the specified record - * @param $module -- Module Name:: Type varchar - * @param $actionid -- Action Id:: Type integer - * @param $recordid -- Record Id:: Type integer - * @param $tabid -- Tab Id:: Type integer - * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user - */ -function isReadWritePermittedBySharing($module,$tabid,$actionid,$record_id) -{ - global $log; - $log->debug("Entering isReadWritePermittedBySharing(".$module.",".$tabid.",".$actionid.",".$record_id.") method ..."); - global $adb; - global $current_user; - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - $ownertype=''; - $ownerid=''; - $sharePer='no'; - - $sharingModuleList=getSharingModuleList(); - if(! in_array($module,$sharingModuleList)) - { - $sharePer='no'; - return $sharePer; - } - - $recordOwnerArr=getRecordOwnerId($record_id); - foreach($recordOwnerArr as $type=>$id) - { - $ownertype=$type; - $ownerid=$id; - } - - $varname=$module."_share_write_permission"; - $write_per_arr=$$varname; - - if($ownertype == 'Users') - { - //Checking the Write Sharing Permission Array in Role Users - $write_role_per=$write_per_arr['ROLE']; - foreach($write_role_per as $roleid=>$userids) - { - if(in_array($ownerid,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; - } - - } - //Checking the Write Sharing Permission Array in Groups Users - $write_grp_per=$write_per_arr['GROUP']; - foreach($write_grp_per as $grpid=>$userids) - { - if(in_array($ownerid,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; - } - - } - - } - elseif($ownertype == 'Groups') - { - $write_grp_per=$write_per_arr['GROUP']; - if(array_key_exists($ownerid,$write_grp_per)) - { - $sharePer='yes'; - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; - } - } - //Checking for the Related Sharing Permission - $relatedModuleArray=$related_module_share[$tabid]; - if(is_array($relatedModuleArray)) - { - foreach($relatedModuleArray as $parModId) - { - $parRecordOwner=getParentRecordOwner($tabid,$parModId,$record_id); - if(sizeof($parRecordOwner) > 0) - { - $parModName=getTabname($parModId); - $rel_var=$parModName."_".$module."_share_write_permission"; - $write_related_per_arr=$$rel_var; - $rel_owner_type=''; - $rel_owner_id=''; - foreach($parRecordOwner as $rel_type=>$rel_id) - { - $rel_owner_type=$rel_type; - $rel_owner_id=$rel_id; - } - if($rel_owner_type=='Users') - { - //Checking in Role Users - $write_related_role_per=$write_related_per_arr['ROLE']; - foreach($write_related_role_per as $roleid=>$userids) - { - if(in_array($rel_owner_id,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; - } - - } - //Checking in Group Users - $write_related_grp_per=$write_related_per_arr['GROUP']; - foreach($write_related_grp_per as $grpid=>$userids) - { - if(in_array($rel_owner_id,$userids)) - { - $sharePer='yes'; - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; - } - - } - - } - elseif($rel_owner_type=='Groups') - { - $write_related_grp_per=$write_related_per_arr['GROUP']; - if(array_key_exists($rel_owner_id,$write_related_grp_per)) - { - $sharePer='yes'; - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; - } - - } - } - } - } - - $log->debug("Exiting isReadWritePermittedBySharing method ..."); - return $sharePer; -} - -/** Function to check if the outlook user is permitted to perform the specified action - * @param $module -- Module Name:: Type varchar - * @param $actionname -- Action Name:: Type varchar - * @param $recordid -- Record Id:: Type integer - * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user - * - */ -function isAllowed_Outlook($module,$action,$user_id,$record_id) -{ - global $log; - $log->debug("Entering isAllowed_Outlook(".$module.",".$action.",".$user_id.",".$record_id.") method ..."); - - $permission = "no"; - if($module == 'Users' || $module == 'Home' || $module == 'Administration' || $module == 'uploads' || $module == 'Settings' || $module == 'Calendar') - { - //These modules done have security - $permission = "yes"; - - } - else - { - global $adb; - global $current_user; - $tabid = getTabid($module); - $actionid = getActionid($action); - $profile_id = fetchUserProfileId($user_id); - $tab_per_Data = getAllTabsPermission($profile_id); - - $permissionData = getTabsActionPermission($profile_id); - $defSharingPermissionData = getDefaultSharingAction(); - $others_permission_id = $defSharingPermissionData[$tabid]; - - //Checking whether this vtiger_tab is allowed - if($tab_per_Data[$tabid] == 0) - { - $permission = 'yes'; - //Checking whether this action is allowed - if($permissionData[$tabid][$actionid] == 0) - { - $permission = 'yes'; - $rec_owner_id = ''; - if($record_id != '' && $module != 'Products' && $module != 'Faq') - { - $rec_owner_id = getUserId($record_id); - } - - if($record_id != '' && $others_permission_id != '' && $module != 'Products' && $module != 'Faq' && $rec_owner_id != 0) - { - if($rec_owner_id != $current_user->id) - { - if($others_permission_id == 0) - { - if($action == 'EditView' || $action == 'Delete') - { - $permission = "no"; - } - else - { - $permission = "yes"; - } - } - elseif($others_permission_id == 1) - { - if($action == 'Delete') - { - $permission = "no"; - } - else - { - $permission = "yes"; - } - } - elseif($others_permission_id == 2) - { - - $permission = "yes"; - } - elseif($others_permission_id == 3) - { - if($action == 'DetailView' || $action == 'EditView' || $action == 'Delete') - { - $permission = "no"; - } - else - { - $permission = "yes"; - } - } - - - } - else - { - $permission = "yes"; - } - } - } - else - { - $permission = "no"; - } - } - else - { - $permission = "no"; - } - } - $log->debug("Exiting isAllowed_Outlook method ..."); - return $permission; - -} - - -/** Function to get the Profile Global Information for the specified vtiger_profileid - * @param $profileid -- Profile Id:: Type integer - * @returns Profile Gloabal Permission Array in the following format: - * $profileGloblaPermisson=Array($viewall_actionid=>permission, $editall_actionid=>permission) - */ -function getProfileGlobalPermission($profileid) -{ -global $log; -$log->debug("Entering getProfileGlobalPermission(".$profileid.") method ..."); - global $adb; - $sql = "select * from vtiger_profile2globalpermissions where profileid=?" ; - $result = $adb->pquery($sql, array($profileid)); - $num_rows = $adb->num_rows($result); - - for($i=0; $i<$num_rows; $i++) - { - $act_id = $adb->query_result($result,$i,"globalactionid"); - $per_id = $adb->query_result($result,$i,"globalactionpermission"); - $copy[$act_id] = $per_id; - } - - $log->debug("Exiting getProfileGlobalPermission method ..."); - return $copy; - -} - -/** Function to get the Profile Tab Permissions for the specified vtiger_profileid - * @param $profileid -- Profile Id:: Type integer - * @returns Profile Tabs Permission Array in the following format: - * $profileTabPermisson=Array($tabid1=>permission, $tabid2=>permission,........., $tabidn=>permission) - */ -function getProfileTabsPermission($profileid) -{ -global $log; -$log->debug("Entering getProfileTabsPermission(".$profileid.") method ..."); - global $adb; - $sql = "select * from vtiger_profile2tab where profileid=?" ; - $result = $adb->pquery($sql, array($profileid)); - $num_rows = $adb->num_rows($result); - - for($i=0; $i<$num_rows; $i++) - { - $tab_id = $adb->query_result($result,$i,"tabid"); - $per_id = $adb->query_result($result,$i,"permissions"); - $copy[$tab_id] = $per_id; - } - -$log->debug("Exiting getProfileTabsPermission method ..."); - return $copy; - -} - - -/** Function to get the Profile Action Permissions for the specified vtiger_profileid - * @param $profileid -- Profile Id:: Type integer - * @returns Profile Tabs Action Permission Array in the following format: - * $tabActionPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * | - * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) - */ -function getProfileActionPermission($profileid) -{ -global $log; -$log->debug("Entering getProfileActionPermission(".$profileid.") method ..."); - global $adb; - $check = Array(); - $temp_tabid = Array(); - $sql1 = "select * from vtiger_profile2standardpermissions where profileid=?"; - $result1 = $adb->pquery($sql1, array($profileid)); - $num_rows1 = $adb->num_rows($result1); - for($i=0; $i<$num_rows1; $i++) - { - $tab_id = $adb->query_result($result1,$i,'tabid'); - if(! in_array($tab_id,$temp_tabid)) - { - $temp_tabid[] = $tab_id; - $access = Array(); - } - - $action_id = $adb->query_result($result1,$i,'operation'); - $per_id = $adb->query_result($result1,$i,'permissions'); - $access[$action_id] = $per_id; - $check[$tab_id] = $access; - - - } - - -$log->debug("Exiting getProfileActionPermission method ..."); - return $check; -} - - - -/** Function to get the Standard and Utility Profile Action Permissions for the specified vtiger_profileid - * @param $profileid -- Profile Id:: Type integer - * @returns Profile Tabs Action Permission Array in the following format: - * $tabActionPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), - * | - * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) - */ -function getProfileAllActionPermission($profileid) -{ -global $log; -$log->debug("Entering getProfileAllActionPermission(".$profileid.") method ..."); - global $adb; - $actionArr=getProfileActionPermission($profileid); - $utilArr=getTabsUtilityActionPermission($profileid); - foreach($utilArr as $tabid=>$act_arr) - { - $act_tab_arr=$actionArr[$tabid]; - foreach($act_arr as $utilid=>$util_perr) - { - $act_tab_arr[$utilid]=$util_perr; - } - $actionArr[$tabid]=$act_tab_arr; - } -$log->debug("Exiting getProfileAllActionPermission method ..."); - return $actionArr; -} - - -/** Function to create vtiger_profile - * @param $profilename -- Profile Name:: Type varchar - * @param $parentProfileId -- Profile Id:: Type integer - */ -function createProfile($profilename,$parentProfileId,$description) -{ -global $log; -$log->debug("Entering createProfile(".$profilename.",".$parentProfileId.",".$description.") method ..."); - global $adb; - //Inserting values into Profile Table - $sql1 = "insert into vtiger_profile values(?,?,?)"; - $params1 = array('', $profilename, $description); - $adb->pquery($sql1, $params1); - - //Retreiving the vtiger_profileid - $sql2 = "select max(profileid) as current_id from vtiger_profile"; - $result2 = $adb->pquery($sql2, array()); - $current_profile_id = $adb->query_result($result2,0,'current_id'); - - //Inserting values into vtiger_profile2globalpermissions - $sql3 = "select * from vtiger_profile2globalpermissions where profileid=?"; - $params3 = array($parentProfileId); - $result3= $adb->pquery($sql3, $params3); - $p2tab_rows = $adb->num_rows($result3); - for($i=0; $i<$p2tab_rows; $i++) - { - $act_id=$adb->query_result($result3,$i,'globalactionid'); - $permissions=$adb->query_result($result3,$i,'globalactionpermission'); - $sql4="insert into vtiger_profile2globalpermissions values(?,?,?)"; - $params4 = array($current_profile_id, $act_id, $permissions); - $adb->pquery($sql4, $params4); - } - - //Inserting values into Profile2tab vtiger_table - $sql3 = "select * from vtiger_profile2tab where profileid=?"; - $params3 = array($parentProfileId); - $result3= $adb->pquery($sql3, $params3); - $p2tab_rows = $adb->num_rows($result3); - for($i=0; $i<$p2tab_rows; $i++) - { - $tab_id=$adb->query_result($result3,$i,'tabid'); - $permissions=$adb->query_result($result3,$i,'permissions'); - $sql4="insert into vtiger_profile2tab values(?,?,?)"; - $params4 = array($current_profile_id, $tab_id, $permissions); - $adb->pquery($sql4, $params4); - } - - //Inserting values into Profile2standard vtiger_table - $sql6 = "select * from vtiger_profile2standardpermissions where profileid=?"; - $params6 = array($parentProfileId); - $result6= $adb->pquery($sql6, $params6); - $p2per_rows = $adb->num_rows($result6); - for($i=0; $i<$p2per_rows; $i++) - { - $tab_id=$adb->query_result($result6,$i,'tabid'); - $action_id=$adb->query_result($result6,$i,'operation'); - $permissions=$adb->query_result($result6,$i,'permissions'); - $sql7="insert into vtiger_profile2standardpermissions values(?,?,?,?)"; - $params7 = array($current_profile_id, $tab_id, $action_id, $permissions); - $adb->pquery($sql7, $params7); - } - - //Inserting values into Profile2Utility vtiger_table - $sql8 = "select * from vtiger_profile2utility where profileid=?"; - $params8 = array($parentProfileId); - $result8= $adb->pquery($sql8, $params8); - $p2util_rows = $adb->num_rows($result8); - for($i=0; $i<$p2util_rows; $i++) - { - $tab_id=$adb->query_result($result8,$i,'tabid'); - $action_id=$adb->query_result($result8,$i,'activityid'); - $permissions=$adb->query_result($result8,$i,'permission'); - $sql9="insert into vtiger_profile2utility values(?,?,?,?)"; - $params9 = array($current_profile_id, $tab_id, $action_id, $permissions); - $adb->pquery($sql9, $params9); - } - - //Inserting values into Profile2field vtiger_table - $sql10 = "select * from vtiger_profile2field where profileid=?"; - $params10 = array($parentProfileId); - $result10= $adb->pquery($sql10, $params10); - $p2field_rows = $adb->num_rows($result10); - for($i=0; $i<$p2field_rows; $i++) - { - $tab_id=$adb->query_result($result10,$i,'tabid'); - $fieldid=$adb->query_result($result10,$i,'fieldid'); - $permissions=$adb->query_result($result10,$i,'visible'); - $readonly=$adb->query_result($result10,$i,'readonly'); - $sql11="insert into vtiger_profile2field values(?,?,?,?,?)"; - $params11 = array($current_profile_id, $tab_id, $fieldid, $permissions ,$readonly); - $adb->pquery($sql11, $params11); - } - $log->debug("Exiting createProfile method ..."); -} - -/** Function to delete vtiger_profile - * @param $transfer_profileid -- Profile Id to which the existing vtiger_role2profile relationships are to be transferred :: Type varchar - * @param $prof_id -- Profile Id to be deleted:: Type integer - */ -function deleteProfile($prof_id,$transfer_profileid='') -{ - global $log; -$log->debug("Entering deleteProfile(".$prof_id.",".$transfer_profileid.") method ..."); - global $adb; - //delete from vtiger_profile2global permissions - $sql4 = "delete from vtiger_profile2globalpermissions where profileid=?"; - $adb->pquery($sql4, array($prof_id)); - - //deleting from vtiger_profile 2 vtiger_tab; - $sql4 = "delete from vtiger_profile2tab where profileid=?"; - $adb->pquery($sql4, array($prof_id)); - - //deleting from vtiger_profile2standardpermissions vtiger_table - $sql5 = "delete from vtiger_profile2standardpermissions where profileid=?"; - $adb->pquery($sql5, array($prof_id)); - - //deleting from vtiger_profile2field - $sql6 ="delete from vtiger_profile2field where profileid=?"; - $adb->pquery($sql6, array($prof_id)); - - //deleting from vtiger_profile2utility - $sql7 ="delete from vtiger_profile2utility where profileid=?"; - $adb->pquery($sql7, array($prof_id)); - - //updating vtiger_role2profile - if(isset($transfer_profileid) && $transfer_profileid != '') - { - - $sql8 = "select roleid from vtiger_role2profile where profileid=?"; - $result = $adb->pquery($sql8, array($prof_id)); - $num_rows=$adb->num_rows($result); - - for($i=0;$i<$num_rows;$i++) - { - $roleid=$adb->query_result($result,$i,'roleid'); - $sql = "select profileid from vtiger_role2profile where roleid=?"; - $profresult=$adb->pquery($sql, array($roleid)); - $num=$adb->num_rows($profresult); - if($num>1) - { - $sql10="delete from vtiger_role2profile where roleid=? and profileid=?"; - $adb->pquery($sql10, array($roleid, $prof_id)); - } - else - { - $sql8 = "update vtiger_role2profile set profileid=? where profileid=? and roleid=?"; - $adb->pquery($sql8, array($transfer_profileid, $prof_id, $roleid)); - } - - - } - } - - //delete from vtiger_profile vtiger_table; - $sql9 = "delete from vtiger_profile where profileid=?"; - $adb->pquery($sql9, array($prof_id)); - $log->debug("Exiting deleteProfile method ..."); - -} - -/** Function to get all the vtiger_role information - * @returns $allRoleDetailArray-- Array will contain the details of all the vtiger_roles. RoleId will be the key:: Type array - */ -function getAllRoleDetails() -{ -global $log; -$log->debug("Entering getAllRoleDetails() method ..."); - global $adb; - $role_det = Array(); - $query = "select * from vtiger_role"; - $result = $adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - for($i=0; $i<$num_rows;$i++) - { - $each_role_det = Array(); - $roleid=$adb->query_result($result,$i,'roleid'); - $rolename=$adb->query_result($result,$i,'rolename'); - $roledepth=$adb->query_result($result,$i,'depth'); - $sub_roledepth=$roledepth + 1; - $parentrole=$adb->query_result($result,$i,'parentrole'); - $sub_role=''; - - //getting the immediate subordinates - $query1="select * from vtiger_role where parentrole like ? and depth=?"; - $res1 = $adb->pquery($query1, array($parentrole."::%", $sub_roledepth)); - $num_roles = $adb->num_rows($res1); - if($num_roles > 0) - { - for($j=0; $j<$num_roles; $j++) - { - if($j == 0) - { - $sub_role .= $adb->query_result($res1,$j,'roleid'); - } - else - { - $sub_role .= ','.$adb->query_result($res1,$j,'roleid'); - } - } - } - - - $each_role_det[]=$rolename; - $each_role_det[]=$roledepth; - $each_role_det[]=$sub_role; - $role_det[$roleid]=$each_role_det; - - } - $log->debug("Exiting getAllRoleDetails method ..."); - return $role_det; -} - - -/** Function to get all the vtiger_profile information - * @returns $allProfileInfoArray-- Array will contain the details of all the vtiger_profiles. Profile ID will be the key:: Type array - */ -function getAllProfileInfo() -{ - global $log; - $log->debug("Entering getAllProfileInfo() method ..."); - global $adb; - $query="select * from vtiger_profile"; - $result = $adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - $prof_details=Array(); - for($i=0;$i<$num_rows;$i++) - { - $profileid=$adb->query_result($result,$i,'profileid'); - $profilename=$adb->query_result($result,$i,'profilename'); - $prof_details[$profileid]=$profilename; - - } - $log->debug("Exiting getAllProfileInfo method ..."); - return $prof_details; -} - -/** Function to get the vtiger_role information of the specified vtiger_role - * @param $roleid -- RoleId :: Type varchar - * @returns $roleInfoArray-- RoleInfoArray in the following format: - * $roleInfo=Array($roleId=>Array($rolename,$parentrole,$roledepth,$immediateParent)); - */ -function getRoleInformation($roleid) -{ - global $log; - $log->debug("Entering getRoleInformation(".$roleid.") method ..."); - global $adb; - $query = "select * from vtiger_role where roleid=?"; - $result = $adb->pquery($query, array($roleid)); - $rolename=$adb->query_result($result,0,'rolename'); - $parentrole=$adb->query_result($result,0,'parentrole'); - $roledepth=$adb->query_result($result,0,'depth'); - $parentRoleArr=explode('::',$parentrole); - $immediateParent=$parentRoleArr[sizeof($parentRoleArr)-2]; - $roleDet=Array(); - $roleDet[]=$rolename; - $roleDet[]=$parentrole; - $roleDet[]=$roledepth; - $roleDet[]=$immediateParent; - $roleInfo=Array(); - $roleInfo[$roleid]=$roleDet; - $log->debug("Exiting getRoleInformation method ..."); - return $roleInfo; -} - - -/** Function to get the vtiger_role related vtiger_profiles - * @param $roleid -- RoleId :: Type varchar - * @returns $roleProfiles-- Role Related Profile Array in the following format: - * $roleProfiles=Array($profileId1=>$profileName,$profileId2=>$profileName,........,$profileIdn=>$profileName)); - */ -function getRoleRelatedProfiles($roleId) -{ - global $log; - $log->debug("Entering getRoleRelatedProfiles(".$roleId.") method ..."); - global $adb; - $query = "select vtiger_role2profile.*,vtiger_profile.profilename from vtiger_role2profile inner join vtiger_profile on vtiger_profile.profileid=vtiger_role2profile.profileid where roleid=?"; - $result = $adb->pquery($query, array($roleId)); - $num_rows=$adb->num_rows($result); - $roleRelatedProfiles=Array(); - for($i=0; $i<$num_rows; $i++) - { - $roleRelatedProfiles[$adb->query_result($result,$i,'profileid')]=$adb->query_result($result,$i,'profilename'); - } - $log->debug("Exiting getRoleRelatedProfiles method ..."); - return $roleRelatedProfiles; -} - - -/** Function to get the vtiger_role related vtiger_users - * @param $roleid -- RoleId :: Type varchar - * @returns $roleUsers-- Role Related User Array in the following format: - * $roleUsers=Array($userId1=>$userName,$userId2=>$userName,........,$userIdn=>$userName)); - */ -function getRoleUsers($roleId) -{ - global $log; - $log->debug("Entering getRoleUsers(".$roleId.") method ..."); - global $adb; - $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid where roleid=?"; - $result = $adb->pquery($query, array($roleId)); - $num_rows=$adb->num_rows($result); - $roleRelatedUsers=Array(); - for($i=0; $i<$num_rows; $i++) - { - $roleRelatedUsers[$adb->query_result($result,$i,'userid')]=$adb->query_result($result,$i,'user_name'); - } - $log->debug("Exiting getRoleUsers method ..."); - return $roleRelatedUsers; - - -} - - -/** Function to get the vtiger_role related user ids - * @param $roleid -- RoleId :: Type varchar - * @returns $roleUserIds-- Role Related User Array in the following format: - * $roleUserIds=Array($userId1,$userId2,........,$userIdn); - */ - -function getRoleUserIds($roleId) -{ - global $log; - $log->debug("Entering getRoleUserIds(".$roleId.") method ..."); - global $adb; - $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid where roleid=?"; - $result = $adb->pquery($query, array($roleId)); - $num_rows=$adb->num_rows($result); - $roleRelatedUsers=Array(); - for($i=0; $i<$num_rows; $i++) - { - $roleRelatedUsers[]=$adb->query_result($result,$i,'userid'); - } - $log->debug("Exiting getRoleUserIds method ..."); - return $roleRelatedUsers; - - -} - -/** Function to get the vtiger_role and subordinate vtiger_users - * @param $roleid -- RoleId :: Type varchar - * @returns $roleSubUsers-- Role and Subordinates Related Users Array in the following format: - * $roleSubUsers=Array($userId1=>$userName,$userId2=>$userName,........,$userIdn=>$userName)); - */ -function getRoleAndSubordinateUsers($roleId) -{ - global $log; - $log->debug("Entering getRoleAndSubordinateUsers(".$roleId.") method ..."); - global $adb; - $roleInfoArr=getRoleInformation($roleId); - $parentRole=$roleInfoArr[$roleId][1]; - $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ?"; - $result = $adb->pquery($query, array($parentRole."%")); - $num_rows=$adb->num_rows($result); - $roleRelatedUsers=Array(); - for($i=0; $i<$num_rows; $i++) - { - $roleRelatedUsers[$adb->query_result($result,$i,'userid')]=$adb->query_result($result,$i,'user_name'); - } - $log->debug("Exiting getRoleAndSubordinateUsers method ..."); - return $roleRelatedUsers; - - -} - - -/** Function to get the vtiger_role and subordinate user ids - * @param $roleid -- RoleId :: Type varchar - * @returns $roleSubUserIds-- Role and Subordinates Related Users Array in the following format: - * $roleSubUserIds=Array($userId1,$userId2,........,$userIdn); - */ -function getRoleAndSubordinateUserIds($roleId) -{ - global $log; - $log->debug("Entering getRoleAndSubordinateUserIds(".$roleId.") method ..."); - global $adb; - $roleInfoArr=getRoleInformation($roleId); - $parentRole=$roleInfoArr[$roleId][1]; - $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ?"; - $result = $adb->pquery($query, array($parentRole."%")); - $num_rows=$adb->num_rows($result); - $roleRelatedUsers=Array(); - for($i=0; $i<$num_rows; $i++) - { - $roleRelatedUsers[]=$adb->query_result($result,$i,'userid'); - } - $log->debug("Exiting getRoleAndSubordinateUserIds method ..."); - return $roleRelatedUsers; - - -} - -/** Function to get the vtiger_role and subordinate Information for the specified vtiger_roleId - * @param $roleid -- RoleId :: Type varchar - * @returns $roleSubInfo-- Role and Subordinates Information array in the following format: - * $roleSubInfo=Array($roleId1=>Array($rolename,$parentrole,$roledepth,$immediateParent), $roleId2=>Array($rolename,$parentrole,$roledepth,$immediateParent),.....); - */ -function getRoleAndSubordinatesInformation($roleId) -{ - global $log; - $log->debug("Entering getRoleAndSubordinatesInformation(".$roleId.") method ..."); - global $adb; - $roleDetails=getRoleInformation($roleId); - $roleInfo=$roleDetails[$roleId]; - $roleParentSeq=$roleInfo[1]; - - $query="select * from vtiger_role where parentrole like ? order by parentrole asc"; - $result=$adb->pquery($query, array($roleParentSeq."%")); - $num_rows=$adb->num_rows($result); - $roleInfo=Array(); - for($i=0;$i<$num_rows;$i++) - { - $roleid=$adb->query_result($result,$i,'roleid'); - $rolename=$adb->query_result($result,$i,'rolename'); - $roledepth=$adb->query_result($result,$i,'depth'); - $parentrole=$adb->query_result($result,$i,'parentrole'); - $roleDet=Array(); - $roleDet[]=$rolename; - $roleDet[]=$parentrole; - $roleDet[]=$roledepth; - $roleInfo[$roleid]=$roleDet; - - } - $log->debug("Exiting getRoleAndSubordinatesInformation method ..."); - return $roleInfo; - -} - - -/** Function to get the vtiger_role and subordinate vtiger_role ids - * @param $roleid -- RoleId :: Type varchar - * @returns $roleSubRoleIds-- Role and Subordinates RoleIds in an Array in the following format: - * $roleSubRoleIds=Array($roleId1,$roleId2,........,$roleIdn); - */ -function getRoleAndSubordinatesRoleIds($roleId) -{ - global $log; - $log->debug("Entering getRoleAndSubordinatesRoleIds(".$roleId.") method ..."); - global $adb; - $roleDetails=getRoleInformation($roleId); - $roleInfo=$roleDetails[$roleId]; - $roleParentSeq=$roleInfo[1]; - - $query="select * from vtiger_role where parentrole like ? order by parentrole asc"; - $result=$adb->pquery($query, array($roleParentSeq."%")); - $num_rows=$adb->num_rows($result); - $roleInfo=Array(); - for($i=0;$i<$num_rows;$i++) - { - $roleid=$adb->query_result($result,$i,'roleid'); - $roleInfo[]=$roleid; - - } - $log->debug("Exiting getRoleAndSubordinatesRoleIds method ..."); - return $roleInfo; - -} - -/** Function to get delete the spcified vtiger_role - * @param $roleid -- RoleId :: Type varchar - * @param $transferRoleId -- RoleId to which vtiger_users of the vtiger_role that is being deleted are transferred:: Type varchar - */ -function deleteRole($roleId,$transferRoleId) -{ - global $log; - $log->debug("Entering deleteRole(".$roleId.",".$transferRoleId.") method ..."); - global $adb; - $roleInfo=getRoleAndSubordinatesInformation($roleId); - foreach($roleInfo as $roleid=>$roleDetArr) - { - - $sql1 = "update vtiger_user2role set roleid=? where roleid=?"; - $adb->pquery($sql1, array($transferRoleId, $roleid)); - - //Deleteing from vtiger_role2profile vtiger_table - $sql2 = "delete from vtiger_role2profile where roleid=?"; - $adb->pquery($sql2, array($roleid)); - - //delete handling for vtiger_groups - $sql10 = "delete from vtiger_group2role where roleid=?"; - $adb->pquery($sql10, array($roleid)); - - $sql11 = "delete from vtiger_group2rs where roleandsubid=?"; - $adb->pquery($sql11, array($roleid)); - - - //delete handling for sharing rules - deleteRoleRelatedSharingRules($roleid); - - //delete from vtiger_role vtiger_table; - $sql9 = "delete from vtiger_role where roleid=?"; - $adb->pquery($sql9, array($roleid)); - - - - } - $log->debug("Exiting deleteRole method ..."); - -} - -/** Function to delete the vtiger_role related sharing rules - * @param $roleid -- RoleId :: Type varchar - */ -function deleteRoleRelatedSharingRules($roleId) -{ - global $log; - $log->debug("Entering deleteRoleRelatedSharingRules(".$roleId.") method ..."); - global $adb; - $dataShareTableColArr=Array('vtiger_datashare_grp2role'=>'to_roleid', - 'vtiger_datashare_grp2rs'=>'to_roleandsubid', - 'vtiger_datashare_role2group'=>'share_roleid', - 'vtiger_datashare_role2role'=>'share_roleid::to_roleid', - 'vtiger_datashare_role2rs'=>'share_roleid::to_roleandsubid', - 'vtiger_datashare_rs2grp'=>'share_roleandsubid', - 'vtiger_datashare_rs2role'=>'share_roleandsubid::to_roleid', - 'vtiger_datashare_rs2rs'=>'share_roleandsubid::to_roleandsubid'); - - foreach($dataShareTableColArr as $tablename=>$colname) - { - $colNameArr=explode('::',$colname); - $query="select shareid from ".$tablename." where ".$colNameArr[0]."=?"; - $params = array($roleId); - if(sizeof($colNameArr) >1) - { - $query .=" or ".$colNameArr[1]."=?"; - array_push($params, $roleId); - } - - $result=$adb->pquery($query, $params); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $shareid=$adb->query_result($result,$i,'shareid'); - deleteSharingRule($shareid); - } - - } - $log->debug("Exiting deleteRoleRelatedSharingRules method ..."); -} - -/** Function to delete the group related sharing rules - * @param $roleid -- RoleId :: Type varchar - */ -function deleteGroupRelatedSharingRules($grpId) -{ - global $log; - $log->debug("Entering deleteGroupRelatedSharingRules(".$grpId.") method ..."); - - global $adb; - $dataShareTableColArr=Array('vtiger_datashare_grp2grp'=>'share_groupid::to_groupid', - 'vtiger_datashare_grp2role'=>'share_groupid', - 'vtiger_datashare_grp2rs'=>'share_groupid', - 'vtiger_datashare_role2group'=>'to_groupid', - 'vtiger_datashare_rs2grp'=>'to_groupid'); - - - foreach($dataShareTableColArr as $tablename=>$colname) - { - $colNameArr=explode('::',$colname); - $query="select shareid from ".$tablename." where ".$colNameArr[0]."=?"; - $params = array($grpId); - if(sizeof($colNameArr) >1) - { - $query .=" or ".$colNameArr[1]."=?"; - array_push($params, $grpId); - } - - $result=$adb->pquery($query, $params); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $shareid=$adb->query_result($result,$i,'shareid'); - deleteSharingRule($shareid); - } - - } - $log->debug("Exiting deleteGroupRelatedSharingRules method ..."); -} - - -/** Function to get userid and username of all vtiger_users - * @returns $userArray -- User Array in the following format: - * $userArray=Array($userid1=>$username, $userid2=>$username,............,$useridn=>$username); - */ -function getAllUserName() -{ - global $log; - $log->debug("Entering getAllUserName() method ..."); - global $adb; - $query="select * from vtiger_users where deleted=0"; - $result = $adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - $user_details=Array(); - for($i=0;$i<$num_rows;$i++) - { - $userid=$adb->query_result($result,$i,'id'); - $username=$adb->query_result($result,$i,'user_name'); - $user_details[$userid]=$username; - - } - $log->debug("Exiting getAllUserName method ..."); - return $user_details; - -} - - -/** Function to get groupid and groupname of all vtiger_groups - * @returns $grpArray -- Group Array in the following format: - * $grpArray=Array($grpid1=>$grpname, $grpid2=>$grpname,............,$grpidn=>$grpname); - */ -function getAllGroupName() -{ - global $log; - $log->debug("Entering getAllGroupName() method ..."); - global $adb; - $query="select * from vtiger_groups"; - $result = $adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - $group_details=Array(); - for($i=0;$i<$num_rows;$i++) - { - $grpid=$adb->query_result($result,$i,'groupid'); - $grpname=$adb->query_result($result,$i,'groupname'); - $group_details[$grpid]=$grpname; - - } - $log->debug("Exiting getAllGroupName method ..."); - return $group_details; - -} - -/** Function to get groupid and groupname of all for the given groupid - * @returns $grpArray -- Group Array in the following format: - * $grpArray=Array($grpid1=>$grpname); - */ -function getGroupDetails($id) -{ - global $log; - $log->debug("Entering getAllGroupDetails() method ..."); - global $adb; - $query="select * from vtiger_groups where groupid = ?"; - $result = $adb->pquery($query, array($id)); - $num_rows=$adb->num_rows($result); - if($num_rows < 1) - return null; - $group_details=Array(); - $grpid=$adb->query_result($result,0,'groupid'); - $grpname=$adb->query_result($result,0,'groupname'); - $grpdesc=$adb->query_result($result,0,'description'); - $group_details=Array($grpid,$grpname,$grpdesc); - - $log->debug("Exiting getAllGroupDetails method ..."); - return $group_details; - -} -/** Function to get group information of all vtiger_groups - * @returns $grpInfoArray -- Group Informaton array in the following format: - * $grpInfoArray=Array($grpid1=>Array($grpname,description) $grpid2=>Array($grpname,description),............,$grpidn=>Array($grpname,description)); - */ -function getAllGroupInfo() -{ - global $log; - $log->debug("Entering getAllGroupInfo() method ..."); - global $adb; - $query="select * from vtiger_groups"; - $result = $adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - $group_details=Array(); - for($i=0;$i<$num_rows;$i++) - { - $grpInfo=Array(); - $grpid=$adb->query_result($result,$i,'groupid'); - $grpname=$adb->query_result($result,$i,'groupname'); - $description=$adb->query_result($result,$i,'description'); - $grpInfo[0]=$grpname; - $grpInfo[1]=$description; - $group_details[$grpid]=$grpInfo; - - } - $log->debug("Exiting getAllGroupInfo method ..."); - return $group_details; - -} - -/** Function to create a group - * @param $groupName -- Group Name :: Type varchar - * @param $groupMemberArray -- Group Members (Groups,Roles,RolesAndsubordinates,Users) - * @param $groupName -- Group Name :: Type varchar - * @returns $groupId -- Group Id :: Type integer - */ -function createGroup($groupName,$groupMemberArray,$description) -{ - global $log; - $log->debug("Entering createGroup(".$groupName.",".$groupMemberArray.",".$description.") method ..."); - global $adb; - $groupId=$adb->getUniqueId("vtiger_users"); - //Insert into group vtiger_table - $query = "insert into vtiger_groups values(?,?,?)"; - $adb->pquery($query, array($groupId, $groupName, $description)); - - //Insert Group to Group Relation - $groupArray=$groupMemberArray['groups']; - $roleArray=$groupMemberArray['roles']; - $rsArray=$groupMemberArray['rs']; - $userArray=$groupMemberArray['users']; - - foreach($groupArray as $group_id) - { - insertGroupToGroupRelation($groupId,$group_id); - } - - //Insert Group to Role Relation - foreach($roleArray as $roleId) - { - insertGroupToRoleRelation($groupId,$roleId); - } - - //Insert Group to RoleAndSubordinate Relation - foreach($rsArray as $rsId) - { - insertGroupToRsRelation($groupId,$rsId); - } - - //Insert Group to Role Relation - foreach($userArray as $userId) - { - insertGroupToUserRelation($groupId,$userId); - } - $log->debug("Exiting createGroup method ..."); - return $groupId; -} - - -/** Function to insert group to group relation - * @param $groupId -- Group Id :: Type integer - * @param $containsGroupId -- Group Id :: Type integer - */ -function insertGroupToGroupRelation($groupId,$containsGroupId) -{ - global $log; - $log->debug("Entering insertGroupToGroupRelation(".$groupId.",".$containsGroupId.") method ..."); - global $adb; - $query="insert into vtiger_group2grouprel values(?,?)"; - $adb->pquery($query, array($groupId, $containsGroupId)); - $log->debug("Exiting insertGroupToGroupRelation method ..."); -} - - -/** Function to insert group to vtiger_role relation - * @param $groupId -- Group Id :: Type integer - * @param $roleId -- Role Id :: Type varchar - */ -function insertGroupToRoleRelation($groupId,$roleId) -{ - global $log; - $log->debug("Entering insertGroupToRoleRelation(".$groupId.",".$roleId.") method ..."); - global $adb; - $query="insert into vtiger_group2role values(?,?)"; - $adb->pquery($query, array($groupId, $roleId)); - $log->debug("Exiting insertGroupToRoleRelation method ..."); -} - - -/** Function to insert group to vtiger_role&subordinate relation - * @param $groupId -- Group Id :: Type integer - * @param $rsId -- Role Sub Id :: Type varchar - */ -function insertGroupToRsRelation($groupId,$rsId) -{ - global $log; - $log->debug("Entering insertGroupToRsRelation(".$groupId.",".$rsId.") method ..."); - global $adb; - $query="insert into vtiger_group2rs values(?,?)"; - $adb->pquery($query, array($groupId, $rsId)); - $log->debug("Exiting insertGroupToRsRelation method ..."); -} - -/** Function to insert group to user relation - * @param $groupId -- Group Id :: Type integer - * @param $userId -- User Id :: Type varchar - */ -function insertGroupToUserRelation($groupId,$userId) -{ - global $log; - $log->debug("Entering insertGroupToUserRelation(".$groupId.",".$userId.") method ..."); - global $adb; - $query="insert into vtiger_users2group values(?,?)"; - $adb->pquery($query, array($groupId, $userId)); - $log->debug("Exiting insertGroupToUserRelation method ..."); -} - - -/** Function to get the group Information of the specified group - * @param $groupId -- Group Id :: Type integer - * @returns Group Detail Array in the following format: - * $groupDetailArray=Array($groupName,$description,$groupMembers); - */ -function getGroupInfo($groupId) -{ - global $log; - $log->debug("Entering getGroupInfo(".$groupId.") method ..."); - global $adb; - $groupDetailArr=Array(); - $groupMemberArr=Array(); - //Retreving the group Info - $query="select * from vtiger_groups where groupid=?"; - $result = $adb->pquery($query, array($groupId)); - $groupName=$adb->query_result($result,0,'groupname'); - $description=$adb->query_result($result,0,'description'); - - //Retreving the Group RelatedMembers - $groupMemberArr=getGroupMembers($groupId); - $groupDetailArr[]=$groupName; - $groupDetailArr[]=$description; - $groupDetailArr[]=$groupMemberArr; - - //Returning the Group Detail Array - $log->debug("Exiting getGroupInfo method ..."); - return $groupDetailArr; - - -} - -/** Function to fetch the group name of the specified group - * @param $groupId -- Group Id :: Type integer - * @returns Group Name :: Type varchar - */ -function fetchGroupName($groupId) -{ - global $log; - $log->debug("Entering fetchGroupName(".$groupId.") method ..."); - - global $adb; - //Retreving the group Info - $query="select * from vtiger_groups where groupid=?"; - $result = $adb->pquery($query, array($groupId)); - $groupName=decode_html($adb->query_result($result,0,'groupname')); - $log->debug("Exiting fetchGroupName method ..."); - return $groupName; - -} - -/** Function to fetch the group members of the specified group - * @param $groupId -- Group Id :: Type integer - * @returns Group Member Array in the follwing format: - * $groupMemberArray=Array([groups]=>Array(groupid1,groupid2,groupid3,.....,groupidn), - * [roles]=>Array(roleid1,roleid2,roleid3,.....,roleidn), - * [rs]=>Array(roleid1,roleid2,roleid3,.....,roleidn), - * [users]=>Array(useridd1,userid2,userid3,.....,groupidn)) - */ -function getGroupMembers($groupId) -{ - global $log; - $log->debug("Entering getGroupMembers(".$groupId.") method ..."); - $groupMemberArr=Array(); - $roleGroupArr=getGroupRelatedRoles($groupId); - $rsGroupArr=getGroupRelatedRoleSubordinates($groupId); - $groupGroupArr=getGroupRelatedGroups($groupId); - $userGroupArr=getGroupRelatedUsers($groupId); - - $groupMemberArr['groups']=$groupGroupArr; - $groupMemberArr['roles']=$roleGroupArr; - $groupMemberArr['rs']=$rsGroupArr; - $groupMemberArr['users']=$userGroupArr; - - $log->debug("Exiting getGroupMembers method ..."); - return($groupMemberArr); -} - -/** Function to get the group related vtiger_roles of the specified group - * @param $groupId -- Group Id :: Type integer - * @returns Group Related Role Array in the follwing format: - * $groupRoles=Array(roleid1,roleid2,roleid3,.....,roleidn); - */ -function getGroupRelatedRoles($groupId) -{ - global $log; - $log->debug("Entering getGroupRelatedRoles(".$groupId.") method ..."); - global $adb; - $roleGroupArr=Array(); - $query="select * from vtiger_group2role where groupid=?"; - $result = $adb->pquery($query, array($groupId)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $roleId=$adb->query_result($result,$i,'roleid'); - $roleGroupArr[]=$roleId; - } - $log->debug("Exiting getGroupRelatedRoles method ..."); - return $roleGroupArr; - -} - - -/** Function to get the group related vtiger_roles and subordinates of the specified group - * @param $groupId -- Group Id :: Type integer - * @returns Group Related Roles & Subordinate Array in the follwing format: - * $groupRoleSubordinates=Array(roleid1,roleid2,roleid3,.....,roleidn); - */ -function getGroupRelatedRoleSubordinates($groupId) -{ - global $log; - $log->debug("Entering getGroupRelatedRoleSubordinates(".$groupId.") method ..."); - global $adb; - $rsGroupArr=Array(); - $query="select * from vtiger_group2rs where groupid=?"; - $result = $adb->pquery($query, array($groupId)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $roleSubId=$adb->query_result($result,$i,'roleandsubid'); - $rsGroupArr[]=$roleSubId; - } - $log->debug("Exiting getGroupRelatedRoleSubordinates method ..."); - return $rsGroupArr; -} - - -/** Function to get the group related vtiger_groups - * @param $groupId -- Group Id :: Type integer - * @returns Group Related Groups Array in the follwing format: - * $groupGroups=Array(grpid1,grpid2,grpid3,.....,grpidn); - */ -function getGroupRelatedGroups($groupId) -{ - global $log; - $log->debug("Entering getGroupRelatedGroups(".$groupId.") method ..."); - global $adb; - $groupGroupArr=Array(); - $query="select * from vtiger_group2grouprel where groupid=?"; - $result = $adb->pquery($query, array($groupId)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $relGroupId=$adb->query_result($result,$i,'containsgroupid'); - $groupGroupArr[]=$relGroupId; - } - $log->debug("Exiting getGroupRelatedGroups method ..."); - return $groupGroupArr; - -} - -/** Function to get the group related vtiger_users - * @param $userId -- User Id :: Type integer - * @returns Group Related Users Array in the follwing format: - * $groupUsers=Array(userid1,userid2,userid3,.....,useridn); - */ -function getGroupRelatedUsers($groupId) -{ - global $log; - $log->debug("Entering getGroupRelatedUsers(".$groupId.") method ..."); - global $adb; - $userGroupArr=Array(); - $query="select * from vtiger_users2group where groupid=?"; - $result = $adb->pquery($query, array($groupId)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $userId=$adb->query_result($result,$i,'userid'); - $userGroupArr[]=$userId; - } - $log->debug("Exiting getGroupRelatedUsers method ..."); - return $userGroupArr; - -} - -/** Function to update the group - * @param $groupId -- Group Id :: Type integer - * @param $groupName -- Group Name :: Type varchar - * @param $groupMemberArray -- Group Members Array :: Type array - * @param $description -- Description :: Type text - */ -function updateGroup($groupId,$groupName,$groupMemberArray,$description) -{ - global $log; - $log->debug("Entering updateGroup(".$groupId.",".$groupName.",".$groupMemberArray.",".$description.") method ..."); - global $adb; - $query="update vtiger_groups set groupname=?, description=? where groupid=?"; - $adb->pquery($query, array($groupName, $description, $groupId)); - - //Deleting the Group Member Relation - deleteGroupRelatedGroups($groupId); - deleteGroupRelatedRoles($groupId); - deleteGroupRelatedRolesAndSubordinates($groupId); - deleteGroupRelatedUsers($groupId); - - //Inserting the Group Member Entries - $groupArray=$groupMemberArray['groups']; - $roleArray=$groupMemberArray['roles']; - $rsArray=$groupMemberArray['rs']; - $userArray=$groupMemberArray['users']; - - foreach($groupArray as $group_id) - { - insertGroupToGroupRelation($groupId,$group_id); - } - - //Insert Group to Role Relation - foreach($roleArray as $roleId) - { - insertGroupToRoleRelation($groupId,$roleId); - } - - //Insert Group to RoleAndSubordinate Relation - foreach($rsArray as $rsId) - { - insertGroupToRsRelation($groupId,$rsId); - } - - //Insert Group to Role Relation - foreach($userArray as $userId) - { - insertGroupToUserRelation($groupId,$userId); - } - $log->debug("Exiting updateGroup method ..."); - -} - -/** Function to delete the specified group - * @param $groupId -- Group Id :: Type integer - * @param $transferId -- Id of the group/user to which record ownership is to be transferred:: Type integer - * @param $transferType -- It can have only two values namely 'Groups' or 'Users'. This determines whether the owneship is to be transferred to a group or user :: Type varchar - */ -function deleteGroup($groupId,$transferId) -{ - global $log; - $log->debug("Entering deleteGroup(".$groupId.") method ..."); - global $adb; - - tranferGroupOwnership($groupId,$transferId); - deleteGroupRelatedSharingRules($groupId); - - $query="delete from vtiger_groups where groupid=?"; - $adb->pquery($query, array($groupId)); - - deleteGroupRelatedGroups($groupId); - deleteGroupRelatedRoles($groupId); - deleteGroupReportRelations($groupId); - deleteGroupRelatedRolesAndSubordinates($groupId); - deleteGroupRelatedUsers($groupId); - $log->debug("Exiting deleteGroup method ..."); -} - - -/** Function to transfer the ownership of records owned by a particular group to the specified group - * @param $groupId -- Group Id of the group which's record ownership has to be transferred:: Type integer - * @param $transferId -- Id of the group/user to which record ownership is to be transferred:: Type integer - * @param $transferType -- It can have only two values namely 'Groups' or 'Users'. This determines whether the owneship is to be transferred to a group or user :: Type varchar - */ -function tranferGroupOwnership($groupId,$transferId) -{ - global $log; - $log->debug("Entering tranferGroupOwnership(".$groupId.") method ..."); - global $adb; - - $query = "update vtiger_crmentity set smownerid=? where smownerid=?"; - $params = array($transferId, $groupId); - $adb->pquery($query, $params); - - $log->debug("Exiting tranferGroupOwnership method ..."); -} - -/** Function to delete group to group relation of the specified group - * @param $groupId -- Group Id :: Type integer - */ -function deleteGroupRelatedGroups($groupId) -{ - global $log; - $log->debug("Entering deleteGroupRelatedGroups(".$groupId.") method ..."); - global $adb; - $query="delete from vtiger_group2grouprel where groupid=?"; - $adb->pquery($query, array($groupId)); - $log->debug("Exiting deleteGroupRelatedGroups method ..."); -} - - -/** Function to delete group to vtiger_role relation of the specified group - * @param $groupId -- Group Id :: Type integer - */ -function deleteGroupRelatedRoles($groupId) -{ - global $log; - $log->debug("Entering deleteGroupRelatedRoles(".$groupId.") method ..."); - global $adb; - $query="delete from vtiger_group2role where groupid=?"; - $adb->pquery($query, array($groupId)); - $log->debug("Exiting deleteGroupRelatedRoles method ..."); -} - - -/** Function to delete group to vtiger_role and subordinates relation of the specified group - * @param $groupId -- Group Id :: Type integer - */ -function deleteGroupRelatedRolesAndSubordinates($groupId) -{ - global $log; - $log->debug("Entering deleteGroupRelatedRolesAndSubordinates(".$groupId.") method ..."); - global $adb; - $query="delete from vtiger_group2rs where groupid=?"; - $adb->pquery($query, array($groupId)); - $log->debug("Exiting deleteGroupRelatedRolesAndSubordinates method ..."); -} - - -/** Function to delete group to user relation of the specified group - * @param $groupId -- Group Id :: Type integer - */ -function deleteGroupRelatedUsers($groupId) -{ - global $log; - $log->debug("Entering deleteGroupRelatedUsers(".$groupId.") method ..."); - global $adb; - $query="delete from vtiger_users2group where groupid=?"; - $adb->pquery($query, array($groupId)); - $log->debug("Exiting deleteGroupRelatedUsers method ..."); -} - -/** This function returns the Default Organisation Sharing Action Name - * @param $share_action_id -- It takes the Default Organisation Sharing ActionId as input :: Type Integer - * @returns The sharing Action Name :: Type Varchar - */ -function getDefOrgShareActionName($share_action_id) -{ - global $log; - $log->debug("Entering getDefOrgShareActionName(".$share_action_id.") method ..."); - global $adb; - $query="select * from vtiger_org_share_action_mapping where share_action_id=?"; - $result=$adb->pquery($query, array($share_action_id)); - $share_action_name=$adb->query_result($result,0,"share_action_name"); - $log->debug("Exiting getDefOrgShareActionName method ..."); - return $share_action_name; - - -} -/** This function returns the Default Organisation Sharing Action Array for the specified Module - * It takes the module tabid as input and constructs the array. - * The output array consists of the 'Default Organisation Sharing Id'=>'Default Organisation Sharing Action' mapping for all the sharing actions available for the specifed module - * The output Array will be in the following format: - * Array = (Default Org ActionId1=>Default Org ActionName1, - * Default Org ActionId2=>Default Org ActionName2, - * | - * | - * Default Org ActionIdn=>Default Org ActionNamen) - */ -function getModuleSharingActionArray($tabid) -{ - global $log; - $log->debug("Entering getModuleSharingActionArray(".$tabid.") method ..."); - global $adb; - $share_action_arr=Array(); - $query = "select vtiger_org_share_action_mapping.share_action_name,vtiger_org_share_action2tab.share_action_id from vtiger_org_share_action2tab inner join vtiger_org_share_action_mapping on vtiger_org_share_action2tab.share_action_id=vtiger_org_share_action_mapping.share_action_id where vtiger_org_share_action2tab.tabid=?"; - $result=$adb->pquery($query, array($tabid)); - $num_rows=$adb->num_rows($result); - for($i=0; $i<$num_rows; $i++) - { - $share_action_name=$adb->query_result($result,$i,"share_action_name"); - $share_action_id=$adb->query_result($result,$i,"share_action_id"); - $share_action_arr[$share_action_id] = $share_action_name; - } - $log->debug("Exiting getModuleSharingActionArray method ..."); - return $share_action_arr; - -} - -/** This function adds a organisation level sharing rule for the specified Module - * It takes the following input parameters: - * $tabid -- Module tabid - Datatype::Integer - * $shareEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String - * $toEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String - * $shareEntityId -- The id of the group,role,rs,user to be shared - * $toEntityId -- The id of the group,role,rs,user to which the specified entity is to be shared - * $sharePermisson -- This can have the following values: - * 0 - Read Only - * 1 - Read/Write - * This function will return the shareid as output - */ -function addSharingRule($tabid,$shareEntityType,$toEntityType,$shareEntityId,$toEntityId,$sharePermission) -{ - global $log; - $log->debug("Entering addSharingRule(".$tabid.",".$shareEntityType.",".$toEntityType.",".$shareEntityId.",".$toEntityId.",".$sharePermission.") method ..."); - - global $adb; - $shareid=$adb->getUniqueId("vtiger_datashare_module_rel"); - - - if($shareEntityType == 'groups' && $toEntityType == 'groups') - { - $type_string='GRP::GRP'; - $query = "insert into vtiger_datashare_grp2grp values(?,?,?,?)"; - } - elseif($shareEntityType == 'groups' && $toEntityType == 'roles') - { - - $type_string='GRP::ROLE'; - $query = "insert into vtiger_datashare_grp2role values(?,?,?,?)"; - } - elseif($shareEntityType == 'groups' && $toEntityType == 'rs') - { - - $type_string='GRP::RS'; - $query = "insert into vtiger_datashare_grp2rs values(?,?,?,?)"; - } - elseif($shareEntityType == 'roles' && $toEntityType == 'groups') - { - - $type_string='ROLE::GRP'; - $query = "insert into vtiger_datashare_role2group values(?,?,?,?)"; - } - elseif($shareEntityType == 'roles' && $toEntityType == 'roles') - { - - $type_string='ROLE::ROLE'; - $query = "insert into vtiger_datashare_role2role values(?,?,?,?)"; - } - elseif($shareEntityType == 'roles' && $toEntityType == 'rs') - { - - $type_string='ROLE::RS'; - $query = "insert into vtiger_datashare_role2rs values(?,?,?,?)"; - } - elseif($shareEntityType == 'rs' && $toEntityType == 'groups') - { - - $type_string='RS::GRP'; - $query = "insert into vtiger_datashare_rs2grp values(?,?,?,?)"; - } - elseif($shareEntityType == 'rs' && $toEntityType == 'roles') - { - - $type_string='RS::ROLE'; - $query = "insert into vtiger_datashare_rs2role values(?,?,?,?)"; - } - elseif($shareEntityType == 'rs' && $toEntityType == 'rs') - { - - $type_string='RS::RS'; - $query = "insert into vtiger_datashare_rs2rs values(?,?,?,?)"; - } - $query1 = "insert into vtiger_datashare_module_rel values(?,?,?)"; - $adb->pquery($query1, array($shareid, $tabid, $type_string)); - - $params = array($shareid, $shareEntityId, $toEntityId, $sharePermission); - $adb->pquery($query, $params); - $log->debug("Exiting addSharingRule method ..."); - return $shareid; - -} - - -/** This function is to update the organisation level sharing rule - * It takes the following input parameters: - * $shareid -- Id of the Sharing Rule to be updated - * $tabid -- Module tabid - Datatype::Integer - * $shareEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String - * $toEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String - * $shareEntityId -- The id of the group,role,rs,user to be shared - * $toEntityId -- The id of the group,role,rs,user to which the specified entity is to be shared - * $sharePermisson -- This can have the following values: - * 0 - Read Only - * 1 - Read/Write - * This function will return the shareid as output - */ -function updateSharingRule($shareid,$tabid,$shareEntityType,$toEntityType,$shareEntityId,$toEntityId,$sharePermission) -{ - global $log; - $log->debug("Entering updateSharingRule(".$shareid.",".$tabid.",".$shareEntityType.",".$toEntityType.",".$shareEntityId.",".$toEntityId.",".$sharePermission.") method ..."); - - global $adb; - $query2="select * from vtiger_datashare_module_rel where shareid=?"; - $res=$adb->pquery($query2, array($shareid)); - $typestr=$adb->query_result($res,0,'relationtype'); - $tabname=getDSTableNameForType($typestr); - $query3="delete from ".$tabname." where shareid=?"; - $adb->pquery($query3, array($shareid)); - - - if($shareEntityType == 'groups' && $toEntityType == 'groups') - { - $type_string='GRP::GRP'; - $query = "insert into vtiger_datashare_grp2grp values(?,?,?,?)"; - } - elseif($shareEntityType == 'groups' && $toEntityType == 'roles') - { - - $type_string='GRP::ROLE'; - $query = "insert into vtiger_datashare_grp2role values(?,?,?,?)"; - } - elseif($shareEntityType == 'groups' && $toEntityType == 'rs') - { - - $type_string='GRP::RS'; - $query = "insert into vtiger_datashare_grp2rs values(?,?,?,?)"; - } - elseif($shareEntityType == 'roles' && $toEntityType == 'groups') - { - - $type_string='ROLE::GRP'; - $query = "insert into vtiger_datashare_role2group values(?,?,?,?)"; - } - elseif($shareEntityType == 'roles' && $toEntityType == 'roles') - { - - $type_string='ROLE::ROLE'; - $query = "insert into vtiger_datashare_role2role values(?,?,?,?)"; - } - elseif($shareEntityType == 'roles' && $toEntityType == 'rs') - { - - $type_string='ROLE::RS'; - $query = "insert into vtiger_datashare_role2rs values(?,?,?,?)"; - } - elseif($shareEntityType == 'rs' && $toEntityType == 'groups') - { - - $type_string='RS::GRP'; - $query = "insert into vtiger_datashare_rs2grp values(?,?,?,?)"; - } - elseif($shareEntityType == 'rs' && $toEntityType == 'roles') - { - - $type_string='RS::ROLE'; - $query = "insert into vtiger_datashare_rs2role values(?,?,?,?)"; - } - elseif($shareEntityType == 'rs' && $toEntityType == 'rs') - { - - $type_string='RS::RS'; - $query = "insert into vtiger_datashare_rs2rs values(?,?,?,?)"; - } - - $query1 = "update vtiger_datashare_module_rel set relationtype=? where shareid=?"; - $adb->pquery($query1, array($type_string, $shareid)); - - $params = array($shareid, $shareEntityId, $toEntityId, $sharePermission); - $adb->pquery($query, $params); - $log->debug("Exiting updateSharingRule method ..."); - return $shareid; - -} - - -/** This function is to delete the organisation level sharing rule - * It takes the following input parameters: - * $shareid -- Id of the Sharing Rule to be updated - */ -function deleteSharingRule($shareid) -{ - global $log; - $log->debug("Entering deleteSharingRule(".$shareid.") method ..."); - global $adb; - $query2="select * from vtiger_datashare_module_rel where shareid=?"; - $res=$adb->pquery($query2, array($shareid)); - $typestr=$adb->query_result($res,0,'relationtype'); - $tabname=getDSTableNameForType($typestr); - $query3="delete from $tabname where shareid=?"; - $adb->pquery($query3, array($shareid)); - $query4="delete from vtiger_datashare_module_rel where shareid=?"; - $adb->pquery($query4, array($shareid)); - - //deleting the releated module sharing permission - $query5="delete from vtiger_datashare_relatedmodule_permission where shareid=?"; - $adb->pquery($query5, array($shareid)); - $log->debug("Exiting deleteSharingRule method ..."); - -} - -/** Function get the Data Share Table and their columns - * @returns -- Data Share Table and Column Array in the following format: - * $dataShareTableColArr=Array('datashare_grp2grp'=>'share_groupid::to_groupid', - * 'datashare_grp2role'=>'share_groupid::to_roleid', - * 'datashare_grp2rs'=>'share_groupid::to_roleandsubid', - * 'datashare_role2group'=>'share_roleid::to_groupid', - * 'datashare_role2role'=>'share_roleid::to_roleid', - * 'datashare_role2rs'=>'share_roleid::to_roleandsubid', - * 'datashare_rs2grp'=>'share_roleandsubid::to_groupid', - * 'datashare_rs2role'=>'share_roleandsubid::to_roleid', - * 'datashare_rs2rs'=>'share_roleandsubid::to_roleandsubid'); - */ -function getDataShareTableandColumnArray() -{ - global $log; - $log->debug("Entering getDataShareTableandColumnArray() method ..."); - $dataShareTableColArr=Array('vtiger_datashare_grp2grp'=>'share_groupid::to_groupid', - 'vtiger_datashare_grp2role'=>'share_groupid::to_roleid', - 'vtiger_datashare_grp2rs'=>'share_groupid::to_roleandsubid', - 'vtiger_datashare_role2group'=>'share_roleid::to_groupid', - 'vtiger_datashare_role2role'=>'share_roleid::to_roleid', - 'vtiger_datashare_role2rs'=>'share_roleid::to_roleandsubid', - 'vtiger_datashare_rs2grp'=>'share_roleandsubid::to_groupid', - 'vtiger_datashare_rs2role'=>'share_roleandsubid::to_roleid', - 'vtiger_datashare_rs2rs'=>'share_roleandsubid::to_roleandsubid'); - $log->debug("Exiting getDataShareTableandColumnArray method ..."); - return $dataShareTableColArr; - -} - - - -/** Function get the Data Share Column Names for the specified Table Name - * @param $tableName -- DataShare Table Name :: Type Varchar - * @returns Column Name -- Type Varchar - * - */ -function getDSTableColumns($tableName) -{ - global $log; - $log->debug("Entering getDSTableColumns(".$tableName.") method ..."); - $dataShareTableColArr=getDataShareTableandColumnArray(); - - $dsTableCols=$dataShareTableColArr[$tableName]; - $dsTableColsArr=explode('::',$dsTableCols); - $log->debug("Exiting getDSTableColumns method ..."); - return $dsTableColsArr; - -} - - -/** Function get the Data Share Table Names - * @returns the following Date Share Table Name Array: - * $dataShareTableColArr=Array('GRP::GRP'=>'datashare_grp2grp', - * 'GRP::ROLE'=>'datashare_grp2role', - * 'GRP::RS'=>'datashare_grp2rs', - * 'ROLE::GRP'=>'datashare_role2group', - * 'ROLE::ROLE'=>'datashare_role2role', - * 'ROLE::RS'=>'datashare_role2rs', - * 'RS::GRP'=>'datashare_rs2grp', - * 'RS::ROLE'=>'datashare_rs2role', - * 'RS::RS'=>'datashare_rs2rs'); - */ -function getDataShareTableName() -{ - global $log; - $log->debug("Entering getDataShareTableName() method ..."); - $dataShareTableColArr=Array('GRP::GRP'=>'vtiger_datashare_grp2grp', - 'GRP::ROLE'=>'vtiger_datashare_grp2role', - 'GRP::RS'=>'vtiger_datashare_grp2rs', - 'ROLE::GRP'=>'vtiger_datashare_role2group', - 'ROLE::ROLE'=>'vtiger_datashare_role2role', - 'ROLE::RS'=>'vtiger_datashare_role2rs', - 'RS::GRP'=>'vtiger_datashare_rs2grp', - 'RS::ROLE'=>'vtiger_datashare_rs2role', - 'RS::RS'=>'vtiger_datashare_rs2rs'); - $log->debug("Exiting getDataShareTableName method ..."); - return $dataShareTableColArr; - -} - -/** Function to get the Data Share Table Name from the speciified type string - * @param $typeString -- Datashare Type Sting :: Type Varchar - * @returns Table Name -- Type Varchar - * - */ -function getDSTableNameForType($typeString) -{ - global $log; - $log->debug("Entering getDSTableNameForType(".$typeString.") method ..."); - $dataShareTableColArr=getDataShareTableName(); - $tableName=$dataShareTableColArr[$typeString]; - $log->debug("Exiting getDSTableNameForType method ..."); - return $tableName; - -} - -/** Function to get the Entity type from the specified DataShare Table Column Name - * @param $colname -- Datashare Table Column Name :: Type Varchar - * @returns The entity type. The entity type may be vtiger_groups or vtiger_roles or rs -- Type Varchar - */ -function getEntityTypeFromCol($colName) -{ - global $log; - $log->debug("Entering getEntityTypeFromCol(".$colName.") method ..."); - - if($colName == 'share_groupid' || $colName == 'to_groupid') - { - $entity_type='groups'; - } - elseif($colName =='share_roleid' || $colName =='to_roleid') - { - $entity_type='roles'; - } - elseif($colName == 'share_roleandsubid' || $colName == 'to_roleandsubid') - { - $entity_type='rs'; - } - - $log->debug("Exiting getEntityTypeFromCol method ..."); - return $entity_type; - -} - -/** Function to get the Entity Display Link - * @param $entityid -- Entity Id - * @params $entityType -- The entity type may be vtiger_groups or vtiger_roles or rs -- Type Varchar - * @returns the Entity Display link - */ -function getEntityDisplayLink($entityType,$entityid) -{ - global $log; - $log->debug("Entering getEntityDisplayLink(".$entityType.",".$entityid.") method ..."); - if($entityType == 'groups') - { - $groupNameArr = getGroupInfo($entityid); - $display_out = "Group::". $groupNameArr[0]." "; - } - elseif($entityType == 'roles') - { - $roleName=getRoleName($entityid); - $display_out = "Role::".$roleName. ""; - } - elseif($entityType == 'rs') - { - $roleName=getRoleName($entityid); - $display_out = "RoleAndSubordinate::".$roleName. ""; - } - $log->debug("Exiting getEntityDisplayLink method ..."); - return $display_out; - -} - - -/** Function to get the Sharing rule Info - * @param $shareId -- Sharing Rule Id - * @returns Sharing Rule Information Array in the following format: - * $shareRuleInfoArr=Array($shareId, $tabid, $type, $share_ent_type, $to_ent_type, $share_entity_id, $to_entity_id,$permission); - */ -function getSharingRuleInfo($shareId) -{ - global $log; - $log->debug("Entering getSharingRuleInfo(".$shareId.") method ..."); - global $adb; - $shareRuleInfoArr=Array(); - $query="select * from vtiger_datashare_module_rel where shareid=?"; - $result=$adb->pquery($query, array($shareId)); - //Retreving the Sharing Tabid - $tabid=$adb->query_result($result,0,'tabid'); - $type=$adb->query_result($result,0,'relationtype'); - - //Retreiving the Sharing Table Name - $tableName=getDSTableNameForType($type); - - //Retreiving the Sharing Col Names - $dsTableColArr=getDSTableColumns($tableName); - $share_ent_col=$dsTableColArr[0]; - $to_ent_col=$dsTableColArr[1]; - - //Retreiving the Sharing Entity Col Types - $share_ent_type=getEntityTypeFromCol($share_ent_col); - $to_ent_type=getEntityTypeFromCol($to_ent_col); - - //Retreiving the Value from Table - $query1="select * from $tableName where shareid=?"; - $result1=$adb->pquery($query1, array($shareId)); - $share_id=$adb->query_result($result1,0,$share_ent_col); - $to_id=$adb->query_result($result1,0,$to_ent_col); - $permission=$adb->query_result($result1,0,'permission'); - - //Constructing the Array - $shareRuleInfoArr[]=$shareId; - $shareRuleInfoArr[]=$tabid; - $shareRuleInfoArr[]=$type; - $shareRuleInfoArr[]=$share_ent_type; - $shareRuleInfoArr[]=$to_ent_type; - $shareRuleInfoArr[]=$share_id; - $shareRuleInfoArr[]=$to_id; - $shareRuleInfoArr[]=$permission; - - $log->debug("Exiting getSharingRuleInfo method ..."); - return $shareRuleInfoArr; - - - -} - -/** This function is to retreive the list of related sharing modules for the specifed module - * It takes the following input parameters: - * $tabid -- The module tabid:: Type Integer - */ - -function getRelatedSharingModules($tabid) -{ - global $log; - $log->debug("Entering getRelatedSharingModules(".$tabid.") method ..."); - global $adb; - $relatedSharingModuleArray=Array(); - $query="select * from vtiger_datashare_relatedmodules where tabid=?"; - $result=$adb->pquery($query, array($tabid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $ds_relmod_id=$adb->query_result($result,$i,'datashare_relatedmodule_id'); - $rel_tabid=$adb->query_result($result,$i,'relatedto_tabid'); - $relatedSharingModuleArray[$rel_tabid]=$ds_relmod_id; - - } - $log->debug("Exiting getRelatedSharingModules method ..."); - return $relatedSharingModuleArray; - -} - - -/** This function is to add the related module sharing permission for a particulare Sharing Rule - * It takes the following input parameters: - * $shareid -- The Sharing Rule Id:: Type Integer - * $tabid -- The module tabid:: Type Integer - * $relatedtabid -- The related module tabid:: Type Integer - * $sharePermisson -- This can have the following values: - * 0 - Read Only - * 1 - Read/Write - */ - -function addRelatedModuleSharingPermission($shareid,$tabid,$relatedtabid,$sharePermission) -{ - global $log; - $log->debug("Entering addRelatedModuleSharingPermission(".$shareid.",".$tabid.",".$relatedtabid.",".$sharePermission.") method ..."); - global $adb; - $relatedModuleSharingId=getRelatedModuleSharingId($tabid,$relatedtabid); - $query="insert into vtiger_datashare_relatedmodule_permission values(?,?,?)" ; - $result=$adb->pquery($query, array($shareid, $relatedModuleSharingId, $sharePermission)); - $log->debug("Exiting addRelatedModuleSharingPermission method ..."); -} - -/** This function is to update the related module sharing permission for a particulare Sharing Rule - * It takes the following input parameters: - * $shareid -- The Sharing Rule Id:: Type Integer - * $tabid -- The module tabid:: Type Integer - * $relatedtabid -- The related module tabid:: Type Integer - * $sharePermisson -- This can have the following values: - * 0 - Read Only - * 1 - Read/Write - */ - -function updateRelatedModuleSharingPermission($shareid,$tabid,$relatedtabid,$sharePermission) -{ - global $log; - $log->debug("Entering updateRelatedModuleSharingPermission(".$shareid.",".$tabid.",".$relatedtabid.",".$sharePermission.") method ..."); - global $adb; - $relatedModuleSharingId=getRelatedModuleSharingId($tabid,$relatedtabid); - $query="update vtiger_datashare_relatedmodule_permission set permission=? where shareid=? and datashare_relatedmodule_id=?"; - $result=$adb->pquery($query, array($sharePermission, $shareid, $relatedModuleSharingId)); - $log->debug("Exiting updateRelatedModuleSharingPermission method ..."); -} - -/** This function is to retreive the Related Module Sharing Id - * It takes the following input parameters: - * $tabid -- The module tabid:: Type Integer - * $related_tabid -- The related module tabid:: Type Integer - * This function returns the Related Module Sharing Id - */ - -function getRelatedModuleSharingId($tabid,$related_tabid) -{ - global $log; - $log->debug("Entering getRelatedModuleSharingId(".$tabid.",".$related_tabid.") method ..."); - global $adb; - $query="select datashare_relatedmodule_id from vtiger_datashare_relatedmodules where tabid=? and relatedto_tabid=?"; - $result=$adb->pquery($query, array($tabid, $related_tabid)); - $relatedModuleSharingId=$adb->query_result($result,0,'datashare_relatedmodule_id'); - $log->debug("Exiting getRelatedModuleSharingId method ..."); - return $relatedModuleSharingId; - -} - -/** This function is to retreive the Related Module Sharing Permissions for the specified Sharing Rule - * It takes the following input parameters: - * $shareid -- The Sharing Rule Id:: Type Integer - *This function will return the Related Module Sharing permissions in an Array in the following format: - * $PermissionArray=($relatedTabid1=>$sharingPermission1, - * $relatedTabid2=>$sharingPermission2, - * | - * | - * $relatedTabid-n=>$sharingPermission-n) - */ -function getRelatedModuleSharingPermission($shareid) -{ - global $log; - $log->debug("Entering getRelatedModuleSharingPermission(".$shareid.") method ..."); - global $adb; - $relatedSharingModulePermissionArray=Array(); - $query="select vtiger_datashare_relatedmodules.*,vtiger_datashare_relatedmodule_permission.permission from vtiger_datashare_relatedmodules inner join vtiger_datashare_relatedmodule_permission on vtiger_datashare_relatedmodule_permission.datashare_relatedmodule_id=vtiger_datashare_relatedmodules.datashare_relatedmodule_id where vtiger_datashare_relatedmodule_permission.shareid=?"; - $result=$adb->pquery($query, array($shareid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $relatedto_tabid=$adb->query_result($result,$i,'relatedto_tabid'); - $permission=$adb->query_result($result,$i,'permission'); - $relatedSharingModulePermissionArray[$relatedto_tabid]=$permission; - - - } - $log->debug("Exiting getRelatedModuleSharingPermission method ..."); - return $relatedSharingModulePermissionArray; - -} - - -/** This function is to retreive the vtiger_profiles associated with the the specified user - * It takes the following input parameters: - * $userid -- The User Id:: Type Integer - *This function will return the vtiger_profiles associated to the specified vtiger_users in an Array in the following format: - * $userProfileArray=(profileid1,profileid2,profileid3,...,profileidn); - */ -function getUserProfile($userId) -{ - global $log; - $log->debug("Entering getUserProfile(".$userId.") method ..."); - global $adb; - $roleId=fetchUserRole($userId); - $profArr=Array(); - $sql1 = "select profileid from vtiger_role2profile where roleid=?"; - $result1 = $adb->pquery($sql1, array($roleId)); - $num_rows=$adb->num_rows($result1); - for($i=0;$i<$num_rows;$i++) - { - - $profileid= $adb->query_result($result1,$i,"profileid"); - $profArr[]=$profileid; - } - $log->debug("Exiting getUserProfile method ..."); - return $profArr; - -} - -/** To retreive the global permission of the specifed user from the various vtiger_profiles associated with the user - * @param $userid -- The User Id:: Type Integer - * @returns user global permission array in the following format: - * $gloabalPerrArray=(view all action id=>permission, - edit all action id=>permission) ); - */ -function getCombinedUserGlobalPermissions($userId) -{ - global $log; - $log->debug("Entering getCombinedUserGlobalPermissions(".$userId.") method ..."); - global $adb; - $profArr=getUserProfile($userId); - $no_of_profiles=sizeof($profArr); - $userGlobalPerrArr=Array(); - - $userGlobalPerrArr=getProfileGlobalPermission($profArr[0]); - if($no_of_profiles != 1) - { - for($i=1;$i<$no_of_profiles;$i++) - { - $tempUserGlobalPerrArr=getProfileGlobalPermission($profArr[$i]); - - foreach($userGlobalPerrArr as $globalActionId=>$globalActionPermission) - { - if($globalActionPermission == 1) - { - $now_permission = $tempUserGlobalPerrArr[$globalActionId]; - if($now_permission == 0) - { - $userGlobalPerrArr[$globalActionId]=$now_permission; - } - - - } - - } - - } - - } - - $log->debug("Exiting getCombinedUserGlobalPermissions method ..."); - return $userGlobalPerrArr; - -} - -/** To retreive the vtiger_tab permissions of the specifed user from the various vtiger_profiles associated with the user - * @param $userid -- The User Id:: Type Integer - * @returns user global permission array in the following format: - * $tabPerrArray=(tabid1=>permission, - * tabid2=>permission) ); - */ -function getCombinedUserTabsPermissions($userId) -{ - global $log; - $log->debug("Entering getCombinedUserTabsPermissions(".$userId.") method ..."); - global $adb; - $profArr=getUserProfile($userId); - $no_of_profiles=sizeof($profArr); - $userTabPerrArr=Array(); - - $userTabPerrArr=getProfileTabsPermission($profArr[0]); - if($no_of_profiles != 1) - { - for($i=1;$i<$no_of_profiles;$i++) - { - $tempUserTabPerrArr=getProfileTabsPermission($profArr[$i]); - - foreach($userTabPerrArr as $tabId=>$tabPermission) - { - if($tabPermission == 1) - { - $now_permission = $tempUserTabPerrArr[$tabId]; - if($now_permission == 0) - { - $userTabPerrArr[$tabId]=$now_permission; - } - - - } - - } - - } - - } - $log->debug("Exiting getCombinedUserTabsPermissions method ..."); - return $userTabPerrArr; - -} - -/** To retreive the vtiger_tab acion permissions of the specifed user from the various vtiger_profiles associated with the user - * @param $userid -- The User Id:: Type Integer - * @returns user global permission array in the following format: - * $actionPerrArray=(tabid1=>permission, - * tabid2=>permission); - */ -function getCombinedUserActionPermissions($userId) -{ - global $log; - $log->debug("Entering getCombinedUserActionPermissions(".$userId.") method ..."); - global $adb; - $profArr=getUserProfile($userId); - $no_of_profiles=sizeof($profArr); - $actionPerrArr=Array(); - - $actionPerrArr=getProfileAllActionPermission($profArr[0]); - if($no_of_profiles != 1) - { - for($i=1;$i<$no_of_profiles;$i++) - { - $tempActionPerrArr=getProfileAllActionPermission($profArr[$i]); - - foreach($actionPerrArr as $tabId=>$perArr) - { - foreach($perArr as $actionid=>$per) - { - if($per == 1) - { - $now_permission = $tempActionPerrArr[$tabId][$actionid]; - if($now_permission == 0) - { - $actionPerrArr[$tabId][$actionid]=$now_permission; - } - - - } - } - - } - - } - - } - $log->debug("Exiting getCombinedUserActionPermissions method ..."); - return $actionPerrArr; - -} - -/** To retreive the parent vtiger_role of the specified vtiger_role - * @param $roleid -- The Role Id:: Type varchar - * @returns parent vtiger_role array in the following format: - * $parentRoleArray=(roleid1,roleid2,.......,roleidn); - */ -function getParentRole($roleId) -{ - global $log; - $log->debug("Entering getParentRole(".$roleId.") method ..."); - $roleInfo=getRoleInformation($roleId); - $parentRole=$roleInfo[$roleId][1]; - $tempParentRoleArr=explode('::',$parentRole); - $parentRoleArr=Array(); - foreach($tempParentRoleArr as $role_id) - { - if($role_id != $roleId) - { - $parentRoleArr[]=$role_id; - } - } - $log->debug("Exiting getParentRole method ..."); - return $parentRoleArr; - -} - -/** To retreive the subordinate vtiger_roles of the specified parent vtiger_role - * @param $roleid -- The Role Id:: Type varchar - * @returns subordinate vtiger_role array in the following format: - * $subordinateRoleArray=(roleid1,roleid2,.......,roleidn); - */ -function getRoleSubordinates($roleId) -{ - global $log; - $log->debug("Entering getRoleSubordinates(".$roleId.") method ..."); - - // Look at cache first for information - $roleSubordinates = VTCacheUtils::lookupRoleSubordinates($roleId); - - if($roleSubordinates === false) { - global $adb; - $roleDetails=getRoleInformation($roleId); - $roleInfo=$roleDetails[$roleId]; - $roleParentSeq=$roleInfo[1]; - - $query="select * from vtiger_role where parentrole like ? order by parentrole asc"; - $result=$adb->pquery($query, array($roleParentSeq."::%")); - $num_rows=$adb->num_rows($result); - $roleSubordinates=Array(); - for($i=0;$i<$num_rows;$i++) - { - $roleid=$adb->query_result($result,$i,'roleid'); - - $roleSubordinates[]=$roleid; - - } - // Update cache for re-use - VTCacheUtils::updateRoleSubordinates($roleId, $roleSubordinates); - } - - $log->debug("Exiting getRoleSubordinates method ..."); - return $roleSubordinates; - -} - -/** To retreive the subordinate vtiger_roles and vtiger_users of the specified parent vtiger_role - * @param $roleid -- The Role Id:: Type varchar - * @returns subordinate vtiger_role array in the following format: - * $subordinateRoleUserArray=(roleid1=>Array(userid1,userid2,userid3), - vtiger_roleid2=>Array(userid1,userid2,userid3) - | - | - vtiger_roleidn=>Array(userid1,userid2,userid3)); - */ -function getSubordinateRoleAndUsers($roleId) -{ - global $log; - $log->debug("Entering getSubordinateRoleAndUsers(".$roleId.") method ..."); - global $adb; - $subRoleAndUsers=Array(); - $subordinateRoles=getRoleSubordinates($roleId); - foreach($subordinateRoles as $subRoleId) - { - $userArray=getRoleUsers($subRoleId); - $subRoleAndUsers[$subRoleId]=$userArray; - - } - $log->debug("Exiting getSubordinateRoleAndUsers method ..."); - return $subRoleAndUsers; - -} - -function getCurrentUserProfileList() -{ - global $log; - $log->debug("Entering getCurrentUserProfileList() method ..."); - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - $profList = array(); - $i=0; - foreach ($current_user_profiles as $profid) - { - array_push($profList, $profid); - $i++; - } - $log->debug("Exiting getCurrentUserProfileList method ..."); - return $profList; - -} - - -function getCurrentUserGroupList() -{ - global $log; - $log->debug("Entering getCurrentUserGroupList() method ..."); - global $current_user; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - $grpList= array(); - if(sizeof($current_user_groups) > 0) - { - $i=0; - foreach ($current_user_groups as $grpid) - { - array_push($grpList, $grpid); - $i++; - } - } - $log->debug("Exiting getCurrentUserGroupList method ..."); - return $grpList; -} - -function getSubordinateUsersList() -{ - global $log; - $log->debug("Entering getSubordinateUsersList() method ..."); - global $current_user; - $user_array=Array(); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - - if(sizeof($subordinate_roles_users) > 0) - { - foreach ($subordinate_roles_users as $roleid => $userArray) - { - foreach($userArray as $userid) - { - if(! in_array($userid,$user_array)) - { - $user_array[]=$userid; - } - } - } - } - $subUserList = constructList($user_array,'INTEGER'); - $log->debug("Exiting getSubordinateUsersList method ..."); - return $subUserList; - -} - -function getReadSharingUsersList($module) -{ - global $log; - $log->debug("Entering getReadSharingUsersList(".$module.") method ..."); - global $adb; - global $current_user; - $user_array=Array(); - $tabid=getTabid($module); - $query = "select shareduserid from vtiger_tmp_read_user_sharing_per where userid=? and tabid=?"; - $result=$adb->pquery($query, array($current_user->id, $tabid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $user_id=$adb->query_result($result,$i,'shareduserid'); - $user_array[]=$user_id; - } - $shareUserList=constructList($user_array,'INTEGER'); - $log->debug("Exiting getReadSharingUsersList method ..."); - return $shareUserList; -} - -function getReadSharingGroupsList($module) -{ - global $log; - $log->debug("Entering getReadSharingGroupsList(".$module.") method ..."); - global $adb; - global $current_user; - $grp_array=Array(); - $tabid=getTabid($module); - $query = "select sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=? and tabid=?"; - $result=$adb->pquery($query, array($current_user->id, $tabid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $grp_id=$adb->query_result($result,$i,'sharedgroupid'); - $grp_array[]=$grp_id; - } - $shareGrpList=constructList($grp_array,'INTEGER'); - $log->debug("Exiting getReadSharingGroupsList method ..."); - return $shareGrpList; -} - -function getWriteSharingGroupsList($module) -{ - global $log; - $log->debug("Entering getWriteSharingGroupsList(".$module.") method ..."); - global $adb; - global $current_user; - $grp_array=Array(); - $tabid=getTabid($module); - $query = "select sharedgroupid from vtiger_tmp_write_group_sharing_per where userid=? and tabid=?"; - $result=$adb->pquery($query, array($current_user->id, $tabid)); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $grp_id=$adb->query_result($result,$i,'sharedgroupid'); - $grp_array[]=$grp_id; - } - $shareGrpList=constructList($grp_array,'INTEGER'); - $log->debug("Exiting getWriteSharingGroupsList method ..."); - return $shareGrpList; -} - -function constructList($array,$data_type) -{ - global $log; - $log->debug("Entering constructList(".$array.",".$data_type.") method ..."); - $list= array(); - if(sizeof($array) > 0) - { - $i=0; - foreach($array as $value) - { - if($data_type == "INTEGER") - { - array_push($list, $value); - } - elseif($data_type == "VARCHAR") - { - array_push($list, "'".$value."'"); - } - $i++; - } - } - $log->debug("Exiting constructList method ..."); - return $list; -} - -function getListViewSecurityParameter($module) -{ - global $log; - $log->debug("Entering getListViewSecurityParameter(".$module.") method ..."); - global $adb; - - $tabid=getTabid($module); - global $current_user; - if($current_user) - { - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - } - if($module == 'Leads') - { - $sec_query .= " and ( - vtiger_crmentity.smownerid in($current_user->id) - or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') - or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") - or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - } - elseif($module == 'Accounts') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) " . - "or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') " . - "or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Contacts') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) " . - "or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') " . - "or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Potentials') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) " . - "or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') " . - "or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= "or vtiger_potential.related_to in " . - "(select crmid from vtiger_crmentity where setype='accounts' " . - "and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) " . - "or vtiger_potential.related_to in " . - "(select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' " . - "and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) "; - } - $sec_query .= " or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'HelpDesk') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") "; - - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= "or vtiger_troubletickets.parent_id in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_troubletickets.parent_id in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) "; - } - $sec_query .= " or ("; - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Emails') - { - $sec_query .= " and vtiger_crmentity.smownerid=".$current_user->id." "; - - } - elseif($module == 'Calendar') - { - require_once('modules/Calendar/CalendarCommon.php'); - $shared_ids = getSharedCalendarId($current_user->id); - if(isset($shared_ids) && $shared_ids != '') - $condition = " or (vtiger_crmentity.smownerid in($shared_ids) and vtiger_activity.visibility = 'Public')"; - else - $condition = null; - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) $condition or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%')"; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " or ((vtiger_groups.groupid in (". implode(",", $current_user_groups) .")))"; - } - $sec_query .= ")"; - } - elseif($module == 'Quotes') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - //Adding crterial for vtiger_account related vtiger_quotes sharing - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= " or vtiger_quotes.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_quotes.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; - } - - //Adding crterial for vtiger_potential related vtiger_quotes sharing - if(vtlib_isModuleActive("Potentials")){ - $sec_query .= " or vtiger_quotes.potentialid in (select crmid from vtiger_crmentity where setype='Potentials' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid.")) or vtiger_quotes.potentialid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Potentials' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid."))"; - } - - //Adding crteria for group sharing - $sec_query .= " or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - elseif($module == 'PurchaseOrder') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'SalesOrder') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - //Adding crterial for vtiger_account related so sharing - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= " or vtiger_salesorder.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_salesorder.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_potential related so sharing - if(vtlib_isModuleActive("Potentials")){ - $sec_query .= " or vtiger_salesorder.potentialid in (select crmid from vtiger_crmentity where setype='Potentials' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid.")) or vtiger_salesorder.potentialid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Potentials' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_quotes related so sharing - if(vtlib_isModuleActive("Quotes")){ - $sec_query .= " or vtiger_salesorder.quoteid in (select crmid from vtiger_crmentity where setype='Quotes' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Quotes')." and relatedtabid=".$tabid.")) or vtiger_salesorder.quoteid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Quotes' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Quotes')." and relatedtabid=".$tabid."))"; - } - - //Adding crteria for group sharing - $sec_query .= " or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Invoice') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - //Adding crterial for vtiger_account related vtiger_invoice sharing - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= " or vtiger_invoice.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_invoice.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_salesorder related vtiger_invoice sharing - if(vtlib_isModuleActive("SalesOrder")){ - $sec_query .= " or vtiger_invoice.salesorderid in (select crmid from vtiger_crmentity where setype='SalesOrder' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('SalesOrder')." and relatedtabid=".$tabid.")) or vtiger_invoice.salesorderid in(select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='SalesOrder' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('SalesOrder')." and relatedtabid=".$tabid."))"; - } - - //Adding crteria for group sharing - $sec_query .= " or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - elseif($module == 'Campaigns') - { - - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - - } - - elseif($module == 'Documents') - { - $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - - else - { - $modObj = CRMEntity::getInstance($module); - $sec_query = $modObj->getListViewSecurityParameter($module); - - } - $log->debug("Exiting getListViewSecurityParameter method ..."); - return $sec_query; -} - - -function getSecListViewSecurityParameter($module) -{ - global $log; - $log->debug("Entering getListViewSecurityParameter(".$module.") method ..."); - global $adb; - global $current_user; - - $tabid=getTabid($module); - global $current_user; - if($current_user) - { - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - } - - if($module == 'Leads') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - } - elseif($module == 'Accounts') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Contacts') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Potentials') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or vtiger_potential.related_to in (select crmid from vtiger_crmentity where setype in ('Accounts', 'Contacts') and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid in (".getTabid('Accounts').", ".getTabid('Contacts').") and relatedtabid=".$tabid.")) "; - - if(vtlib_isModuleActive("Accounts")){ - "or vtiger_potential.related_to in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in (select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) "; - } - if(vtlib_isModuleActive("Contacts")){ - "or vtiger_potential.related_to in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Contacts' and vtiger_groups.groupid in (select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Contacts')." and relatedtabid=".$tabid.")) "; - } - $sec_query .= " or ("; - if(sizeof($current_user_groups) > 0){ - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'HelpDesk') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") "; - - if(vtlib_isModuleActive("Accounts")){ - "or vtiger_troubletickets.parent_id in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_troubletickets.parent_id in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) "; - } - - $sec_query .= " or ("; - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Calendar') - { - require_once('modules/Calendar/CalendarCommon.php'); - $shared_ids = getSharedCalendarId($current_user->id); - if(isset($shared_ids) && $shared_ids != '') - $condition = " or (vtiger_crmentity$module.smownerid in($shared_ids) and vtiger_activity.visibility = 'Public')"; - else - $condition = null; - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) $condition or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%')"; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " or ((vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .")))"; - } - $sec_query .= ")"; - } - elseif($module == 'Quotes') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - //Adding crterial for vtiger_account related vtiger_quotes sharing - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= " or vtiger_quotes.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_quotes.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_potential related vtiger_quotes sharing - if(vtlib_isModuleActive("Potentials")){ - $sec_query .= " or vtiger_quotes.potentialid in (select crmid from vtiger_crmentity where setype='Potentials' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid.")) or vtiger_quotes.potentialid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Potentials' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid."))"; - } - - //Adding crteria for group sharing - $sec_query .= " or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - elseif($module == 'PurchaseOrder') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'SalesOrder') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - //Adding crterial for vtiger_account related so sharing - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= " or vtiger_salesorder.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_salesorder.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_potential related so sharing - if(vtlib_isModuleActive("Potentials")){ - $sec_query .= " or vtiger_salesorder.potentialid in (select crmid from vtiger_crmentity where setype='Potentials' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid.")) or vtiger_salesorder.potentialid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Potentials' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_quotes related so sharing - if(vtlib_isModuleActive("Quotes")){ - $sec_query .= " or vtiger_salesorder.quoteid in (select crmid from vtiger_crmentity where setype='Quotes' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Quotes')." and relatedtabid=".$tabid.")) or vtiger_salesorder.quoteid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Quotes' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Quotes')." and relatedtabid=".$tabid."))"; - } - - //Adding crteria for group sharing - $sec_query .= " or ("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; - - } - elseif($module == 'Invoice') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; - - //Adding crterial for vtiger_account related vtiger_invoice sharing - if(vtlib_isModuleActive("Accounts")){ - $sec_query .= " or vtiger_invoice.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_invoice.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; - } - //Adding crterial for vtiger_salesorder related vtiger_invoice sharing - if(vtlib_isModuleActive("SalesOrder")){ - $sec_query .= " or vtiger_invoice.salesorderid in (select crmid from vtiger_crmentity where setype='SalesOrder' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('SalesOrder')." and relatedtabid=".$tabid.")) or vtiger_invoice.salesorderid in(select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='SalesOrder' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('SalesOrder')." and relatedtabid=".$tabid."))"; - } - - //Adding crteria for group sharing - $sec_query .= " or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - elseif($module == 'Campaigns') - { - - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - - } - - elseif($module == 'Documents') - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - - else - { - $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; - - if(sizeof($current_user_groups) > 0) - { - $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; - } - $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; - - } - $log->debug("Exiting getListViewSecurityParameter method ..."); - return $sec_query; -} - -function get_current_user_access_groups($module) -{ - global $log; - $log->debug("Entering get_current_user_access_groups(".$module.") method ..."); - global $adb,$noof_group_rows; - $current_user_group_list=getCurrentUserGroupList(); - $sharing_write_group_list=getWriteSharingGroupsList($module); - $query ="select groupname,groupid from vtiger_groups"; - $params = array(); - if(count($current_user_group_list) > 0 && count($sharing_write_group_list) > 0) - { - $query .= " where (groupid in (". generateQuestionMarks($current_user_group_list) .") or groupid in (". generateQuestionMarks($sharing_write_group_list) ."))"; - array_push($params, $current_user_group_list, $sharing_write_group_list); - $result = $adb->pquery($query, $params); - $noof_group_rows=$adb->num_rows($result); - } - elseif(count($current_user_group_list) > 0) - { - $query .= " where groupid in (". generateQuestionMarks($current_user_group_list) .")"; - array_push($params, $current_user_group_list); - $result = $adb->pquery($query, $params); - $noof_group_rows=$adb->num_rows($result); - } - elseif(count($sharing_write_group_list) > 0) - { - $query .= " where groupid in (". generateQuestionMarks($sharing_write_group_list) .")"; - array_push($params, $sharing_write_group_list); - $result = $adb->pquery($query, $params); - $noof_group_rows=$adb->num_rows($result); - } - $log->debug("Exiting get_current_user_access_groups method ..."); - return $result; -} -/** Function to get the Group Id for a given group groupname - * @param $groupname -- Groupname - * @returns Group Id -- Type Integer - */ - -function getGrpId($groupname) -{ - global $log; - $log->debug("Entering getGrpId(".$groupname.") method ..."); - global $adb; - - $result = $adb->pquery("select groupid from vtiger_groups where groupname=?", array($groupname)); - $groupid = $adb->query_result($result,0,'groupid'); - $log->debug("Exiting getGrpId method ..."); - return $groupid; -} - -/** Function to check permission to access a vtiger_field for a given user - * @param $fld_module -- Module :: Type String - * @param $userid -- User Id :: Type integer - * @param $fieldname -- Field Name :: Type varchar - * @returns $rolename -- Role Name :: Type varchar - * - */ -function getFieldVisibilityPermission($fld_module, $userid, $fieldname) -{ - global $log; - $log->debug("Entering getFieldVisibilityPermission(".$fld_module.",". $userid.",". $fieldname.") method ..."); - - global $adb; - global $current_user; - - // Check if field is in-active - $fieldActive = isFieldActive($fld_module,$fieldname); - if($fieldActive == false) { - return '1'; - } - - require('user_privileges/user_privileges_'.$userid.'.php'); - - /* Asha: Fix for ticket #4508. Users with View all and Edit all permission will also have visibility permission for all fields */ - if($is_admin || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0) - { - $log->debug("Exiting getFieldVisibilityPermission method ..."); - return '0'; - } - else - { - //get vtiger_profile list using userid - $profilelist = getCurrentUserProfileList(); - - //get tabid - $tabid = getTabid($fld_module); - - if (count($profilelist) > 0) { - $query="SELECT vtiger_profile2field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid in (". generateQuestionMarks($profilelist) .") AND vtiger_field.fieldname= ? and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; - $params = array($tabid, $profilelist, $fieldname); - } else { - $query="SELECT vtiger_profile2field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_field.fieldname= ? and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; - $params = array($tabid, $fieldname); - } - //Postgres 8 fixes - if( $adb->dbType == "pgsql") - $query = fixPostgresQuery( $query, $log, 0); - - - $result = $adb->pquery($query, $params); - - $log->debug("Exiting getFieldVisibilityPermission method ..."); - - if($adb->num_rows($result) == 0) return '1'; - return ($adb->query_result($result,"0","visible")+""); - } -} - -/** Function to check permission to access the column for a given user - * @param $userid -- User Id :: Type integer - * @param $tablename -- tablename :: Type String - * @param $columnname -- columnname :: Type String - * @param $module -- Module Name :: Type varchar - */ -function getColumnVisibilityPermission($userid,$columnname, $module) -{ - global $adb,$log; - $log->debug("in function getcolumnvisibilitypermission $columnname -$userid"); - $tabid = getTabid($module); - - // Look at cache if information is available. - $cacheFieldInfo = VTCacheUtils::lookupFieldInfoByColumn($tabid, $columnname); - $fieldname = false; - if($cacheFieldInfo === false) { - $res = $adb->pquery("select fieldname from vtiger_field where tabid=? and columnname=? and vtiger_field.presence in (0,2)", array($tabid, $columnname)); - $fieldname = $adb->query_result($res, 0, 'fieldname'); - } else { - $fieldname = $cacheFieldInfo['fieldname']; - } - - return getFieldVisibilityPermission($module,$userid,$fieldname); -} - -/** Function to get the vtiger_field access module array - * @returns The vtiger_field Access module Array :: Type Array - * - */ -function getFieldModuleAccessArray() -{ - global $log; - global $adb; - $log->debug("Entering getFieldModuleAccessArray() method ..."); - - $fldModArr=Array(); - $query = 'select distinct(name) from vtiger_profile2field inner join vtiger_tab on vtiger_tab.tabid=vtiger_profile2field.tabid'; - $result = $adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $mod_name = $adb->query_result($result,$i,'name'); - $fldModArr[$mod_name] = $mod_name; - } - $log->debug("Exiting getFieldModuleAccessArray method ..."); - return $fldModArr; -} - -/** Function to get the permitted module name Array with presence as 0 - * @returns permitted module name Array :: Type Array - * - */ -function getPermittedModuleNames() -{ - global $log; - $log->debug("Entering getPermittedModuleNames() method ..."); - global $current_user; - $permittedModules=Array(); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - include('tabdata.php'); - - if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) - { - foreach($tab_seq_array as $tabid=>$seq_value) - { - if($seq_value === 0 && $profileTabsPermission[$tabid] === 0) - { - $permittedModules[]=getTabModuleName($tabid); - } - - } - - - } - else - { - foreach($tab_seq_array as $tabid=>$seq_value) - { - if($seq_value === 0) - { - $permittedModules[]=getTabModuleName($tabid); - } - - } - } - $log->debug("Exiting getPermittedModuleNames method ..."); - return $permittedModules; -} - - - -/** Function to recalculate the Sharing Rules for all the vtiger_users - * This function will recalculate all the sharing rules for all the vtiger_users in the Organization and will write them in flat vtiger_files - * - */ -function RecalculateSharingRules() -{ - global $log; - $log->debug("Entering RecalculateSharingRules() method ..."); - global $adb; - require_once('modules/Users/CreateUserPrivilegeFile.php'); - $query="select id from vtiger_users where deleted=0"; - $result=$adb->pquery($query, array()); - $num_rows=$adb->num_rows($result); - for($i=0;$i<$num_rows;$i++) - { - $id=$adb->query_result($result,$i,'id'); - createUserPrivilegesfile($id); - createUserSharingPrivilegesfile($id); - } - $log->debug("Exiting RecalculateSharingRules method ..."); - -} - -/** Function to get the list of module for which the user defined sharing rules can be defined - * @returns Array:: Type array - * - */ -function getSharingModuleList($eliminateModules=false) -{ - global $log; - - $sharingModuleArray = Array(); - - global $adb; - if(empty($eliminateModules)) $eliminateModules = Array(); - - // Module that needs to be eliminated explicitly - if(!in_array('Calendar', $eliminateModules)) $eliminateModules[] = 'Calendar'; - if(!in_array('Events', $eliminateModules)) $eliminateModules[] = 'Events'; - - $query = "SELECT name FROM vtiger_tab WHERE presence=0 AND ownedby = 0 AND isentitytype = 1"; - $query .= " AND name NOT IN('" . implode("','", $eliminateModules) . "')"; - - $result = $adb->query($query); - while($resrow = $adb->fetch_array($result)) { - $sharingModuleArray[] = $resrow['name']; - } - - return $sharingModuleArray; -} - - -function isCalendarPermittedBySharing($recordId) -{ - global $adb; - global $current_user; - $permission = 'no'; - $query = "select * from vtiger_sharedcalendar where userid in(select smownerid from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid where activityid=? and visibility='Public' and smownerid !=0) and sharedid=?"; - $result=$adb->pquery($query, array($recordId, $current_user->id)); - if($adb->num_rows($result) >0) - { - $permission = 'yes'; - } - return $permission; -} -/* - * * Function to populate default entries for the picklist while creating a new role--vashni - * */ -function insertRole2Picklist($roleid,$parentroleid) -{ - global $adb,$log; - $log->debug("Entering into the function insertRole2Picklist($roleid,$parentroleid)"); - $sql = "insert into vtiger_role2picklist select '".$roleid."',picklistvalueid,picklistid,sortid from vtiger_role2picklist where roleid=?"; - $adb->pquery($sql, array($parentroleid)); - $log->debug("Exiting from the function insertRole2Picklist($roleid,$parentroleid)"); -} - -/** Function to delete group to report relation of the specified group - * @param $groupId -- Group Id :: Type integer - */ -function deleteGroupReportRelations($groupId) -{ - global $log; - $log->debug("Entering deleteGroupReportRelations(".$groupId.") method ..."); - global $adb; - $query="delete from vtiger_reportsharing where shareid=? and setype='groups'"; - $adb->pquery($query, array($groupId)); - $log->debug("Exiting deleteGroupReportRelations method ..."); -} -//end - -/** Function to check if the field is Active - * @params $modulename -- Module Name :: String Type - * $fieldname -- Field Name :: String Type - */ -function isFieldActive($modulename,$fieldname){ - $fieldid = getFieldid(getTabid($modulename), $fieldname, true); - return ($fieldid !== false); -} - +debug("Entering getMailServerInfo(".$user->user_name.") method ..."); + global $adb; + $sql = "select * from vtiger_mail_accounts where status=1 and user_id=?"; + $result = $adb->pquery($sql, array($user->id)); + $log->debug("Exiting getMailServerInfo method ..."); + return $result; +} + +/** To get the Role of the specified user + * @param $userid -- The user Id:: Type integer + * @returns vtiger_roleid :: Type String + */ +function fetchUserRole($userid) +{ + global $log; + $log->debug("Entering fetchUserRole(".$userid.") method ..."); + global $adb; + $sql = "select roleid from vtiger_user2role where userid=?"; + $result = $adb->pquery($sql, array($userid)); + $roleid= $adb->query_result($result,0,"roleid"); + $log->debug("Exiting fetchUserRole method ..."); + return $roleid; +} + +/** Depricated. Function to be replaced by getUserProfile() + * Should be done accross the product + * + */ +function fetchUserProfileId($userid) +{ + global $log; + $log->debug("Entering fetchUserProfileId(".$userid.") method ..."); + + // Look up information in cache first + $profileid = VTCacheUtils::lookupUserProfileId($userid); + + if($profileid === false) { + global $adb; + + $query = "SELECT profileid FROM vtiger_role2profile WHERE roleid=(SELECT roleid FROM vtiger_user2role WHERE userid=?)"; + $result = $adb->pquery($query, array($userid)); + + if($result && $adb->num_rows($result)) { + $profileid = $adb->query_result($result, 0, 'profileid'); + // TODO: What if there are multiple profile to one role? + } + + // Update information to cache for re-use + VTCacheUtils::updateUserProfileId($userid, $profileid); + } + + $log->debug("Exiting fetchUserProfileId method ..."); + return $profileid; +} + +/** Function to get the lists of groupids releated with an user + * This function accepts the user id as arguments and + * returns the groupids related with the user id + * as a comma seperated string +*/ +function fetchUserGroupids($userid) +{ + global $log; + $log->debug("Entering fetchUserGroupids(".$userid.") method ..."); + global $adb; + $focus = new GetUserGroups(); + $focus->getAllUserGroups($userid); + //Asha: Remove implode if not required and if so, also remove explode functions used at the recieving end of this function + $groupidlists = implode(",",$focus->user_groups); + $log->debug("Exiting fetchUserGroupids method ..."); + return $groupidlists; + +} + +/** Function to load all the permissions + * + */ +function loadAllPerms() + { + global $log; + $log->debug("Entering loadAllPerms() method ..."); + global $adb,$MAX_TAB_PER; + global $persistPermArray; + + $persistPermArray = Array(); + $profiles = Array(); + $sql = "select distinct profileid from vtiger_profile2tab"; + $result = $adb->pquery($sql, array()); + $num_rows = $adb->num_rows($result); + for ( $i=0; $i < $num_rows; $i++ ) + $profiles[] = $adb->query_result($result,$i,'profileid'); + + $persistPermArray = Array(); + foreach ( $profiles as $profileid ) + { + $sql = "select * from vtiger_profile2tab where profileid=?"; + $result = $adb->pquery($sql, array($profileid)); + if($MAX_TAB_PER !='') + { + $persistPermArray[$profileid] = array_fill(0,$MAX_TAB_PER,0); + } + $num_rows = $adb->num_rows($result); + for($i=0; $i<$num_rows; $i++) + { + $tabid= $adb->query_result($result,$i,'tabid'); + $tab_per= $adb->query_result($result,$i,'permissions'); + $persistPermArray[$profileid][$tabid] = $tab_per; + } + } + $log->debug("Exiting loadAllPerms method ..."); +} + +/** Function to get all the vtiger_tab permission for the specified vtiger_profile + * @param $profileid -- Profile Id:: Type integer + * @returns TabPermission Array in the following format: + * $tabPermission = Array($tabid1=>permission, + * $tabid2=>permission, + * | + * $tabidn=>permission) + * + */ +function getAllTabsPermission($profileid) +{ + global $log; + $log->debug("Entering getAllTabsPermission(".$profileid.") method ..."); + global $persistPermArray; + global $adb,$MAX_TAB_PER; + // Mike Crowe Mod -------------------------------------------------------- + if ( $cache_tab_perms ) + { + if ( count($persistPermArray) == 0 ) + loadAllPerms(); + $log->debug("Exiting getAllTabsPermission method ..."); + return $persistPermArray[$profileid]; + } + else + { + $sql = "select * from vtiger_profile2tab where profileid=?"; + $result = $adb->pquery($sql, array($profileid)); + $tab_perr_array = Array(); + if($MAX_TAB_PER !='') + { + $tab_perr_array = array_fill(0,$MAX_TAB_PER,0); + } + $num_rows = $adb->num_rows($result); + for($i=0; $i<$num_rows; $i++) + { + $tabid= $adb->query_result($result,$i,'tabid'); + $tab_per= $adb->query_result($result,$i,'permissions'); + $tab_perr_array[$tabid] = $tab_per; + } + $log->debug("Exiting getAllTabsPermission method ..."); + return $tab_perr_array; + } + // Mike Crowe Mod ---------------------------------------------------------------- + +} + +/** Function to get all the vtiger_tab permission for the specified vtiger_profile other than tabid 15 + * @param $profileid -- Profile Id:: Type integer + * @returns TabPermission Array in the following format: + * $tabPermission = Array($tabid1=>permission, + * $tabid2=>permission, + * | + * $tabidn=>permission) + * + */ +function getTabsPermission($profileid) +{ + global $log; + $log->debug("Entering getTabsPermission(".$profileid.") method ..."); + global $persistPermArray; + global $adb; + // Mike Crowe Mod ------------------------------------------------------- + if ( $cache_tab_perms ) + { + if ( count($persistPermArray) == 0 ) + loadAllPerms(); + $tab_perr_array = $persistPermArray; + foreach( array(1,3,16,15) as $tabid ) + $tab_perr_array[$tabid] = 0; + $log->debug("Exiting getTabsPermission method ..."); + return $tab_perr_array; + } + else + { + $sql = "select * from vtiger_profile2tab where profileid=?"; + $result = $adb->pquery($sql, array($profileid)); + $tab_perr_array = Array(); + $num_rows = $adb->num_rows($result); + for($i=0; $i<$num_rows; $i++) + { + $tabid= $adb->query_result($result,$i,'tabid'); + $tab_per= $adb->query_result($result,$i,'permissions'); + if($tabid != 3 && $tabid != 16) + { + $tab_perr_array[$tabid] = $tab_per; + } + } + $log->debug("Exiting getTabsPermission method ..."); + return $tab_perr_array; + } + +} + +/** Function to get all the vtiger_tab standard action permission for the specified vtiger_profile + * @param $profileid -- Profile Id:: Type integer + * @returns Tab Action Permission Array in the following format: + * $tabPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * | + * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) + * + */ +function getTabsActionPermission($profileid) +{ + global $log; + $log->debug("Entering getTabsActionPermission(".$profileid.") method ..."); + global $adb; + $check = Array(); + $temp_tabid = Array(); + $sql1 = "select * from vtiger_profile2standardpermissions where profileid=? and tabid not in(16) order by(tabid)"; + $result1 = $adb->pquery($sql1, array($profileid)); + $num_rows1 = $adb->num_rows($result1); + for($i=0; $i<$num_rows1; $i++) + { + $tab_id = $adb->query_result($result1,$i,'tabid'); + if(! in_array($tab_id,$temp_tabid)) + { + $temp_tabid[] = $tab_id; + $access = Array(); + } + + $action_id = $adb->query_result($result1,$i,'operation'); + $per_id = $adb->query_result($result1,$i,'permissions'); + $access[$action_id] = $per_id; + $check[$tab_id] = $access; + } + $log->debug("Exiting getTabsActionPermission method ..."); + return $check; +} + +/** Function to get all the vtiger_tab utility action permission for the specified vtiger_profile + * @param $profileid -- Profile Id:: Type integer + * @returns Tab Utility Action Permission Array in the following format: + * $tabPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * | + * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) + * + */ + +function getTabsUtilityActionPermission($profileid) +{ + global $log; + $log->debug("Entering getTabsUtilityActionPermission(".$profileid.") method ..."); + + global $adb; + $check = Array(); + $temp_tabid = Array(); + $sql1 = "select * from vtiger_profile2utility where profileid=? order by(tabid)"; + $result1 = $adb->pquery($sql1, array($profileid)); + $num_rows1 = $adb->num_rows($result1); + for($i=0; $i<$num_rows1; $i++) + { + $tab_id = $adb->query_result($result1,$i,'tabid'); + if(! in_array($tab_id,$temp_tabid)) + { + $temp_tabid[] = $tab_id; + $access = Array(); + } + + $action_id = $adb->query_result($result1,$i,'activityid'); + $per_id = $adb->query_result($result1,$i,'permission'); + $access[$action_id] = $per_id; + $check[$tab_id] = $access; + + + } + + $log->debug("Exiting getTabsUtilityActionPermission method ..."); + return $check; + +} +/**This Function returns the Default Organisation Sharing Action Array for all modules whose sharing actions are editable + * The result array will be in the following format: + * Arr=(tabid1=>Sharing Action Id, + * tabid2=>SharingAction Id, + * | + * | + * | + * tabid3=>SharingAcion Id) + */ + +function getDefaultSharingEditAction() +{ + global $log; + $log->debug("Entering getDefaultSharingEditAction() method ..."); + global $adb; + //retreiving the standard permissions + $sql= "select * from vtiger_def_org_share where editstatus=0"; + $result = $adb->pquery($sql, array()); + $permissionRow=$adb->fetch_array($result); + do + { + for($j=0;$jfetch_array($result)); + + $log->debug("Exiting getDefaultSharingEditAction method ..."); + return $copy; + +} +/**This Function returns the Default Organisation Sharing Action Array for modules with edit status in (0,1) + * The result array will be in the following format: + * Arr=(tabid1=>Sharing Action Id, + * tabid2=>SharingAction Id, + * | + * | + * | + * tabid3=>SharingAcion Id) + */ +function getDefaultSharingAction() +{ + global $log; + $log->debug("Entering getDefaultSharingAction() method ..."); + global $adb; + //retreivin the standard permissions + $sql= "select * from vtiger_def_org_share where editstatus in(0,1)"; + $result = $adb->pquery($sql, array()); + $permissionRow=$adb->fetch_array($result); + do + { + for($j=0;$jfetch_array($result)); + $log->debug("Exiting getDefaultSharingAction method ..."); + return $copy; + +} + + +/**This Function returns the Default Organisation Sharing Action Array for all modules + * The result array will be in the following format: + * Arr=(tabid1=>Sharing Action Id, + * tabid2=>SharingAction Id, + * | + * | + * | + * tabid3=>SharingAcion Id) + */ +function getAllDefaultSharingAction() +{ + global $log; + $log->debug("Entering getAllDefaultSharingAction() method ..."); + global $adb; + $copy=Array(); + //retreiving the standard permissions + $sql= "select * from vtiger_def_org_share"; + $result = $adb->pquery($sql, array()); + $num_rows=$adb->num_rows($result); + + for($i=0;$i<$num_rows;$i++) + { + $tabid=$adb->query_result($result,$i,'tabid'); + $permission=$adb->query_result($result,$i,'permission'); + $copy[$tabid]=$permission; + + } + + $log->debug("Exiting getAllDefaultSharingAction method ..."); + return $copy; + +} + + +/** Function to create the vtiger_role + * @param $roleName -- Role Name:: Type varchar + * @param $parentRoleId -- Parent Role Id:: Type varchar + * @param $roleProfileArray -- Profile to be associated with this vtiger_role:: Type Array + * @returns the Rold Id :: Type varchar + * + */ + +function createRole($roleName,$parentRoleId,$roleProfileArray) +{ + global $log; + $log->debug("Entering createRole(".$roleName.",".$parentRoleId.",".$roleProfileArray.") method ..."); + global $adb; + $parentRoleDetails=getRoleInformation($parentRoleId); + $parentRoleInfo=$parentRoleDetails[$parentRoleId]; + $roleid_no=$adb->getUniqueId("vtiger_role"); + $roleId='H'.$roleid_no; + $parentRoleHr=$parentRoleInfo[1]; + $parentRoleDepth=$parentRoleInfo[2]; + $nowParentRoleHr=$parentRoleHr.'::'.$roleId; + $nowRoleDepth=$parentRoleDepth + 1; + + // Invalidate any cached information + VTCacheUtils::clearRoleSubordinates($roleId); + + //Inserting vtiger_role into db + $query="insert into vtiger_role values(?,?,?,?)"; + $qparams = array($roleId,$roleName,$nowParentRoleHr,$nowRoleDepth); + $adb->pquery($query,$qparams); + + //Inserting into vtiger_role2profile vtiger_table + foreach($roleProfileArray as $profileId) + { + if($profileId != '') + { + insertRole2ProfileRelation($roleId,$profileId); + } + } + + $log->debug("Exiting createRole method ..."); + return $roleId; + +} + +/** Function to update the vtiger_role + * @param $roleName -- Role Name:: Type varchar + * @param $roleId -- Role Id:: Type varchar + * @param $roleProfileArray -- Profile to be associated with this vtiger_role:: Type Array + * + */ +function updateRole($roleId,$roleName,$roleProfileArray) +{ + global $log; + $log->debug("Entering updateRole(".$roleId.",".$roleName.",".$roleProfileArray.") method ..."); + + // Invalidate any cached information + VTCacheUtils::clearRoleSubordinates($roleId); + + global $adb; + $sql1 = "update vtiger_role set rolename=? where roleid=?"; + $adb->pquery($sql1, array($roleName, $roleId)); + //Updating the Role2Profile relation + $sql2 = "delete from vtiger_role2profile where roleId=?"; + $adb->pquery($sql2, array($roleId)); + + foreach($roleProfileArray as $profileId) + { + if($profileId != '') + { + insertRole2ProfileRelation($roleId,$profileId); + } + } + $log->debug("Exiting updateRole method ..."); + +} + +/** Function to add the vtiger_role to vtiger_profile relation + * @param $profileId -- Profile Id:: Type integer + * @param $roleId -- Role Id:: Type varchar + * + */ +function insertRole2ProfileRelation($roleId,$profileId) +{ + global $log; + $log->debug("Entering insertRole2ProfileRelation(".$roleId.",".$profileId.") method ..."); + global $adb; + $query="insert into vtiger_role2profile values(?,?)"; + $qparams = array($roleId,$profileId); + $adb->pquery($query, $qparams); + $log->debug("Exiting insertRole2ProfileRelation method ..."); + +} + + +/** Function to get the vtiger_roleid from vtiger_rolename + * @param $rolename -- Role Name:: Type varchar + * @returns Role Id:: Type varchar + * + */ +function fetchRoleId($rolename) +{ +global $log; +$log->debug("Entering fetchRoleId(".$rolename.") method ..."); + + global $adb; + $sqlfetchroleid = "select roleid from vtiger_role where rolename=?"; + $resultroleid = $adb->pquery($sqlfetchroleid, array($rolename)); + $role_id = $adb->query_result($resultroleid,0,"roleid"); +$log->debug("Exiting fetchRoleId method ..."); + return $role_id; +} + +/** Function to update user to vtiger_role mapping based on the userid + * @param $roleid -- Role Id:: Type varchar + * @param $userid User Id:: Type integer + * + */ +function updateUser2RoleMapping($roleid,$userid) +{ +global $log; +$log->debug("Entering updateUser2RoleMapping(".$roleid.",".$userid.") method ..."); + global $adb; + //Check if row already exists + $sqlcheck = "select * from vtiger_user2role where userid=?"; + $resultcheck = $adb->pquery($sqlcheck, array($userid)); + if($adb->num_rows($resultcheck) == 1) + { + $sqldelete = "delete from vtiger_user2role where userid=?"; + $delparams = array($userid); + $result_delete = $adb->pquery($sqldelete, $delparams); + } + $sql = "insert into vtiger_user2role(userid,roleid) values(?,?)"; + $params = array($userid, $roleid); + $result = $adb->pquery($sql, $params); + $log->debug("Exiting updateUser2RoleMapping method ..."); + +} + + +/** Function to update user to group mapping based on the userid + * @param $groupname -- Group Name:: Type varchar + * @param $userid User Id:: Type integer + * + */ +function updateUsers2GroupMapping($groupname,$userid) +{ +global $log; +$log->debug("Entering updateUsers2GroupMapping(".$groupname.",".$userid.") method ..."); + global $adb; + $sqldelete = "delete from vtiger_users2group where userid = ?"; + $delparams = array($userid); + $result_delete = $adb->pquery($sqldelete, $delparams); + + $sql = "insert into vtiger_users2group(groupname,userid) values(?,?)"; + $params = array($groupname,$userid); + $result = $adb->pquery($sql, $params); + $log->debug("Exiting updateUsers2GroupMapping method ..."); +} + +/** Function to add user to vtiger_role mapping + * @param $roleid -- Role Id:: Type varchar + * @param $userid User Id:: Type integer + * + */ +function insertUser2RoleMapping($roleid,$userid) +{ +global $log; +$log->debug("Entering insertUser2RoleMapping(".$roleid.",".$userid.") method ..."); + + global $adb; + $sql = "insert into vtiger_user2role(userid,roleid) values(?,?)"; + $params = array($userid, $roleid); + $adb->pquery($sql, $params); +$log->debug("Exiting insertUser2RoleMapping method ..."); + +} + +/** Function to add user to group mapping + * @param $groupname -- Group Name:: Type varchar + * @param $userid User Id:: Type integer + * + */ +function insertUsers2GroupMapping($groupname,$userid) +{ +global $log; +$log->debug("Entering insertUsers2GroupMapping(".$groupname.",".$userid.") method ..."); + global $adb; + $sql = "insert into vtiger_users2group(groupname,userid) values(?,?)"; + $params = array($groupname, $userid); + $adb->pquery($sql, $params); +$log->debug("Exiting insertUsers2GroupMapping method ..."); +} + +/** Function to get the word template resultset + * @param $module -- Module Name:: Type varchar + * @returns Type:: resultset + * + */ +function fetchWordTemplateList($module) +{ + global $log; + $log->debug("Entering fetchWordTemplateList(".$module.") method ..."); + global $adb; + $sql_word = "select templateid, filename from vtiger_wordtemplates where module =?" ; + $result=$adb->pquery($sql_word, array($module)); + $log->debug("Exiting fetchWordTemplateList method ..."); + return $result; +} + + + +/** Function to get the email template iformation + * @param $templateName -- Template Name:: Type varchar + * @returns Type:: resultset + * + */ +function fetchEmailTemplateInfo($templateName) +{ + global $log; + $log->debug("Entering fetchEmailTemplateInfo(".$templateName.") method ..."); + global $adb; + $sql= "select * from vtiger_emailtemplates where templatename=?"; + $result = $adb->pquery($sql, array($templateName)); + $log->debug("Exiting fetchEmailTemplateInfo method ..."); + return $result; +} + +/** Function to substitute the tokens in the specified file + * @param $templateName -- Template Name:: Type varchar + * @param $globals + * + */ +function substituteTokens($filename,$globals) +{ +global $log; +$log->debug("Entering substituteTokens(".$filename.",".$globals.") method ..."); + $log->debug("in substituteTokens method with filename ".$filename.' and content globals as '.$globals); + + global $root_directory; + + if (!$filename) + { + + $log->debug("filename is not set in substituteTokens"); + $filename = $this->filename; + $log->debug("filename is not set in substituteTokens so taking default filename"); + } + + if (!$dump = file ($filename)) + { + $log->debug("not able to create the file or get access to the file with filename ".$filename." so returning 0"); + $log->debug("Exiting substituteTokens method ..."); + return 0; + } + + $log->debug("about to start replacing the tokens"); + require_once($root_directory .'/modules/Emails/templates/testemailtemplateusage.php'); + eval ("global $globals; "); + while (list($key,$val) = each($dump)) + { + $replacedString ; + if (preg_match( "/\$/g",$val)) + { + $log->debug("token is ".$val); + eval( "\$val = \"$val\";"); + $val = stripslashes ($val); + $replacedString .= $val; + } + } + + $log->debug("the replacedString is ".$replacedString); + $log->debug("Exiting substituteTokens method ..."); + return $replacedString; +} + +/** Function to get the vtiger_role name from the vtiger_roleid + * @param $roleid -- Role Id:: Type varchar + * @returns $rolename -- Role Name:: Type varchar + * + */ +function getRoleName($roleid) +{ + global $log; + $log->debug("Entering getRoleName(".$roleid.") method ..."); + global $adb; + $sql1 = "select * from vtiger_role where roleid=?"; + $result = $adb->pquery($sql1, array($roleid)); + $rolename = $adb->query_result($result,0,"rolename"); + $log->debug("Exiting getRoleName method ..."); + return $rolename; +} + +/** Function to get the vtiger_profile name from the vtiger_profileid + * @param $profileid -- Profile Id:: Type integer + * @returns $rolename -- Role Name:: Type varchar + * + */ +function getProfileName($profileid) +{ + global $log; + $log->debug("Entering getProfileName(".$profileid.") method ..."); + global $adb; + $sql1 = "select * from vtiger_profile where profileid=?"; + $result = $adb->pquery($sql1, array($profileid)); + $profilename = $adb->query_result($result,0,"profilename"); + $log->debug("Exiting getProfileName method ..."); + return $profilename; +} +/** Function to get the vtiger_profile Description from the vtiger_profileid + * @param $profileid -- Profile Id:: Type integer + * @returns $rolename -- Role Name:: Type varchar + * + */ +function getProfileDescription($profileid) +{ + global $log; + $log->debug("Entering getProfileDescription(".$profileid.") method ..."); + global $adb; + $sql1 = "select description from vtiger_profile where profileid=?"; + $result = $adb->pquery($sql1, array($profileid)); + $profileDescription = $adb->query_result($result,0,"description"); + $log->debug("Exiting getProfileDescription method ..."); + return $profileDescription; +} + + +/** Function to check if the currently logged in user is permitted to perform the specified action + * @param $module -- Module Name:: Type varchar + * @param $actionname -- Action Name:: Type varchar + * @param $recordid -- Record Id:: Type integer + * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user + * + */ +function isPermitted($module,$actionname,$record_id='') +{ + global $log; + $log->debug("Entering isPermitted(".$module.",".$actionname.",".$record_id.") method ..."); + + global $adb; + global $current_user; + global $seclog; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $permission = "no"; + if($module == 'Users' || $module == 'Home' || $module == 'uploads') + { + //These modules dont have security right now + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + + } + + //Checking the Access for the Settings Module + if($module == 'Settings' || $module == 'Administration' || $module == 'System' || $_REQUEST['parenttab'] == 'Settings') + { + if(! $is_admin) + { + $permission = "no"; + } + else + { + $permission = "yes"; + } + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + + //Checking whether the user is admin + if($is_admin) + { + $permission ="yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + //Retreiving the Tabid and Action Id + $tabid = getTabid($module); + $actionid=getActionid($actionname); + //If no actionid, then allow action is vtiger_tab permission is available + if($actionid == '') + { + if($profileTabsPermission[$tabid] ==0) + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + } + else + { + $permission ="no"; + } + return $permission; + + } + + $action = getActionname($actionid); + //Checking for view all permission + if($profileGlobalPermission[1] ==0 || $profileGlobalPermission[2] ==0) + { + if($actionid == 3 || $actionid == 4) + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + + } + } + //Checking for edit all permission + if($profileGlobalPermission[2] ==0) + { + if($actionid == 3 || $actionid == 4 || $actionid ==0 || $actionid ==1) + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + + } + } + //Checking for vtiger_tab permission + if($profileTabsPermission[$tabid] !=0) + { + $permission = "no"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + //Checking for Action Permission + if(strlen($profileActionPermission[$tabid][$actionid]) < 1 && $profileActionPermission[$tabid][$actionid] == '') + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + + if($profileActionPermission[$tabid][$actionid] != 0 && $profileActionPermission[$tabid][$actionid] != '') + { + $permission = "no"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + //Checking and returning true if recorid is null + if($record_id == '') + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + + //If modules is Products,Vendors,Faq,PriceBook then no sharing + if($record_id != '') + { + if(getTabOwnedBy($module) == 1) + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + } + + //Retreiving the RecordOwnerId + $recOwnType=''; + $recOwnId=''; + $recordOwnerArr=getRecordOwnerId($record_id); + foreach($recordOwnerArr as $type=>$id) + { + $recOwnType=$type; + $recOwnId=$id; + } + //Retreiving the default Organisation sharing Access + $others_permission_id = $defaultOrgSharingPermission[$tabid]; + + if($recOwnType == 'Users') + { + //Checking if the Record Owner is the current User + if($current_user->id == $recOwnId) + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + //Checking if the Record Owner is the Subordinate User + foreach($subordinate_roles_users as $roleid=>$userids) + { + if(in_array($recOwnId,$userids)) + { + $permission='yes'; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + + } + + + } + elseif($recOwnType == 'Groups') + { + //Checking if the record owner is the current user's group + if(in_array($recOwnId,$current_user_groups)) + { + $permission='yes'; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + } + + //Checking for Default Org Sharing permission + if($others_permission_id == 0) + { + if($actionid == 1 || $actionid == 0) + { + + if($module == 'Calendar') + { + if($recOwnType == 'Users') + { + $permission = isCalendarPermittedBySharing($record_id); + } + else + { + $permission='no'; + } + } + else + { + $permission = isReadWritePermittedBySharing($module,$tabid,$actionid,$record_id); + } + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + elseif($actionid == 2) + { + $permission = "no"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + else + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + } + elseif($others_permission_id == 1) + { + if($actionid == 2) + { + $permission = "no"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + else + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + } + elseif($others_permission_id == 2) + { + + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + elseif($others_permission_id == 3) + { + + if($actionid == 3 || $actionid == 4) + { + if($module == 'Calendar') + { + if($recOwnType == 'Users') + { + $permission = isCalendarPermittedBySharing($record_id); + } + else + { + $permission='no'; + } + } + else + { + $permission = isReadPermittedBySharing($module,$tabid,$actionid,$record_id); + } + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + elseif($actionid ==0 || $actionid ==1) + { + if($module == 'Calendar') + { + $permission='no'; + } + else + { + $permission = isReadWritePermittedBySharing($module,$tabid,$actionid,$record_id); + } + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + elseif($actionid ==2) + { + $permission ="no"; + return $permission; + } + else + { + $permission = "yes"; + $log->debug("Exiting isPermitted method ..."); + return $permission; + } + } + else + { + $permission = "yes"; + } + + $log->debug("Exiting isPermitted method ..."); + return $permission; + +} + +/** Function to check if the currently logged in user has Read Access due to Sharing for the specified record + * @param $module -- Module Name:: Type varchar + * @param $actionid -- Action Id:: Type integer + * @param $recordid -- Record Id:: Type integer + * @param $tabid -- Tab Id:: Type integer + * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user + */ +function isReadPermittedBySharing($module,$tabid,$actionid,$record_id) +{ + global $log; + $log->debug("Entering isReadPermittedBySharing(".$module.",".$tabid.",".$actionid.",".$record_id.") method ..."); + global $adb; + global $current_user; + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $ownertype=''; + $ownerid=''; + $sharePer='no'; + + $sharingModuleList=getSharingModuleList(); + if(! in_array($module,$sharingModuleList)) + { + $sharePer='no'; + return $sharePer; + } + + $recordOwnerArr=getRecordOwnerId($record_id); + foreach($recordOwnerArr as $type=>$id) + { + $ownertype=$type; + $ownerid=$id; + } + + $varname=$module."_share_read_permission"; + $read_per_arr=$$varname; + if($ownertype == 'Users') + { + //Checking the Read Sharing Permission Array in Role Users + $read_role_per=$read_per_arr['ROLE']; + foreach($read_role_per as $roleid=>$userids) + { + if(in_array($ownerid,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; + } + + } + + //Checking the Read Sharing Permission Array in Groups Users + $read_grp_per=$read_per_arr['GROUP']; + foreach($read_grp_per as $grpid=>$userids) + { + if(in_array($ownerid,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; + } + + } + + } + elseif($ownertype == 'Groups') + { + $read_grp_per=$read_per_arr['GROUP']; + if(array_key_exists($ownerid,$read_grp_per)) + { + $sharePer='yes'; + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; + } + } + + //Checking for the Related Sharing Permission + $relatedModuleArray=$related_module_share[$tabid]; + if(is_array($relatedModuleArray)) + { + foreach($relatedModuleArray as $parModId) + { + $parRecordOwner=getParentRecordOwner($tabid,$parModId,$record_id); + if(sizeof($parRecordOwner) > 0) + { + $parModName=getTabname($parModId); + $rel_var=$parModName."_".$module."_share_read_permission"; + $read_related_per_arr=$$rel_var; + $rel_owner_type=''; + $rel_owner_id=''; + foreach($parRecordOwner as $rel_type=>$rel_id) + { + $rel_owner_type=$rel_type; + $rel_owner_id=$rel_id; + } + if($rel_owner_type=='Users') + { + //Checking in Role Users + $read_related_role_per=$read_related_per_arr['ROLE']; + foreach($read_related_role_per as $roleid=>$userids) + { + if(in_array($rel_owner_id,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; + } + + } + //Checking in Group Users + $read_related_grp_per=$read_related_per_arr['GROUP']; + foreach($read_related_grp_per as $grpid=>$userids) + { + if(in_array($rel_owner_id,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; + } + + } + + } + elseif($rel_owner_type=='Groups') + { + $read_related_grp_per=$read_related_per_arr['GROUP']; + if(array_key_exists($rel_owner_id,$read_related_grp_per)) + { + $sharePer='yes'; + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; + } + + } + } + } + } + $log->debug("Exiting isReadPermittedBySharing method ..."); + return $sharePer; +} + + + +/** Function to check if the currently logged in user has Write Access due to Sharing for the specified record + * @param $module -- Module Name:: Type varchar + * @param $actionid -- Action Id:: Type integer + * @param $recordid -- Record Id:: Type integer + * @param $tabid -- Tab Id:: Type integer + * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user + */ +function isReadWritePermittedBySharing($module,$tabid,$actionid,$record_id) +{ + global $log; + $log->debug("Entering isReadWritePermittedBySharing(".$module.",".$tabid.",".$actionid.",".$record_id.") method ..."); + global $adb; + global $current_user; + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $ownertype=''; + $ownerid=''; + $sharePer='no'; + + $sharingModuleList=getSharingModuleList(); + if(! in_array($module,$sharingModuleList)) + { + $sharePer='no'; + return $sharePer; + } + + $recordOwnerArr=getRecordOwnerId($record_id); + foreach($recordOwnerArr as $type=>$id) + { + $ownertype=$type; + $ownerid=$id; + } + + $varname=$module."_share_write_permission"; + $write_per_arr=$$varname; + + if($ownertype == 'Users') + { + //Checking the Write Sharing Permission Array in Role Users + $write_role_per=$write_per_arr['ROLE']; + foreach($write_role_per as $roleid=>$userids) + { + if(in_array($ownerid,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; + } + + } + //Checking the Write Sharing Permission Array in Groups Users + $write_grp_per=$write_per_arr['GROUP']; + foreach($write_grp_per as $grpid=>$userids) + { + if(in_array($ownerid,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; + } + + } + + } + elseif($ownertype == 'Groups') + { + $write_grp_per=$write_per_arr['GROUP']; + if(array_key_exists($ownerid,$write_grp_per)) + { + $sharePer='yes'; + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; + } + } + //Checking for the Related Sharing Permission + $relatedModuleArray=$related_module_share[$tabid]; + if(is_array($relatedModuleArray)) + { + foreach($relatedModuleArray as $parModId) + { + $parRecordOwner=getParentRecordOwner($tabid,$parModId,$record_id); + if(sizeof($parRecordOwner) > 0) + { + $parModName=getTabname($parModId); + $rel_var=$parModName."_".$module."_share_write_permission"; + $write_related_per_arr=$$rel_var; + $rel_owner_type=''; + $rel_owner_id=''; + foreach($parRecordOwner as $rel_type=>$rel_id) + { + $rel_owner_type=$rel_type; + $rel_owner_id=$rel_id; + } + if($rel_owner_type=='Users') + { + //Checking in Role Users + $write_related_role_per=$write_related_per_arr['ROLE']; + foreach($write_related_role_per as $roleid=>$userids) + { + if(in_array($rel_owner_id,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; + } + + } + //Checking in Group Users + $write_related_grp_per=$write_related_per_arr['GROUP']; + foreach($write_related_grp_per as $grpid=>$userids) + { + if(in_array($rel_owner_id,$userids)) + { + $sharePer='yes'; + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; + } + + } + + } + elseif($rel_owner_type=='Groups') + { + $write_related_grp_per=$write_related_per_arr['GROUP']; + if(array_key_exists($rel_owner_id,$write_related_grp_per)) + { + $sharePer='yes'; + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; + } + + } + } + } + } + + $log->debug("Exiting isReadWritePermittedBySharing method ..."); + return $sharePer; +} + +/** Function to check if the outlook user is permitted to perform the specified action + * @param $module -- Module Name:: Type varchar + * @param $actionname -- Action Name:: Type varchar + * @param $recordid -- Record Id:: Type integer + * @returns yes or no. If Yes means this action is allowed for the currently logged in user. If no means this action is not allowed for the currently logged in user + * + */ +function isAllowed_Outlook($module,$action,$user_id,$record_id) +{ + global $log; + $log->debug("Entering isAllowed_Outlook(".$module.",".$action.",".$user_id.",".$record_id.") method ..."); + + $permission = "no"; + if($module == 'Users' || $module == 'Home' || $module == 'Administration' || $module == 'uploads' || $module == 'Settings' || $module == 'Calendar') + { + //These modules done have security + $permission = "yes"; + + } + else + { + global $adb; + global $current_user; + $tabid = getTabid($module); + $actionid = getActionid($action); + $profile_id = fetchUserProfileId($user_id); + $tab_per_Data = getAllTabsPermission($profile_id); + + $permissionData = getTabsActionPermission($profile_id); + $defSharingPermissionData = getDefaultSharingAction(); + $others_permission_id = $defSharingPermissionData[$tabid]; + + //Checking whether this vtiger_tab is allowed + if($tab_per_Data[$tabid] == 0) + { + $permission = 'yes'; + //Checking whether this action is allowed + if($permissionData[$tabid][$actionid] == 0) + { + $permission = 'yes'; + $rec_owner_id = ''; + if($record_id != '' && $module != 'Products' && $module != 'Faq') + { + $rec_owner_id = getUserId($record_id); + } + + if($record_id != '' && $others_permission_id != '' && $module != 'Products' && $module != 'Faq' && $rec_owner_id != 0) + { + if($rec_owner_id != $current_user->id) + { + if($others_permission_id == 0) + { + if($action == 'EditView' || $action == 'Delete') + { + $permission = "no"; + } + else + { + $permission = "yes"; + } + } + elseif($others_permission_id == 1) + { + if($action == 'Delete') + { + $permission = "no"; + } + else + { + $permission = "yes"; + } + } + elseif($others_permission_id == 2) + { + + $permission = "yes"; + } + elseif($others_permission_id == 3) + { + if($action == 'DetailView' || $action == 'EditView' || $action == 'Delete') + { + $permission = "no"; + } + else + { + $permission = "yes"; + } + } + + + } + else + { + $permission = "yes"; + } + } + } + else + { + $permission = "no"; + } + } + else + { + $permission = "no"; + } + } + $log->debug("Exiting isAllowed_Outlook method ..."); + return $permission; + +} + + +/** Function to get the Profile Global Information for the specified vtiger_profileid + * @param $profileid -- Profile Id:: Type integer + * @returns Profile Gloabal Permission Array in the following format: + * $profileGloblaPermisson=Array($viewall_actionid=>permission, $editall_actionid=>permission) + */ +function getProfileGlobalPermission($profileid) +{ +global $log; +$log->debug("Entering getProfileGlobalPermission(".$profileid.") method ..."); + global $adb; + $sql = "select * from vtiger_profile2globalpermissions where profileid=?" ; + $result = $adb->pquery($sql, array($profileid)); + $num_rows = $adb->num_rows($result); + + for($i=0; $i<$num_rows; $i++) + { + $act_id = $adb->query_result($result,$i,"globalactionid"); + $per_id = $adb->query_result($result,$i,"globalactionpermission"); + $copy[$act_id] = $per_id; + } + + $log->debug("Exiting getProfileGlobalPermission method ..."); + return $copy; + +} + +/** Function to get the Profile Tab Permissions for the specified vtiger_profileid + * @param $profileid -- Profile Id:: Type integer + * @returns Profile Tabs Permission Array in the following format: + * $profileTabPermisson=Array($tabid1=>permission, $tabid2=>permission,........., $tabidn=>permission) + */ +function getProfileTabsPermission($profileid) +{ +global $log; +$log->debug("Entering getProfileTabsPermission(".$profileid.") method ..."); + global $adb; + $sql = "select * from vtiger_profile2tab where profileid=?" ; + $result = $adb->pquery($sql, array($profileid)); + $num_rows = $adb->num_rows($result); + + for($i=0; $i<$num_rows; $i++) + { + $tab_id = $adb->query_result($result,$i,"tabid"); + $per_id = $adb->query_result($result,$i,"permissions"); + $copy[$tab_id] = $per_id; + } + +$log->debug("Exiting getProfileTabsPermission method ..."); + return $copy; + +} + + +/** Function to get the Profile Action Permissions for the specified vtiger_profileid + * @param $profileid -- Profile Id:: Type integer + * @returns Profile Tabs Action Permission Array in the following format: + * $tabActionPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * | + * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) + */ +function getProfileActionPermission($profileid) +{ +global $log; +$log->debug("Entering getProfileActionPermission(".$profileid.") method ..."); + global $adb; + $check = Array(); + $temp_tabid = Array(); + $sql1 = "select * from vtiger_profile2standardpermissions where profileid=?"; + $result1 = $adb->pquery($sql1, array($profileid)); + $num_rows1 = $adb->num_rows($result1); + for($i=0; $i<$num_rows1; $i++) + { + $tab_id = $adb->query_result($result1,$i,'tabid'); + if(! in_array($tab_id,$temp_tabid)) + { + $temp_tabid[] = $tab_id; + $access = Array(); + } + + $action_id = $adb->query_result($result1,$i,'operation'); + $per_id = $adb->query_result($result1,$i,'permissions'); + $access[$action_id] = $per_id; + $check[$tab_id] = $access; + + + } + + +$log->debug("Exiting getProfileActionPermission method ..."); + return $check; +} + + + +/** Function to get the Standard and Utility Profile Action Permissions for the specified vtiger_profileid + * @param $profileid -- Profile Id:: Type integer + * @returns Profile Tabs Action Permission Array in the following format: + * $tabActionPermission = Array($tabid1=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * $tabid2=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission), + * | + * $tabidn=>Array(actionid1=>permission, actionid2=>permission,...,actionidn=>permission)) + */ +function getProfileAllActionPermission($profileid) +{ +global $log; +$log->debug("Entering getProfileAllActionPermission(".$profileid.") method ..."); + global $adb; + $actionArr=getProfileActionPermission($profileid); + $utilArr=getTabsUtilityActionPermission($profileid); + foreach($utilArr as $tabid=>$act_arr) + { + $act_tab_arr=$actionArr[$tabid]; + foreach($act_arr as $utilid=>$util_perr) + { + $act_tab_arr[$utilid]=$util_perr; + } + $actionArr[$tabid]=$act_tab_arr; + } +$log->debug("Exiting getProfileAllActionPermission method ..."); + return $actionArr; +} + + +/** Function to create vtiger_profile + * @param $profilename -- Profile Name:: Type varchar + * @param $parentProfileId -- Profile Id:: Type integer + */ +function createProfile($profilename,$parentProfileId,$description) +{ +global $log; +$log->debug("Entering createProfile(".$profilename.",".$parentProfileId.",".$description.") method ..."); + global $adb; + //Inserting values into Profile Table + $sql1 = "insert into vtiger_profile values(?,?,?)"; + $params1 = array('', $profilename, $description); + $adb->pquery($sql1, $params1); + + //Retreiving the vtiger_profileid + $sql2 = "select max(profileid) as current_id from vtiger_profile"; + $result2 = $adb->pquery($sql2, array()); + $current_profile_id = $adb->query_result($result2,0,'current_id'); + + //Inserting values into vtiger_profile2globalpermissions + $sql3 = "select * from vtiger_profile2globalpermissions where profileid=?"; + $params3 = array($parentProfileId); + $result3= $adb->pquery($sql3, $params3); + $p2tab_rows = $adb->num_rows($result3); + for($i=0; $i<$p2tab_rows; $i++) + { + $act_id=$adb->query_result($result3,$i,'globalactionid'); + $permissions=$adb->query_result($result3,$i,'globalactionpermission'); + $sql4="insert into vtiger_profile2globalpermissions values(?,?,?)"; + $params4 = array($current_profile_id, $act_id, $permissions); + $adb->pquery($sql4, $params4); + } + + //Inserting values into Profile2tab vtiger_table + $sql3 = "select * from vtiger_profile2tab where profileid=?"; + $params3 = array($parentProfileId); + $result3= $adb->pquery($sql3, $params3); + $p2tab_rows = $adb->num_rows($result3); + for($i=0; $i<$p2tab_rows; $i++) + { + $tab_id=$adb->query_result($result3,$i,'tabid'); + $permissions=$adb->query_result($result3,$i,'permissions'); + $sql4="insert into vtiger_profile2tab values(?,?,?)"; + $params4 = array($current_profile_id, $tab_id, $permissions); + $adb->pquery($sql4, $params4); + } + + //Inserting values into Profile2standard vtiger_table + $sql6 = "select * from vtiger_profile2standardpermissions where profileid=?"; + $params6 = array($parentProfileId); + $result6= $adb->pquery($sql6, $params6); + $p2per_rows = $adb->num_rows($result6); + for($i=0; $i<$p2per_rows; $i++) + { + $tab_id=$adb->query_result($result6,$i,'tabid'); + $action_id=$adb->query_result($result6,$i,'operation'); + $permissions=$adb->query_result($result6,$i,'permissions'); + $sql7="insert into vtiger_profile2standardpermissions values(?,?,?,?)"; + $params7 = array($current_profile_id, $tab_id, $action_id, $permissions); + $adb->pquery($sql7, $params7); + } + + //Inserting values into Profile2Utility vtiger_table + $sql8 = "select * from vtiger_profile2utility where profileid=?"; + $params8 = array($parentProfileId); + $result8= $adb->pquery($sql8, $params8); + $p2util_rows = $adb->num_rows($result8); + for($i=0; $i<$p2util_rows; $i++) + { + $tab_id=$adb->query_result($result8,$i,'tabid'); + $action_id=$adb->query_result($result8,$i,'activityid'); + $permissions=$adb->query_result($result8,$i,'permission'); + $sql9="insert into vtiger_profile2utility values(?,?,?,?)"; + $params9 = array($current_profile_id, $tab_id, $action_id, $permissions); + $adb->pquery($sql9, $params9); + } + + //Inserting values into Profile2field vtiger_table + $sql10 = "select * from vtiger_profile2field where profileid=?"; + $params10 = array($parentProfileId); + $result10= $adb->pquery($sql10, $params10); + $p2field_rows = $adb->num_rows($result10); + for($i=0; $i<$p2field_rows; $i++) + { + $tab_id=$adb->query_result($result10,$i,'tabid'); + $fieldid=$adb->query_result($result10,$i,'fieldid'); + $permissions=$adb->query_result($result10,$i,'visible'); + $readonly=$adb->query_result($result10,$i,'readonly'); + $sql11="insert into vtiger_profile2field values(?,?,?,?,?)"; + $params11 = array($current_profile_id, $tab_id, $fieldid, $permissions ,$readonly); + $adb->pquery($sql11, $params11); + } + $log->debug("Exiting createProfile method ..."); +} + +/** Function to delete vtiger_profile + * @param $transfer_profileid -- Profile Id to which the existing vtiger_role2profile relationships are to be transferred :: Type varchar + * @param $prof_id -- Profile Id to be deleted:: Type integer + */ +function deleteProfile($prof_id,$transfer_profileid='') +{ + global $log; +$log->debug("Entering deleteProfile(".$prof_id.",".$transfer_profileid.") method ..."); + global $adb; + //delete from vtiger_profile2global permissions + $sql4 = "delete from vtiger_profile2globalpermissions where profileid=?"; + $adb->pquery($sql4, array($prof_id)); + + //deleting from vtiger_profile 2 vtiger_tab; + $sql4 = "delete from vtiger_profile2tab where profileid=?"; + $adb->pquery($sql4, array($prof_id)); + + //deleting from vtiger_profile2standardpermissions vtiger_table + $sql5 = "delete from vtiger_profile2standardpermissions where profileid=?"; + $adb->pquery($sql5, array($prof_id)); + + //deleting from vtiger_profile2field + $sql6 ="delete from vtiger_profile2field where profileid=?"; + $adb->pquery($sql6, array($prof_id)); + + //deleting from vtiger_profile2utility + $sql7 ="delete from vtiger_profile2utility where profileid=?"; + $adb->pquery($sql7, array($prof_id)); + + //updating vtiger_role2profile + if(isset($transfer_profileid) && $transfer_profileid != '') + { + + $sql8 = "select roleid from vtiger_role2profile where profileid=?"; + $result = $adb->pquery($sql8, array($prof_id)); + $num_rows=$adb->num_rows($result); + + for($i=0;$i<$num_rows;$i++) + { + $roleid=$adb->query_result($result,$i,'roleid'); + $sql = "select profileid from vtiger_role2profile where roleid=?"; + $profresult=$adb->pquery($sql, array($roleid)); + $num=$adb->num_rows($profresult); + if($num>1) + { + $sql10="delete from vtiger_role2profile where roleid=? and profileid=?"; + $adb->pquery($sql10, array($roleid, $prof_id)); + } + else + { + $sql8 = "update vtiger_role2profile set profileid=? where profileid=? and roleid=?"; + $adb->pquery($sql8, array($transfer_profileid, $prof_id, $roleid)); + } + + + } + } + + //delete from vtiger_profile vtiger_table; + $sql9 = "delete from vtiger_profile where profileid=?"; + $adb->pquery($sql9, array($prof_id)); + $log->debug("Exiting deleteProfile method ..."); + +} + +/** Function to get all the vtiger_role information + * @returns $allRoleDetailArray-- Array will contain the details of all the vtiger_roles. RoleId will be the key:: Type array + */ +function getAllRoleDetails() +{ +global $log; +$log->debug("Entering getAllRoleDetails() method ..."); + global $adb; + $role_det = Array(); + $query = "select * from vtiger_role"; + $result = $adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + for($i=0; $i<$num_rows;$i++) + { + $each_role_det = Array(); + $roleid=$adb->query_result($result,$i,'roleid'); + $rolename=$adb->query_result($result,$i,'rolename'); + $roledepth=$adb->query_result($result,$i,'depth'); + $sub_roledepth=$roledepth + 1; + $parentrole=$adb->query_result($result,$i,'parentrole'); + $sub_role=''; + + //getting the immediate subordinates + $query1="select * from vtiger_role where parentrole like ? and depth=?"; + $res1 = $adb->pquery($query1, array($parentrole."::%", $sub_roledepth)); + $num_roles = $adb->num_rows($res1); + if($num_roles > 0) + { + for($j=0; $j<$num_roles; $j++) + { + if($j == 0) + { + $sub_role .= $adb->query_result($res1,$j,'roleid'); + } + else + { + $sub_role .= ','.$adb->query_result($res1,$j,'roleid'); + } + } + } + + + $each_role_det[]=$rolename; + $each_role_det[]=$roledepth; + $each_role_det[]=$sub_role; + $role_det[$roleid]=$each_role_det; + + } + $log->debug("Exiting getAllRoleDetails method ..."); + return $role_det; +} + + +/** Function to get all the vtiger_profile information + * @returns $allProfileInfoArray-- Array will contain the details of all the vtiger_profiles. Profile ID will be the key:: Type array + */ +function getAllProfileInfo() +{ + global $log; + $log->debug("Entering getAllProfileInfo() method ..."); + global $adb; + $query="select * from vtiger_profile"; + $result = $adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + $prof_details=Array(); + for($i=0;$i<$num_rows;$i++) + { + $profileid=$adb->query_result($result,$i,'profileid'); + $profilename=$adb->query_result($result,$i,'profilename'); + $prof_details[$profileid]=$profilename; + + } + $log->debug("Exiting getAllProfileInfo method ..."); + return $prof_details; +} + +/** Function to get the vtiger_role information of the specified vtiger_role + * @param $roleid -- RoleId :: Type varchar + * @returns $roleInfoArray-- RoleInfoArray in the following format: + * $roleInfo=Array($roleId=>Array($rolename,$parentrole,$roledepth,$immediateParent)); + */ +function getRoleInformation($roleid) +{ + global $log; + $log->debug("Entering getRoleInformation(".$roleid.") method ..."); + global $adb; + $query = "select * from vtiger_role where roleid=?"; + $result = $adb->pquery($query, array($roleid)); + $rolename=$adb->query_result($result,0,'rolename'); + $parentrole=$adb->query_result($result,0,'parentrole'); + $roledepth=$adb->query_result($result,0,'depth'); + $parentRoleArr=explode('::',$parentrole); + $immediateParent=$parentRoleArr[sizeof($parentRoleArr)-2]; + $roleDet=Array(); + $roleDet[]=$rolename; + $roleDet[]=$parentrole; + $roleDet[]=$roledepth; + $roleDet[]=$immediateParent; + $roleInfo=Array(); + $roleInfo[$roleid]=$roleDet; + $log->debug("Exiting getRoleInformation method ..."); + return $roleInfo; +} + + +/** Function to get the vtiger_role related vtiger_profiles + * @param $roleid -- RoleId :: Type varchar + * @returns $roleProfiles-- Role Related Profile Array in the following format: + * $roleProfiles=Array($profileId1=>$profileName,$profileId2=>$profileName,........,$profileIdn=>$profileName)); + */ +function getRoleRelatedProfiles($roleId) +{ + global $log; + $log->debug("Entering getRoleRelatedProfiles(".$roleId.") method ..."); + global $adb; + $query = "select vtiger_role2profile.*,vtiger_profile.profilename from vtiger_role2profile inner join vtiger_profile on vtiger_profile.profileid=vtiger_role2profile.profileid where roleid=?"; + $result = $adb->pquery($query, array($roleId)); + $num_rows=$adb->num_rows($result); + $roleRelatedProfiles=Array(); + for($i=0; $i<$num_rows; $i++) + { + $roleRelatedProfiles[$adb->query_result($result,$i,'profileid')]=$adb->query_result($result,$i,'profilename'); + } + $log->debug("Exiting getRoleRelatedProfiles method ..."); + return $roleRelatedProfiles; +} + + +/** Function to get the vtiger_role related vtiger_users + * @param $roleid -- RoleId :: Type varchar + * @returns $roleUsers-- Role Related User Array in the following format: + * $roleUsers=Array($userId1=>$userName,$userId2=>$userName,........,$userIdn=>$userName)); + */ +function getRoleUsers($roleId) +{ + global $log; + $log->debug("Entering getRoleUsers(".$roleId.") method ..."); + global $adb; + $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid where roleid=?"; + $result = $adb->pquery($query, array($roleId)); + $num_rows=$adb->num_rows($result); + $roleRelatedUsers=Array(); + for($i=0; $i<$num_rows; $i++) + { + $roleRelatedUsers[$adb->query_result($result,$i,'userid')]=$adb->query_result($result,$i,'user_name'); + } + $log->debug("Exiting getRoleUsers method ..."); + return $roleRelatedUsers; + + +} + + +/** Function to get the vtiger_role related user ids + * @param $roleid -- RoleId :: Type varchar + * @returns $roleUserIds-- Role Related User Array in the following format: + * $roleUserIds=Array($userId1,$userId2,........,$userIdn); + */ + +function getRoleUserIds($roleId) +{ + global $log; + $log->debug("Entering getRoleUserIds(".$roleId.") method ..."); + global $adb; + $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid where roleid=?"; + $result = $adb->pquery($query, array($roleId)); + $num_rows=$adb->num_rows($result); + $roleRelatedUsers=Array(); + for($i=0; $i<$num_rows; $i++) + { + $roleRelatedUsers[]=$adb->query_result($result,$i,'userid'); + } + $log->debug("Exiting getRoleUserIds method ..."); + return $roleRelatedUsers; + + +} + +/** Function to get the vtiger_role and subordinate vtiger_users + * @param $roleid -- RoleId :: Type varchar + * @returns $roleSubUsers-- Role and Subordinates Related Users Array in the following format: + * $roleSubUsers=Array($userId1=>$userName,$userId2=>$userName,........,$userIdn=>$userName)); + */ +function getRoleAndSubordinateUsers($roleId) +{ + global $log; + $log->debug("Entering getRoleAndSubordinateUsers(".$roleId.") method ..."); + global $adb; + $roleInfoArr=getRoleInformation($roleId); + $parentRole=$roleInfoArr[$roleId][1]; + $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ?"; + $result = $adb->pquery($query, array($parentRole."%")); + $num_rows=$adb->num_rows($result); + $roleRelatedUsers=Array(); + for($i=0; $i<$num_rows; $i++) + { + $roleRelatedUsers[$adb->query_result($result,$i,'userid')]=$adb->query_result($result,$i,'user_name'); + } + $log->debug("Exiting getRoleAndSubordinateUsers method ..."); + return $roleRelatedUsers; + + +} + + +/** Function to get the vtiger_role and subordinate user ids + * @param $roleid -- RoleId :: Type varchar + * @returns $roleSubUserIds-- Role and Subordinates Related Users Array in the following format: + * $roleSubUserIds=Array($userId1,$userId2,........,$userIdn); + */ +function getRoleAndSubordinateUserIds($roleId) +{ + global $log; + $log->debug("Entering getRoleAndSubordinateUserIds(".$roleId.") method ..."); + global $adb; + $roleInfoArr=getRoleInformation($roleId); + $parentRole=$roleInfoArr[$roleId][1]; + $query = "select vtiger_user2role.*,vtiger_users.user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ?"; + $result = $adb->pquery($query, array($parentRole."%")); + $num_rows=$adb->num_rows($result); + $roleRelatedUsers=Array(); + for($i=0; $i<$num_rows; $i++) + { + $roleRelatedUsers[]=$adb->query_result($result,$i,'userid'); + } + $log->debug("Exiting getRoleAndSubordinateUserIds method ..."); + return $roleRelatedUsers; + + +} + +/** Function to get the vtiger_role and subordinate Information for the specified vtiger_roleId + * @param $roleid -- RoleId :: Type varchar + * @returns $roleSubInfo-- Role and Subordinates Information array in the following format: + * $roleSubInfo=Array($roleId1=>Array($rolename,$parentrole,$roledepth,$immediateParent), $roleId2=>Array($rolename,$parentrole,$roledepth,$immediateParent),.....); + */ +function getRoleAndSubordinatesInformation($roleId) +{ + global $log; + $log->debug("Entering getRoleAndSubordinatesInformation(".$roleId.") method ..."); + global $adb; + $roleDetails=getRoleInformation($roleId); + $roleInfo=$roleDetails[$roleId]; + $roleParentSeq=$roleInfo[1]; + + $query="select * from vtiger_role where parentrole like ? order by parentrole asc"; + $result=$adb->pquery($query, array($roleParentSeq."%")); + $num_rows=$adb->num_rows($result); + $roleInfo=Array(); + for($i=0;$i<$num_rows;$i++) + { + $roleid=$adb->query_result($result,$i,'roleid'); + $rolename=$adb->query_result($result,$i,'rolename'); + $roledepth=$adb->query_result($result,$i,'depth'); + $parentrole=$adb->query_result($result,$i,'parentrole'); + $roleDet=Array(); + $roleDet[]=$rolename; + $roleDet[]=$parentrole; + $roleDet[]=$roledepth; + $roleInfo[$roleid]=$roleDet; + + } + $log->debug("Exiting getRoleAndSubordinatesInformation method ..."); + return $roleInfo; + +} + + +/** Function to get the vtiger_role and subordinate vtiger_role ids + * @param $roleid -- RoleId :: Type varchar + * @returns $roleSubRoleIds-- Role and Subordinates RoleIds in an Array in the following format: + * $roleSubRoleIds=Array($roleId1,$roleId2,........,$roleIdn); + */ +function getRoleAndSubordinatesRoleIds($roleId) +{ + global $log; + $log->debug("Entering getRoleAndSubordinatesRoleIds(".$roleId.") method ..."); + global $adb; + $roleDetails=getRoleInformation($roleId); + $roleInfo=$roleDetails[$roleId]; + $roleParentSeq=$roleInfo[1]; + + $query="select * from vtiger_role where parentrole like ? order by parentrole asc"; + $result=$adb->pquery($query, array($roleParentSeq."%")); + $num_rows=$adb->num_rows($result); + $roleInfo=Array(); + for($i=0;$i<$num_rows;$i++) + { + $roleid=$adb->query_result($result,$i,'roleid'); + $roleInfo[]=$roleid; + + } + $log->debug("Exiting getRoleAndSubordinatesRoleIds method ..."); + return $roleInfo; + +} + +/** Function to get delete the spcified vtiger_role + * @param $roleid -- RoleId :: Type varchar + * @param $transferRoleId -- RoleId to which vtiger_users of the vtiger_role that is being deleted are transferred:: Type varchar + */ +function deleteRole($roleId,$transferRoleId) +{ + global $log; + $log->debug("Entering deleteRole(".$roleId.",".$transferRoleId.") method ..."); + global $adb; + $roleInfo=getRoleAndSubordinatesInformation($roleId); + foreach($roleInfo as $roleid=>$roleDetArr) + { + + $sql1 = "update vtiger_user2role set roleid=? where roleid=?"; + $adb->pquery($sql1, array($transferRoleId, $roleid)); + + //Deleteing from vtiger_role2profile vtiger_table + $sql2 = "delete from vtiger_role2profile where roleid=?"; + $adb->pquery($sql2, array($roleid)); + + //delete handling for vtiger_groups + $sql10 = "delete from vtiger_group2role where roleid=?"; + $adb->pquery($sql10, array($roleid)); + + $sql11 = "delete from vtiger_group2rs where roleandsubid=?"; + $adb->pquery($sql11, array($roleid)); + + + //delete handling for sharing rules + deleteRoleRelatedSharingRules($roleid); + + //delete from vtiger_role vtiger_table; + $sql9 = "delete from vtiger_role where roleid=?"; + $adb->pquery($sql9, array($roleid)); + + + + } + $log->debug("Exiting deleteRole method ..."); + +} + +/** Function to delete the vtiger_role related sharing rules + * @param $roleid -- RoleId :: Type varchar + */ +function deleteRoleRelatedSharingRules($roleId) +{ + global $log; + $log->debug("Entering deleteRoleRelatedSharingRules(".$roleId.") method ..."); + global $adb; + $dataShareTableColArr=Array('vtiger_datashare_grp2role'=>'to_roleid', + 'vtiger_datashare_grp2rs'=>'to_roleandsubid', + 'vtiger_datashare_role2group'=>'share_roleid', + 'vtiger_datashare_role2role'=>'share_roleid::to_roleid', + 'vtiger_datashare_role2rs'=>'share_roleid::to_roleandsubid', + 'vtiger_datashare_rs2grp'=>'share_roleandsubid', + 'vtiger_datashare_rs2role'=>'share_roleandsubid::to_roleid', + 'vtiger_datashare_rs2rs'=>'share_roleandsubid::to_roleandsubid'); + + foreach($dataShareTableColArr as $tablename=>$colname) + { + $colNameArr=explode('::',$colname); + $query="select shareid from ".$tablename." where ".$colNameArr[0]."=?"; + $params = array($roleId); + if(sizeof($colNameArr) >1) + { + $query .=" or ".$colNameArr[1]."=?"; + array_push($params, $roleId); + } + + $result=$adb->pquery($query, $params); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $shareid=$adb->query_result($result,$i,'shareid'); + deleteSharingRule($shareid); + } + + } + $log->debug("Exiting deleteRoleRelatedSharingRules method ..."); +} + +/** Function to delete the group related sharing rules + * @param $roleid -- RoleId :: Type varchar + */ +function deleteGroupRelatedSharingRules($grpId) +{ + global $log; + $log->debug("Entering deleteGroupRelatedSharingRules(".$grpId.") method ..."); + + global $adb; + $dataShareTableColArr=Array('vtiger_datashare_grp2grp'=>'share_groupid::to_groupid', + 'vtiger_datashare_grp2role'=>'share_groupid', + 'vtiger_datashare_grp2rs'=>'share_groupid', + 'vtiger_datashare_role2group'=>'to_groupid', + 'vtiger_datashare_rs2grp'=>'to_groupid'); + + + foreach($dataShareTableColArr as $tablename=>$colname) + { + $colNameArr=explode('::',$colname); + $query="select shareid from ".$tablename." where ".$colNameArr[0]."=?"; + $params = array($grpId); + if(sizeof($colNameArr) >1) + { + $query .=" or ".$colNameArr[1]."=?"; + array_push($params, $grpId); + } + + $result=$adb->pquery($query, $params); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $shareid=$adb->query_result($result,$i,'shareid'); + deleteSharingRule($shareid); + } + + } + $log->debug("Exiting deleteGroupRelatedSharingRules method ..."); +} + + +/** Function to get userid and username of all vtiger_users + * @returns $userArray -- User Array in the following format: + * $userArray=Array($userid1=>$username, $userid2=>$username,............,$useridn=>$username); + */ +function getAllUserName() +{ + global $log; + $log->debug("Entering getAllUserName() method ..."); + global $adb; + $query="select * from vtiger_users where deleted=0"; + $result = $adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + $user_details=Array(); + for($i=0;$i<$num_rows;$i++) + { + $userid=$adb->query_result($result,$i,'id'); + $username=$adb->query_result($result,$i,'user_name'); + $user_details[$userid]=$username; + + } + $log->debug("Exiting getAllUserName method ..."); + return $user_details; + +} + + +/** Function to get groupid and groupname of all vtiger_groups + * @returns $grpArray -- Group Array in the following format: + * $grpArray=Array($grpid1=>$grpname, $grpid2=>$grpname,............,$grpidn=>$grpname); + */ +function getAllGroupName() +{ + global $log; + $log->debug("Entering getAllGroupName() method ..."); + global $adb; + $query="select * from vtiger_groups"; + $result = $adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + $group_details=Array(); + for($i=0;$i<$num_rows;$i++) + { + $grpid=$adb->query_result($result,$i,'groupid'); + $grpname=$adb->query_result($result,$i,'groupname'); + $group_details[$grpid]=$grpname; + + } + $log->debug("Exiting getAllGroupName method ..."); + return $group_details; + +} + +/** Function to get groupid and groupname of all for the given groupid + * @returns $grpArray -- Group Array in the following format: + * $grpArray=Array($grpid1=>$grpname); + */ +function getGroupDetails($id) +{ + global $log; + $log->debug("Entering getAllGroupDetails() method ..."); + global $adb; + $query="select * from vtiger_groups where groupid = ?"; + $result = $adb->pquery($query, array($id)); + $num_rows=$adb->num_rows($result); + if($num_rows < 1) + return null; + $group_details=Array(); + $grpid=$adb->query_result($result,0,'groupid'); + $grpname=$adb->query_result($result,0,'groupname'); + $grpdesc=$adb->query_result($result,0,'description'); + $group_details=Array($grpid,$grpname,$grpdesc); + + $log->debug("Exiting getAllGroupDetails method ..."); + return $group_details; + +} +/** Function to get group information of all vtiger_groups + * @returns $grpInfoArray -- Group Informaton array in the following format: + * $grpInfoArray=Array($grpid1=>Array($grpname,description) $grpid2=>Array($grpname,description),............,$grpidn=>Array($grpname,description)); + */ +function getAllGroupInfo() +{ + global $log; + $log->debug("Entering getAllGroupInfo() method ..."); + global $adb; + $query="select * from vtiger_groups"; + $result = $adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + $group_details=Array(); + for($i=0;$i<$num_rows;$i++) + { + $grpInfo=Array(); + $grpid=$adb->query_result($result,$i,'groupid'); + $grpname=$adb->query_result($result,$i,'groupname'); + $description=$adb->query_result($result,$i,'description'); + $grpInfo[0]=$grpname; + $grpInfo[1]=$description; + $group_details[$grpid]=$grpInfo; + + } + $log->debug("Exiting getAllGroupInfo method ..."); + return $group_details; + +} + +/** Function to create a group + * @param $groupName -- Group Name :: Type varchar + * @param $groupMemberArray -- Group Members (Groups,Roles,RolesAndsubordinates,Users) + * @param $groupName -- Group Name :: Type varchar + * @returns $groupId -- Group Id :: Type integer + */ +function createGroup($groupName,$groupMemberArray,$description) +{ + global $log; + $log->debug("Entering createGroup(".$groupName.",".$groupMemberArray.",".$description.") method ..."); + global $adb; + $groupId=$adb->getUniqueId("vtiger_users"); + //Insert into group vtiger_table + $query = "insert into vtiger_groups values(?,?,?)"; + $adb->pquery($query, array($groupId, $groupName, $description)); + + //Insert Group to Group Relation + $groupArray=$groupMemberArray['groups']; + $roleArray=$groupMemberArray['roles']; + $rsArray=$groupMemberArray['rs']; + $userArray=$groupMemberArray['users']; + + foreach($groupArray as $group_id) + { + insertGroupToGroupRelation($groupId,$group_id); + } + + //Insert Group to Role Relation + foreach($roleArray as $roleId) + { + insertGroupToRoleRelation($groupId,$roleId); + } + + //Insert Group to RoleAndSubordinate Relation + foreach($rsArray as $rsId) + { + insertGroupToRsRelation($groupId,$rsId); + } + + //Insert Group to Role Relation + foreach($userArray as $userId) + { + insertGroupToUserRelation($groupId,$userId); + } + $log->debug("Exiting createGroup method ..."); + return $groupId; +} + + +/** Function to insert group to group relation + * @param $groupId -- Group Id :: Type integer + * @param $containsGroupId -- Group Id :: Type integer + */ +function insertGroupToGroupRelation($groupId,$containsGroupId) +{ + global $log; + $log->debug("Entering insertGroupToGroupRelation(".$groupId.",".$containsGroupId.") method ..."); + global $adb; + $query="insert into vtiger_group2grouprel values(?,?)"; + $adb->pquery($query, array($groupId, $containsGroupId)); + $log->debug("Exiting insertGroupToGroupRelation method ..."); +} + + +/** Function to insert group to vtiger_role relation + * @param $groupId -- Group Id :: Type integer + * @param $roleId -- Role Id :: Type varchar + */ +function insertGroupToRoleRelation($groupId,$roleId) +{ + global $log; + $log->debug("Entering insertGroupToRoleRelation(".$groupId.",".$roleId.") method ..."); + global $adb; + $query="insert into vtiger_group2role values(?,?)"; + $adb->pquery($query, array($groupId, $roleId)); + $log->debug("Exiting insertGroupToRoleRelation method ..."); +} + + +/** Function to insert group to vtiger_role&subordinate relation + * @param $groupId -- Group Id :: Type integer + * @param $rsId -- Role Sub Id :: Type varchar + */ +function insertGroupToRsRelation($groupId,$rsId) +{ + global $log; + $log->debug("Entering insertGroupToRsRelation(".$groupId.",".$rsId.") method ..."); + global $adb; + $query="insert into vtiger_group2rs values(?,?)"; + $adb->pquery($query, array($groupId, $rsId)); + $log->debug("Exiting insertGroupToRsRelation method ..."); +} + +/** Function to insert group to user relation + * @param $groupId -- Group Id :: Type integer + * @param $userId -- User Id :: Type varchar + */ +function insertGroupToUserRelation($groupId,$userId) +{ + global $log; + $log->debug("Entering insertGroupToUserRelation(".$groupId.",".$userId.") method ..."); + global $adb; + $query="insert into vtiger_users2group values(?,?)"; + $adb->pquery($query, array($groupId, $userId)); + $log->debug("Exiting insertGroupToUserRelation method ..."); +} + + +/** Function to get the group Information of the specified group + * @param $groupId -- Group Id :: Type integer + * @returns Group Detail Array in the following format: + * $groupDetailArray=Array($groupName,$description,$groupMembers); + */ +function getGroupInfo($groupId) +{ + global $log; + $log->debug("Entering getGroupInfo(".$groupId.") method ..."); + global $adb; + $groupDetailArr=Array(); + $groupMemberArr=Array(); + //Retreving the group Info + $query="select * from vtiger_groups where groupid=?"; + $result = $adb->pquery($query, array($groupId)); + $groupName=$adb->query_result($result,0,'groupname'); + $description=$adb->query_result($result,0,'description'); + + //Retreving the Group RelatedMembers + $groupMemberArr=getGroupMembers($groupId); + $groupDetailArr[]=$groupName; + $groupDetailArr[]=$description; + $groupDetailArr[]=$groupMemberArr; + + //Returning the Group Detail Array + $log->debug("Exiting getGroupInfo method ..."); + return $groupDetailArr; + + +} + +/** Function to fetch the group name of the specified group + * @param $groupId -- Group Id :: Type integer + * @returns Group Name :: Type varchar + */ +function fetchGroupName($groupId) +{ + global $log; + $log->debug("Entering fetchGroupName(".$groupId.") method ..."); + + global $adb; + //Retreving the group Info + $query="select * from vtiger_groups where groupid=?"; + $result = $adb->pquery($query, array($groupId)); + $groupName=decode_html($adb->query_result($result,0,'groupname')); + $log->debug("Exiting fetchGroupName method ..."); + return $groupName; + +} + +/** Function to fetch the group members of the specified group + * @param $groupId -- Group Id :: Type integer + * @returns Group Member Array in the follwing format: + * $groupMemberArray=Array([groups]=>Array(groupid1,groupid2,groupid3,.....,groupidn), + * [roles]=>Array(roleid1,roleid2,roleid3,.....,roleidn), + * [rs]=>Array(roleid1,roleid2,roleid3,.....,roleidn), + * [users]=>Array(useridd1,userid2,userid3,.....,groupidn)) + */ +function getGroupMembers($groupId) +{ + global $log; + $log->debug("Entering getGroupMembers(".$groupId.") method ..."); + $groupMemberArr=Array(); + $roleGroupArr=getGroupRelatedRoles($groupId); + $rsGroupArr=getGroupRelatedRoleSubordinates($groupId); + $groupGroupArr=getGroupRelatedGroups($groupId); + $userGroupArr=getGroupRelatedUsers($groupId); + + $groupMemberArr['groups']=$groupGroupArr; + $groupMemberArr['roles']=$roleGroupArr; + $groupMemberArr['rs']=$rsGroupArr; + $groupMemberArr['users']=$userGroupArr; + + $log->debug("Exiting getGroupMembers method ..."); + return($groupMemberArr); +} + +/** Function to get the group related vtiger_roles of the specified group + * @param $groupId -- Group Id :: Type integer + * @returns Group Related Role Array in the follwing format: + * $groupRoles=Array(roleid1,roleid2,roleid3,.....,roleidn); + */ +function getGroupRelatedRoles($groupId) +{ + global $log; + $log->debug("Entering getGroupRelatedRoles(".$groupId.") method ..."); + global $adb; + $roleGroupArr=Array(); + $query="select * from vtiger_group2role where groupid=?"; + $result = $adb->pquery($query, array($groupId)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $roleId=$adb->query_result($result,$i,'roleid'); + $roleGroupArr[]=$roleId; + } + $log->debug("Exiting getGroupRelatedRoles method ..."); + return $roleGroupArr; + +} + + +/** Function to get the group related vtiger_roles and subordinates of the specified group + * @param $groupId -- Group Id :: Type integer + * @returns Group Related Roles & Subordinate Array in the follwing format: + * $groupRoleSubordinates=Array(roleid1,roleid2,roleid3,.....,roleidn); + */ +function getGroupRelatedRoleSubordinates($groupId) +{ + global $log; + $log->debug("Entering getGroupRelatedRoleSubordinates(".$groupId.") method ..."); + global $adb; + $rsGroupArr=Array(); + $query="select * from vtiger_group2rs where groupid=?"; + $result = $adb->pquery($query, array($groupId)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $roleSubId=$adb->query_result($result,$i,'roleandsubid'); + $rsGroupArr[]=$roleSubId; + } + $log->debug("Exiting getGroupRelatedRoleSubordinates method ..."); + return $rsGroupArr; +} + + +/** Function to get the group related vtiger_groups + * @param $groupId -- Group Id :: Type integer + * @returns Group Related Groups Array in the follwing format: + * $groupGroups=Array(grpid1,grpid2,grpid3,.....,grpidn); + */ +function getGroupRelatedGroups($groupId) +{ + global $log; + $log->debug("Entering getGroupRelatedGroups(".$groupId.") method ..."); + global $adb; + $groupGroupArr=Array(); + $query="select * from vtiger_group2grouprel where groupid=?"; + $result = $adb->pquery($query, array($groupId)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $relGroupId=$adb->query_result($result,$i,'containsgroupid'); + $groupGroupArr[]=$relGroupId; + } + $log->debug("Exiting getGroupRelatedGroups method ..."); + return $groupGroupArr; + +} + +/** Function to get the group related vtiger_users + * @param $userId -- User Id :: Type integer + * @returns Group Related Users Array in the follwing format: + * $groupUsers=Array(userid1,userid2,userid3,.....,useridn); + */ +function getGroupRelatedUsers($groupId) +{ + global $log; + $log->debug("Entering getGroupRelatedUsers(".$groupId.") method ..."); + global $adb; + $userGroupArr=Array(); + $query="select * from vtiger_users2group where groupid=?"; + $result = $adb->pquery($query, array($groupId)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $userId=$adb->query_result($result,$i,'userid'); + $userGroupArr[]=$userId; + } + $log->debug("Exiting getGroupRelatedUsers method ..."); + return $userGroupArr; + +} + +/** Function to update the group + * @param $groupId -- Group Id :: Type integer + * @param $groupName -- Group Name :: Type varchar + * @param $groupMemberArray -- Group Members Array :: Type array + * @param $description -- Description :: Type text + */ +function updateGroup($groupId,$groupName,$groupMemberArray,$description) +{ + global $log; + $log->debug("Entering updateGroup(".$groupId.",".$groupName.",".$groupMemberArray.",".$description.") method ..."); + global $adb; + $query="update vtiger_groups set groupname=?, description=? where groupid=?"; + $adb->pquery($query, array($groupName, $description, $groupId)); + + //Deleting the Group Member Relation + deleteGroupRelatedGroups($groupId); + deleteGroupRelatedRoles($groupId); + deleteGroupRelatedRolesAndSubordinates($groupId); + deleteGroupRelatedUsers($groupId); + + //Inserting the Group Member Entries + $groupArray=$groupMemberArray['groups']; + $roleArray=$groupMemberArray['roles']; + $rsArray=$groupMemberArray['rs']; + $userArray=$groupMemberArray['users']; + + foreach($groupArray as $group_id) + { + insertGroupToGroupRelation($groupId,$group_id); + } + + //Insert Group to Role Relation + foreach($roleArray as $roleId) + { + insertGroupToRoleRelation($groupId,$roleId); + } + + //Insert Group to RoleAndSubordinate Relation + foreach($rsArray as $rsId) + { + insertGroupToRsRelation($groupId,$rsId); + } + + //Insert Group to Role Relation + foreach($userArray as $userId) + { + insertGroupToUserRelation($groupId,$userId); + } + $log->debug("Exiting updateGroup method ..."); + +} + +/** Function to delete the specified group + * @param $groupId -- Group Id :: Type integer + * @param $transferId -- Id of the group/user to which record ownership is to be transferred:: Type integer + * @param $transferType -- It can have only two values namely 'Groups' or 'Users'. This determines whether the owneship is to be transferred to a group or user :: Type varchar + */ +function deleteGroup($groupId,$transferId) +{ + global $log; + $log->debug("Entering deleteGroup(".$groupId.") method ..."); + global $adb; + + tranferGroupOwnership($groupId,$transferId); + deleteGroupRelatedSharingRules($groupId); + + $query="delete from vtiger_groups where groupid=?"; + $adb->pquery($query, array($groupId)); + + deleteGroupRelatedGroups($groupId); + deleteGroupRelatedRoles($groupId); + deleteGroupReportRelations($groupId); + deleteGroupRelatedRolesAndSubordinates($groupId); + deleteGroupRelatedUsers($groupId); + $log->debug("Exiting deleteGroup method ..."); +} + + +/** Function to transfer the ownership of records owned by a particular group to the specified group + * @param $groupId -- Group Id of the group which's record ownership has to be transferred:: Type integer + * @param $transferId -- Id of the group/user to which record ownership is to be transferred:: Type integer + * @param $transferType -- It can have only two values namely 'Groups' or 'Users'. This determines whether the owneship is to be transferred to a group or user :: Type varchar + */ +function tranferGroupOwnership($groupId,$transferId) +{ + global $log; + $log->debug("Entering tranferGroupOwnership(".$groupId.") method ..."); + global $adb; + + $query = "update vtiger_crmentity set smownerid=? where smownerid=?"; + $params = array($transferId, $groupId); + $adb->pquery($query, $params); + + $log->debug("Exiting tranferGroupOwnership method ..."); +} + +/** Function to delete group to group relation of the specified group + * @param $groupId -- Group Id :: Type integer + */ +function deleteGroupRelatedGroups($groupId) +{ + global $log; + $log->debug("Entering deleteGroupRelatedGroups(".$groupId.") method ..."); + global $adb; + $query="delete from vtiger_group2grouprel where groupid=?"; + $adb->pquery($query, array($groupId)); + $log->debug("Exiting deleteGroupRelatedGroups method ..."); +} + + +/** Function to delete group to vtiger_role relation of the specified group + * @param $groupId -- Group Id :: Type integer + */ +function deleteGroupRelatedRoles($groupId) +{ + global $log; + $log->debug("Entering deleteGroupRelatedRoles(".$groupId.") method ..."); + global $adb; + $query="delete from vtiger_group2role where groupid=?"; + $adb->pquery($query, array($groupId)); + $log->debug("Exiting deleteGroupRelatedRoles method ..."); +} + + +/** Function to delete group to vtiger_role and subordinates relation of the specified group + * @param $groupId -- Group Id :: Type integer + */ +function deleteGroupRelatedRolesAndSubordinates($groupId) +{ + global $log; + $log->debug("Entering deleteGroupRelatedRolesAndSubordinates(".$groupId.") method ..."); + global $adb; + $query="delete from vtiger_group2rs where groupid=?"; + $adb->pquery($query, array($groupId)); + $log->debug("Exiting deleteGroupRelatedRolesAndSubordinates method ..."); +} + + +/** Function to delete group to user relation of the specified group + * @param $groupId -- Group Id :: Type integer + */ +function deleteGroupRelatedUsers($groupId) +{ + global $log; + $log->debug("Entering deleteGroupRelatedUsers(".$groupId.") method ..."); + global $adb; + $query="delete from vtiger_users2group where groupid=?"; + $adb->pquery($query, array($groupId)); + $log->debug("Exiting deleteGroupRelatedUsers method ..."); +} + +/** This function returns the Default Organisation Sharing Action Name + * @param $share_action_id -- It takes the Default Organisation Sharing ActionId as input :: Type Integer + * @returns The sharing Action Name :: Type Varchar + */ +function getDefOrgShareActionName($share_action_id) +{ + global $log; + $log->debug("Entering getDefOrgShareActionName(".$share_action_id.") method ..."); + global $adb; + $query="select * from vtiger_org_share_action_mapping where share_action_id=?"; + $result=$adb->pquery($query, array($share_action_id)); + $share_action_name=$adb->query_result($result,0,"share_action_name"); + $log->debug("Exiting getDefOrgShareActionName method ..."); + return $share_action_name; + + +} +/** This function returns the Default Organisation Sharing Action Array for the specified Module + * It takes the module tabid as input and constructs the array. + * The output array consists of the 'Default Organisation Sharing Id'=>'Default Organisation Sharing Action' mapping for all the sharing actions available for the specifed module + * The output Array will be in the following format: + * Array = (Default Org ActionId1=>Default Org ActionName1, + * Default Org ActionId2=>Default Org ActionName2, + * | + * | + * Default Org ActionIdn=>Default Org ActionNamen) + */ +function getModuleSharingActionArray($tabid) +{ + global $log; + $log->debug("Entering getModuleSharingActionArray(".$tabid.") method ..."); + global $adb; + $share_action_arr=Array(); + $query = "select vtiger_org_share_action_mapping.share_action_name,vtiger_org_share_action2tab.share_action_id from vtiger_org_share_action2tab inner join vtiger_org_share_action_mapping on vtiger_org_share_action2tab.share_action_id=vtiger_org_share_action_mapping.share_action_id where vtiger_org_share_action2tab.tabid=?"; + $result=$adb->pquery($query, array($tabid)); + $num_rows=$adb->num_rows($result); + for($i=0; $i<$num_rows; $i++) + { + $share_action_name=$adb->query_result($result,$i,"share_action_name"); + $share_action_id=$adb->query_result($result,$i,"share_action_id"); + $share_action_arr[$share_action_id] = $share_action_name; + } + $log->debug("Exiting getModuleSharingActionArray method ..."); + return $share_action_arr; + +} + +/** This function adds a organisation level sharing rule for the specified Module + * It takes the following input parameters: + * $tabid -- Module tabid - Datatype::Integer + * $shareEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String + * $toEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String + * $shareEntityId -- The id of the group,role,rs,user to be shared + * $toEntityId -- The id of the group,role,rs,user to which the specified entity is to be shared + * $sharePermisson -- This can have the following values: + * 0 - Read Only + * 1 - Read/Write + * This function will return the shareid as output + */ +function addSharingRule($tabid,$shareEntityType,$toEntityType,$shareEntityId,$toEntityId,$sharePermission) +{ + global $log; + $log->debug("Entering addSharingRule(".$tabid.",".$shareEntityType.",".$toEntityType.",".$shareEntityId.",".$toEntityId.",".$sharePermission.") method ..."); + + global $adb; + $shareid=$adb->getUniqueId("vtiger_datashare_module_rel"); + + + if($shareEntityType == 'groups' && $toEntityType == 'groups') + { + $type_string='GRP::GRP'; + $query = "insert into vtiger_datashare_grp2grp values(?,?,?,?)"; + } + elseif($shareEntityType == 'groups' && $toEntityType == 'roles') + { + + $type_string='GRP::ROLE'; + $query = "insert into vtiger_datashare_grp2role values(?,?,?,?)"; + } + elseif($shareEntityType == 'groups' && $toEntityType == 'rs') + { + + $type_string='GRP::RS'; + $query = "insert into vtiger_datashare_grp2rs values(?,?,?,?)"; + } + elseif($shareEntityType == 'roles' && $toEntityType == 'groups') + { + + $type_string='ROLE::GRP'; + $query = "insert into vtiger_datashare_role2group values(?,?,?,?)"; + } + elseif($shareEntityType == 'roles' && $toEntityType == 'roles') + { + + $type_string='ROLE::ROLE'; + $query = "insert into vtiger_datashare_role2role values(?,?,?,?)"; + } + elseif($shareEntityType == 'roles' && $toEntityType == 'rs') + { + + $type_string='ROLE::RS'; + $query = "insert into vtiger_datashare_role2rs values(?,?,?,?)"; + } + elseif($shareEntityType == 'rs' && $toEntityType == 'groups') + { + + $type_string='RS::GRP'; + $query = "insert into vtiger_datashare_rs2grp values(?,?,?,?)"; + } + elseif($shareEntityType == 'rs' && $toEntityType == 'roles') + { + + $type_string='RS::ROLE'; + $query = "insert into vtiger_datashare_rs2role values(?,?,?,?)"; + } + elseif($shareEntityType == 'rs' && $toEntityType == 'rs') + { + + $type_string='RS::RS'; + $query = "insert into vtiger_datashare_rs2rs values(?,?,?,?)"; + } + $query1 = "insert into vtiger_datashare_module_rel values(?,?,?)"; + $adb->pquery($query1, array($shareid, $tabid, $type_string)); + + $params = array($shareid, $shareEntityId, $toEntityId, $sharePermission); + $adb->pquery($query, $params); + $log->debug("Exiting addSharingRule method ..."); + return $shareid; + +} + + +/** This function is to update the organisation level sharing rule + * It takes the following input parameters: + * $shareid -- Id of the Sharing Rule to be updated + * $tabid -- Module tabid - Datatype::Integer + * $shareEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String + * $toEntityType -- The Entity Type may be vtiger_groups,roles,rs and vtiger_users - Datatype::String + * $shareEntityId -- The id of the group,role,rs,user to be shared + * $toEntityId -- The id of the group,role,rs,user to which the specified entity is to be shared + * $sharePermisson -- This can have the following values: + * 0 - Read Only + * 1 - Read/Write + * This function will return the shareid as output + */ +function updateSharingRule($shareid,$tabid,$shareEntityType,$toEntityType,$shareEntityId,$toEntityId,$sharePermission) +{ + global $log; + $log->debug("Entering updateSharingRule(".$shareid.",".$tabid.",".$shareEntityType.",".$toEntityType.",".$shareEntityId.",".$toEntityId.",".$sharePermission.") method ..."); + + global $adb; + $query2="select * from vtiger_datashare_module_rel where shareid=?"; + $res=$adb->pquery($query2, array($shareid)); + $typestr=$adb->query_result($res,0,'relationtype'); + $tabname=getDSTableNameForType($typestr); + $query3="delete from ".$tabname." where shareid=?"; + $adb->pquery($query3, array($shareid)); + + + if($shareEntityType == 'groups' && $toEntityType == 'groups') + { + $type_string='GRP::GRP'; + $query = "insert into vtiger_datashare_grp2grp values(?,?,?,?)"; + } + elseif($shareEntityType == 'groups' && $toEntityType == 'roles') + { + + $type_string='GRP::ROLE'; + $query = "insert into vtiger_datashare_grp2role values(?,?,?,?)"; + } + elseif($shareEntityType == 'groups' && $toEntityType == 'rs') + { + + $type_string='GRP::RS'; + $query = "insert into vtiger_datashare_grp2rs values(?,?,?,?)"; + } + elseif($shareEntityType == 'roles' && $toEntityType == 'groups') + { + + $type_string='ROLE::GRP'; + $query = "insert into vtiger_datashare_role2group values(?,?,?,?)"; + } + elseif($shareEntityType == 'roles' && $toEntityType == 'roles') + { + + $type_string='ROLE::ROLE'; + $query = "insert into vtiger_datashare_role2role values(?,?,?,?)"; + } + elseif($shareEntityType == 'roles' && $toEntityType == 'rs') + { + + $type_string='ROLE::RS'; + $query = "insert into vtiger_datashare_role2rs values(?,?,?,?)"; + } + elseif($shareEntityType == 'rs' && $toEntityType == 'groups') + { + + $type_string='RS::GRP'; + $query = "insert into vtiger_datashare_rs2grp values(?,?,?,?)"; + } + elseif($shareEntityType == 'rs' && $toEntityType == 'roles') + { + + $type_string='RS::ROLE'; + $query = "insert into vtiger_datashare_rs2role values(?,?,?,?)"; + } + elseif($shareEntityType == 'rs' && $toEntityType == 'rs') + { + + $type_string='RS::RS'; + $query = "insert into vtiger_datashare_rs2rs values(?,?,?,?)"; + } + + $query1 = "update vtiger_datashare_module_rel set relationtype=? where shareid=?"; + $adb->pquery($query1, array($type_string, $shareid)); + + $params = array($shareid, $shareEntityId, $toEntityId, $sharePermission); + $adb->pquery($query, $params); + $log->debug("Exiting updateSharingRule method ..."); + return $shareid; + +} + + +/** This function is to delete the organisation level sharing rule + * It takes the following input parameters: + * $shareid -- Id of the Sharing Rule to be updated + */ +function deleteSharingRule($shareid) +{ + global $log; + $log->debug("Entering deleteSharingRule(".$shareid.") method ..."); + global $adb; + $query2="select * from vtiger_datashare_module_rel where shareid=?"; + $res=$adb->pquery($query2, array($shareid)); + $typestr=$adb->query_result($res,0,'relationtype'); + $tabname=getDSTableNameForType($typestr); + $query3="delete from $tabname where shareid=?"; + $adb->pquery($query3, array($shareid)); + $query4="delete from vtiger_datashare_module_rel where shareid=?"; + $adb->pquery($query4, array($shareid)); + + //deleting the releated module sharing permission + $query5="delete from vtiger_datashare_relatedmodule_permission where shareid=?"; + $adb->pquery($query5, array($shareid)); + $log->debug("Exiting deleteSharingRule method ..."); + +} + +/** Function get the Data Share Table and their columns + * @returns -- Data Share Table and Column Array in the following format: + * $dataShareTableColArr=Array('datashare_grp2grp'=>'share_groupid::to_groupid', + * 'datashare_grp2role'=>'share_groupid::to_roleid', + * 'datashare_grp2rs'=>'share_groupid::to_roleandsubid', + * 'datashare_role2group'=>'share_roleid::to_groupid', + * 'datashare_role2role'=>'share_roleid::to_roleid', + * 'datashare_role2rs'=>'share_roleid::to_roleandsubid', + * 'datashare_rs2grp'=>'share_roleandsubid::to_groupid', + * 'datashare_rs2role'=>'share_roleandsubid::to_roleid', + * 'datashare_rs2rs'=>'share_roleandsubid::to_roleandsubid'); + */ +function getDataShareTableandColumnArray() +{ + global $log; + $log->debug("Entering getDataShareTableandColumnArray() method ..."); + $dataShareTableColArr=Array('vtiger_datashare_grp2grp'=>'share_groupid::to_groupid', + 'vtiger_datashare_grp2role'=>'share_groupid::to_roleid', + 'vtiger_datashare_grp2rs'=>'share_groupid::to_roleandsubid', + 'vtiger_datashare_role2group'=>'share_roleid::to_groupid', + 'vtiger_datashare_role2role'=>'share_roleid::to_roleid', + 'vtiger_datashare_role2rs'=>'share_roleid::to_roleandsubid', + 'vtiger_datashare_rs2grp'=>'share_roleandsubid::to_groupid', + 'vtiger_datashare_rs2role'=>'share_roleandsubid::to_roleid', + 'vtiger_datashare_rs2rs'=>'share_roleandsubid::to_roleandsubid'); + $log->debug("Exiting getDataShareTableandColumnArray method ..."); + return $dataShareTableColArr; + +} + + + +/** Function get the Data Share Column Names for the specified Table Name + * @param $tableName -- DataShare Table Name :: Type Varchar + * @returns Column Name -- Type Varchar + * + */ +function getDSTableColumns($tableName) +{ + global $log; + $log->debug("Entering getDSTableColumns(".$tableName.") method ..."); + $dataShareTableColArr=getDataShareTableandColumnArray(); + + $dsTableCols=$dataShareTableColArr[$tableName]; + $dsTableColsArr=explode('::',$dsTableCols); + $log->debug("Exiting getDSTableColumns method ..."); + return $dsTableColsArr; + +} + + +/** Function get the Data Share Table Names + * @returns the following Date Share Table Name Array: + * $dataShareTableColArr=Array('GRP::GRP'=>'datashare_grp2grp', + * 'GRP::ROLE'=>'datashare_grp2role', + * 'GRP::RS'=>'datashare_grp2rs', + * 'ROLE::GRP'=>'datashare_role2group', + * 'ROLE::ROLE'=>'datashare_role2role', + * 'ROLE::RS'=>'datashare_role2rs', + * 'RS::GRP'=>'datashare_rs2grp', + * 'RS::ROLE'=>'datashare_rs2role', + * 'RS::RS'=>'datashare_rs2rs'); + */ +function getDataShareTableName() +{ + global $log; + $log->debug("Entering getDataShareTableName() method ..."); + $dataShareTableColArr=Array('GRP::GRP'=>'vtiger_datashare_grp2grp', + 'GRP::ROLE'=>'vtiger_datashare_grp2role', + 'GRP::RS'=>'vtiger_datashare_grp2rs', + 'ROLE::GRP'=>'vtiger_datashare_role2group', + 'ROLE::ROLE'=>'vtiger_datashare_role2role', + 'ROLE::RS'=>'vtiger_datashare_role2rs', + 'RS::GRP'=>'vtiger_datashare_rs2grp', + 'RS::ROLE'=>'vtiger_datashare_rs2role', + 'RS::RS'=>'vtiger_datashare_rs2rs'); + $log->debug("Exiting getDataShareTableName method ..."); + return $dataShareTableColArr; + +} + +/** Function to get the Data Share Table Name from the speciified type string + * @param $typeString -- Datashare Type Sting :: Type Varchar + * @returns Table Name -- Type Varchar + * + */ +function getDSTableNameForType($typeString) +{ + global $log; + $log->debug("Entering getDSTableNameForType(".$typeString.") method ..."); + $dataShareTableColArr=getDataShareTableName(); + $tableName=$dataShareTableColArr[$typeString]; + $log->debug("Exiting getDSTableNameForType method ..."); + return $tableName; + +} + +/** Function to get the Entity type from the specified DataShare Table Column Name + * @param $colname -- Datashare Table Column Name :: Type Varchar + * @returns The entity type. The entity type may be vtiger_groups or vtiger_roles or rs -- Type Varchar + */ +function getEntityTypeFromCol($colName) +{ + global $log; + $log->debug("Entering getEntityTypeFromCol(".$colName.") method ..."); + + if($colName == 'share_groupid' || $colName == 'to_groupid') + { + $entity_type='groups'; + } + elseif($colName =='share_roleid' || $colName =='to_roleid') + { + $entity_type='roles'; + } + elseif($colName == 'share_roleandsubid' || $colName == 'to_roleandsubid') + { + $entity_type='rs'; + } + + $log->debug("Exiting getEntityTypeFromCol method ..."); + return $entity_type; + +} + +/** Function to get the Entity Display Link + * @param $entityid -- Entity Id + * @params $entityType -- The entity type may be vtiger_groups or vtiger_roles or rs -- Type Varchar + * @returns the Entity Display link + */ +function getEntityDisplayLink($entityType,$entityid) +{ + global $log; + $log->debug("Entering getEntityDisplayLink(".$entityType.",".$entityid.") method ..."); + if($entityType == 'groups') + { + $groupNameArr = getGroupInfo($entityid); + $display_out = "Group::". $groupNameArr[0]." "; + } + elseif($entityType == 'roles') + { + $roleName=getRoleName($entityid); + $display_out = "Role::".$roleName. ""; + } + elseif($entityType == 'rs') + { + $roleName=getRoleName($entityid); + $display_out = "RoleAndSubordinate::".$roleName. ""; + } + $log->debug("Exiting getEntityDisplayLink method ..."); + return $display_out; + +} + + +/** Function to get the Sharing rule Info + * @param $shareId -- Sharing Rule Id + * @returns Sharing Rule Information Array in the following format: + * $shareRuleInfoArr=Array($shareId, $tabid, $type, $share_ent_type, $to_ent_type, $share_entity_id, $to_entity_id,$permission); + */ +function getSharingRuleInfo($shareId) +{ + global $log; + $log->debug("Entering getSharingRuleInfo(".$shareId.") method ..."); + global $adb; + $shareRuleInfoArr=Array(); + $query="select * from vtiger_datashare_module_rel where shareid=?"; + $result=$adb->pquery($query, array($shareId)); + //Retreving the Sharing Tabid + $tabid=$adb->query_result($result,0,'tabid'); + $type=$adb->query_result($result,0,'relationtype'); + + //Retreiving the Sharing Table Name + $tableName=getDSTableNameForType($type); + + //Retreiving the Sharing Col Names + $dsTableColArr=getDSTableColumns($tableName); + $share_ent_col=$dsTableColArr[0]; + $to_ent_col=$dsTableColArr[1]; + + //Retreiving the Sharing Entity Col Types + $share_ent_type=getEntityTypeFromCol($share_ent_col); + $to_ent_type=getEntityTypeFromCol($to_ent_col); + + //Retreiving the Value from Table + $query1="select * from $tableName where shareid=?"; + $result1=$adb->pquery($query1, array($shareId)); + $share_id=$adb->query_result($result1,0,$share_ent_col); + $to_id=$adb->query_result($result1,0,$to_ent_col); + $permission=$adb->query_result($result1,0,'permission'); + + //Constructing the Array + $shareRuleInfoArr[]=$shareId; + $shareRuleInfoArr[]=$tabid; + $shareRuleInfoArr[]=$type; + $shareRuleInfoArr[]=$share_ent_type; + $shareRuleInfoArr[]=$to_ent_type; + $shareRuleInfoArr[]=$share_id; + $shareRuleInfoArr[]=$to_id; + $shareRuleInfoArr[]=$permission; + + $log->debug("Exiting getSharingRuleInfo method ..."); + return $shareRuleInfoArr; + + + +} + +/** This function is to retreive the list of related sharing modules for the specifed module + * It takes the following input parameters: + * $tabid -- The module tabid:: Type Integer + */ + +function getRelatedSharingModules($tabid) +{ + global $log; + $log->debug("Entering getRelatedSharingModules(".$tabid.") method ..."); + global $adb; + $relatedSharingModuleArray=Array(); + $query="select * from vtiger_datashare_relatedmodules where tabid=?"; + $result=$adb->pquery($query, array($tabid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $ds_relmod_id=$adb->query_result($result,$i,'datashare_relatedmodule_id'); + $rel_tabid=$adb->query_result($result,$i,'relatedto_tabid'); + $relatedSharingModuleArray[$rel_tabid]=$ds_relmod_id; + + } + $log->debug("Exiting getRelatedSharingModules method ..."); + return $relatedSharingModuleArray; + +} + + +/** This function is to add the related module sharing permission for a particulare Sharing Rule + * It takes the following input parameters: + * $shareid -- The Sharing Rule Id:: Type Integer + * $tabid -- The module tabid:: Type Integer + * $relatedtabid -- The related module tabid:: Type Integer + * $sharePermisson -- This can have the following values: + * 0 - Read Only + * 1 - Read/Write + */ + +function addRelatedModuleSharingPermission($shareid,$tabid,$relatedtabid,$sharePermission) +{ + global $log; + $log->debug("Entering addRelatedModuleSharingPermission(".$shareid.",".$tabid.",".$relatedtabid.",".$sharePermission.") method ..."); + global $adb; + $relatedModuleSharingId=getRelatedModuleSharingId($tabid,$relatedtabid); + $query="insert into vtiger_datashare_relatedmodule_permission values(?,?,?)" ; + $result=$adb->pquery($query, array($shareid, $relatedModuleSharingId, $sharePermission)); + $log->debug("Exiting addRelatedModuleSharingPermission method ..."); +} + +/** This function is to update the related module sharing permission for a particulare Sharing Rule + * It takes the following input parameters: + * $shareid -- The Sharing Rule Id:: Type Integer + * $tabid -- The module tabid:: Type Integer + * $relatedtabid -- The related module tabid:: Type Integer + * $sharePermisson -- This can have the following values: + * 0 - Read Only + * 1 - Read/Write + */ + +function updateRelatedModuleSharingPermission($shareid,$tabid,$relatedtabid,$sharePermission) +{ + global $log; + $log->debug("Entering updateRelatedModuleSharingPermission(".$shareid.",".$tabid.",".$relatedtabid.",".$sharePermission.") method ..."); + global $adb; + $relatedModuleSharingId=getRelatedModuleSharingId($tabid,$relatedtabid); + $query="update vtiger_datashare_relatedmodule_permission set permission=? where shareid=? and datashare_relatedmodule_id=?"; + $result=$adb->pquery($query, array($sharePermission, $shareid, $relatedModuleSharingId)); + $log->debug("Exiting updateRelatedModuleSharingPermission method ..."); +} + +/** This function is to retreive the Related Module Sharing Id + * It takes the following input parameters: + * $tabid -- The module tabid:: Type Integer + * $related_tabid -- The related module tabid:: Type Integer + * This function returns the Related Module Sharing Id + */ + +function getRelatedModuleSharingId($tabid,$related_tabid) +{ + global $log; + $log->debug("Entering getRelatedModuleSharingId(".$tabid.",".$related_tabid.") method ..."); + global $adb; + $query="select datashare_relatedmodule_id from vtiger_datashare_relatedmodules where tabid=? and relatedto_tabid=?"; + $result=$adb->pquery($query, array($tabid, $related_tabid)); + $relatedModuleSharingId=$adb->query_result($result,0,'datashare_relatedmodule_id'); + $log->debug("Exiting getRelatedModuleSharingId method ..."); + return $relatedModuleSharingId; + +} + +/** This function is to retreive the Related Module Sharing Permissions for the specified Sharing Rule + * It takes the following input parameters: + * $shareid -- The Sharing Rule Id:: Type Integer + *This function will return the Related Module Sharing permissions in an Array in the following format: + * $PermissionArray=($relatedTabid1=>$sharingPermission1, + * $relatedTabid2=>$sharingPermission2, + * | + * | + * $relatedTabid-n=>$sharingPermission-n) + */ +function getRelatedModuleSharingPermission($shareid) +{ + global $log; + $log->debug("Entering getRelatedModuleSharingPermission(".$shareid.") method ..."); + global $adb; + $relatedSharingModulePermissionArray=Array(); + $query="select vtiger_datashare_relatedmodules.*,vtiger_datashare_relatedmodule_permission.permission from vtiger_datashare_relatedmodules inner join vtiger_datashare_relatedmodule_permission on vtiger_datashare_relatedmodule_permission.datashare_relatedmodule_id=vtiger_datashare_relatedmodules.datashare_relatedmodule_id where vtiger_datashare_relatedmodule_permission.shareid=?"; + $result=$adb->pquery($query, array($shareid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $relatedto_tabid=$adb->query_result($result,$i,'relatedto_tabid'); + $permission=$adb->query_result($result,$i,'permission'); + $relatedSharingModulePermissionArray[$relatedto_tabid]=$permission; + + + } + $log->debug("Exiting getRelatedModuleSharingPermission method ..."); + return $relatedSharingModulePermissionArray; + +} + + +/** This function is to retreive the vtiger_profiles associated with the the specified user + * It takes the following input parameters: + * $userid -- The User Id:: Type Integer + *This function will return the vtiger_profiles associated to the specified vtiger_users in an Array in the following format: + * $userProfileArray=(profileid1,profileid2,profileid3,...,profileidn); + */ +function getUserProfile($userId) +{ + global $log; + $log->debug("Entering getUserProfile(".$userId.") method ..."); + global $adb; + $roleId=fetchUserRole($userId); + $profArr=Array(); + $sql1 = "select profileid from vtiger_role2profile where roleid=?"; + $result1 = $adb->pquery($sql1, array($roleId)); + $num_rows=$adb->num_rows($result1); + for($i=0;$i<$num_rows;$i++) + { + + $profileid= $adb->query_result($result1,$i,"profileid"); + $profArr[]=$profileid; + } + $log->debug("Exiting getUserProfile method ..."); + return $profArr; + +} + +/** To retreive the global permission of the specifed user from the various vtiger_profiles associated with the user + * @param $userid -- The User Id:: Type Integer + * @returns user global permission array in the following format: + * $gloabalPerrArray=(view all action id=>permission, + edit all action id=>permission) ); + */ +function getCombinedUserGlobalPermissions($userId) +{ + global $log; + $log->debug("Entering getCombinedUserGlobalPermissions(".$userId.") method ..."); + global $adb; + $profArr=getUserProfile($userId); + $no_of_profiles=sizeof($profArr); + $userGlobalPerrArr=Array(); + + $userGlobalPerrArr=getProfileGlobalPermission($profArr[0]); + if($no_of_profiles != 1) + { + for($i=1;$i<$no_of_profiles;$i++) + { + $tempUserGlobalPerrArr=getProfileGlobalPermission($profArr[$i]); + + foreach($userGlobalPerrArr as $globalActionId=>$globalActionPermission) + { + if($globalActionPermission == 1) + { + $now_permission = $tempUserGlobalPerrArr[$globalActionId]; + if($now_permission == 0) + { + $userGlobalPerrArr[$globalActionId]=$now_permission; + } + + + } + + } + + } + + } + + $log->debug("Exiting getCombinedUserGlobalPermissions method ..."); + return $userGlobalPerrArr; + +} + +/** To retreive the vtiger_tab permissions of the specifed user from the various vtiger_profiles associated with the user + * @param $userid -- The User Id:: Type Integer + * @returns user global permission array in the following format: + * $tabPerrArray=(tabid1=>permission, + * tabid2=>permission) ); + */ +function getCombinedUserTabsPermissions($userId) +{ + global $log; + $log->debug("Entering getCombinedUserTabsPermissions(".$userId.") method ..."); + global $adb; + $profArr=getUserProfile($userId); + $no_of_profiles=sizeof($profArr); + $userTabPerrArr=Array(); + + $userTabPerrArr=getProfileTabsPermission($profArr[0]); + if($no_of_profiles != 1) + { + for($i=1;$i<$no_of_profiles;$i++) + { + $tempUserTabPerrArr=getProfileTabsPermission($profArr[$i]); + + foreach($userTabPerrArr as $tabId=>$tabPermission) + { + if($tabPermission == 1) + { + $now_permission = $tempUserTabPerrArr[$tabId]; + if($now_permission == 0) + { + $userTabPerrArr[$tabId]=$now_permission; + } + + + } + + } + + } + + } + $log->debug("Exiting getCombinedUserTabsPermissions method ..."); + return $userTabPerrArr; + +} + +/** To retreive the vtiger_tab acion permissions of the specifed user from the various vtiger_profiles associated with the user + * @param $userid -- The User Id:: Type Integer + * @returns user global permission array in the following format: + * $actionPerrArray=(tabid1=>permission, + * tabid2=>permission); + */ +function getCombinedUserActionPermissions($userId) +{ + global $log; + $log->debug("Entering getCombinedUserActionPermissions(".$userId.") method ..."); + global $adb; + $profArr=getUserProfile($userId); + $no_of_profiles=sizeof($profArr); + $actionPerrArr=Array(); + + $actionPerrArr=getProfileAllActionPermission($profArr[0]); + if($no_of_profiles != 1) + { + for($i=1;$i<$no_of_profiles;$i++) + { + $tempActionPerrArr=getProfileAllActionPermission($profArr[$i]); + + foreach($actionPerrArr as $tabId=>$perArr) + { + foreach($perArr as $actionid=>$per) + { + if($per == 1) + { + $now_permission = $tempActionPerrArr[$tabId][$actionid]; + if($now_permission == 0) + { + $actionPerrArr[$tabId][$actionid]=$now_permission; + } + + + } + } + + } + + } + + } + $log->debug("Exiting getCombinedUserActionPermissions method ..."); + return $actionPerrArr; + +} + +/** To retreive the parent vtiger_role of the specified vtiger_role + * @param $roleid -- The Role Id:: Type varchar + * @returns parent vtiger_role array in the following format: + * $parentRoleArray=(roleid1,roleid2,.......,roleidn); + */ +function getParentRole($roleId) +{ + global $log; + $log->debug("Entering getParentRole(".$roleId.") method ..."); + $roleInfo=getRoleInformation($roleId); + $parentRole=$roleInfo[$roleId][1]; + $tempParentRoleArr=explode('::',$parentRole); + $parentRoleArr=Array(); + foreach($tempParentRoleArr as $role_id) + { + if($role_id != $roleId) + { + $parentRoleArr[]=$role_id; + } + } + $log->debug("Exiting getParentRole method ..."); + return $parentRoleArr; + +} + +/** To retreive the subordinate vtiger_roles of the specified parent vtiger_role + * @param $roleid -- The Role Id:: Type varchar + * @returns subordinate vtiger_role array in the following format: + * $subordinateRoleArray=(roleid1,roleid2,.......,roleidn); + */ +function getRoleSubordinates($roleId) +{ + global $log; + $log->debug("Entering getRoleSubordinates(".$roleId.") method ..."); + + // Look at cache first for information + $roleSubordinates = VTCacheUtils::lookupRoleSubordinates($roleId); + + if($roleSubordinates === false) { + global $adb; + $roleDetails=getRoleInformation($roleId); + $roleInfo=$roleDetails[$roleId]; + $roleParentSeq=$roleInfo[1]; + + $query="select * from vtiger_role where parentrole like ? order by parentrole asc"; + $result=$adb->pquery($query, array($roleParentSeq."::%")); + $num_rows=$adb->num_rows($result); + $roleSubordinates=Array(); + for($i=0;$i<$num_rows;$i++) + { + $roleid=$adb->query_result($result,$i,'roleid'); + + $roleSubordinates[]=$roleid; + + } + // Update cache for re-use + VTCacheUtils::updateRoleSubordinates($roleId, $roleSubordinates); + } + + $log->debug("Exiting getRoleSubordinates method ..."); + return $roleSubordinates; + +} + +/** To retreive the subordinate vtiger_roles and vtiger_users of the specified parent vtiger_role + * @param $roleid -- The Role Id:: Type varchar + * @returns subordinate vtiger_role array in the following format: + * $subordinateRoleUserArray=(roleid1=>Array(userid1,userid2,userid3), + vtiger_roleid2=>Array(userid1,userid2,userid3) + | + | + vtiger_roleidn=>Array(userid1,userid2,userid3)); + */ +function getSubordinateRoleAndUsers($roleId) +{ + global $log; + $log->debug("Entering getSubordinateRoleAndUsers(".$roleId.") method ..."); + global $adb; + $subRoleAndUsers=Array(); + $subordinateRoles=getRoleSubordinates($roleId); + foreach($subordinateRoles as $subRoleId) + { + $userArray=getRoleUsers($subRoleId); + $subRoleAndUsers[$subRoleId]=$userArray; + + } + $log->debug("Exiting getSubordinateRoleAndUsers method ..."); + return $subRoleAndUsers; + +} + +function getCurrentUserProfileList() +{ + global $log; + $log->debug("Entering getCurrentUserProfileList() method ..."); + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $profList = array(); + $i=0; + foreach ($current_user_profiles as $profid) + { + array_push($profList, $profid); + $i++; + } + $log->debug("Exiting getCurrentUserProfileList method ..."); + return $profList; + +} + + +function getCurrentUserGroupList() +{ + global $log; + $log->debug("Entering getCurrentUserGroupList() method ..."); + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $grpList= array(); + if(sizeof($current_user_groups) > 0) + { + $i=0; + foreach ($current_user_groups as $grpid) + { + array_push($grpList, $grpid); + $i++; + } + } + $log->debug("Exiting getCurrentUserGroupList method ..."); + return $grpList; +} + +function getSubordinateUsersList() +{ + global $log; + $log->debug("Entering getSubordinateUsersList() method ..."); + global $current_user; + $user_array=Array(); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + if(sizeof($subordinate_roles_users) > 0) + { + foreach ($subordinate_roles_users as $roleid => $userArray) + { + foreach($userArray as $userid) + { + if(! in_array($userid,$user_array)) + { + $user_array[]=$userid; + } + } + } + } + $subUserList = constructList($user_array,'INTEGER'); + $log->debug("Exiting getSubordinateUsersList method ..."); + return $subUserList; + +} + +function getReadSharingUsersList($module) +{ + global $log; + $log->debug("Entering getReadSharingUsersList(".$module.") method ..."); + global $adb; + global $current_user; + $user_array=Array(); + $tabid=getTabid($module); + $query = "select shareduserid from vtiger_tmp_read_user_sharing_per where userid=? and tabid=?"; + $result=$adb->pquery($query, array($current_user->id, $tabid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $user_id=$adb->query_result($result,$i,'shareduserid'); + $user_array[]=$user_id; + } + $shareUserList=constructList($user_array,'INTEGER'); + $log->debug("Exiting getReadSharingUsersList method ..."); + return $shareUserList; +} + +function getReadSharingGroupsList($module) +{ + global $log; + $log->debug("Entering getReadSharingGroupsList(".$module.") method ..."); + global $adb; + global $current_user; + $grp_array=Array(); + $tabid=getTabid($module); + $query = "select sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=? and tabid=?"; + $result=$adb->pquery($query, array($current_user->id, $tabid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $grp_id=$adb->query_result($result,$i,'sharedgroupid'); + $grp_array[]=$grp_id; + } + $shareGrpList=constructList($grp_array,'INTEGER'); + $log->debug("Exiting getReadSharingGroupsList method ..."); + return $shareGrpList; +} + +function getWriteSharingGroupsList($module) +{ + global $log; + $log->debug("Entering getWriteSharingGroupsList(".$module.") method ..."); + global $adb; + global $current_user; + $grp_array=Array(); + $tabid=getTabid($module); + $query = "select sharedgroupid from vtiger_tmp_write_group_sharing_per where userid=? and tabid=?"; + $result=$adb->pquery($query, array($current_user->id, $tabid)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $grp_id=$adb->query_result($result,$i,'sharedgroupid'); + $grp_array[]=$grp_id; + } + $shareGrpList=constructList($grp_array,'INTEGER'); + $log->debug("Exiting getWriteSharingGroupsList method ..."); + return $shareGrpList; +} + +function constructList($array,$data_type) +{ + global $log; + $log->debug("Entering constructList(".$array.",".$data_type.") method ..."); + $list= array(); + if(sizeof($array) > 0) + { + $i=0; + foreach($array as $value) + { + if($data_type == "INTEGER") + { + array_push($list, $value); + } + elseif($data_type == "VARCHAR") + { + array_push($list, "'".$value."'"); + } + $i++; + } + } + $log->debug("Exiting constructList method ..."); + return $list; +} + +function getListViewSecurityParameter($module) +{ + global $log; + $log->debug("Entering getListViewSecurityParameter(".$module.") method ..."); + global $adb; + + $tabid=getTabid($module); + global $current_user; + if($current_user) + { + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + } + if($module == 'Leads') + { + $sec_query .= " and ( + vtiger_crmentity.smownerid in($current_user->id) + or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') + or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") + or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + } + elseif($module == 'Accounts') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) " . + "or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') " . + "or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Contacts') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) " . + "or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') " . + "or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Potentials') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) " . + "or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') " . + "or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + $sec_query .= " or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'HelpDesk') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") "; + + $sec_query .= " or ("; + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Emails') + { + $sec_query .= " and vtiger_crmentity.smownerid=".$current_user->id." "; + + } + elseif($module == 'Calendar') + { + require_once('modules/Calendar/CalendarCommon.php'); + $shared_ids = getSharedCalendarId($current_user->id); + if(isset($shared_ids) && $shared_ids != '') + $condition = " or (vtiger_crmentity.smownerid in($shared_ids) and vtiger_activity.visibility = 'Public')"; + else + $condition = null; + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) $condition or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%')"; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " or ((vtiger_groups.groupid in (". implode(",", $current_user_groups) .")))"; + } + $sec_query .= ")"; + } + elseif($module == 'Quotes') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + //Adding crteria for group sharing + $sec_query .= " or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + elseif($module == 'PurchaseOrder') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'SalesOrder') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + //Adding crteria for group sharing + $sec_query .= " or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Invoice') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + //Adding crteria for group sharing + $sec_query .= " or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + elseif($module == 'Campaigns') + { + + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + + } + + elseif($module == 'Documents') + { + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + + else + { + $modObj = CRMEntity::getInstance($module); + $sec_query = $modObj->getListViewSecurityParameter($module); + + } + $log->debug("Exiting getListViewSecurityParameter method ..."); + return $sec_query; +} + + +function getSecListViewSecurityParameter($module) +{ + global $log; + $log->debug("Entering getListViewSecurityParameter(".$module.") method ..."); + global $adb; + global $current_user; + + $tabid=getTabid($module); + global $current_user; + if($current_user) + { + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + } + + if($module == 'Leads') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + } + elseif($module == 'Accounts') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Contacts') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Potentials') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or vtiger_potential.related_to in (select crmid from vtiger_crmentity where setype in ('Accounts', 'Contacts') and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid in (".getTabid('Accounts').", ".getTabid('Contacts').") and relatedtabid=".$tabid.")) "; + + if(vtlib_isModuleActive("Accounts")){ + "or vtiger_potential.related_to in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in (select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) "; + } + if(vtlib_isModuleActive("Contacts")){ + "or vtiger_potential.related_to in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Contacts' and vtiger_groups.groupid in (select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Contacts')." and relatedtabid=".$tabid.")) "; + } + $sec_query .= " or ("; + if(sizeof($current_user_groups) > 0){ + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'HelpDesk') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") "; + + if(vtlib_isModuleActive("Accounts")){ + "or vtiger_troubletickets.parent_id in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_troubletickets.parent_id in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) "; + } + + $sec_query .= " or ("; + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Calendar') + { + require_once('modules/Calendar/CalendarCommon.php'); + $shared_ids = getSharedCalendarId($current_user->id); + if(isset($shared_ids) && $shared_ids != '') + $condition = " or (vtiger_crmentity$module.smownerid in($shared_ids) and vtiger_activity.visibility = 'Public')"; + else + $condition = null; + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) $condition or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%')"; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " or ((vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .")))"; + } + $sec_query .= ")"; + } + elseif($module == 'Quotes') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + //Adding crterial for vtiger_account related vtiger_quotes sharing + if(vtlib_isModuleActive("Accounts")){ + $sec_query .= " or vtiger_quotes.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_quotes.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; + } + //Adding crterial for vtiger_potential related vtiger_quotes sharing + if(vtlib_isModuleActive("Potentials")){ + $sec_query .= " or vtiger_quotes.potentialid in (select crmid from vtiger_crmentity where setype='Potentials' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid.")) or vtiger_quotes.potentialid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Potentials' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid."))"; + } + + //Adding crteria for group sharing + $sec_query .= " or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + elseif($module == 'PurchaseOrder') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'SalesOrder') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + //Adding crterial for vtiger_account related so sharing + if(vtlib_isModuleActive("Accounts")){ + $sec_query .= " or vtiger_salesorder.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_salesorder.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; + } + //Adding crterial for vtiger_potential related so sharing + if(vtlib_isModuleActive("Potentials")){ + $sec_query .= " or vtiger_salesorder.potentialid in (select crmid from vtiger_crmentity where setype='Potentials' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid.")) or vtiger_salesorder.potentialid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Potentials' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Potentials')." and relatedtabid=".$tabid."))"; + } + //Adding crterial for vtiger_quotes related so sharing + if(vtlib_isModuleActive("Quotes")){ + $sec_query .= " or vtiger_salesorder.quoteid in (select crmid from vtiger_crmentity where setype='Quotes' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Quotes')." and relatedtabid=".$tabid.")) or vtiger_salesorder.quoteid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Quotes' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Quotes')." and relatedtabid=".$tabid."))"; + } + + //Adding crteria for group sharing + $sec_query .= " or ("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid."))) "; + + } + elseif($module == 'Invoice') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")"; + + //Adding crterial for vtiger_account related vtiger_invoice sharing + if(vtlib_isModuleActive("Accounts")){ + $sec_query .= " or vtiger_invoice.accountid in (select crmid from vtiger_crmentity where setype='Accounts' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid.")) or vtiger_invoice.accountid in (select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='Accounts' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('Accounts')." and relatedtabid=".$tabid."))"; + } + //Adding crterial for vtiger_salesorder related vtiger_invoice sharing + if(vtlib_isModuleActive("SalesOrder")){ + $sec_query .= " or vtiger_invoice.salesorderid in (select crmid from vtiger_crmentity where setype='SalesOrder' and vtiger_crmentity.smownerid in(select shareduserid from vtiger_tmp_read_user_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('SalesOrder')." and relatedtabid=".$tabid.")) or vtiger_invoice.salesorderid in(select crmid from vtiger_crmentity inner join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where setype='SalesOrder' and vtiger_groups.groupid in(select vtiger_tmp_read_group_rel_sharing_per.sharedgroupid from vtiger_tmp_read_group_rel_sharing_per where userid=".$current_user->id." and tabid=".getTabid('SalesOrder')." and relatedtabid=".$tabid."))"; + } + + //Adding crteria for group sharing + $sec_query .= " or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + elseif($module == 'Campaigns') + { + + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + + } + + elseif($module == 'Documents') + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + + else + { + $sec_query .= " and (vtiger_crmentity$module.smownerid in($current_user->id) or vtiger_crmentity$module.smownerid in(select vtiger_user2role.userid from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like '".$current_user_parent_role_seq."::%') or vtiger_crmentity$module.smownerid in(select shareduserid from vtiger_tmp_read_user_sharing_per where userid=".$current_user->id." and tabid=".$tabid.") or (("; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " vtiger_groups$module.groupid in (". implode(",", $current_user_groups) .") or "; + } + $sec_query .= " vtiger_groups$module.groupid in(select vtiger_tmp_read_group_sharing_per.sharedgroupid from vtiger_tmp_read_group_sharing_per where userid=".$current_user->id." and tabid=".$tabid.")))) "; + + } + $log->debug("Exiting getListViewSecurityParameter method ..."); + return $sec_query; +} + +function get_current_user_access_groups($module) +{ + global $log; + $log->debug("Entering get_current_user_access_groups(".$module.") method ..."); + global $adb,$noof_group_rows; + $current_user_group_list=getCurrentUserGroupList(); + $sharing_write_group_list=getWriteSharingGroupsList($module); + $query ="select groupname,groupid from vtiger_groups"; + $params = array(); + if(count($current_user_group_list) > 0 && count($sharing_write_group_list) > 0) + { + $query .= " where (groupid in (". generateQuestionMarks($current_user_group_list) .") or groupid in (". generateQuestionMarks($sharing_write_group_list) ."))"; + array_push($params, $current_user_group_list, $sharing_write_group_list); + $result = $adb->pquery($query, $params); + $noof_group_rows=$adb->num_rows($result); + } + elseif(count($current_user_group_list) > 0) + { + $query .= " where groupid in (". generateQuestionMarks($current_user_group_list) .")"; + array_push($params, $current_user_group_list); + $result = $adb->pquery($query, $params); + $noof_group_rows=$adb->num_rows($result); + } + elseif(count($sharing_write_group_list) > 0) + { + $query .= " where groupid in (". generateQuestionMarks($sharing_write_group_list) .")"; + array_push($params, $sharing_write_group_list); + $result = $adb->pquery($query, $params); + $noof_group_rows=$adb->num_rows($result); + } + $log->debug("Exiting get_current_user_access_groups method ..."); + return $result; +} +/** Function to get the Group Id for a given group groupname + * @param $groupname -- Groupname + * @returns Group Id -- Type Integer + */ + +function getGrpId($groupname) +{ + global $log; + $log->debug("Entering getGrpId(".$groupname.") method ..."); + global $adb; + + $result = $adb->pquery("select groupid from vtiger_groups where groupname=?", array($groupname)); + $groupid = $adb->query_result($result,0,'groupid'); + $log->debug("Exiting getGrpId method ..."); + return $groupid; +} + +/** Function to check permission to access a vtiger_field for a given user + * @param $fld_module -- Module :: Type String + * @param $userid -- User Id :: Type integer + * @param $fieldname -- Field Name :: Type varchar + * @returns $rolename -- Role Name :: Type varchar + * + */ +function getFieldVisibilityPermission($fld_module, $userid, $fieldname) +{ + global $log; + $log->debug("Entering getFieldVisibilityPermission(".$fld_module.",". $userid.",". $fieldname.") method ..."); + + global $adb; + global $current_user; + + // Check if field is in-active + $fieldActive = isFieldActive($fld_module,$fieldname); + if($fieldActive == false) { + return '1'; + } + + require('user_privileges/user_privileges_'.$userid.'.php'); + + /* Asha: Fix for ticket #4508. Users with View all and Edit all permission will also have visibility permission for all fields */ + if($is_admin || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0) + { + $log->debug("Exiting getFieldVisibilityPermission method ..."); + return '0'; + } + else + { + //get vtiger_profile list using userid + $profilelist = getCurrentUserProfileList(); + + //get tabid + $tabid = getTabid($fld_module); + + if (count($profilelist) > 0) { + $query="SELECT vtiger_profile2field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid in (". generateQuestionMarks($profilelist) .") AND vtiger_field.fieldname= ? and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; + $params = array($tabid, $profilelist, $fieldname); + } else { + $query="SELECT vtiger_profile2field.* FROM vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid WHERE vtiger_field.tabid=? AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_field.fieldname= ? and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid"; + $params = array($tabid, $fieldname); + } + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query = fixPostgresQuery( $query, $log, 0); + + + $result = $adb->pquery($query, $params); + + $log->debug("Exiting getFieldVisibilityPermission method ..."); + + if($adb->num_rows($result) == 0) return '1'; + return ($adb->query_result($result,"0","visible")+""); + } +} + +/** Function to check permission to access the column for a given user + * @param $userid -- User Id :: Type integer + * @param $tablename -- tablename :: Type String + * @param $columnname -- columnname :: Type String + * @param $module -- Module Name :: Type varchar + */ +function getColumnVisibilityPermission($userid,$columnname, $module) +{ + global $adb,$log; + $log->debug("in function getcolumnvisibilitypermission $columnname -$userid"); + $tabid = getTabid($module); + + // Look at cache if information is available. + $cacheFieldInfo = VTCacheUtils::lookupFieldInfoByColumn($tabid, $columnname); + $fieldname = false; + if($cacheFieldInfo === false) { + $res = $adb->pquery("select fieldname from vtiger_field where tabid=? and columnname=? and vtiger_field.presence in (0,2)", array($tabid, $columnname)); + $fieldname = $adb->query_result($res, 0, 'fieldname'); + } else { + $fieldname = $cacheFieldInfo['fieldname']; + } + + return getFieldVisibilityPermission($module,$userid,$fieldname); +} + +/** Function to get the vtiger_field access module array + * @returns The vtiger_field Access module Array :: Type Array + * + */ +function getFieldModuleAccessArray() +{ + global $log; + global $adb; + $log->debug("Entering getFieldModuleAccessArray() method ..."); + + $fldModArr=Array(); + $query = 'select distinct(name) from vtiger_profile2field inner join vtiger_tab on vtiger_tab.tabid=vtiger_profile2field.tabid'; + $result = $adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $mod_name = $adb->query_result($result,$i,'name'); + $fldModArr[$mod_name] = $mod_name; + } + $log->debug("Exiting getFieldModuleAccessArray method ..."); + return $fldModArr; +} + +/** Function to get the permitted module name Array with presence as 0 + * @returns permitted module name Array :: Type Array + * + */ +function getPermittedModuleNames() +{ + global $log; + $log->debug("Entering getPermittedModuleNames() method ..."); + global $current_user; + $permittedModules=Array(); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + include('tabdata.php'); + + if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + { + foreach($tab_seq_array as $tabid=>$seq_value) + { + if($seq_value === 0 && $profileTabsPermission[$tabid] === 0) + { + $permittedModules[]=getTabModuleName($tabid); + } + + } + + + } + else + { + foreach($tab_seq_array as $tabid=>$seq_value) + { + if($seq_value === 0) + { + $permittedModules[]=getTabModuleName($tabid); + } + + } + } + $log->debug("Exiting getPermittedModuleNames method ..."); + return $permittedModules; +} + + +/** + * Function to get the permitted module id Array with presence as 0 + * @global Users $current_user + * @return Array Array of accessible tabids. + */ +function getPermittedModuleIdList() { + global $current_user; + $permittedModules=Array(); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + include('tabdata.php'); + + if($is_admin == false && $profileGlobalPermission[1] == 1 && + $profileGlobalPermission[2] == 1) { + foreach($tab_seq_array as $tabid=>$seq_value) { + if($seq_value === 0 && $profileTabsPermission[$tabid] === 0) { + $permittedModules[]=($tabid); + } + } + } else { + foreach($tab_seq_array as $tabid=>$seq_value) { + if($seq_value === 0) { + $permittedModules[]=($tabid); + } + } + } + return $permittedModules; +} + +/** Function to recalculate the Sharing Rules for all the vtiger_users + * This function will recalculate all the sharing rules for all the vtiger_users in the Organization and will write them in flat vtiger_files + * + */ +function RecalculateSharingRules() +{ + global $log; + $log->debug("Entering RecalculateSharingRules() method ..."); + global $adb; + require_once('modules/Users/CreateUserPrivilegeFile.php'); + $query="select id from vtiger_users where deleted=0"; + $result=$adb->pquery($query, array()); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $id=$adb->query_result($result,$i,'id'); + createUserPrivilegesfile($id); + createUserSharingPrivilegesfile($id); + } + $log->debug("Exiting RecalculateSharingRules method ..."); + +} + +/** Function to get the list of module for which the user defined sharing rules can be defined + * @returns Array:: Type array + * + */ +function getSharingModuleList($eliminateModules=false) +{ + global $log; + + $sharingModuleArray = Array(); + + global $adb; + if(empty($eliminateModules)) $eliminateModules = Array(); + + // Module that needs to be eliminated explicitly + if(!in_array('Calendar', $eliminateModules)) $eliminateModules[] = 'Calendar'; + if(!in_array('Events', $eliminateModules)) $eliminateModules[] = 'Events'; + + $query = "SELECT name FROM vtiger_tab WHERE presence=0 AND ownedby = 0 AND isentitytype = 1"; + $query .= " AND name NOT IN('" . implode("','", $eliminateModules) . "')"; + + $result = $adb->query($query); + while($resrow = $adb->fetch_array($result)) { + $sharingModuleArray[] = $resrow['name']; + } + + return $sharingModuleArray; +} + + +function isCalendarPermittedBySharing($recordId) +{ + global $adb; + global $current_user; + $permission = 'no'; + $query = "select * from vtiger_sharedcalendar where userid in(select smownerid from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid where activityid=? and visibility='Public' and smownerid !=0) and sharedid=?"; + $result=$adb->pquery($query, array($recordId, $current_user->id)); + if($adb->num_rows($result) >0) + { + $permission = 'yes'; + } + return $permission; +} +/* + * * Function to populate default entries for the picklist while creating a new role--vashni + * */ +function insertRole2Picklist($roleid,$parentroleid) +{ + global $adb,$log; + $log->debug("Entering into the function insertRole2Picklist($roleid,$parentroleid)"); + $sql = "insert into vtiger_role2picklist select '".$roleid."',picklistvalueid,picklistid,sortid from vtiger_role2picklist where roleid=?"; + $adb->pquery($sql, array($parentroleid)); + $log->debug("Exiting from the function insertRole2Picklist($roleid,$parentroleid)"); +} + +/** Function to delete group to report relation of the specified group + * @param $groupId -- Group Id :: Type integer + */ +function deleteGroupReportRelations($groupId) +{ + global $log; + $log->debug("Entering deleteGroupReportRelations(".$groupId.") method ..."); + global $adb; + $query="delete from vtiger_reportsharing where shareid=? and setype='groups'"; + $adb->pquery($query, array($groupId)); + $log->debug("Exiting deleteGroupReportRelations method ..."); +} +//end + +/** Function to check if the field is Active + * @params $modulename -- Module Name :: String Type + * $fieldname -- Field Name :: String Type + */ +function isFieldActive($modulename,$fieldname){ + $fieldid = getFieldid(getTabid($modulename), $fieldname, true); + return ($fieldid !== false); +} + +/** + * + * @param String $module - module name for which query needs to be generated. + * @param Users $user - user for which query needs to be generated. + * @return String Access control Query for the user. + */ +function getNonAdminAccessControlQuery($module,$user,$scope=''){ + $instance = CRMEntity::getInstance($module); + return $instance->getNonAdminAccessControlQuery($module,$user,$scope); +} + +function appendFromClauseToQuery($query,$fromClause) { + $query = preg_replace('/\s+/', ' ', $query); + $condition = substr($query, strripos($query,' where '),strlen($query)); + $newQuery = substr($query, 0, strripos($query,' where ')); + $query = $newQuery.$fromClause.$condition; + return $query; +} + ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/VTCacheUtils.php b/oss/vtiger/trunk/include/utils/VTCacheUtils.php index 987fb3e8..adfd6d03 100644 --- a/oss/vtiger/trunk/include/utils/VTCacheUtils.php +++ b/oss/vtiger/trunk/include/utils/VTCacheUtils.php @@ -1,254 +1,254 @@ - $tabid, - 'fieldid' => $fieldid, - 'fieldname' => $fieldname, - 'fieldlabel'=> $fieldlabel, - 'columnname'=> $columnname, - 'tablename' => $tablename, - 'uitype' => $uitype, - 'typeofdata'=> $typeofdata, - 'presence' => $presence, - ); - } - static function lookupFieldInfo($tabid, $fieldname) { - if(isset(self::$_fieldinfo_cache[$tabid]) && isset(self::$_fieldinfo_cache[$tabid][$fieldname])) { - return self::$_fieldinfo_cache[$tabid][$fieldname]; - } - return false; - } - static function lookupFieldInfo_Module($module, $presencein = array('0', '2')) { - $tabid = getTabid($module); - $modulefields = false; - - if(isset(self::$_fieldinfo_cache[$tabid])) { - $modulefields = array(); - - $fldcache = self::$_fieldinfo_cache[$tabid]; - foreach($fldcache as $fieldname=>$fieldinfo) { - if(in_array($fieldinfo['presence'], $presencein)) { - $modulefields[] = $fieldinfo; - } - } - } - return $modulefields; - } - - static function lookupFieldInfoByColumn($tabid, $columnname) { - if(isset(self::$_fieldinfo_cache[$tabid])) { - foreach(self::$_fieldinfo_cache[$tabid] as $fieldname=>$fieldinfo) { - if($fieldinfo['columnname'] == $columnname) { - return $fieldinfo; - } - } - } - return false; - } - - /** Module active column fields caching */ - static $_module_columnfields_cache = array(); - static function updateModuleColumnFields($module, $column_fields) { - self::$_module_columnfields_cache[$module] = $column_fields; - } - static function lookupModuleColumnFields($module) { - if(isset(self::$_module_columnfields_cache[$module])) { - return self::$_module_columnfields_cache[$module]; - } - return false; - } - - /** User currency id caching */ - static $_usercurrencyid_cache = array(); - static function lookupUserCurrenyId($userid) { - global $current_user; - if(isset($current_user) && $current_user->id == $userid) { - return array( - 'currencyid' => $current_user->column_fields['currency_id'] - ); - } - - if(isset(self::$_usercurrencyid_cache[$userid])) { - return self::$_usercurrencyid_cache[$userid]; - } - - return false; - } - static function updateUserCurrencyId($userid, $currencyid) { - self::$_usercurrencyid_cache[$userid] = array( - 'currencyid' => $currencyid - ); - } - - /** Currency information caching */ - static $_currencyinfo_cache = array(); - static function lookupCurrencyInfo($currencyid) { - if(isset(self::$_currencyinfo_cache[$currencyid])) { - return self::$_currencyinfo_cache[$currencyid]; - } - return false; - } - static function updateCurrencyInfo($currencyid, $name, $code, $symbol, $rate) { - self::$_currencyinfo_cache[$currencyid] = array( - 'currencyid' => $currencyid, - 'name' => $name, - 'code' => $code, - 'symbol' => $symbol, - 'rate' => $rate - ); - } - - - /** ProfileId information caching */ - static $_userprofileid_cache = array(); - static function updateUserProfileId($userid, $profileid) { - self::$_userprofileid_cache[$userid] = $profileid; - } - static function lookupUserProfileId($userid) { - if(isset(self::$_userprofileid_cache[$userid])) { - return self::$_userprofileid_cache[$userid]; - } - return false; - } - - /** Profile2Field information caching */ - static $_profile2fieldpermissionlist_cache = array(); - static function lookupProfile2FieldPermissionList($module, $profileid) { - $pro2fld_perm = self::$_profile2fieldpermissionlist_cache; - if(isset($pro2fld_perm[$module]) && isset($pro2fld_perm[$module][$profileid])) { - return $pro2fld_perm[$module][$profileid]; - } - return false; - } - static function updateProfile2FieldPermissionList($module, $profileid, $value) { - self::$_profile2fieldpermissionlist_cache[$module][$profileid] = $value; - } - - /** Role information */ - static $_subroles_roleid_cache = array(); - static function lookupRoleSubordinates($roleid) { - if(isset(self::$_subroles_roleid_cache[$roleid])) { - return self::$_subroles_roleid_cache[$roleid]; - } - return false; - } - static function updateRoleSubordinates($roleid, $roles) { - self::$_subroles_roleid_cache[$roleid] = $roles; - } - static function clearRoleSubordinates($roleid = false) { - if($roleid === false) { - self::$_subroles_roleid_cache = array(); - } else if(isset(self::$_subroles_roleid_cache[$roleid])) { - unset(self::$_subroles_roleid_cache[$roleid]); - } - } - - /** Related module information for Report */ - static $_report_listofmodules_cache = false; - static function lookupReport_ListofModuleInfos() { - return self::$_report_listofmodules_cache; - } - static function updateReport_ListofModuleInfos($module_list, $related_modules) { - if(self::$_report_listofmodules_cache === false) { - self::$_report_listofmodules_cache = array( - 'module_list' => $module_list, - 'related_modules' => $related_modules - ); - } - } - - /** Report module information based on used. */ - static $_reportmodule_infoperuser_cache = array(); - static function lookupReport_Info($userid, $reportid) { - - if(isset(self::$_reportmodule_infoperuser_cache[$userid])) { - if(isset(self::$_reportmodule_infoperuser_cache[$userid][$reportid])) { - return self::$_reportmodule_infoperuser_cache[$userid][$reportid]; - } - } - return false; - } - static function updateReport_Info($userid, $reportid, $primarymodule, $secondarymodules, $reporttype, - $reportname, $description, $folderid, $owner) { - if(!isset(self::$_reportmodule_infoperuser_cache[$userid])) { - self::$_reportmodule_infoperuser_cache[$userid] = array(); - } - if(!isset(self::$_reportmodule_infoperuser_cache[$userid][$reportid])) { - self::$_reportmodule_infoperuser_cache[$userid][$reportid] = array ( - 'reportid' => $reportid, - 'primarymodule' => $primarymodule, - 'secondarymodules'=> $secondarymodules, - 'reporttype' => $reporttype, - 'reportname' => $reportname, - 'description' => $description, - 'folderid' => $folderid, - 'owner' => $owner - ); - } - } - - /** Report module sub-ordinate users information. */ - static $_reportmodule_subordinateuserid_cache = array(); - static function lookupReport_SubordinateUsers($reportid) { - if(isset(self::$_reportmodule_subordinateuserid_cache[$reportid])) { - return self::$_reportmodule_subordinateuserid_cache[$reportid]; - } - return false; - } - static function updateReport_SubordinateUsers($reportid, $userids) { - self::$_reportmodule_subordinateuserid_cache[$reportid] = $userids; - } -} - + $tabid, + 'fieldid' => $fieldid, + 'fieldname' => $fieldname, + 'fieldlabel'=> $fieldlabel, + 'columnname'=> $columnname, + 'tablename' => $tablename, + 'uitype' => $uitype, + 'typeofdata'=> $typeofdata, + 'presence' => $presence, + ); + } + static function lookupFieldInfo($tabid, $fieldname) { + if(isset(self::$_fieldinfo_cache[$tabid]) && isset(self::$_fieldinfo_cache[$tabid][$fieldname])) { + return self::$_fieldinfo_cache[$tabid][$fieldname]; + } + return false; + } + static function lookupFieldInfo_Module($module, $presencein = array('0', '2')) { + $tabid = getTabid($module); + $modulefields = false; + + if(isset(self::$_fieldinfo_cache[$tabid])) { + $modulefields = array(); + + $fldcache = self::$_fieldinfo_cache[$tabid]; + foreach($fldcache as $fieldname=>$fieldinfo) { + if(in_array($fieldinfo['presence'], $presencein)) { + $modulefields[] = $fieldinfo; + } + } + } + return $modulefields; + } + + static function lookupFieldInfoByColumn($tabid, $columnname) { + if(isset(self::$_fieldinfo_cache[$tabid])) { + foreach(self::$_fieldinfo_cache[$tabid] as $fieldname=>$fieldinfo) { + if($fieldinfo['columnname'] == $columnname) { + return $fieldinfo; + } + } + } + return false; + } + + /** Module active column fields caching */ + static $_module_columnfields_cache = array(); + static function updateModuleColumnFields($module, $column_fields) { + self::$_module_columnfields_cache[$module] = $column_fields; + } + static function lookupModuleColumnFields($module) { + if(isset(self::$_module_columnfields_cache[$module])) { + return self::$_module_columnfields_cache[$module]; + } + return false; + } + + /** User currency id caching */ + static $_usercurrencyid_cache = array(); + static function lookupUserCurrenyId($userid) { + global $current_user; + if(isset($current_user) && $current_user->id == $userid) { + return array( + 'currencyid' => $current_user->column_fields['currency_id'] + ); + } + + if(isset(self::$_usercurrencyid_cache[$userid])) { + return self::$_usercurrencyid_cache[$userid]; + } + + return false; + } + static function updateUserCurrencyId($userid, $currencyid) { + self::$_usercurrencyid_cache[$userid] = array( + 'currencyid' => $currencyid + ); + } + + /** Currency information caching */ + static $_currencyinfo_cache = array(); + static function lookupCurrencyInfo($currencyid) { + if(isset(self::$_currencyinfo_cache[$currencyid])) { + return self::$_currencyinfo_cache[$currencyid]; + } + return false; + } + static function updateCurrencyInfo($currencyid, $name, $code, $symbol, $rate) { + self::$_currencyinfo_cache[$currencyid] = array( + 'currencyid' => $currencyid, + 'name' => $name, + 'code' => $code, + 'symbol' => $symbol, + 'rate' => $rate + ); + } + + + /** ProfileId information caching */ + static $_userprofileid_cache = array(); + static function updateUserProfileId($userid, $profileid) { + self::$_userprofileid_cache[$userid] = $profileid; + } + static function lookupUserProfileId($userid) { + if(isset(self::$_userprofileid_cache[$userid])) { + return self::$_userprofileid_cache[$userid]; + } + return false; + } + + /** Profile2Field information caching */ + static $_profile2fieldpermissionlist_cache = array(); + static function lookupProfile2FieldPermissionList($module, $profileid) { + $pro2fld_perm = self::$_profile2fieldpermissionlist_cache; + if(isset($pro2fld_perm[$module]) && isset($pro2fld_perm[$module][$profileid])) { + return $pro2fld_perm[$module][$profileid]; + } + return false; + } + static function updateProfile2FieldPermissionList($module, $profileid, $value) { + self::$_profile2fieldpermissionlist_cache[$module][$profileid] = $value; + } + + /** Role information */ + static $_subroles_roleid_cache = array(); + static function lookupRoleSubordinates($roleid) { + if(isset(self::$_subroles_roleid_cache[$roleid])) { + return self::$_subroles_roleid_cache[$roleid]; + } + return false; + } + static function updateRoleSubordinates($roleid, $roles) { + self::$_subroles_roleid_cache[$roleid] = $roles; + } + static function clearRoleSubordinates($roleid = false) { + if($roleid === false) { + self::$_subroles_roleid_cache = array(); + } else if(isset(self::$_subroles_roleid_cache[$roleid])) { + unset(self::$_subroles_roleid_cache[$roleid]); + } + } + + /** Related module information for Report */ + static $_report_listofmodules_cache = false; + static function lookupReport_ListofModuleInfos() { + return self::$_report_listofmodules_cache; + } + static function updateReport_ListofModuleInfos($module_list, $related_modules) { + if(self::$_report_listofmodules_cache === false) { + self::$_report_listofmodules_cache = array( + 'module_list' => $module_list, + 'related_modules' => $related_modules + ); + } + } + + /** Report module information based on used. */ + static $_reportmodule_infoperuser_cache = array(); + static function lookupReport_Info($userid, $reportid) { + + if(isset(self::$_reportmodule_infoperuser_cache[$userid])) { + if(isset(self::$_reportmodule_infoperuser_cache[$userid][$reportid])) { + return self::$_reportmodule_infoperuser_cache[$userid][$reportid]; + } + } + return false; + } + static function updateReport_Info($userid, $reportid, $primarymodule, $secondarymodules, $reporttype, + $reportname, $description, $folderid, $owner) { + if(!isset(self::$_reportmodule_infoperuser_cache[$userid])) { + self::$_reportmodule_infoperuser_cache[$userid] = array(); + } + if(!isset(self::$_reportmodule_infoperuser_cache[$userid][$reportid])) { + self::$_reportmodule_infoperuser_cache[$userid][$reportid] = array ( + 'reportid' => $reportid, + 'primarymodule' => $primarymodule, + 'secondarymodules'=> $secondarymodules, + 'reporttype' => $reporttype, + 'reportname' => $reportname, + 'description' => $description, + 'folderid' => $folderid, + 'owner' => $owner + ); + } + } + + /** Report module sub-ordinate users information. */ + static $_reportmodule_subordinateuserid_cache = array(); + static function lookupReport_SubordinateUsers($reportid) { + if(isset(self::$_reportmodule_subordinateuserid_cache[$reportid])) { + return self::$_reportmodule_subordinateuserid_cache[$reportid]; + } + return false; + } + static function updateReport_SubordinateUsers($reportid, $userids) { + self::$_reportmodule_subordinateuserid_cache[$reportid] = $userids; + } +} + ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/VtlibUtils.php b/oss/vtiger/trunk/include/utils/VtlibUtils.php index 42040b2d..22cec3cb 100644 --- a/oss/vtiger/trunk/include/utils/VtlibUtils.php +++ b/oss/vtiger/trunk/include/utils/VtlibUtils.php @@ -1,569 +1,590 @@ -pquery("SELECT name FROM vtiger_tab WHERE tabid = ?",array($tabid)); - if($adb->num_rows($sqlresult)) return $adb->query_result($sqlresult, 0, 'name'); - return null; -} - -/** - * Get module names for which sharing access can be controlled. - * NOTE: Ignore the standard modules which is already handled. - */ -function vtlib_getModuleNameForSharing() { - global $adb; - $vtlib_sqlres = $adb->query("SELECT * from vtiger_tab WHERE ownedby = 0 - AND name NOT IN('Calendar','Leads','Accounts','Contacts','Potentials', - 'HelpDesk','Campaigns','Quotes','PurchaseOrder','SalesOrder','Invoice','Events')"); - $vtlib_numrows = $adb->num_rows($vtlib_sqlres); - $modules = Array(); - for($idx = 0; $idx < $vtlib_numrows; ++$idx) $modules[] = $adb->query_result($vtlib_sqlres, 0, 'name'); - return $modules; -} - -/** - * Cache the module active information for performance - */ -$__cache_module_activeinfo = Array(); - -/** - * Fetch module active information at one shot, but return all the information fetched. - */ -function vtlib_prefetchModuleActiveInfo($force = true) { - global $__cache_module_activeinfo; - - // Look up if cache has information - $tabrows = VTCacheUtils::lookupAllTabsInfo(); - - // Initialize from DB if cache information is not available or force flag is set - if($tabrows === false || $force) { - global $adb; - $tabres = $adb->query("SELECT * FROM vtiger_tab"); - $tabrows = array(); - if($tabres) { - while($tabresrow = $adb->fetch_array($tabres)) { - $tabrows[] = $tabresrow; - $__cache_module_activeinfo[$tabresrow['name']] = $tabresrow['presence']; - } - // Update cache for further re-use - VTCacheUtils::updateAllTabsInfo($tabrows); - } - } - - return $tabrows; -} - -/** - * Check if module is set active (or enabled) - */ -function vtlib_isModuleActive($module) { - global $adb, $__cache_module_activeinfo; - - if(in_array($module, vtlib_moduleAlwaysActive())){ - return true; - } - - if(!isset($__cache_module_activeinfo[$module])) { - $tabres = $adb->pquery("SELECT presence FROM vtiger_tab WHERE name=?", array($module)); - $presence = $adb->query_result($tabres, 0, 'presence'); - $__cache_module_activeinfo[$module] = $presence; - } else { - $presence = $__cache_module_activeinfo[$module]; - } - - $active = false; - if($presence != 1) $active = true; - - return $active; -} - -/** - * Recreate user privileges files. - */ -function vtlib_RecreateUserPrivilegeFiles() { - global $adb; - $userres = $adb->query('SELECT id FROM vtiger_users WHERE deleted = 0'); - if($userres && $adb->num_rows($userres)) { - while($userrow = $adb->fetch_array($userres)) { - createUserPrivilegesfile($userrow['id']); - } - } -} - -/** - * Get list module names which are always active (cannot be disabled) - */ -function vtlib_moduleAlwaysActive() { - $modules = Array ( - 'Administration', 'CustomView', 'Settings', 'Users', 'Migration', - 'Utilities', 'uploads', 'Import', 'System', 'com_vtiger_workflow', 'PickList', - ); - return $modules; -} - -/** - * Toggle the module (enable/disable) - */ -function vtlib_toggleModuleAccess($module, $enable_disable) { - global $adb, $__cache_module_activeinfo; - - include_once('vtlib/Vtiger/Module.php'); - - $event_type = false; - - if($enable_disable === true) { - $enable_disable = 0; - $event_type = Vtiger_Module::EVENT_MODULE_ENABLED; - } else if($enable_disable === false) { - $enable_disable = 1; - $event_type = Vtiger_Module::EVENT_MODULE_DISABLED; - } - - $adb->pquery("UPDATE vtiger_tab set presence = ? WHERE name = ?", array($enable_disable,$module)); - - $__cache_module_activeinfo[$module] = $enable_disable; - - create_tab_data_file(); - create_parenttab_data_file(); - - // UserPrivilege file needs to be regenerated if module state is changed from - // vtiger 5.1.0 onwards - global $vtiger_current_version; - if(version_compare($vtiger_current_version, '5.0.4', '>')) { - vtlib_RecreateUserPrivilegeFiles(); - } - - Vtiger_Module::fireEvent($module, $event_type); -} - -/** - * Get list of module with current status which can be controlled. - */ -function vtlib_getToggleModuleInfo() { - global $adb; - - $modinfo = Array(); - - $sqlresult = $adb->query("SELECT name, presence, customized, isentitytype FROM vtiger_tab WHERE name NOT IN ('Users') AND presence IN (0,1) ORDER BY name"); - $num_rows = $adb->num_rows($sqlresult); - for($idx = 0; $idx < $num_rows; ++$idx) { - $module = $adb->query_result($sqlresult, $idx, 'name'); - $presence=$adb->query_result($sqlresult, $idx, 'presence'); - $customized=$adb->query_result($sqlresult, $idx, 'customized'); - $isentitytype=$adb->query_result($sqlresult, $idx, 'isentitytype'); - $hassettings=file_exists("modules/$module/Settings.php"); - - $modinfo[$module] = Array( 'customized'=>$customized, 'presence'=>$presence, 'hassettings'=>$hassettings, 'isentitytype' => $isentitytype ); - } - return $modinfo; -} - -/** - * Get list of language and its current status. - */ -function vtlib_getToggleLanguageInfo() { - global $adb; - - // The table might not exists! - $old_dieOnError = $adb->dieOnError; - $adb->dieOnError = false; - - $langinfo = Array(); - $sqlresult = $adb->query("SELECT * FROM vtiger_language"); - if($sqlresult) { - for($idx = 0; $idx < $adb->num_rows($sqlresult); ++$idx) { - $row = $adb->fetch_array($sqlresult); - $langinfo[$row['prefix']] = Array( 'label'=>$row['label'], 'active'=>$row['active'] ); - } - } - $adb->dieOnError = $old_dieOnError; - return $langinfo; -} - -/** - * Toggle the language (enable/disable) - */ -function vtlib_toggleLanguageAccess($langprefix, $enable_disable) { - global $adb; - - // The table might not exists! - $old_dieOnError = $adb->dieOnError; - $adb->dieOnError = false; - - if($enable_disable === true) $enable_disable = 1; - else if($enable_disable === false) $enable_disable = 0; - - $adb->pquery('UPDATE vtiger_language set active = ? WHERE prefix = ?', Array($enable_disable, $langprefix)); - - $adb->dieOnError = $old_dieOnError; -} - -/** - * Get help information set for the module fields. - */ -function vtlib_getFieldHelpInfo($module) { - global $adb; - $fieldhelpinfo = Array(); - if(in_array('helpinfo', $adb->getColumnNames('vtiger_field'))) { - $result = $adb->pquery('SELECT fieldname,helpinfo FROM vtiger_field WHERE tabid=?', Array(getTabid($module))); - if($result && $adb->num_rows($result)) { - while($fieldrow = $adb->fetch_array($result)) { - $helpinfo = decode_html($fieldrow['helpinfo']); - if(!empty($helpinfo)) { - $fieldhelpinfo[$fieldrow['fieldname']] = getTranslatedString($helpinfo, $module); - } - } - } - } - return $fieldhelpinfo; -} - -/** - * Setup mandatory (requried) module variable values in the module class. - */ -function vtlib_setup_modulevars($module, $focus) { - - $checkfor = Array('table_name', 'table_index', 'related_tables', 'popup_fields', 'IsCustomModule'); - foreach($checkfor as $check) { - if(!isset($focus->$check)) $focus->$check = __vtlib_get_modulevar_value($module, $check); - } -} -function __vtlib_get_modulevar_value($module, $varname) { - $mod_var_mapping = - Array( - 'Accounts' => - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_account', - 'table_index' => 'accountid', - // related_tables variable should define the association (relation) between dependent tables - // FORMAT: related_tablename => Array ( related_tablename_column[, base_tablename, base_tablename_column] ) - // Here base_tablename_column should establish relation with related_tablename_column - // NOTE: If base_tablename and base_tablename_column are not specified, it will default to modules (table_name, related_tablename_column) - 'related_tables' => Array( - 'vtiger_accountbillads' => Array ('accountaddressid', 'vtiger_account', 'accountid'), - 'vtiger_accountshipads' => Array ('accountaddressid', 'vtiger_account', 'accountid'), - ), - 'popup_fields' => Array('accountname'), // TODO: Add this initialization to all the standard module - ), - 'Contacts' => - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_contactdetails', - 'table_index' => 'contactid', - 'related_tables'=> Array( 'vtiger_account' => Array ('accountid' ) ), - 'popup_fields' => Array ('lastname'), - ), - 'Leads' => - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_leaddetails', - 'table_index' => 'leadid', - 'related_tables' => Array ( - 'vtiger_leadsubdetails' => Array ( 'leadsubscriptionid', 'vtiger_leaddetails', 'leadid' ), - 'vtiger_leadaddress' => Array ( 'leadaddressid', 'vtiger_leaddetails', 'leadid' ), - ), - 'popup_fields'=> Array ('lastname'), - ), - 'Campaigns' => - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_campaign', - 'table_index' => 'campaignid', - 'popup_fields' => Array ('campaignname'), - ), - 'Potentials' => - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_potential', - 'table_index'=> 'potentialid', - // NOTE: UIType 10 is being used instead of direct relationship from 5.1.0 - //'related_tables' => Array ('vtiger_account' => Array('accountid')), - 'popup_fields'=> Array('potentialname'), - ), - 'Quotes' => - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_quotes', - 'table_index'=> 'quoteid', - 'related_tables' => Array ('vtiger_account' => Array('accountid')), - 'popup_fields'=>Array('subject'), - ), - 'SalesOrder'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_salesorder', - 'table_index'=> 'salesorderid', - 'related_tables'=> Array ('vtiger_account' => Array('accountid')), - 'popup_fields'=>Array('subject'), - ), - 'PurchaseOrder'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_purchaseorder', - 'table_index'=> 'purchaseorderid', - 'popup_fields'=>Array('subject'), - ), - 'Invoice'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_invoice', - 'table_index'=> 'invoiceid', - 'popup_fields'=> Array('subject'), - ), - 'HelpDesk'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_troubletickets', - 'table_index'=> 'ticketid', - 'popup_fields'=> Array('ticket_title') - ), - 'Faq'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_faq', - 'table_index'=> 'id', - ), - 'Documents'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_notes', - 'table_index'=> 'notesid', - ), - 'Products'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_products', - 'table_index'=> 'productid', - 'popup_fields'=> Array('productname'), - ), - 'PriceBooks'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_pricebook', - 'table_index'=> 'pricebookid', - ), - 'Vendors'=> - Array( - 'IsCustomModule'=>false, - 'table_name' => 'vtiger_vendor', - 'table_index'=> 'vendorid', - 'popup_fields'=>Array('vendorname'), - ) - ); - return $mod_var_mapping[$module][$varname]; -} - -/** - * Convert given text input to singular. - */ -function vtlib_tosingular($text) { - $lastpos = strripos($text, 's'); - if($lastpos == strlen($text)-1) - return substr($text, 0, -1); - return $text; -} - -/** - * Get picklist values that is accessible by all roles. - */ -function vtlib_getPicklistValues_AccessibleToAll($field_columnname) { - global $adb; - - $columnname = $adb->sql_escape_string($field_columnname); - $tablename = "vtiger_$columnname"; - - // Gather all the roles (except H1 which is organization role) - $roleres = $adb->query("SELECT roleid FROM vtiger_role WHERE roleid != 'H1'"); - $roleresCount= $adb->num_rows($roleres); - $allroles = Array(); - if($roleresCount) { - for($index = 0; $index < $roleresCount; ++$index) - $allroles[] = $adb->query_result($roleres, $index, 'roleid'); - } - sort($allroles); - - // Get all the picklist values associated to roles (except H1 - organization role). - $picklistres = $adb->query( - "SELECT $columnname as pickvalue, roleid FROM $tablename - INNER JOIN vtiger_role2picklist ON $tablename.picklist_valueid=vtiger_role2picklist.picklistvalueid - WHERE roleid != 'H1'"); - - $picklistresCount = $adb->num_rows($picklistres); - - $picklistval_roles = Array(); - if($picklistresCount) { - for($index = 0; $index < $picklistresCount; ++$index) { - $picklistval = $adb->query_result($picklistres, $index, 'pickvalue'); - $pickvalroleid=$adb->query_result($picklistres, $index, 'roleid'); - $picklistval_roles[$picklistval][] = $pickvalroleid; - } - } - // Collect picklist value which is associated to all the roles. - $allrolevalues = Array(); - foreach($picklistval_roles as $picklistval => $pickvalroles) { - sort($pickvalroles); - $diff = array_diff($pickvalroles,$allroles); - if(empty($diff)) $allrolevalues[] = $picklistval; - } - - return $allrolevalues; -} - -/** - * Get all picklist values for a non-standard picklist type. - */ -function vtlib_getPicklistValues($field_columnname) { - global $adb; - - $columnname = $adb->sql_escape_string($field_columnname); - $tablename = "vtiger_$columnname"; - - $picklistres = $adb->query("SELECT $columnname as pickvalue FROM $tablename"); - - $picklistresCount = $adb->num_rows($picklistres); - - $picklistvalues = Array(); - if($picklistresCount) { - for($index = 0; $index < $picklistresCount; ++$index) { - $picklistvalues[] = $adb->query_result($picklistres, $index, 'pickvalue'); - } - } - return $picklistvalues; -} - -/** - * Check for custom module by its name. - */ -function vtlib_isCustomModule($moduleName) { - $moduleFile = "modules/$moduleName/$moduleName.php"; - if(file_exists($moduleFile)) { - if(function_exists('checkFileAccess')) { - checkFileAccess($moduleFile); - } - include_once($moduleFile); - $focus = new $moduleName(); - return (isset($focus->IsCustomModule) && $focus->IsCustomModule); - } - return false; -} - -/** - * Get module specific smarty template path. - */ -function vtlib_getModuleTemplate($module, $templateName) { - return ("modules/$module/$templateName"); -} - -/** - * Check if give path is writeable. - */ -function vtlib_isWriteable($path) { - if(is_dir($path)) { - return vtlib_isDirWriteable($path); - } else { - return is_writable($path); - } -} - -/** - * Check if given directory is writeable. - * NOTE: The check is made by trying to create a random file in the directory. - */ -function vtlib_isDirWriteable($dirpath) { - if(is_dir($dirpath)) { - do { - $tmpfile = 'vtiger' . time() . '-' . rand(1,1000) . '.tmp'; - // Continue the loop unless we find a name that does not exists already. - $usefilename = "$dirpath/$tmpfile"; - if(!file_exists($usefilename)) break; - } while(true); - $fh = @fopen($usefilename,'a'); - if($fh) { - fclose($fh); - unlink($usefilename); - return true; - } - } - return false; -} - -/** HTML Purifier global instance */ -$__htmlpurifier_instance = false; -/** - * Purify (Cleanup) malicious snippets of code from the input - * - * @param String $value - * @param Boolean $ignore Skip cleaning of the input - * @return String - */ -function vtlib_purify($input, $ignore=false) { - global $__htmlpurifier_instance, $root_directory, $default_charset; - - $use_charset = $default_charset; - $use_root_directory = $root_directory; - - $value = $input; - if(!$ignore) { - // Initialize the instance if it has not yet done - if($__htmlpurifier_instance == false) { - if(empty($use_charset)) $use_charset = 'UTF-8'; - if(empty($use_root_directory)) $use_root_directory = dirname(__FILE__) . '/../..'; - - include_once ('include/htmlpurifier/library/HTMLPurifier.auto.php'); - - $config = HTMLPurifier_Config::createDefault(); - $config->set('Core', 'Encoding', $use_charset); - $config->set('Cache', 'SerializerPath', "$use_root_directory/test/vtlib"); - - $__htmlpurifier_instance = new HTMLPurifier($config); - } - if($__htmlpurifier_instance) { - $value = $__htmlpurifier_instance->purify($input); - } - } - return $value; -} - -?> \ No newline at end of file +pquery("SELECT name FROM vtiger_tab WHERE tabid = ?",array($tabid)); + if($adb->num_rows($sqlresult)) return $adb->query_result($sqlresult, 0, 'name'); + return null; +} + +/** + * Get module names for which sharing access can be controlled. + * NOTE: Ignore the standard modules which is already handled. + */ +function vtlib_getModuleNameForSharing() { + global $adb; + $std_modules = array('Calendar','Leads','Accounts','Contacts','Potentials', + 'HelpDesk','Campaigns','Quotes','PurchaseOrder','SalesOrder','Invoice','Events'); + $modulesList = getSharingModuleList($std_modules); + return $modulesList; +} + +/** + * Cache the module active information for performance + */ +$__cache_module_activeinfo = Array(); + +/** + * Fetch module active information at one shot, but return all the information fetched. + */ +function vtlib_prefetchModuleActiveInfo($force = true) { + global $__cache_module_activeinfo; + + // Look up if cache has information + $tabrows = VTCacheUtils::lookupAllTabsInfo(); + + // Initialize from DB if cache information is not available or force flag is set + if($tabrows === false || $force) { + global $adb; + $tabres = $adb->query("SELECT * FROM vtiger_tab"); + $tabrows = array(); + if($tabres) { + while($tabresrow = $adb->fetch_array($tabres)) { + $tabrows[] = $tabresrow; + $__cache_module_activeinfo[$tabresrow['name']] = $tabresrow['presence']; + } + // Update cache for further re-use + VTCacheUtils::updateAllTabsInfo($tabrows); + } + } + + return $tabrows; +} + +/** + * Check if module is set active (or enabled) + */ +function vtlib_isModuleActive($module) { + global $adb, $__cache_module_activeinfo; + + if(in_array($module, vtlib_moduleAlwaysActive())){ + return true; + } + + if(!isset($__cache_module_activeinfo[$module])) { + include 'tabdata.php'; + $presence = isset($tab_info_array[$module])? 0: 1; + $__cache_module_activeinfo[$module] = $presence; + } else { + $presence = $__cache_module_activeinfo[$module]; + } + + $active = false; + if($presence != 1) $active = true; + + return $active; +} + +/** + * Recreate user privileges files. + */ +function vtlib_RecreateUserPrivilegeFiles() { + global $adb; + $userres = $adb->query('SELECT id FROM vtiger_users WHERE deleted = 0'); + if($userres && $adb->num_rows($userres)) { + while($userrow = $adb->fetch_array($userres)) { + createUserPrivilegesfile($userrow['id']); + } + } +} + +/** + * Get list module names which are always active (cannot be disabled) + */ +function vtlib_moduleAlwaysActive() { + $modules = Array ( + 'Administration', 'CustomView', 'Settings', 'Users', 'Migration', + 'Utilities', 'uploads', 'Import', 'System', 'com_vtiger_workflow', 'PickList', + ); + return $modules; +} + +/** + * Toggle the module (enable/disable) + */ +function vtlib_toggleModuleAccess($module, $enable_disable) { + global $adb, $__cache_module_activeinfo; + + include_once('vtlib/Vtiger/Module.php'); + + $event_type = false; + + if($enable_disable === true) { + $enable_disable = 0; + $event_type = Vtiger_Module::EVENT_MODULE_ENABLED; + } else if($enable_disable === false) { + $enable_disable = 1; + $event_type = Vtiger_Module::EVENT_MODULE_DISABLED; + } + + $adb->pquery("UPDATE vtiger_tab set presence = ? WHERE name = ?", array($enable_disable,$module)); + + $__cache_module_activeinfo[$module] = $enable_disable; + + create_tab_data_file(); + create_parenttab_data_file(); + + // UserPrivilege file needs to be regenerated if module state is changed from + // vtiger 5.1.0 onwards + global $vtiger_current_version; + if(version_compare($vtiger_current_version, '5.0.4', '>')) { + vtlib_RecreateUserPrivilegeFiles(); + } + + Vtiger_Module::fireEvent($module, $event_type); +} + +/** + * Get list of module with current status which can be controlled. + */ +function vtlib_getToggleModuleInfo() { + global $adb; + + $modinfo = Array(); + + $sqlresult = $adb->query("SELECT name, presence, customized, isentitytype FROM vtiger_tab WHERE name NOT IN ('Users') AND presence IN (0,1) ORDER BY name"); + $num_rows = $adb->num_rows($sqlresult); + for($idx = 0; $idx < $num_rows; ++$idx) { + $module = $adb->query_result($sqlresult, $idx, 'name'); + $presence=$adb->query_result($sqlresult, $idx, 'presence'); + $customized=$adb->query_result($sqlresult, $idx, 'customized'); + $isentitytype=$adb->query_result($sqlresult, $idx, 'isentitytype'); + $hassettings=file_exists("modules/$module/Settings.php"); + + $modinfo[$module] = Array( 'customized'=>$customized, 'presence'=>$presence, 'hassettings'=>$hassettings, 'isentitytype' => $isentitytype ); + } + return $modinfo; +} + +/** + * Get list of language and its current status. + */ +function vtlib_getToggleLanguageInfo() { + global $adb; + + // The table might not exists! + $old_dieOnError = $adb->dieOnError; + $adb->dieOnError = false; + + $langinfo = Array(); + $sqlresult = $adb->query("SELECT * FROM vtiger_language"); + if($sqlresult) { + for($idx = 0; $idx < $adb->num_rows($sqlresult); ++$idx) { + $row = $adb->fetch_array($sqlresult); + $langinfo[$row['prefix']] = Array( 'label'=>$row['label'], 'active'=>$row['active'] ); + } + } + $adb->dieOnError = $old_dieOnError; + return $langinfo; +} + +/** + * Toggle the language (enable/disable) + */ +function vtlib_toggleLanguageAccess($langprefix, $enable_disable) { + global $adb; + + // The table might not exists! + $old_dieOnError = $adb->dieOnError; + $adb->dieOnError = false; + + if($enable_disable === true) $enable_disable = 1; + else if($enable_disable === false) $enable_disable = 0; + + $adb->pquery('UPDATE vtiger_language set active = ? WHERE prefix = ?', Array($enable_disable, $langprefix)); + + $adb->dieOnError = $old_dieOnError; +} + +/** + * Get help information set for the module fields. + */ +function vtlib_getFieldHelpInfo($module) { + global $adb; + $fieldhelpinfo = Array(); + if(in_array('helpinfo', $adb->getColumnNames('vtiger_field'))) { + $result = $adb->pquery('SELECT fieldname,helpinfo FROM vtiger_field WHERE tabid=?', Array(getTabid($module))); + if($result && $adb->num_rows($result)) { + while($fieldrow = $adb->fetch_array($result)) { + $helpinfo = decode_html($fieldrow['helpinfo']); + if(!empty($helpinfo)) { + $fieldhelpinfo[$fieldrow['fieldname']] = getTranslatedString($helpinfo, $module); + } + } + } + } + return $fieldhelpinfo; +} + +/** + * Setup mandatory (requried) module variable values in the module class. + */ +function vtlib_setup_modulevars($module, $focus) { + + $checkfor = Array('table_name', 'table_index', 'related_tables', 'popup_fields', 'IsCustomModule'); + foreach($checkfor as $check) { + if(!isset($focus->$check)) $focus->$check = __vtlib_get_modulevar_value($module, $check); + } +} +function __vtlib_get_modulevar_value($module, $varname) { + $mod_var_mapping = + Array( + 'Accounts' => + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_account', + 'table_index' => 'accountid', + // related_tables variable should define the association (relation) between dependent tables + // FORMAT: related_tablename => Array ( related_tablename_column[, base_tablename, base_tablename_column] ) + // Here base_tablename_column should establish relation with related_tablename_column + // NOTE: If base_tablename and base_tablename_column are not specified, it will default to modules (table_name, related_tablename_column) + 'related_tables' => Array( + 'vtiger_accountbillads' => Array ('accountaddressid', 'vtiger_account', 'accountid'), + 'vtiger_accountshipads' => Array ('accountaddressid', 'vtiger_account', 'accountid'), + ), + 'popup_fields' => Array('accountname'), // TODO: Add this initialization to all the standard module + ), + 'Contacts' => + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_contactdetails', + 'table_index' => 'contactid', + 'related_tables'=> Array( 'vtiger_account' => Array ('accountid' ) ), + 'popup_fields' => Array ('lastname'), + ), + 'Leads' => + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_leaddetails', + 'table_index' => 'leadid', + 'related_tables' => Array ( + 'vtiger_leadsubdetails' => Array ( 'leadsubscriptionid', 'vtiger_leaddetails', 'leadid' ), + 'vtiger_leadaddress' => Array ( 'leadaddressid', 'vtiger_leaddetails', 'leadid' ), + ), + 'popup_fields'=> Array ('lastname'), + ), + 'Campaigns' => + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_campaign', + 'table_index' => 'campaignid', + 'popup_fields' => Array ('campaignname'), + ), + 'Potentials' => + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_potential', + 'table_index'=> 'potentialid', + // NOTE: UIType 10 is being used instead of direct relationship from 5.1.0 + //'related_tables' => Array ('vtiger_account' => Array('accountid')), + 'popup_fields'=> Array('potentialname'), + ), + 'Quotes' => + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_quotes', + 'table_index'=> 'quoteid', + 'related_tables' => Array ('vtiger_account' => Array('accountid')), + 'popup_fields'=>Array('subject'), + ), + 'SalesOrder'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_salesorder', + 'table_index'=> 'salesorderid', + 'related_tables'=> Array ('vtiger_account' => Array('accountid')), + 'popup_fields'=>Array('subject'), + ), + 'PurchaseOrder'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_purchaseorder', + 'table_index'=> 'purchaseorderid', + 'popup_fields'=>Array('subject'), + ), + 'Invoice'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_invoice', + 'table_index'=> 'invoiceid', + 'popup_fields'=> Array('subject'), + ), + 'HelpDesk'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_troubletickets', + 'table_index'=> 'ticketid', + 'popup_fields'=> Array('ticket_title') + ), + 'Faq'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_faq', + 'table_index'=> 'id', + ), + 'Documents'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_notes', + 'table_index'=> 'notesid', + ), + 'Products'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_products', + 'table_index'=> 'productid', + 'popup_fields'=> Array('productname'), + ), + 'PriceBooks'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_pricebook', + 'table_index'=> 'pricebookid', + ), + 'Vendors'=> + Array( + 'IsCustomModule'=>false, + 'table_name' => 'vtiger_vendor', + 'table_index'=> 'vendorid', + 'popup_fields'=>Array('vendorname'), + ) + ); + return $mod_var_mapping[$module][$varname]; +} + +/** + * Convert given text input to singular. + */ +function vtlib_tosingular($text) { + $lastpos = strripos($text, 's'); + if($lastpos == strlen($text)-1) + return substr($text, 0, -1); + return $text; +} + +/** + * Get picklist values that is accessible by all roles. + */ +function vtlib_getPicklistValues_AccessibleToAll($field_columnname) { + global $adb; + + $columnname = $adb->sql_escape_string($field_columnname); + $tablename = "vtiger_$columnname"; + + // Gather all the roles (except H1 which is organization role) + $roleres = $adb->query("SELECT roleid FROM vtiger_role WHERE roleid != 'H1'"); + $roleresCount= $adb->num_rows($roleres); + $allroles = Array(); + if($roleresCount) { + for($index = 0; $index < $roleresCount; ++$index) + $allroles[] = $adb->query_result($roleres, $index, 'roleid'); + } + sort($allroles); + + // Get all the picklist values associated to roles (except H1 - organization role). + $picklistres = $adb->query( + "SELECT $columnname as pickvalue, roleid FROM $tablename + INNER JOIN vtiger_role2picklist ON $tablename.picklist_valueid=vtiger_role2picklist.picklistvalueid + WHERE roleid != 'H1'"); + + $picklistresCount = $adb->num_rows($picklistres); + + $picklistval_roles = Array(); + if($picklistresCount) { + for($index = 0; $index < $picklistresCount; ++$index) { + $picklistval = $adb->query_result($picklistres, $index, 'pickvalue'); + $pickvalroleid=$adb->query_result($picklistres, $index, 'roleid'); + $picklistval_roles[$picklistval][] = $pickvalroleid; + } + } + // Collect picklist value which is associated to all the roles. + $allrolevalues = Array(); + foreach($picklistval_roles as $picklistval => $pickvalroles) { + sort($pickvalroles); + $diff = array_diff($pickvalroles,$allroles); + if(empty($diff)) $allrolevalues[] = $picklistval; + } + + return $allrolevalues; +} + +/** + * Get all picklist values for a non-standard picklist type. + */ +function vtlib_getPicklistValues($field_columnname) { + global $adb; + + $columnname = $adb->sql_escape_string($field_columnname); + $tablename = "vtiger_$columnname"; + + $picklistres = $adb->query("SELECT $columnname as pickvalue FROM $tablename"); + + $picklistresCount = $adb->num_rows($picklistres); + + $picklistvalues = Array(); + if($picklistresCount) { + for($index = 0; $index < $picklistresCount; ++$index) { + $picklistvalues[] = $adb->query_result($picklistres, $index, 'pickvalue'); + } + } + return $picklistvalues; +} + +/** + * Check for custom module by its name. + */ +function vtlib_isCustomModule($moduleName) { + $moduleFile = "modules/$moduleName/$moduleName.php"; + if(file_exists($moduleFile)) { + if(function_exists('checkFileAccess')) { + checkFileAccess($moduleFile); + } + include_once($moduleFile); + $focus = new $moduleName(); + return (isset($focus->IsCustomModule) && $focus->IsCustomModule); + } + return false; +} + +/** + * Get module specific smarty template path. + */ +function vtlib_getModuleTemplate($module, $templateName) { + return ("modules/$module/$templateName"); +} + +/** + * Check if give path is writeable. + */ +function vtlib_isWriteable($path) { + if(is_dir($path)) { + return vtlib_isDirWriteable($path); + } else { + return is_writable($path); + } +} + +/** + * Check if given directory is writeable. + * NOTE: The check is made by trying to create a random file in the directory. + */ +function vtlib_isDirWriteable($dirpath) { + if(is_dir($dirpath)) { + do { + $tmpfile = 'vtiger' . time() . '-' . rand(1,1000) . '.tmp'; + // Continue the loop unless we find a name that does not exists already. + $usefilename = "$dirpath/$tmpfile"; + if(!file_exists($usefilename)) break; + } while(true); + $fh = @fopen($usefilename,'a'); + if($fh) { + fclose($fh); + unlink($usefilename); + return true; + } + } + return false; +} + +/** HTML Purifier global instance */ +$__htmlpurifier_instance = false; +/** + * Purify (Cleanup) malicious snippets of code from the input + * + * @param String $value + * @param Boolean $ignore Skip cleaning of the input + * @return String + */ +function vtlib_purify($input, $ignore=false) { + global $__htmlpurifier_instance, $root_directory, $default_charset; + + $use_charset = $default_charset; + $use_root_directory = $root_directory; + + $value = $input; + if(!$ignore) { + // Initialize the instance if it has not yet done + if($__htmlpurifier_instance == false) { + if(empty($use_charset)) $use_charset = 'UTF-8'; + if(empty($use_root_directory)) $use_root_directory = dirname(__FILE__) . '/../..'; + + include_once ('include/htmlpurifier/library/HTMLPurifier.auto.php'); + + $config = HTMLPurifier_Config::createDefault(); + $config->set('Core', 'Encoding', $use_charset); + $config->set('Cache', 'SerializerPath', "$use_root_directory/test/vtlib"); + + $__htmlpurifier_instance = new HTMLPurifier($config); + } + if($__htmlpurifier_instance) { + $value = $__htmlpurifier_instance->purify($input); + } + } + return $value; +} + +/** + * Process the UI Widget requested + * @param Vtiger_Link $widgetLinkInfo + * @param Current Smarty Context $context + * @return + */ +function vtlib_process_widget($widgetLinkInfo, $context = false) { + if (preg_match("/^block:\/\/(.*)/", $widgetLinkInfo->linkurl, $matches)) { + list($widgetControllerClass, $widgetControllerClassFile) = explode(':', $matches[1]); + if (!class_exists($widgetControllerClass)) { + checkFileAccess($widgetControllerClassFile); + include_once $widgetControllerClassFile; + } + if (class_exists($widgetControllerClass)) { + $widgetControllerInstance = new $widgetControllerClass; + $widgetInstance = $widgetControllerInstance->getWidget($widgetLinkInfo->linklabel); + if ($widgetInstance) { + return $widgetInstance->process($context); + } + } + } + return ""; +} + +?> diff --git a/oss/vtiger/trunk/include/utils/encryption.php b/oss/vtiger/trunk/include/utils/encryption.php index 3d177758..2b73a11d 100644 --- a/oss/vtiger/trunk/include/utils/encryption.php +++ b/oss/vtiger/trunk/include/utils/encryption.php @@ -1,111 +1,111 @@ -asc2bin($message); - $enc_message = $this -> xor_string($enc_message); - $enc_message = $this -> urlsafe_b64encode($enc_message); - return $enc_message; - } - function asc2bin($inputString, $byteLength=8) - { - $binaryOutput = ''; - $strSize = strlen($inputString); - for($x=0; $x<$strSize; $x++) - { - $charBin = decbin(ord($inputString{$x})); - $charBin = str_pad($charBin, $byteLength, '0', STR_PAD_LEFT); - $binaryOutput .= $charBin; - } - - return $binaryOutput; - } - - function bin2asc($binaryInput, $byteLength=8) - { - if (strlen($binaryInput) % $byteLength) - { - return false; - } - // why run strlen() so many times in a loop? Use of constants = speed increase. - $strSize = strlen($binaryInput); - $origStr = ''; - // jump between bytes. - for($x=0; $x<$strSize; $x += $byteLength) - { - // extract character's binary code - $charBinary = substr($binaryInput, $x, $byteLength); - $origStr .= chr(bindec($charBinary)); // conversion to ASCII. - } - return $origStr; - } - - function decrypt($message) - { - $dec_message = $this -> urlsafe_b64decode($message); - $dec_message = $this -> xor_string($dec_message); - $dec_message = $this->bin2asc($dec_message); - return $dec_message; - } - function xor_string($string) - { - $buf = ''; - $size = strlen($string); - for ($i=0; $i<$size; $i++) - $buf .= chr(ord($string[$i]) ^ 255); - return $buf; - } - function urlsafe_b64encode($string) - { - $data = base64_encode($string); - $data = str_replace(array('+','/','='),array('-','_','.'),$data); - return $data; - } - - function urlsafe_b64decode($string) - { - $data = str_replace(array('-','_'),array('+','/'),$string); - $mod4 = strlen($data) % 4; - if ($mod4) - { - $data .= substr('====', $mod4); - } - return base64_decode($data); - } - function x_Encrypt($string, $key) - { - for($i=0; $iasc2bin($message); + $enc_message = $this -> xor_string($enc_message); + $enc_message = $this -> urlsafe_b64encode($enc_message); + return $enc_message; + } + function asc2bin($inputString, $byteLength=8) + { + $binaryOutput = ''; + $strSize = strlen($inputString); + for($x=0; $x<$strSize; $x++) + { + $charBin = decbin(ord($inputString{$x})); + $charBin = str_pad($charBin, $byteLength, '0', STR_PAD_LEFT); + $binaryOutput .= $charBin; + } + + return $binaryOutput; + } + + function bin2asc($binaryInput, $byteLength=8) + { + if (strlen($binaryInput) % $byteLength) + { + return false; + } + // why run strlen() so many times in a loop? Use of constants = speed increase. + $strSize = strlen($binaryInput); + $origStr = ''; + // jump between bytes. + for($x=0; $x<$strSize; $x += $byteLength) + { + // extract character's binary code + $charBinary = substr($binaryInput, $x, $byteLength); + $origStr .= chr(bindec($charBinary)); // conversion to ASCII. + } + return $origStr; + } + + function decrypt($message) + { + $dec_message = $this -> urlsafe_b64decode($message); + $dec_message = $this -> xor_string($dec_message); + $dec_message = $this->bin2asc($dec_message); + return $dec_message; + } + function xor_string($string) + { + $buf = ''; + $size = strlen($string); + for ($i=0; $i<$size; $i++) + $buf .= chr(ord($string[$i]) ^ 255); + return $buf; + } + function urlsafe_b64encode($string) + { + $data = base64_encode($string); + $data = str_replace(array('+','/','='),array('-','_','.'),$data); + return $data; + } + + function urlsafe_b64decode($string) + { + $data = str_replace(array('-','_'),array('+','/'),$string); + $mod4 = strlen($data) % 4; + if ($mod4) + { + $data .= substr('====', $mod4); + } + return base64_decode($data); + } + function x_Encrypt($string, $key) + { + for($i=0; $iretrieveCurrentUserInfoFromFile($_SESSION['authenticated_user_id'],"Users"); - if($result == null) - { - session_destroy(); - header("Location: index.php?action=Login&module=Users"); - exit; - } - -} - -//Security Check -if(isPermitted($_REQUEST['module'],"Export") == "no") -{ - $allow_exports="none"; -} - -if ($allow_exports=='none' || ( $allow_exports=='admin' && ! is_admin($current_user) ) ) -{ - -?> - - - -debug("Entering br2nl_vt(".$str.") method ..."); - $str = preg_replace("/(\r\n)/", " ", $str); - $log->debug("Exiting br2nl_vt method ..."); - return $str; -} - -/** - * This function exports all the data for a given module - * Param $type - module name - * Return type text - */ -function export($type){ - global $log,$list_max_entries_per_page; - $log->debug("Entering export(".$type.") method ..."); - global $adb; - - $focus = 0; - $content = ''; - - if ($type != ""){ - // vtlib customization: Hook to dynamically include required module file. - // Refer to the logic in setting $currentModule in index.php - $focus = CRMEntity::getInstance($type); - } - $log = LoggerManager::getLogger('export_'.$type); - $db = PearDatabase::getInstance(); - - $oCustomView = new CustomView("$type"); - $viewid = $oCustomView->getViewId("$type"); - $sorder = $focus->getSortOrder(); - $order_by = $focus->getOrderBy(); - - $search_type = $_REQUEST['search_type']; - $export_data = $_REQUEST['export_data']; - - if(isset($_SESSION['export_where']) && $_SESSION['export_where']!='' && $search_type == 'includesearch'){ - $where =$_SESSION['export_where']; - } - - $query = $focus->create_export_query($where); - $stdfiltersql = $oCustomView->getCVStdFilterSQL($viewid); - $advfiltersql = $oCustomView->getCVAdvFilterSQL($viewid); - if(isset($stdfiltersql) && $stdfiltersql != ''){ - $query .= ' and '.$stdfiltersql; - } - if(isset($advfiltersql) && $advfiltersql != '') { - $query .= ' and '.$advfiltersql; - } - $params = array(); - - if(($search_type == 'withoutsearch' || $search_type == 'includesearch') && $export_data == 'selecteddata'){ - $idstring = explode(";", $_REQUEST['idstring']); - if($type == 'Accounts' && count($idstring) > 0) { - $query .= ' and vtiger_account.accountid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'Contacts' && count($idstring) > 0) { - $query .= ' and vtiger_contactdetails.contactid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'Potentials' && count($idstring) > 0) { - $query .= ' and vtiger_potential.potentialid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'Leads' && count($idstring) > 0) { - $query .= ' and vtiger_leaddetails.leadid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'Products' && count($idstring) > 0) { - $query .= ' and vtiger_products.productid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'Documents' && count($idstring) > 0) { - $query .= ' and vtiger_notes.notesid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'HelpDesk' && count($idstring) > 0) { - $query .= ' and vtiger_troubletickets.ticketid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } elseif($type == 'Vendors' && count($idstring) > 0) { - $query .= ' and vtiger_vendor.vendorid in ('. generateQuestionMarks($idstring) .')'; - array_push($params, $idstring); - } else if(count($idstring) > 0) { - // vtlib customization: Hook to make the export feature available for custom modules. - $query .= " and $focus->table_name.$focus->table_index in (" . generateQuestionMarks($idstring) . ')'; - array_push($params, $idstring); - // END - } - } - - if(isset($order_by) && $order_by != ''){ - if($order_by == 'smownerid'){ - $query .= ' ORDER BY user_name '.$sorder; - }elseif($order_by == 'lastname' && $type == 'Documents'){ - $query .= ' ORDER BY vtiger_contactdetails.lastname '. $sorder; - }elseif($order_by == 'crmid' && $type == 'HelpDesk'){ - $query .= ' ORDER BY vtiger_troubletickets.ticketid '. $sorder; - }else{ - $tablename = getTableNameForField($type,$order_by); - $tablename = (($tablename != '')?($tablename."."):''); - if( $adb->dbType == "pgsql"){ - $query .= ' GROUP BY '.$tablename.$order_by; - } - $query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; - } - } - - if($export_data == 'currentpage'){ - $current_page = ListViewSession::getCurrentPage($type,$viewid); - $limit_start_rec = ($current_page - 1) * $list_max_entries_per_page; - if ($limit_start_rec < 0) $limit_start_rec = 0; - $query .= ' LIMIT '.$limit_start_rec.','.$list_max_entries_per_page; - } - - $result = $adb->pquery($query, $params, true, "Error exporting $type: "."
$query"); - $fields_array = $adb->getFieldsArray($result); - $fields_array = array_diff($fields_array,array("user_name")); - - $__processor = new ExportUtils($type, $fields_array); - - // Translated the field names based on the language used. - $translated_fields_array = array(); - for($i=0; $ifetchByAssoc($result, -1, false)){ - $new_arr = array(); - $val = $__processor->sanitizeValues($val); - foreach ($val as $key => $value){ - if($type == 'Documents' && $key == 'description'){ - $value = strip_tags($value); - $value = str_replace(' ','',$value); - array_push($new_arr,$value); - }elseif($key != "user_name"){ - // Let us provide the module to transform the value before we save it to CSV file - $value = $focus->transform_export_value($key, $value); - - array_push($new_arr, preg_replace("/\"/","\"\"",$value)); - } - } - $line = implode("\",\"",$new_arr); - $line = "\"" .$line; - $line .= "\"\r\n"; - - /** Output each row information */ - echo $line; - } - $log->debug("Exiting export method ..."); - return true; -} - -/** Send the output header and invoke function for contents output */ -header("Content-Disposition:attachment;filename={$_REQUEST['module']}.csv"); -header("Content-Type:text/csv;charset=UTF-8"); -header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); -header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" ); -header("Cache-Control: post-check=0, pre-check=0", false ); - -export(vtlib_purify($_REQUEST['module'])); - -exit; - -/** - * this class will provide utility functions to process the export data. - * this is to make sure that the data is sanitized before sending for export - */ -class ExportUtils{ - var $fieldsArr = array(); - var $picklistValues = array(); - - function ExportUtils($module, $fields_array){ - self::__init($module, $fields_array); - } - - - function __init($module, $fields_array){ - $infoArr = self::getInformationArray($module); - - //attach extra fields related information to the fields_array; this will be useful for processing the export data - foreach($infoArr as $fieldname=>$fieldinfo){ - if(in_array($fieldinfo["fieldlabel"], $fields_array)){ - $this->fieldsArr[$fieldname] = $fieldinfo; - } - } - } - - /** - * this function takes in an array of values for an user and sanitizes it for export - * @param array $arr - the array of values - */ - function sanitizeValues($arr){ - global $current_user, $adb; - $roleid = fetchUserRole($current_user->id); - - foreach($arr as $fieldlabel=>&$value){ - $fieldInfo = $this->fieldsArr[$fieldlabel]; - - $uitype = $fieldInfo['uitype']; - $fieldname = $fieldInfo['fieldname']; - if($uitype == 15 || $uitype == 16 || $uitype == 33){ - //picklists - if(empty($this->picklistValues[$fieldname])){ - $this->picklistValues[$fieldname] = getAssignedPicklistValues($fieldname, $roleid, $adb); - } - $value = trim($value); - if(!empty($this->picklistValues[$fieldname]) && !in_array($value, $this->picklistValues[$fieldname]) && !empty($value)){ - $value = getTranslatedString("LBL_NOT_ACCESSIBLE"); - } - }elseif($uitype == 10){ - //have to handle uitype 10 - $value = trim($value); - if(!empty($value)) { - $parent_module = getSalesEntityType($value); - $displayValueArray = getEntityName($parent_module, $value); - if(!empty($displayValueArray)){ - foreach($displayValueArray as $k=>$v){ - $displayValue = $v; - } - } - if(!empty($parent_module) && !empty($displayValue)){ - $value = $parent_module."::::".$displayValue; - }else{ - $value = ""; - } - } else { - $value = ''; - } - } - } - return $arr; - } - - /** - * this function takes in a module name and returns the field information for it - */ - function getInformationArray($module){ - require_once 'include/utils/utils.php'; - global $adb; - $tabid = getTabid($module); - - $result = $adb->pquery("select * from vtiger_field where tabid=?", array($tabid)); - $count = $adb->num_rows($result); - $arr = array(); - $data = array(); - - for($i=0;$i<$count;$i++){ - $arr['uitype'] = $adb->query_result($result, $i, "uitype"); - $arr['fieldname'] = $adb->query_result($result, $i, "fieldname"); - $arr['columnname'] = $adb->query_result($result, $i, "columnname"); - $arr['tablename'] = $adb->query_result($result, $i, "tablename"); - $arr['fieldlabel'] = $adb->query_result($result, $i, "fieldlabel"); - $fieldlabel = strtolower($arr['fieldlabel']); - $data[$fieldlabel] = $arr; - } - return $data; - } -} +retrieveCurrentUserInfoFromFile($_SESSION['authenticated_user_id'],"Users"); + if($result == null) + { + session_destroy(); + header("Location: index.php?action=Login&module=Users"); + exit; + } + +} + +//Security Check +if(isPermitted($_REQUEST['module'],"Export") == "no") +{ + $allow_exports="none"; +} + +if ($allow_exports=='none' || ( $allow_exports=='admin' && ! is_admin($current_user) ) ) +{ + +?> + + + +debug("Entering br2nl_vt(".$str.") method ..."); + $str = preg_replace("/(\r\n)/", " ", $str); + $log->debug("Exiting br2nl_vt method ..."); + return $str; +} + +/** + * This function exports all the data for a given module + * Param $type - module name + * Return type text + */ +function export($type){ + global $log,$list_max_entries_per_page; + $log->debug("Entering export(".$type.") method ..."); + global $adb; + + $focus = 0; + $content = ''; + + if ($type != ""){ + // vtlib customization: Hook to dynamically include required module file. + // Refer to the logic in setting $currentModule in index.php + $focus = CRMEntity::getInstance($type); + } + $log = LoggerManager::getLogger('export_'.$type); + $db = PearDatabase::getInstance(); + + $oCustomView = new CustomView("$type"); + $viewid = $oCustomView->getViewId("$type"); + $sorder = $focus->getSortOrder(); + $order_by = $focus->getOrderBy(); + + $search_type = $_REQUEST['search_type']; + $export_data = $_REQUEST['export_data']; + + if(isset($_SESSION['export_where']) && $_SESSION['export_where']!='' && $search_type == 'includesearch'){ + $where =$_SESSION['export_where']; + } + + $query = $focus->create_export_query($where); + if($search_type != 'includesearch' && $type != 'Calendar') { + $stdfiltersql = $oCustomView->getCVStdFilterSQL($viewid); + $advfiltersql = $oCustomView->getCVAdvFilterSQL($viewid); + if(isset($stdfiltersql) && $stdfiltersql != ''){ + $query .= ' and '.$stdfiltersql; + } + if(isset($advfiltersql) && $advfiltersql != '') { + $query .= ' and '.$advfiltersql; + } + } + $params = array(); + + if(($search_type == 'withoutsearch' || $search_type == 'includesearch') && $export_data == 'selecteddata'){ + $idstring = explode(";", $_REQUEST['idstring']); + if($type == 'Accounts' && count($idstring) > 0) { + $query .= ' and vtiger_account.accountid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'Contacts' && count($idstring) > 0) { + $query .= ' and vtiger_contactdetails.contactid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'Potentials' && count($idstring) > 0) { + $query .= ' and vtiger_potential.potentialid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'Leads' && count($idstring) > 0) { + $query .= ' and vtiger_leaddetails.leadid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'Products' && count($idstring) > 0) { + $query .= ' and vtiger_products.productid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'Documents' && count($idstring) > 0) { + $query .= ' and vtiger_notes.notesid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'HelpDesk' && count($idstring) > 0) { + $query .= ' and vtiger_troubletickets.ticketid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } elseif($type == 'Vendors' && count($idstring) > 0) { + $query .= ' and vtiger_vendor.vendorid in ('. generateQuestionMarks($idstring) .')'; + array_push($params, $idstring); + } else if(count($idstring) > 0) { + // vtlib customization: Hook to make the export feature available for custom modules. + $query .= " and $focus->table_name.$focus->table_index in (" . generateQuestionMarks($idstring) . ')'; + array_push($params, $idstring); + // END + } + } + + if(isset($order_by) && $order_by != ''){ + if($order_by == 'smownerid'){ + $query .= ' ORDER BY user_name '.$sorder; + }elseif($order_by == 'lastname' && $type == 'Documents'){ + $query .= ' ORDER BY vtiger_contactdetails.lastname '. $sorder; + }elseif($order_by == 'crmid' && $type == 'HelpDesk'){ + $query .= ' ORDER BY vtiger_troubletickets.ticketid '. $sorder; + }else{ + $tablename = getTableNameForField($type,$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if( $adb->dbType == "pgsql"){ + $query .= ' GROUP BY '.$tablename.$order_by; + } + $query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } + } + + if($export_data == 'currentpage'){ + $current_page = ListViewSession::getCurrentPage($type,$viewid); + $limit_start_rec = ($current_page - 1) * $list_max_entries_per_page; + if ($limit_start_rec < 0) $limit_start_rec = 0; + $query .= ' LIMIT '.$limit_start_rec.','.$list_max_entries_per_page; + } + + $result = $adb->pquery($query, $params, true, "Error exporting $type: "."
$query"); + $fields_array = $adb->getFieldsArray($result); + $fields_array = array_diff($fields_array,array("user_name")); + + $__processor = new ExportUtils($type, $fields_array); + + // Translated the field names based on the language used. + $translated_fields_array = array(); + for($i=0; $ifetchByAssoc($result, -1, false)){ + $new_arr = array(); + $val = $__processor->sanitizeValues($val); + foreach ($val as $key => $value){ + if($type == 'Documents' && $key == 'description'){ + $value = strip_tags($value); + $value = str_replace(' ','',$value); + array_push($new_arr,$value); + }elseif($key != "user_name"){ + // Let us provide the module to transform the value before we save it to CSV file + $value = $focus->transform_export_value($key, $value); + + array_push($new_arr, preg_replace("/\"/","\"\"",$value)); + } + } + $line = implode("\",\"",$new_arr); + $line = "\"" .$line; + $line .= "\"\r\n"; + + /** Output each row information */ + echo $line; + } + $log->debug("Exiting export method ..."); + return true; +} + +/** Send the output header and invoke function for contents output */ +header("Content-Disposition:attachment;filename={$_REQUEST['module']}.csv"); +header("Content-Type:text/csv;charset=UTF-8"); +header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); +header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" ); +header("Cache-Control: post-check=0, pre-check=0", false ); + +export(vtlib_purify($_REQUEST['module'])); + +exit; + +/** + * this class will provide utility functions to process the export data. + * this is to make sure that the data is sanitized before sending for export + */ +class ExportUtils{ + var $fieldsArr = array(); + var $picklistValues = array(); + + function ExportUtils($module, $fields_array){ + self::__init($module, $fields_array); + } + + + function __init($module, $fields_array){ + $infoArr = self::getInformationArray($module); + + //attach extra fields related information to the fields_array; this will be useful for processing the export data + foreach($infoArr as $fieldname=>$fieldinfo){ + if(in_array($fieldinfo["fieldlabel"], $fields_array)){ + $this->fieldsArr[$fieldname] = $fieldinfo; + } + } + } + + /** + * this function takes in an array of values for an user and sanitizes it for export + * @param array $arr - the array of values + */ + function sanitizeValues($arr){ + global $current_user, $adb; + $roleid = fetchUserRole($current_user->id); + + foreach($arr as $fieldlabel=>&$value){ + $fieldInfo = $this->fieldsArr[$fieldlabel]; + + $uitype = $fieldInfo['uitype']; + $fieldname = $fieldInfo['fieldname']; + if($uitype == 15 || $uitype == 16 || $uitype == 33){ + //picklists + if(empty($this->picklistValues[$fieldname])){ + $this->picklistValues[$fieldname] = getAssignedPicklistValues($fieldname, $roleid, $adb); + } + $value = trim($value); + if(!empty($this->picklistValues[$fieldname]) && !in_array($value, $this->picklistValues[$fieldname]) && !empty($value)){ + $value = getTranslatedString("LBL_NOT_ACCESSIBLE"); + } + }elseif($uitype == 10){ + //have to handle uitype 10 + $value = trim($value); + if(!empty($value)) { + $parent_module = getSalesEntityType($value); + $displayValueArray = getEntityName($parent_module, $value); + if(!empty($displayValueArray)){ + foreach($displayValueArray as $k=>$v){ + $displayValue = $v; + } + } + if(!empty($parent_module) && !empty($displayValue)){ + $value = $parent_module."::::".$displayValue; + }else{ + $value = ""; + } + } else { + $value = ''; + } + } + } + return $arr; + } + + /** + * this function takes in a module name and returns the field information for it + */ + function getInformationArray($module){ + require_once 'include/utils/utils.php'; + global $adb; + $tabid = getTabid($module); + + $result = $adb->pquery("select * from vtiger_field where tabid=?", array($tabid)); + $count = $adb->num_rows($result); + $arr = array(); + $data = array(); + + for($i=0;$i<$count;$i++){ + $arr['uitype'] = $adb->query_result($result, $i, "uitype"); + $arr['fieldname'] = $adb->query_result($result, $i, "fieldname"); + $arr['columnname'] = $adb->query_result($result, $i, "columnname"); + $arr['tablename'] = $adb->query_result($result, $i, "tablename"); + $arr['fieldlabel'] = $adb->query_result($result, $i, "fieldlabel"); + $fieldlabel = strtolower($arr['fieldlabel']); + $data[$fieldlabel] = $arr; + } + return $data; + } +} ?> \ No newline at end of file diff --git a/oss/vtiger/trunk/include/utils/utils.php b/oss/vtiger/trunk/include/utils/utils.php index 9be70360..77a37494 100644 --- a/oss/vtiger/trunk/include/utils/utils.php +++ b/oss/vtiger/trunk/include/utils/utils.php @@ -1,4872 +1,4866 @@ -debug("Entering return_name(".$row.",".$first_column.",".$last_column.") method ..."); - $first_name = ""; - $last_name = ""; - $full_name = ""; - - if(isset($row[$first_column])) - { - $first_name = stripslashes($row[$first_column]); - } - - if(isset($row[$last_column])) - { - $last_name = stripslashes($row[$last_column]); - } - - $full_name = $first_name; - - // If we have a first name and we have a last name - if($full_name != "" && $last_name != "") - { - // append a space, then the last name - $full_name .= " ".$last_name; - } - // If we have no first name, but we have a last name - else if($last_name != "") - { - // append the last name without the space. - $full_name .= $last_name; - } - - $log->debug("Exiting return_name method ..."); - return $full_name; -} - -/** Function to return language - * @returns $languages -- languages:: Type string - * -*/ - -function get_languages() -{ - global $log; - $log->debug("Entering get_languages() method ..."); - global $languages; - $log->debug("Exiting get_languages method ..."); - return $languages; -} - -/** Function to return language - * @param $key -- key:: Type string - * @returns $languages -- languages:: Type string - * -*/ - -//seems not used -function get_language_display($key) -{ - global $log; - $log->debug("Entering get_language_display(".$key.") method ..."); - global $languages; - $log->debug("Exiting get_language_display method ..."); - return $languages[$key]; -} - -/** Function returns the user array - * @param $assigned_user_id -- assigned_user_id:: Type string - * @returns $user_list -- user list:: Type array - * -*/ - -function get_assigned_user_name(&$assigned_user_id) -{ - global $log; - $log->debug("Entering get_assigned_user_name(".$assigned_user_id.") method ..."); - $user_list = &get_user_array(false,""); - if(isset($user_list[$assigned_user_id])) - { - $log->debug("Exiting get_assigned_user_name method ..."); - return $user_list[$assigned_user_id]; - } - - $log->debug("Exiting get_assigned_user_name method ..."); - return ""; -} - -/** Function returns the user key in user array - * @param $add_blank -- boolean:: Type boolean - * @param $status -- user status:: Type string - * @param $assigned_user -- user id:: Type string - * @param $private -- sharing type:: Type string - * @returns $user_array -- user array:: Type array - * -*/ - -//used in module file -function get_user_array($add_blank=true, $status="Active", $assigned_user="",$private="") -{ - global $log; - $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); - global $current_user; - if(isset($current_user) && $current_user->id != '') - { - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - } - static $user_array = null; - $module=$_REQUEST['module']; - - if($user_array == null) - { - require_once('include/database/PearDatabase.php'); - $db = PearDatabase::getInstance(); - $temp_result = Array(); - // Including deleted vtiger_users for now. - if (empty($status)) { - $query = "SELECT id, user_name from vtiger_users"; - $params = array(); - } - else { - if($private == 'private') - { - $log->debug("Sharing is Private. Only the current user should be listed"); - $query = "select id as id,user_name as user_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ? and status='Active' union select shareduserid as id,vtiger_users.user_name as user_name from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=?"; - $params = array($current_user->id, $current_user_parent_role_seq."::%", $current_user->id, getTabid($module)); - } - else - { - $log->debug("Sharing is Public. All vtiger_users should be listed"); - $query = "SELECT id, user_name from vtiger_users WHERE status=?"; - $params = array($status); - } - } - if (!empty($assigned_user)) { - $query .= " OR id=?"; - array_push($params, $assigned_user); - } - - $query .= " order by user_name ASC"; - - $result = $db->pquery($query, $params, true, "Error filling in user array: "); - - if ($add_blank==true){ - // Add in a blank row - $temp_result[''] = ''; - } - - // Get the id and the name. - while($row = $db->fetchByAssoc($result)) - { - $temp_result[$row['id']] = $row['user_name']; - } - - $user_array = &$temp_result; - } - - $log->debug("Exiting get_user_array method ..."); - - return $user_array; -} - -function get_group_array($add_blank=true, $status="Active", $assigned_user="",$private="") -{ - global $log; - $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); - global $current_user; - if(isset($current_user) && $current_user->id != '') - { - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - } - static $group_array = null; - $module=$_REQUEST['module']; - - if($group_array == null) - { - require_once('include/database/PearDatabase.php'); - $db = PearDatabase::getInstance(); - $temp_result = Array(); - // Including deleted vtiger_users for now. - $log->debug("Sharing is Public. All vtiger_users should be listed"); - $query = "SELECT groupid, groupname from vtiger_groups"; - $params = array(); - - if($private == 'private'){ - - $query .= " WHERE groupid=?"; - $params = array( $current_user->id); - - if(count($current_user_groups) != 0) { - $query .= " OR vtiger_groups.groupid in (".generateQuestionMarks($current_user_groups).")"; - array_push($params, $current_user_groups); - } - $log->debug("Sharing is Private. Only the current user should be listed"); - $query .= " union select vtiger_group2role.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_group2role inner join vtiger_groups on vtiger_groups.groupid=vtiger_group2role.groupid inner join vtiger_role on vtiger_role.roleid=vtiger_group2role.roleid where vtiger_role.parentrole like ?"; - array_push($params, $current_user_parent_role_seq."::%"); - - if(count($current_user_groups) != 0) { - $query .= " union select vtiger_groups.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_groups inner join vtiger_group2rs on vtiger_groups.groupid=vtiger_group2rs.groupid where vtiger_group2rs.roleandsubid in (".generateQuestionMarks($parent_roles).")"; - array_push($params, $parent_roles); - } - - $query .= " union select sharedgroupid as groupid,vtiger_groups.groupname as groupname from vtiger_tmp_write_group_sharing_per inner join vtiger_groups on vtiger_groups.groupid=vtiger_tmp_write_group_sharing_per.sharedgroupid where vtiger_tmp_write_group_sharing_per.userid=?"; - array_push($params, $current_user->id); - - $query .= " and vtiger_tmp_write_group_sharing_per.tabid=?"; - array_push($params, getTabid($module)); - } - $query .= " order by groupname ASC"; - - $result = $db->pquery($query, $params, true, "Error filling in user array: "); - - if ($add_blank==true){ - // Add in a blank row - $temp_result[''] = ''; - } - - // Get the id and the name. - while($row = $db->fetchByAssoc($result)) - { - $temp_result[$row['groupid']] = $row['groupname']; - } - - $group_array = &$temp_result; - } - - $log->debug("Exiting get_user_array method ..."); - return $group_array; -} -/** Function skips executing arbitary commands given in a string - * @param $string -- string:: Type string - * @param $maxlength -- maximun length:: Type integer - * @returns $string -- escaped string:: Type string - * -*/ - -function clean($string, $maxLength) -{ - global $log; - $log->debug("Entering clean(".$string.",". $maxLength.") method ..."); - $string = substr($string, 0, $maxLength); - $log->debug("Exiting clean method ..."); - return escapeshellcmd($string); -} - -/** - * Copy the specified request variable to the member variable of the specified object. - * Do no copy if the member variable is already set. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function safe_map($request_var, & $focus, $always_copy = false) -{ - global $log; - $log->debug("Entering safe_map(".$request_var.",".get_class($focus).",".$always_copy.") method ..."); - safe_map_named($request_var, $focus, $request_var, $always_copy); - $log->debug("Exiting safe_map method ..."); -} - -/** - * Copy the specified request variable to the member variable of the specified object. - * Do no copy if the member variable is already set. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function safe_map_named($request_var, & $focus, $member_var, $always_copy) -{ - global $log; - $log->debug("Entering safe_map_named(".$request_var.",".get_class($focus).",".$member_var.",".$always_copy.") method ..."); - if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) { - $log->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var"); - $focus->$member_var = $_REQUEST[$request_var]; - } - $log->debug("Exiting safe_map_named method ..."); -} - -/** This function retrieves an application language file and returns the array of strings included in the $app_list_strings var. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are using the current language, do not call this function unless you are loading it for the first time */ - -function return_app_list_strings_language($language) -{ - global $log; - $log->debug("Entering return_app_list_strings_language(".$language.") method ..."); - global $app_list_strings, $default_language, $log, $translation_string_prefix; - $temp_app_list_strings = $app_list_strings; - $language_used = $language; - - @include("include/language/$language.lang.php"); - if(!isset($app_list_strings)) - { - $log->warn("Unable to find the application language file for language: ".$language); - require("include/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($app_list_strings)) - { - $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_app_list_strings_language method ..."); - return null; - } - - - $return_value = $app_list_strings; - $app_list_strings = $temp_app_list_strings; - - $log->debug("Exiting return_app_list_strings_language method ..."); - return $return_value; -} - -/** - * Retrieve the app_currency_strings for the required language. - */ -function return_app_currency_strings_language($language) { - global $log; - $log->debug("Entering return_app_currency_strings_language(".$language.") method ..."); - global $app_currency_strings, $default_language, $log, $translation_string_prefix; - // Backup the value first - $temp_app_currency_strings = $app_currency_strings; - @include("include/language/$language.lang.php"); - if(!isset($app_currency_strings)) - { - $log->warn("Unable to find the application language file for language: ".$language); - require("include/language/$default_language.lang.php"); - $language_used = $default_language; - } - if(!isset($app_currency_strings)) - { - $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_app_currency_strings_language method ..."); - return null; - } - $return_value = $app_currency_strings; - - // Restore the value back - $app_currency_strings = $temp_app_currency_strings; - - $log->debug("Exiting return_app_currency_strings_language method ..."); - return $return_value; -} - -/** This function retrieves an application language file and returns the array of strings included. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are using the current language, do not call this function unless you are loading it for the first time */ -function return_application_language($language) -{ - global $log; - $log->debug("Entering return_application_language(".$language.") method ..."); - global $app_strings, $default_language, $log, $translation_string_prefix; - $temp_app_strings = $app_strings; - $language_used = $language; - - @include("include/language/$language.lang.php"); - if(!isset($app_strings)) - { - $log->warn("Unable to find the application language file for language: ".$language); - require("include/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($app_strings)) - { - $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_application_language method ..."); - return null; - } - - // If we are in debug mode for translating, turn on the prefix now! - if($translation_string_prefix) - { - foreach($app_strings as $entry_key=>$entry_value) - { - $app_strings[$entry_key] = $language_used.' '.$entry_value; - } - } - - $return_value = $app_strings; - $app_strings = $temp_app_strings; - - $log->debug("Exiting return_application_language method ..."); - return $return_value; -} - -/** This function retrieves a module's language file and returns the array of strings included. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are in the current module, do not call this function unless you are loading it for the first time */ -function return_module_language($language, $module) -{ - global $log; - $log->debug("Entering return_module_language(".$language.",". $module.") method ..."); - global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; - static $cachedModuleStrings = array(); - - if(!empty($cachedModuleStrings[$module])) { - $log->debug("Exiting return_module_language method ..."); - return $cachedModuleStrings[$module]; - } - - $temp_mod_strings = $mod_strings; - $language_used = $language; - - @include("modules/$module/language/$language.lang.php"); - if(!isset($mod_strings)) - { - $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); - require("modules/$module/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($mod_strings)) - { - $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_module_language method ..."); - return null; - } - - // If we are in debug mode for translating, turn on the prefix now! - if($translation_string_prefix) - { - foreach($mod_strings as $entry_key=>$entry_value) - { - $mod_strings[$entry_key] = $language_used.' '.$entry_value; - } - } - - $return_value = $mod_strings; - $mod_strings = $temp_mod_strings; - - $log->debug("Exiting return_module_language method ..."); - $cachedModuleStrings[$module] = $return_value; - return $return_value; -} - -/*This function returns the mod_strings for the current language and the specified module -*/ - -function return_specified_module_language($language, $module) -{ - global $log; - global $default_language, $translation_string_prefix; - - @include("modules/$module/language/$language.lang.php"); - if(!isset($mod_strings)) - { - $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); - require("modules/$module/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($mod_strings)) - { - $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_module_language method ..."); - return null; - } - - $return_value = $mod_strings; - - $log->debug("Exiting return_module_language method ..."); - return $return_value; -} - -/** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are using the current language, do not call this function unless you are loading it for the first time */ -function return_mod_list_strings_language($language,$module) -{ - global $log; - $log->debug("Entering return_mod_list_strings_language(".$language.",".$module.") method ..."); - global $mod_list_strings, $default_language, $log, $currentModule,$translation_string_prefix; - - $language_used = $language; - $temp_mod_list_strings = $mod_list_strings; - - if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null) - { - $log->debug("Exiting return_mod_list_strings_language method ..."); - return $mod_list_strings; - } - - @include("modules/$module/language/$language.lang.php"); - - if(!isset($mod_list_strings)) - { - $log->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_mod_list_strings_language method ..."); - return null; - } - - $return_value = $mod_list_strings; - $mod_list_strings = $temp_mod_list_strings; - - $log->debug("Exiting return_mod_list_strings_language method ..."); - return $return_value; -} - -/** This function retrieves a theme's language file and returns the array of strings included. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function return_theme_language($language, $theme) -{ - global $log; - $log->debug("Entering return_theme_language(".$language.",". $theme.") method ..."); - global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; - - $language_used = $language; - - @include("themes/$theme/language/$current_language.lang.php"); - if(!isset($theme_strings)) - { - $log->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme); - require("themes/$theme/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($theme_strings)) - { - $log->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_theme_language method ..."); - return null; - } - - // If we are in debug mode for translating, turn on the prefix now! - if($translation_string_prefix) - { - foreach($theme_strings as $entry_key=>$entry_value) - { - $theme_strings[$entry_key] = $language_used.' '.$entry_value; - } - } - - $log->debug("Exiting return_theme_language method ..."); - return $theme_strings; -} - - - -/** If the session variable is defined and is not equal to "" then return it. Otherwise, return the default value. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. -*/ -function return_session_value_or_default($varname, $default) -{ - global $log; - $log->debug("Entering return_session_value_or_default(".$varname.",". $default.") method ..."); - if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "") - { - $log->debug("Exiting return_session_value_or_default method ..."); - return $_SESSION[$varname]; - } - - $log->debug("Exiting return_session_value_or_default method ..."); - return $default; -} - -/** - * Creates an array of where restrictions. These are used to construct a where SQL statement on the query - * It looks for the variable in the $_REQUEST array. If it is set and is not "" it will create a where clause out of it. - * @param &$where_clauses - The array to append the clause to - * @param $variable_name - The name of the variable to look for an add to the where clause if found - * @param $SQL_name - [Optional] If specified, this is the SQL column name that is used. If not specified, the $variable_name is used as the SQL_name. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null) -{ - global $log; - $log->debug("Entering append_where_clause(".$where_clauses.",".$variable_name.",".$SQL_name.") method ..."); - if($SQL_name == null) - { - $SQL_name = $variable_name; - } - - if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "") - { - array_push($where_clauses, "$SQL_name like '$_REQUEST[$variable_name]%'"); - } - $log->debug("Exiting append_where_clause method ..."); -} - -/** - * Generate the appropriate SQL based on the where clauses. - * @param $where_clauses - An Array of individual where clauses stored as strings - * @returns string where_clause - The final SQL where clause to be executed. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function generate_where_statement($where_clauses) -{ - global $log; - $log->debug("Entering generate_where_statement(".$where_clauses.") method ..."); - $where = ""; - foreach($where_clauses as $clause) - { - if($where != "") - $where .= " and "; - $where .= $clause; - } - - $log->info("Here is the where clause for the list view: $where"); - $log->debug("Exiting generate_where_statement method ..."); - return $where; -} - -/** - * A temporary method of generating GUIDs of the correct format for our DB. - * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee - * - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. -*/ -function create_guid() -{ - global $log; - $log->debug("Entering create_guid() method ..."); - $microTime = microtime(); - list($a_dec, $a_sec) = explode(" ", $microTime); - - $dec_hex = sprintf("%x", $a_dec* 1000000); - $sec_hex = sprintf("%x", $a_sec); - - ensure_length($dec_hex, 5); - ensure_length($sec_hex, 6); - - $guid = ""; - $guid .= $dec_hex; - $guid .= create_guid_section(3); - $guid .= '-'; - $guid .= create_guid_section(4); - $guid .= '-'; - $guid .= create_guid_section(4); - $guid .= '-'; - $guid .= create_guid_section(4); - $guid .= '-'; - $guid .= $sec_hex; - $guid .= create_guid_section(6); - - $log->debug("Exiting create_guid method ..."); - return $guid; - -} - -/** Function to create guid section for a given character - * @param $characters -- characters:: Type string - * @returns $return -- integer:: Type integer`` - */ -function create_guid_section($characters) -{ - global $log; - $log->debug("Entering create_guid_section(".$characters.") method ..."); - $return = ""; - for($i=0; $i<$characters; $i++) - { - $return .= sprintf("%x", rand(0,15)); - } - $log->debug("Exiting create_guid_section method ..."); - return $return; -} - -/** Function to ensure length - * @param $string -- string:: Type string - * @param $length -- length:: Type string - */ - -function ensure_length(&$string, $length) -{ - global $log; - $log->debug("Entering ensure_length(".$string.",". $length.") method ..."); - $strlen = strlen($string); - if($strlen < $length) - { - $string = str_pad($string,$length,"0"); - } - else if($strlen > $length) - { - $string = substr($string, 0, $length); - } - $log->debug("Exiting ensure_length method ..."); -} -/* -function microtime_diff($a, $b) { - global $log; - $log->debug("Entering microtime_diff(".$a.",". $b.") method ..."); - list($a_dec, $a_sec) = explode(" ", $a); - list($b_dec, $b_sec) = explode(" ", $b); - $log->debug("Exiting microtime_diff method ..."); - return $b_sec - $a_sec + $b_dec - $a_dec; -} - */ - -/** - * Return the display name for a theme if it exists. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_theme_display($theme) { - global $log; - $log->debug("Entering get_theme_display(".$theme.") method ..."); - global $theme_name, $theme_description; - $temp_theme_name = $theme_name; - $temp_theme_description = $theme_description; - - if (is_file("./themes/$theme/config.php")) { - @include("./themes/$theme/config.php"); - $return_theme_value = $theme_name; - } - else { - $return_theme_value = $theme; - } - $theme_name = $temp_theme_name; - $theme_description = $temp_theme_description; - - $log->debug("Exiting get_theme_display method ..."); - return $return_theme_value; -} - -/** - * Return an array of directory names. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_themes() { - global $log; - $log->debug("Entering get_themes() method ..."); - if ($dir = @opendir("./themes")) { - while (($file = readdir($dir)) !== false) { - if ($file != ".." && $file != "." && $file != "CVS" && $file != "Attic" && $file != "akodarkgem" && $file != "bushtree" && $file != "coolblue" && $file != "Amazon" && $file != "busthree" && $file != "Aqua" && $file != "nature" && $file != "orange" && $file != "blue") { - if(is_dir("./themes/".$file)) { - if(!($file[0] == '.')) { - // set the initial theme name to the filename - $name = $file; - - // if there is a configuration class, load that. - if(is_file("./themes/$file/config.php")) - { - require_once("./themes/$file/config.php"); - } - - if(is_file("./themes/$file/header.php")) - { - $filelist[$file] = $name; - } - } - } - } - } - closedir($dir); - } - - ksort($filelist); - $log->debug("Exiting get_themes method ..."); - return $filelist; -} - - - -/** - * Create javascript to clear values of all elements in a form. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_clear_form_js () { -global $log; -$log->debug("Entering get_clear_form_js () method ..."); -$the_script = << - - -EOQ; - -$log->debug("Exiting get_clear_form_js method ..."); -return $the_script; -} - -/** - * Create javascript to set the cursor focus to specific vtiger_field in a form - * when the screen is rendered. The vtiger_field name is currently hardcoded into the - * the function. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_set_focus_js () { -global $log; -$log->debug("Entering set_focus() method ..."); -//TODO Clint 5/20 - Make this function more generic so that it can take in the target form and vtiger_field names as variables -$the_script = << - - -EOQ; - -$log->debug("Exiting get_set_focus_js method ..."); -return $the_script; -} - -/** - * Very cool algorithm for sorting multi-dimensional arrays. Found at http://us2.php.net/manual/en/function.array-multisort.php - * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...); - * Explanation: $array is the array you want to sort, 'col1' is the name of the column - * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING - * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to - * the first - so the array is sorted by the last given column first, then the one before ... - * Example: $array = array_csort($array,'town','age',SORT_DESC,'name'); - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function array_csort() { - global $log; - $log->debug("Entering array_csort() method ..."); - $args = func_get_args(); - $marray = array_shift($args); - $i = 0; - - $msortline = "return(array_multisort("; - foreach ($args as $arg) { - $i++; - if (is_string($arg)) { - foreach ($marray as $row) { - $sortarr[$i][] = $row[$arg]; - } - } else { - $sortarr[$i] = $arg; - } - $msortline .= "\$sortarr[".$i."],"; - } - $msortline .= "\$marray));"; - - eval($msortline); - $log->debug("Exiting array_csort method ..."); - return $marray; -} - -/** Function to set default varibles on to the global variable - * @param $defaults -- default values:: Type array - */ -function set_default_config(&$defaults) -{ - global $log; - $log->debug("Entering set_default_config(".$defaults.") method ..."); - - foreach ($defaults as $name=>$value) - { - if ( ! isset($GLOBALS[$name]) ) - { - $GLOBALS[$name] = $value; - } - } - $log->debug("Exiting set_default_config method ..."); -} - -$toHtml = array( - '"' => '"', - '<' => '<', - '>' => '>', - '& ' => '& ', - "'" => ''', - '' => '\r', - '\r\n'=>'\n', - -); - -/** Function to convert the given string to html - * @param $string -- string:: Type string - * @param $ecnode -- boolean:: Type boolean - * @returns $string -- string:: Type string - * - */ -function to_html($string, $encode=true) -{ - global $log,$default_charset; - //$log->debug("Entering to_html(".$string.",".$encode.") method ..."); - global $toHtml; - $action = $_REQUEST['action']; - $search = $_REQUEST['search']; - - $doconvert = false; - - if($_REQUEST['module'] != 'Settings' && $_REQUEST['file'] != 'ListView' && $_REQUEST['module'] != 'Portal' && $_REQUEST['module'] != "Reports")// && $_REQUEST['module'] != 'Emails') - $ajax_action = $_REQUEST['module'].'Ajax'; - - if(is_string($string)) - { - if($action != 'CustomView' && $action != 'Export' && $action != $ajax_action && $action != 'LeadConvertToEntities' && $action != 'CreatePDF' && $action != 'ConvertAsFAQ' && $_REQUEST['module'] != 'Dashboard' && $action != 'CreateSOPDF' && $action != 'SendPDFMail' && (!isset($_REQUEST['submode'])) ) - { - $doconvert = true; - } - else if($search == true) - { - // Fix for tickets #4647, #4648. Conversion required in case of search results also. - $doconvert = true; - } - if ($doconvert == true) - { - if(strtolower($default_charset) == 'utf-8') - $string = htmlentities($string, ENT_QUOTES, $default_charset); - else - $string = preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); - } - } - - //$log->debug("Exiting to_html method ..."); - return $string; -} - -/** Function to get the tablabel for a given id - * @param $tabid -- tab id:: Type integer - * @returns $string -- string:: Type string - * - */ - -function getTabname($tabid) -{ - global $log; - $log->debug("Entering getTabname(".$tabid.") method ..."); - $log->info("tab id is ".$tabid); - global $adb; - $sql = "select tablabel from vtiger_tab where tabid=?"; - $result = $adb->pquery($sql, array($tabid)); - $tabname= $adb->query_result($result,0,"tablabel"); - $log->debug("Exiting getTabname method ..."); - return $tabname; - -} - -/** Function to get the tab module name for a given id - * @param $tabid -- tab id:: Type integer - * @returns $string -- string:: Type string - * - */ - -function getTabModuleName($tabid) -{ - global $log; - $log->debug("Entering getTabModuleName(".$tabid.") method ..."); - - // Lookup information in cache first - $tabname = VTCacheUtils::lookupModulename($tabid); - if($tabname === false) { - if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { - include('tabdata.php'); - $tabname = array_search($tabid,$tab_info_array); - - // Update information to cache for re-use - VTCacheUtils::updateTabidInfo($tabid, $tabname); - - } else { - $log->info("tab id is ".$tabid); - global $adb; - $sql = "select name from vtiger_tab where tabid=?"; - $result = $adb->pquery($sql, array($tabid)); - $tabname= $adb->query_result($result,0,"name"); - - // Update information to cache for re-use - VTCacheUtils::updateTabidInfo($tabid, $tabname); - } - } - $log->debug("Exiting getTabModuleName method ..."); - return $tabname; -} - -/** Function to get column fields for a given module - * @param $module -- module:: Type string - * @returns $column_fld -- column field :: Type array - * - */ - -function getColumnFields($module) -{ - global $log; - $log->debug("Entering getColumnFields(".$module.") method ..."); - $log->debug("in getColumnFields ".$module); - - // Lookup in cache for information - $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); - - if($cachedModuleFields === false) { - global $adb; - $tabid = getTabid($module); - if ($module == 'Calendar') { - $tabid = array('9','16'); - } - - // Let us pick up all the fields first so that we can cache information - $sql = "SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence - FROM vtiger_field WHERE tabid in (" . generateQuestionMarks($tabid) . ")"; - - $result = $adb->pquery($sql, array($tabid)); - $noofrows = $adb->num_rows($result); - - if($noofrows) { - while($resultrow = $adb->fetch_array($result)) { - // Update information to cache for re-use - VTCacheUtils::updateFieldInfo( - $resultrow['tabid'], $resultrow['fieldname'], $resultrow['fieldid'], - $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], - $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence'] - ); - } - } - - // For consistency get information from cache - $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); - } - - if($module == 'Calendar') { - $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events'); - if($cachedModuleFields == false) $cachedModuleFields = $cachedEventsFields; - else $cachedModuleFields = array_merge($cachedModuleFields, $cachedEventsFields); - } - - $column_fld = array(); - if($cachedModuleFields) { - foreach($cachedModuleFields as $fieldinfo) { - $column_fld[$fieldinfo['fieldname']] = ''; - } - } - - $log->debug("Exiting getColumnFields method ..."); - return $column_fld; -} - -/** Function to get a users's mail id - * @param $userid -- userid :: Type integer - * @returns $email -- email :: Type string - * - */ - -function getUserEmail($userid) -{ - global $log; - $log->debug("Entering getUserEmail(".$userid.") method ..."); - $log->info("in getUserEmail ".$userid); - - global $adb; - if($userid != '') - { - $sql = "select email1 from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($userid)); - $email = $adb->query_result($result,0,"email1"); - } - $log->debug("Exiting getUserEmail method ..."); - return $email; -} - -/** Function to get a userid for outlook - * @param $username -- username :: Type string - * @returns $user_id -- user id :: Type integer - */ - -//outlook security -function getUserId_Ol($username) -{ - global $log; - $log->debug("Entering getUserId_Ol(".$username.") method ..."); - $log->info("in getUserId_Ol ".$username); - - global $adb; - $sql = "select id from vtiger_users where user_name=?"; - $result = $adb->pquery($sql, array($username)); - $num_rows = $adb->num_rows($result); - if($num_rows > 0) - { - $user_id = $adb->query_result($result,0,"id"); - } - else - { - $user_id = 0; - } - $log->debug("Exiting getUserId_Ol method ..."); - return $user_id; -} - - -/** Function to get a action id for a given action name - * @param $action -- action name :: Type string - * @returns $actionid -- action id :: Type integer - */ - -//outlook security - -function getActionid($action) -{ - global $log; - $log->debug("Entering getActionid(".$action.") method ..."); - global $adb; - $log->info("get Actionid ".$action); - $actionid = ''; - if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) - { - include('tabdata.php'); - $actionid= $action_id_array[$action]; - } - else - { - $query="select * from vtiger_actionmapping where actionname=?"; - $result =$adb->pquery($query, array($action)); - $actionid=$adb->query_result($result,0,'actionid'); - - } - $log->info("action id selected is ".$actionid ); - $log->debug("Exiting getActionid method ..."); - return $actionid; -} - -/** Function to get a action for a given action id - * @param $action id -- action id :: Type integer - * @returns $actionname-- action name :: Type string - */ - - -function getActionname($actionid) -{ - global $log; - $log->debug("Entering getActionname(".$actionid.") method ..."); - global $adb; - - $actionname=''; - - if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) - { - include('tabdata.php'); - $actionname= $action_name_array[$actionid]; - } - else - { - - $query="select * from vtiger_actionmapping where actionid=? and securitycheck=0"; - $result =$adb->pquery($query, array($actionid)); - $actionname=$adb->query_result($result,0,"actionname"); - } - $log->debug("Exiting getActionname method ..."); - return $actionname; -} - -/** Function to get a assigned user id for a given entity - * @param $record -- entity id :: Type integer - * @returns $user_id -- user id :: Type integer - */ - -function getUserId($record) -{ - global $log; - $log->debug("Entering getUserId(".$record.") method ..."); - $log->info("in getUserId ".$record); - - global $adb; - $user_id=$adb->query_result($adb->pquery("select * from vtiger_crmentity where crmid = ?", array($record)),0,'smownerid'); - $log->debug("Exiting getUserId method ..."); - return $user_id; -} - -/** Function to get a user id or group id for a given entity - * @param $record -- entity id :: Type integer - * @returns $ownerArr -- owner id :: Type array - */ - -function getRecordOwnerId($record) -{ - global $log; - $log->debug("Entering getRecordOwnerId(".$record.") method ..."); - global $adb; - $ownerArr=Array(); - $query="select smownerid from vtiger_crmentity where crmid = ?"; - $result=$adb->pquery($query, array($record)); - if($adb->num_rows($result) > 0) - { - $ownerId=$adb->query_result($result,0,'smownerid'); - $sql_result = $adb->pquery("select count(*) as count from vtiger_users where id = ?",array($ownerId)); - if($adb->query_result($sql_result,0,'count') > 0) - $ownerArr['Users'] = $ownerId; - else - $ownerArr['Groups'] = $ownerId; - } - $log->debug("Exiting getRecordOwnerId method ..."); - return $ownerArr; - -} - -/** Function to insert value to profile2field table - * @param $profileid -- profileid :: Type integer - */ - - -function insertProfile2field($profileid) -{ - global $log; - $log->debug("Entering insertProfile2field(".$profileid.") method ..."); - $log->info("in insertProfile2field ".$profileid); - - global $adb; - $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); - $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); - $num_rows = $adb->num_rows($fld_result); - for($i=0; $i<$num_rows; $i++) - { - $tab_id = $adb->query_result($fld_result,$i,'tabid'); - $field_id = $adb->query_result($fld_result,$i,'fieldid'); - $params = array($profileid, $tab_id, $field_id, 0, 1); - $adb->pquery("insert into vtiger_profile2field values (?,?,?,?,?)", $params); - } - $log->debug("Exiting insertProfile2field method ..."); -} - -/** Function to insert into default org field - */ - -function insert_def_org_field() -{ - global $log; - $log->debug("Entering insert_def_org_field() method ..."); - global $adb; - $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); - $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); - $num_rows = $adb->num_rows($fld_result); - for($i=0; $i<$num_rows; $i++) - { - $tab_id = $adb->query_result($fld_result,$i,'tabid'); - $field_id = $adb->query_result($fld_result,$i,'fieldid'); - $params = array($tab_id, $field_id, 0, 1); - $adb->pquery("insert into vtiger_def_org_field values (?,?,?,?)", $params); - } - $log->debug("Exiting insert_def_org_field() method ..."); -} - -/** Function to insert value to profile2field table - * @param $fld_module -- field module :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $result -- result :: Type string - */ - -function getProfile2FieldList($fld_module, $profileid) -{ - global $log; - $log->debug("Entering getProfile2FieldList(".$fld_module.",". $profileid.") method ..."); - $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "select vtiger_profile2field.visible,vtiger_field.* from vtiger_profile2field inner join vtiger_field on vtiger_field.fieldid=vtiger_profile2field.fieldid where vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)"; - $result = $adb->pquery($query, array($profileid, $tabid)); - $log->debug("Exiting getProfile2FieldList method ..."); - return $result; -} - -/** Function to insert value to profile2fieldPermissions table - * @param $fld_module -- field module :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $return_data -- return_data :: Type string - */ - -//added by jeri - -function getProfile2FieldPermissionList($fld_module, $profileid) -{ - global $log; - $log->debug("Entering getProfile2FieldPermissionList(".$fld_module.",". $profileid.") method ..."); - $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); - - // Cache information to re-use - static $_module_fieldpermission_cache = array(); - - if(!isset($_module_fieldpermission_cache[$fld_module])) { - $_module_fieldpermission_cache[$fld_module] = array(); - } - - // Lookup cache first - $return_data = VTCacheUtils::lookupProfile2FieldPermissionList($fld_module, $profileid); - - if($return_data === false) { - - $return_data = array(); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "SELECT vtiger_profile2field.visible, vtiger_field.fieldlabel, vtiger_field.uitype, - vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata - FROM vtiger_profile2field INNER JOIN vtiger_field ON vtiger_field.fieldid=vtiger_profile2field.fieldid - WHERE vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)"; - - $qparams = array($profileid, $tabid); - $result = $adb->pquery($query, $qparams); - - for($i=0; $i<$adb->num_rows($result); $i++) { - $return_data[]=array( - $adb->query_result($result,$i,"fieldlabel"), - $adb->query_result($result,$i,"visible"), // From vtiger_profile2field.visible - $adb->query_result($result,$i,"uitype"), - $adb->query_result($result,$i,"visible"), - $adb->query_result($result,$i,"fieldid"), - $adb->query_result($result,$i,"displaytype"), - $adb->query_result($result,$i,"typeofdata") - ); - } - - // Update information to cache for re-use - VTCacheUtils::updateProfile2FieldPermissionList($fld_module, $profileid, $return_data); - } - - - $log->debug("Exiting getProfile2FieldPermissionList method ..."); - return $return_data; -} - -/** Function to getProfile2allfieldsListinsert value to profile2fieldPermissions table - * @param $mod_array -- mod_array :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $profilelist -- profilelist :: Type string - */ - -function getProfile2AllFieldList($mod_array,$profileid) -{ - global $log; - $log->debug("Entering getProfile2AllFieldList(".$mod_array.",".$profileid.") method ..."); - $log->info("in getProfile2AllFieldList vtiger_profile id is " .$profileid); - - global $adb; - $profilelist=array(); - for($i=0;$idebug("Exiting getProfile2AllFieldList method ..."); - return $profilelist; -} - -/** Function to getdefaultfield organisation list for a given module - * @param $fld_module -- module name :: Type string - * @returns $result -- string :: Type object - */ - -//end of fn added by jeri - -function getDefOrgFieldList($fld_module) -{ - global $log; - $log->debug("Entering getDefOrgFieldList(".$fld_module.") method ..."); - $log->info("in getDefOrgFieldList ".$fld_module); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "select vtiger_def_org_field.visible,vtiger_field.* from vtiger_def_org_field inner join vtiger_field on vtiger_field.fieldid=vtiger_def_org_field.fieldid where vtiger_def_org_field.tabid=? and vtiger_field.presence in (0,2)"; - $qparams = array($tabid); - $result = $adb->pquery($query, $qparams); - $log->debug("Exiting getDefOrgFieldList method ..."); - return $result; -} - -/** Function to getQuickCreate for a given tabid - * @param $tabid -- tab id :: Type string - * @param $actionid -- action id :: Type integer - * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean - */ - -function getQuickCreate($tabid,$actionid) -{ - global $log; - $log->debug("Entering getQuickCreate(".$tabid.",".$actionid.") method ..."); - $module=getTabModuleName($tabid); - $actionname=getActionname($actionid); - $QuickCreateForm= 'true'; - - $perr=isPermitted($module,$actionname); - if($perr = 'no') - { - $QuickCreateForm= 'false'; - } - $log->debug("Exiting getQuickCreate method ..."); - return $QuickCreateForm; - -} - -/** Function to getQuickCreate for a given tabid - * @param $tabid -- tab id :: Type string - * @param $actionid -- action id :: Type integer - * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean - */ - -function ChangeStatus($status,$activityid,$activity_mode='') - { - global $log; - $log->debug("Entering ChangeStatus(".$status.",".$activityid.",".$activity_mode."='') method ..."); - $log->info("in ChangeStatus ".$status. ' vtiger_activityid is '.$activityid); - - global $adb; - if ($activity_mode == 'Task') - { - $query = "Update vtiger_activity set status=? where activityid = ?"; - } - elseif ($activity_mode == 'Events') - { - $query = "Update vtiger_activity set eventstatus=? where activityid = ?"; - } - if($query) { - $adb->pquery($query, array($status, $activityid)); - } - $log->debug("Exiting ChangeStatus method ..."); - } - -/** Function to set date values compatible to database (YY_MM_DD) - * @param $value -- value :: Type string - * @returns $insert_date -- insert_date :: Type string - */ - -function getDBInsertDateValue($value) -{ - global $log; - $log->debug("Entering getDBInsertDateValue(".$value.") method ..."); - global $current_user; - $dat_fmt = $current_user->date_format; - if($dat_fmt == '') { - $dat_fmt = 'dd-mm-yyyy'; - } - $insert_date=''; - if($dat_fmt == 'dd-mm-yyyy') - { - list($d,$m,$y) = split('-',$value); - } - elseif($dat_fmt == 'mm-dd-yyyy') - { - list($m,$d,$y) = split('-',$value); - } - elseif($dat_fmt == 'yyyy-mm-dd') - { - list($y,$m,$d) = split('-',$value); - } - - if(!$y && !$m && !$d) { - $insert_date = ''; - } else { - $insert_date=$y.'-'.$m.'-'.$d; - } - $log->debug("Exiting getDBInsertDateValue method ..."); - return $insert_date; -} - -/** Function to get unitprice for a given product id - * @param $productid -- product id :: Type integer - * @returns $up -- up :: Type string - */ - -function getUnitPrice($productid, $module='Products') -{ - global $log, $adb; - $log->debug("Entering getUnitPrice($productid,$module) method ..."); - - if($module == 'Services') { - $query = "select unit_price from vtiger_service where serviceid=?"; - } else { - $query = "select unit_price from vtiger_products where productid=?"; - } - $result = $adb->pquery($query, array($productid)); - $unitpice = $adb->query_result($result,0,'unit_price'); - $log->debug("Exiting getUnitPrice method ..."); - return $unitpice; -} - -/** Function to upload product image file - * @param $mode -- mode :: Type string - * @param $id -- id :: Type integer - * @returns $ret_array -- return array:: Type array - */ - -function upload_product_image_file($mode,$id) -{ - global $log; - $log->debug("Entering upload_product_image_file(".$mode.",".$id.") method ..."); - global $root_directory; - $log->debug("Inside upload_product_image_file. The id is ".$id); - $uploaddir = $root_directory ."/test/product/"; - - $file_path_name = $_FILES['imagename']['name']; - if (isset($_REQUEST['imagename_hidden'])) { - $file_name = $_REQUEST['imagename_hidden']; - } else { - //allowed file pathname like UTF-8 Character - $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name); - } - $file_name = $id.'_'.$file_name; - $filetype= $_FILES['imagename']['type']; - $filesize = $_FILES['imagename']['size']; - - $ret_array = Array(); - - if($filesize > 0) - { - - if(move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$file_name)) - { - - $upload_status = "yes"; - $ret_array["status"] = $upload_status; - $ret_array["file_name"] = $file_name; - - - } - else - { - $errorCode = $_FILES['imagename']['error']; - $upload_status = "no"; - $ret_array["status"] = $upload_status; - $ret_array["errorcode"] = $errorCode; - - - } - - } - else - { - $upload_status = "no"; - $ret_array["status"] = $upload_status; - } - $log->debug("Exiting upload_product_image_file method ..."); - return $ret_array; - -} - -/** Function to upload product image file - * @param $id -- id :: Type integer - * @param $deleted_array -- images to be deleted :: Type array - * @returns $imagename -- imagelist:: Type array - */ - -function getProductImageName($id,$deleted_array='') -{ - global $log; - $log->debug("Entering getProductImageName(".$id.",".$deleted_array."='') method ..."); - global $adb; - $image_array=array(); - $query = "select imagename from vtiger_products where productid=?"; - $result = $adb->pquery($query, array($id)); - $image_name = $adb->query_result($result,0,"imagename"); - $image_array=explode("###",$image_name); - $log->debug("Inside getProductImageName. The image_name is ".$image_name); - if($deleted_array!='') - { - $resultant_image = array(); - $resultant_image=array_merge(array_diff($image_array,$deleted_array)); - $imagelists=implode('###',$resultant_image); - $log->debug("Exiting getProductImageName method ..."); - return $imagelists; - } - else - { - $log->debug("Exiting getProductImageName method ..."); - return $image_name; - } -} - -/** Function to get Contact images - * @param $id -- id :: Type integer - * @returns $imagename -- imagename:: Type string - */ - -function getContactImageName($id) -{ - global $log; - $log->debug("Entering getContactImageName(".$id.") method ..."); - global $adb; - $query = "select imagename from vtiger_contactdetails where contactid=?"; - $result = $adb->pquery($query, array($id)); - $image_name = $adb->query_result($result,0,"imagename"); - $log->debug("Inside getContactImageName. The image_name is ".$image_name); - $log->debug("Exiting getContactImageName method ..."); - return $image_name; - -} - -/** Function to update sub total in inventory - * @param $module -- module name :: Type string - * @param $tablename -- tablename :: Type string - * @param $colname -- colname :: Type string - * @param $colname1 -- coluname1 :: Type string - * @param $entid_fld -- entity field :: Type string - * @param $entid -- entid :: Type integer - * @param $prod_total -- totalproduct :: Type integer - */ - -function updateSubTotal($module,$tablename,$colname,$colname1,$entid_fld,$entid,$prod_total) -{ - global $log; - $log->debug("Entering updateSubTotal(".$module.",".$tablename.",".$colname.",".$colname1.",".$entid_fld.",".$entid.",".$prod_total.") method ..."); - global $adb; - //getting the subtotal - $query = "select ".$colname.",".$colname1." from ".$tablename." where ".$entid_fld."=?"; - $result1 = $adb->pquery($query, array($entid)); - $subtot = $adb->query_result($result1,0,$colname); - $subtot_upd = $subtot - $prod_total; - - $gdtot = $adb->query_result($result1,0,$colname1); - $gdtot_upd = $gdtot - $prod_total; - - //updating the subtotal - $sub_query = "update $tablename set $colname=?, $colname1=? where $entid_fld=?"; - $adb->pquery($sub_query, array($subtot_upd, $gdtot_upd, $entid)); - $log->debug("Exiting updateSubTotal method ..."); -} - -/** Function to get Inventory Total - * @param $return_module -- return module :: Type string - * @param $id -- entity id :: Type integer - * @returns $total -- total:: Type integer - */ - -function getInventoryTotal($return_module,$id) -{ - global $log; - $log->debug("Entering getInventoryTotal(".$return_module.",".$id.") method ..."); - global $adb; - if($return_module == "Potentials") - { - $query ="select vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?"; - } - elseif($return_module == "Products") - { - $query="select vtiger_products.productid,vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?"; - } - $result = $adb->pquery($query, array($id)); - $num_rows=$adb->num_rows($result); - $total=0; - for($i=1;$i<=$num_rows;$i++) - { - $unitprice=$adb->query_result($result,$i-1,'unit_price'); - $qty=$adb->query_result($result,$i-1,'quantity'); - $listprice=$adb->query_result($result,$i-1,'listprice'); - if($listprice == '') - $listprice = $unitprice; - if($qty =='') - $qty = 1; - $total = $total+($qty*$listprice); - } - $log->debug("Exiting getInventoryTotal method ..."); - return $total; -} - -/** Function to update product quantity - * @param $product_id -- product id :: Type integer - * @param $upd_qty -- quantity :: Type integer - */ - -function updateProductQty($product_id, $upd_qty) -{ - global $log; - $log->debug("Entering updateProductQty(".$product_id.",". $upd_qty.") method ..."); - global $adb; - $query= "update vtiger_products set qtyinstock=? where productid=?"; - $adb->pquery($query, array($upd_qty, $product_id)); - $log->debug("Exiting updateProductQty method ..."); - -} - -/** Function to get account information - * @param $parent_id -- parent id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function get_account_info($parent_id) -{ - global $log; - $log->debug("Entering get_account_info(".$parent_id.") method ..."); - global $adb; - $query = "select related_to from vtiger_potential where potentialid=?"; - $result = $adb->pquery($query, array($parent_id)); - $accountid=$adb->query_result($result,0,'related_to'); - $log->debug("Exiting get_account_info method ..."); - return $accountid; -} - -/** Function to get quick create form fields - * @param $fieldlabel -- field label :: Type string - * @param $uitype -- uitype :: Type integer - * @param $fieldname -- field name :: Type string - * @param $tabid -- tabid :: Type integer - * @returns $return_field -- return field:: Type string - */ - -//for Quickcreate-Form - -function get_quickcreate_form($fieldlabel,$uitype,$fieldname,$tabid) -{ - global $log; - $log->debug("Entering get_quickcreate_form(".$fieldlabel.",".$uitype.",".$fieldname.",".$tabid.") method ..."); - $return_field =''; - switch($uitype) - { - case 1: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 2: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 6: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 11: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 13: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 15: $return_field .=get_textcomboField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 16: $return_field .=get_textcomboField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 17: $return_field .=get_textwebField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 19: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 22: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 23: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 50: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 51: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 55: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 63: $return_field .=get_textdurationField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 71: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - } -} - -/** Function to get quick create form fields - * @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_textmanField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textmanField(".$label.",".$name.",".$tid.") method ..."); - $form_field=''; - if($tid == 9) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textmanField method ..."); - return $form_field; - } - if($tid == 16) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textmanField method ..."); - return $form_field; - } - else - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $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 .=''; - $form_field .= $label.':
http://
'; - $form_field .=''; - $log->debug("Exiting get_textwebField method ..."); - return $form_field; - -} - -/** Function to get textfield - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @returns $form_field -- return field:: Type string - */ - -function get_textField($label,$name) -{ - global $log; - $log->debug("Entering get_textField(".$label.",".$name.") method ..."); - $form_field=''; - if($name == "amount") - { - $form_field .=''; - $form_field .= $label.':(U.S Dollar:$)
'; - $form_field .=''; - $log->debug("Exiting get_textField method ..."); - return $form_field; - } - else - { - - $form_field .=''; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textField method ..."); - return $form_field; - } - -} - -/** Function to get account textfield - * @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_textaccField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textaccField(".$label.",".$name.",".$tid.") method ..."); - - global $app_strings; - - $form_field=''; - if($tid == 2) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .='
'; - $form_field .=' '; - $log->debug("Exiting get_textaccField method ..."); - return $form_field; - } - else - { - $form_field .=''; - $form_field .= $label.':
'; - $form_field .='
'; - $form_field .=' '; - $log->debug("Exiting get_textaccField method ..."); - return $form_field; - } - -} - -/** Function to get combo field values - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @returns $form_field -- return field:: Type string - */ - -function get_textcomboField($label,$name) -{ - global $log; - $log->debug("Entering get_textcomboField(".$label.",".$name.") method ..."); - $form_field=''; - if($name == "sales_stage") - { - $comboFieldNames = Array('leadsource'=>'leadsource_dom' - ,'opportunity_type'=>'opportunity_type_dom' - ,'sales_stage'=>'sales_stage_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - } - if($name == "productcategory") - { - $comboFieldNames = Array('productcategory'=>'productcategory_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - } - if($name == "ticketpriorities") - { - $comboFieldNames = Array('ticketpriorities'=>'ticketpriorities_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - } - if($name == "activitytype") - { - $comboFieldNames = Array('activitytype'=>'activitytype_dom', - 'duration_minutes'=>'duration_minutes_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - - } - if($name == "eventstatus") - { - $comboFieldNames = Array('eventstatus'=>'eventstatus_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - - } - if($name == "taskstatus") - { - $comboFieldNames = Array('taskstatus'=>'taskstatus_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.'
'; - $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 .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .='('.$current_user->date_format.')
'; - $form_field .=' '; - $form_field .=''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - - } - if($tid == 9) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=' '; - $form_field.= ' '; - $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - } - if($tid == 16) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=' '; - $form_field.= ' '; - $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - } - - else - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=' '; - $form_field.= ' '; - $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - } - -} - -/** Function to get duration text field in activity - * @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_textdurationField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textdurationField(".$label.",".$name.",".$tid.") method ..."); - $form_field=''; - if($tid == 16) - { - - $comboFieldNames = Array('activitytype'=>'activitytype_dom', - 'duration_minutes'=>'duration_minutes_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=' '; - $form_field .='
(hours/minutes)
'; - $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; - // If the information is not sent then read it - if($focus === false) { - if($module == 'Contacts') - $focus = new Contacts(); - if($module == 'Leads') - $focus = new 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 vtiger_field where tabid = ? and fieldname= ? and vtiger_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; - $sql = "select postatus from vtiger_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; - $qtyInStck=getProductQtyInStock($productId); - $updQty=$qtyInStck + $qty; - $sql = "UPDATE vtiger_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; - $qtyInStck=getProductQtyInDemand($productId); - $updQty=$qtyInStck + $qty; - $sql = "UPDATE vtiger_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; - $qtyInStck=getProductQtyInStock($productId); - $updQty=$qtyInStck - $qty; - $sql = "UPDATE vtiger_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; - $qtyInStck=getProductQtyInDemand($productId); - $updQty=$qtyInStck - $qty; - $sql = "UPDATE vtiger_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; - $query1 = "select qtyinstock from vtiger_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; - $query1 = "select qtyindemand from vtiger_products where productid=?"; - $result = $adb->pquery($query1, array($product_id)); - $qtyInDemand = $adb->query_result($result,0,"qtyindemand"); - $log->debug("Exiting getProductQtyInDemand method ..."); - return $qtyInDemand; -} - -/** Function to seperate the Date and Time - * This function accepts a sting with date and time and - * returns an array of two elements.The first element - * contains the date and the second one contains the time - */ -function getDateFromDateAndtime($date_time) -{ - global $log; - $log->debug("Entering getDateFromDateAndtime(".$date_time.") method ..."); - $result = explode(" ",$date_time); - $log->debug("Exiting getDateFromDateAndtime method ..."); - return $result; -} - - -/** Function to get header for block in edit/create and detailview - * @param $header_label -- header label :: Type string - * @returns $output -- output:: Type string - */ - -function getBlockTableHeader($header_label) -{ - global $log; - $log->debug("Entering getBlockTableHeader(".$header_label.") method ..."); - global $mod_strings; - $label = $mod_strings[$header_label]; - $output = $label; - $log->debug("Exiting getBlockTableHeader method ..."); - return $output; - -} - - - -/** Function to get the vtiger_table name from 'field' vtiger_table for the input vtiger_field based on the module - * @param : string $module - current module value - * @param : string $fieldname - vtiger_fieldname to which we want the vtiger_tablename - * @return : string $tablename - vtiger_tablename in which $fieldname is a column, which is retrieved from 'field' vtiger_table per $module basis - */ -function getTableNameForField($module,$fieldname) -{ - global $log; - $log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ..."); - global $adb; - $tabid = getTabid($module); - //Asha - if($module == 'Calendar') { - $tabid = array('9','16'); - } - $sql = "select tablename from vtiger_field where tabid in (". generateQuestionMarks($tabid) .") and vtiger_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; -} - -/** Function to get parent record owner - * @param $tabid -- tabid :: Type integer - * @param $parModId -- parent module id :: Type integer - * @param $record_id -- record id :: Type integer - * @returns $parentRecOwner -- parentRecOwner:: Type integer - */ - -function getParentRecordOwner($tabid,$parModId,$record_id) -{ - global $log; - $log->debug("Entering getParentRecordOwner(".$tabid.",".$parModId.",".$record_id.") method ..."); - $parentRecOwner=Array(); - $parentTabName=getTabname($parModId); - $relTabName=getTabname($tabid); - $fn_name="get".$relTabName."Related".$parentTabName; - $ent_id=$fn_name($record_id); - if($ent_id != '') - { - $parentRecOwner=getRecordOwnerId($ent_id); - } - $log->debug("Exiting getParentRecordOwner method ..."); - return $parentRecOwner; -} - -/** Function to get potential related accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getPotentialsRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getPotentialsRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select related_to from vtiger_potential where potentialid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'related_to'); - $log->debug("Exiting getPotentialsRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get email related accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ -function getEmailsRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getEmailsRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Accounts' and activityid=?"; - $result = $adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'crmid'); - $log->debug("Exiting getEmailsRelatedAccounts method ..."); - return $accountid; -} -/** Function to get email related Leads - * @param $record_id -- record id :: Type integer - * @returns $leadid -- leadid:: Type integer - */ - -function getEmailsRelatedLeads($record_id) -{ - global $log; - $log->debug("Entering getEmailsRelatedLeads(".$record_id.") method ..."); - global $adb; - $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Leads' and activityid=?"; - $result = $adb->pquery($query, array($record_id)); - $leadid=$adb->query_result($result,0,'crmid'); - $log->debug("Exiting getEmailsRelatedLeads method ..."); - return $leadid; -} - -/** Function to get HelpDesk related Accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getHelpDeskRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getHelpDeskRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select parent_id from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.parent_id where ticketid=? and vtiger_crmentity.setype='Accounts'"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'parent_id'); - $log->debug("Exiting getHelpDeskRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get Quotes related Accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getQuotesRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getQuotesRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select accountid from vtiger_quotes where quoteid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'accountid'); - $log->debug("Exiting getQuotesRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get Quotes related Potentials - * @param $record_id -- record id :: Type integer - * @returns $potid -- potid:: Type integer - */ - -function getQuotesRelatedPotentials($record_id) -{ - global $log; - $log->debug("Entering getQuotesRelatedPotentials(".$record_id.") method ..."); - global $adb; - $query="select potentialid from vtiger_quotes where quoteid=?"; - $result=$adb->pquery($query, array($record_id)); - $potid=$adb->query_result($result,0,'potentialid'); - $log->debug("Exiting getQuotesRelatedPotentials method ..."); - return $potid; -} - -/** Function to get Quotes related Potentials - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getSalesOrderRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getSalesOrderRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select accountid from vtiger_salesorder where salesorderid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'accountid'); - $log->debug("Exiting getSalesOrderRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get SalesOrder related Potentials - * @param $record_id -- record id :: Type integer - * @returns $potid -- potid:: Type integer - */ - -function getSalesOrderRelatedPotentials($record_id) -{ - global $log; - $log->debug("Entering getSalesOrderRelatedPotentials(".$record_id.") method ..."); - global $adb; - $query="select potentialid from vtiger_salesorder where salesorderid=?"; - $result=$adb->pquery($query, array($record_id)); - $potid=$adb->query_result($result,0,'potentialid'); - $log->debug("Exiting getSalesOrderRelatedPotentials method ..."); - return $potid; -} -/** Function to get SalesOrder related Quotes - * @param $record_id -- record id :: Type integer - * @returns $qtid -- qtid:: Type integer - */ - -function getSalesOrderRelatedQuotes($record_id) -{ - global $log; - $log->debug("Entering getSalesOrderRelatedQuotes(".$record_id.") method ..."); - global $adb; - $query="select quoteid from vtiger_salesorder where salesorderid=?"; - $result=$adb->pquery($query, array($record_id)); - $qtid=$adb->query_result($result,0,'quoteid'); - $log->debug("Exiting getSalesOrderRelatedQuotes method ..."); - return $qtid; -} - -/** Function to get Invoice related Accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getInvoiceRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getInvoiceRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select accountid from vtiger_invoice where invoiceid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'accountid'); - $log->debug("Exiting getInvoiceRelatedAccounts method ..."); - return $accountid; -} -/** Function to get Invoice related SalesOrder - * @param $record_id -- record id :: Type integer - * @returns $soid -- soid:: Type integer - */ - -function getInvoiceRelatedSalesOrder($record_id) -{ - global $log; - $log->debug("Entering getInvoiceRelatedSalesOrder(".$record_id.") method ..."); - global $adb; - $query="select salesorderid from vtiger_invoice where invoiceid=?"; - $result=$adb->pquery($query, array($record_id)); - $soid=$adb->query_result($result,0,'salesorderid'); - $log->debug("Exiting getInvoiceRelatedSalesOrder method ..."); - return $soid; -} - - -/** Function to get Days and Dates in between the dates specified - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -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 - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -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 vtiger_table format for a particular date - based upon the period - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -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 vtiger_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; - $image_lists=array(); - $query="select imagename from vtiger_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; - $query = "select imagename from vtiger_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; - $query = "select imagename from vtiger_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 remove the script tag in the contents - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function strip_selected_tags($text, $tags = array()) -{ - $args = func_get_args(); - $text = array_shift($args); - $tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags; - foreach ($tags as $tag){ - if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){ - $text = str_replace($found[0],$found[1],$text); - } - } - - return $text; -} - -/** Function to check whether user has opted for internal mailer - * @returns $int_mailer -- int mailer:: Type boolean - */ -function useInternalMailer() { - global $current_user,$adb; - return $adb->query_result($adb->pquery("select int_mailer from vtiger_mail_accounts where user_id=?", array($current_user->id)),0,"int_mailer"); -} - -/** -* 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("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data); -} - -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; -} - -// Return Question mark -function _questionify($v){ - return "?"; -} - -/** -* Function to generate question marks for a given list of items -*/ -function generateQuestionMarks($items_list) { - // array_map will call the function specified in the first parameter for every element of the list in second parameter - if (is_array($items_list)) { - return implode(",", array_map("_questionify", $items_list)); - } else { - return implode(",", array_map("_questionify", explode(",", $items_list))); - } -} - -/** -* 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 && !ereg("[/.]",$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(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') - { - $current_language = $_SESSION['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; - $log->debug("Entering into function getAccessPickListValues($module)"); - - $id = getTabid($module); - $query = "select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid = ? and uitype in ('15','33','55') and vtiger_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"); - - $keyvalue = $columnname; - $fieldvalues = Array(); - if (count($roleids) > 1) - { - $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; - } - else - { - $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; - } - if($fieldname != 'firstname') - $mulselresult = $adb->query($mulsel); - for($j=0;$j < $adb->num_rows($mulselresult);$j++) - { - $fieldvalues[] = $adb->query_result($mulselresult,$j,$fieldname); - } - $field_count = count($fieldvalues); - if($uitype == 15 && $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 == 15) - $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; -} - -function getMigrationCharsetFlag() { - global $adb; - - if(!$adb->isPostgres()) - $db_status=check_db_utf8_support($adb); - $config_status=get_config_status(); - - if ($db_status == $config_status) { - if ($db_status == 1) { // Both are UTF-8 - $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_UTF8; - } else { // Both are Non UTF-8 - $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8; - } - } else { - if ($db_status == 1) { // Database charset is UTF-8 and CRM charset is Non UTF-8 - $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_UTF8; - } else { // Database charset is Non UTF-8 and CRM charset is UTF-8 - $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_NONUTF8; - } - } - return $db_migration_status; -} - -/** Function to convert a given time string to Minutes */ -function ConvertToMinutes($time_string) -{ - $interval = split(' ', $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; -} - -//added to find duplicates -/** To get the converted record values which have to be display in duplicates merging tpl*/ -function getRecordValues($id_array,$module) { - global $adb,$current_user; - global $app_strings; - $tabid=getTabid($module); - $query="select fieldname,fieldlabel,uitype from vtiger_field where tabid=? and fieldname not in ('createdtime','modifiedtime') and vtiger_field.presence in (0,2) and uitype not in('4')"; - $result=$adb->pquery($query, array($tabid)); - $no_rows=$adb->num_rows($result); - - $focus = new $module(); - if(isset($id_array) && $id_array !='') { - foreach($id_array as $value) { - $focus->id=$value; - $focus->retrieve_entity_info($value,$module); - $field_values[]=$focus->column_fields; - } - } - $labl_array=array(); - $value_pair = array(); - $c = 0; - for($i=0;$i<$no_rows;$i++) { - $fld_name=$adb->query_result($result,$i,"fieldname"); - $fld_label=$adb->query_result($result,$i,"fieldlabel"); - $ui_type=$adb->query_result($result,$i,"uitype"); - - if(getFieldVisibilityPermission($module,$current_user->id,$fld_name) == '0') { - $fld_array []= $fld_name; - $record_values[$c][$fld_label] = Array(); - $ui_value[]=$ui_type; - for($j=0;$j < count($field_values);$j++) { - - if($ui_type ==56) { - if($field_values[$j][$fld_name] == 0) - $value_pair['disp_value']=$app_strings['no']; - else - $value_pair['disp_value']=$app_strings['yes']; - } elseif($ui_type == 51 || $ui_type == 50) { - $entity_id=$field_values[$j][$fld_name]; - if($module !='Products') - $entity_name=getAccountName($entity_id); - else - $entity_name=getProductName($entity_id); - $value_pair['disp_value']=$entity_name; - } elseif($ui_type == 53) { - $owner_id=$field_values[$j][$fld_name]; - $ownername=getOwnerName($owner_id); - $value_pair['disp_value']=$ownername; - } elseif($ui_type ==57) { - $contact_id= $field_values[$j][$fld_name]; - if($contact_id != '') { - $contactname=getContactName($contact_id); - } - $value_pair['disp_value']=$contactname; - } elseif($ui_type == 75 || $ui_type ==81) { - $vendor_id=$field_values[$j][$fld_name]; - if($vendor_id != '') { - $vendor_name=getVendorName($vendor_id); - } - $value_pair['disp_value']=$vendor_name; - } elseif($ui_type == 52) { - $user_id = $field_values[$j][$fld_name]; - $user_name=getUserName($user_id); - $value_pair['disp_value']=$user_name; - } elseif($ui_type ==68) { - $parent_id = $field_values[$j][$fld_name]; - $value_pair['disp_value'] = getAccountName($parent_id); - if($value_pair['disp_value'] == '' || $value_pair['disp_value'] == NULL) - $value_pair['disp_value'] = getContactName($parent_id); - } elseif($ui_type ==59) { - $product_name=getProductName($field_values[$j][$fld_name]); - if($product_name != '') - $value_pair['disp_value']=$product_name; - else $value_pair['disp_value']=''; - } elseif($ui_type==58) { - $campaign_name=getCampaignName($field_values[$j][$fld_name]); - if($campaign_name != '') - $value_pair['disp_value']=$campaign_name; - else $value_pair['disp_value']=''; - } elseif($ui_type == 10) { - $value_pair['disp_value'] = getRecordInfoFromID($field_values[$j][$fld_name]); - } else { - $value_pair['disp_value']=$field_values[$j][$fld_name]; - } - $value_pair['org_value'] = $field_values[$j][$fld_name]; - - array_push($record_values[$c][$fld_label],$value_pair); - } - $c++; - } - - } - $parent_array[0]=$record_values; - $parent_array[1]=$fld_array; - $parent_array[2]=$fld_array; - return $parent_array; -} - -/** Function to check whether the relationship entries are exist or not on elationship tables */ -function is_related($relation_table,$crm_field,$related_module_id,$crmid) -{ - global $adb; - $check_res = $adb->query("select * from $relation_table where $crm_field=$related_module_id and crmid=$crmid"); - $count = $adb->num_rows($check_res); - if($count > 0) - return true; - else - return false; -} - -/** Function to get a to find duplicates in a particular module*/ -function getDuplicateQuery($module,$field_values,$ui_type_arr) -{ - global $current_user; - $tbl_col_fld = explode(",", $field_values); - $i=0; - foreach($tbl_col_fld as $val) { - list($tbl[$i], $cols[$i], $fields[$i]) = explode(".", $val); - $tbl_cols[$i] = $tbl[$i]. "." . $cols[$i]; - $i++; - } - $table_cols = implode(",",$tbl_cols); - $sec_parameter = getSecParameterforMerge($module); - if( stristr($_REQUEST['action'],'ImportStep') || ($_REQUEST['action'] == $_REQUEST['module'].'Ajax' && $_REQUEST['current_action'] == 'ImportSteplast')) - { - if($module == 'Contacts') - { - $ret_arr = get_special_on_clause($table_cols); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $nquery="select vtiger_contactdetails.contactid as recordid,vtiger_users_last_import.deleted,$table_cols - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid - INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid - INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid - LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid - LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid - LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (select $select_clause from vtiger_contactdetails t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.contactid - INNER JOIN vtiger_contactaddress addr ON t.contactid = addr.contactaddressid - INNER JOIN vtiger_contactsubdetails subd ON addr.contactaddressid = subd.contactsubscriptionid - LEFT JOIN vtiger_contactscf tcf ON t.contactid = tcf.contactid - LEFT JOIN vtiger_account acc ON acc.accountid=t.accountid - LEFT JOIN vtiger_customerdetails custd ON custd.customerid=t.contactid - WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC"; - - } - - else if($module == 'Accounts') - { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $nquery="SELECT vtiger_account.accountid AS recordid,vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_account - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid - INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid - INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid - LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (select $select_clause from vtiger_account t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.accountid - INNER JOIN vtiger_accountbillads badd ON t.accountid = badd.accountaddressid - INNER JOIN vtiger_accountshipads sadd ON t.accountid = sadd.accountaddressid - LEFT JOIN vtiger_accountscf tcf ON t.accountid = tcf.accountid - WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC"; - - } - else if($module == 'Leads') - { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $nquery="select vtiger_leaddetails.leadid as recordid, vtiger_users_last_import.deleted,$table_cols - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid - INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid - LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid - INNER JOIN (select $select_clause from vtiger_leaddetails t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.leadid - INNER JOIN vtiger_leadsubdetails subd ON subd.leadsubscriptionid = t.leadid - INNER JOIN vtiger_leadaddress addr ON addr.leadaddressid = subd.leadsubscriptionid - LEFT JOIN vtiger_leadscf tcf ON tcf.leadid=t.leadid - WHERE crm.deleted=0 and t.converted = 0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC"; - - } - else if($module == 'Products') - { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - - $nquery="SELECT vtiger_products.productid AS recordid,vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_products - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid - LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid - INNER JOIN (select $select_clause from vtiger_products t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.productid - LEFT JOIN vtiger_productcf tcf ON tcf.productid=t.productid - WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_products.productid ASC"; - - } - else if($module == 'HelpDesk') - { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $nquery="SELECT vtiger_troubletickets.ticketid AS recordid,vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_troubletickets - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid - LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid - LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid - LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid - INNER JOIN (select $select_clause from vtiger_troubletickets t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.ticketid - LEFT JOIN vtiger_account acc ON acc.accountid = t.parent_id - LEFT JOIN vtiger_contactdetails contd ON contd.contactid = t.parent_id - LEFT JOIN vtiger_ticketcf tcf ON tcf.ticketid = t.ticketid - WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0". $sec_parameter ." ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC"; - - } - else if($module == 'Potentials') - { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $nquery="SELECT vtiger_potential.potentialid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_potential - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid - LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid - INNER JOIN (select $select_clause from vtiger_potential t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.potentialid - LEFT JOIN vtiger_potentialscf tcf ON tcf.potentialid=t.potentialid - WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC"; - - } - else if($module == 'Vendors') - { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $nquery="SELECT vtiger_vendor.vendorid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_vendor - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid - LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid - INNER JOIN (select $select_clause from vtiger_vendor t - INNER JOIN vtiger_crmentity crm ON crm.crmid=t.vendorid - LEFT JOIN vtiger_vendorcf tcf ON tcf.vendorid=t.vendorid - WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module)." - WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC"; - - } else { - $ret_arr = get_special_on_clause($field_values); - $select_clause = $ret_arr['sel_clause']; - $on_clause = $ret_arr['on_clause']; - $modObj = CRMEntity::getInstance($module); - if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) { - $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr,$select_clause); - } - } - } - else - { - - if($module == 'Contacts') - { - $nquery = "SELECT vtiger_contactdetails.contactid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid - INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid - INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid - LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid - LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid - LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid - INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid - INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid - LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid - LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC"; - - } - else if($module == 'Accounts') - { - $nquery="SELECT vtiger_account.accountid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_account - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid - INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid - INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid - LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_account - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid - INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid - INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid - LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC"; - } - else if($module == 'Leads') - { - $nquery = "SELECT vtiger_leaddetails.leadid AS recordid, vtiger_users_last_import.deleted,$table_cols - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid - INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid - LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid - INNER JOIN (SELECT $table_cols - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid - INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid - LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter - GROUP BY $table_cols HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC"; - - } - else if($module == 'Products') - { - $nquery = "SELECT vtiger_products.productid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_products - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid - LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid - INNER JOIN (SELECT $table_cols - FROM vtiger_products - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid - LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid - WHERE vtiger_crmentity.deleted=0 - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_products.productid ASC"; - } - else if($module == "HelpDesk") - { - $nquery = "SELECT vtiger_troubletickets.ticketid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_troubletickets - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid - LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid - LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid - INNER JOIN (SELECT $table_cols FROM vtiger_troubletickets - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid - LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_contactdetails contd ON contd.contactid = vtiger_troubletickets.parent_id - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC"; - } - else if($module == "Potentials") - { - $nquery = "SELECT vtiger_potential.potentialid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_potential - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid - LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_potential - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid - LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC"; - } - else if($module == "Vendors") - { - $nquery = "SELECT vtiger_vendor.vendorid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_vendor - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid - LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid - INNER JOIN (SELECT $table_cols - FROM vtiger_vendor - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid - LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid - WHERE vtiger_crmentity.deleted=0 - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC"; - } else { - $modObj = CRMEntity::getInstance($module); - if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) { - $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr); - } - } - } - return $nquery; -} - -/** Function to return the duplicate records data as a formatted array */ -function getDuplicateRecordsArr($module) -{ - global $adb,$app_strings,$list_max_entries_per_page,$theme; - $field_values_array=getFieldValues($module); - $field_values=$field_values_array['fieldnames_list']; - $fld_arr=$field_values_array['fieldnames_array']; - $col_arr=$field_values_array['columnnames_array']; - $fld_labl_arr=$field_values_array['fieldlabels_array']; - $ui_type=$field_values_array['fieldname_uitype']; - - $dup_query = getDuplicateQuery($module,$field_values,$ui_type); - // added for page navigation - $dup_count_query = substr($dup_query, stripos($dup_query,'FROM'),strlen($dup_query)); - $dup_count_query = "SELECT count(*) as count ".$dup_count_query; - $count_res = $adb->query($dup_count_query); - $no_of_rows = $adb->query_result($count_res,0,"count"); - - if($no_of_rows <= $list_max_entries_per_page) - $_SESSION['dup_nav_start'.$module] = 1; - else if(isset($_REQUEST["start"]) && $_REQUEST["start"] != "" && $_SESSION['dup_nav_start'.$module] != $_REQUEST["start"]) - $_SESSION['dup_nav_start'.$module] = ListViewSession::getRequestStartPage(); - $start = ($_SESSION['dup_nav_start'.$module] != "")?$_SESSION['dup_nav_start'.$module]:1; - $navigation_array = getNavigationValues($start, $no_of_rows, $list_max_entries_per_page); - $start_rec = $navigation_array['start']; - $end_rec = $navigation_array['end_val']; - $navigationOutput = getTableHeaderNavigation($navigation_array, "",$module,"FindDuplicate",""); - if ($start_rec == 0) - $limit_start_rec = 0; - else - $limit_start_rec = $start_rec -1; - $dup_query .= " LIMIT $limit_start_rec, $list_max_entries_per_page"; - //ends - - $nresult=$adb->query($dup_query); - $no_rows=$adb->num_rows($nresult); - $theme_path="themes/".$theme."/"; - $image_path=$theme_path."images/"; - require_once($theme_path.'layout_utils.php'); - if($no_rows == 0) - { - if ($_REQUEST['action'] == 'FindDuplicateRecords') - { - //echo "

".$app_strings['LBL_NO_DUPLICATE']." ".$app_strings['LBL_GO_BACK'].".
"; - //die; - echo ""; - echo "
"; - echo "
- - - - - - - - - -
$app_strings[LBL_NO_DUPLICATE]
- $app_strings[LBL_GO_BACK]
-
"; - echo "
"; - exit(); - } - else - { - echo "

".$app_strings['LBL_NO_DUPLICATE']."
"; - die; - } - } - - $rec_cnt = 0; - $temp = Array(); - $sl_arr = Array(); - $grp = "group0"; - $gcnt = 0; - $ii = 0; //ii'th record in group - while ( $rec_cnt < $no_rows ) - { - $result = $adb->fetchByAssoc($nresult); - //echo '
';print_r($result);echo '
'; - if($rec_cnt != 0) - { - $sl_arr = array_slice($result,2); - array_walk($temp,'lower_array'); - array_walk($sl_arr,'lower_array'); - $arr_diff = array_diff($temp,$sl_arr); - if(count($arr_diff) > 0) - { - $gcnt++; - $temp = $sl_arr; - $ii = 0; - } - $grp = "group".$gcnt; - } - $fld_values[$grp][$ii]['recordid'] = $result['recordid']; - for($k=0;$k"accountid","Contacts"=>"contactid","Leads"=>"leadid","Products"=>"productid","HelpDesk"=>"ticketid","Potentials"=>"potentialid","Vendors"=>"vendorid"); - $id = ($module_id_array[$_REQUEST['modulename']] != '')?$module_id_array[$_REQUEST['modulename']]:$module_id_array[$_REQUEST['module']]; - $sub_res = ''; - $sub_result = $adb->query($sub_query); - $row_count = $adb->num_rows($sub_result); - $sub_res = ''; - if($row_count > 0) - { - while($rows = $adb->fetchByAssoc($sub_result)) - { - $sub_res .= $rows[$id].","; - } - $sub_res = trim($sub_res,","); - } - else - $sub_res .= "''"; - return $sub_res; -} - -/** Function to get tablename, columnname, fieldname, fieldlabel and uitypes of fields of merge criteria for a particular module*/ -function getFieldValues($module) -{ - global $adb,$current_user; - - //In future if we want to change a id mapping to name or other string then we can add that elements in this array. - //$fld_table_arr = Array("vtiger_contactdetails.account_id"=>"vtiger_account.accountname"); - //$special_fld_arr = Array("account_id"=>"accountname"); - - $fld_table_arr = Array(); - $special_fld_arr = Array(); - $tabid = getTabid($module); - - $fieldname_query="select fieldname,fieldlabel,uitype,tablename,columnname from vtiger_field where fieldid in - (select fieldid from vtiger_user2mergefields WHERE tabid=? AND userid=? AND visible = ?) and vtiger_field.presence in (0,2)"; - $fieldname_result = $adb->pquery($fieldname_query, array($tabid, $current_user->id, 1)); - - $field_num_rows = $adb->num_rows($fieldname_result); - - $fld_arr = array(); - $col_arr = array(); - for($j=0;$j< $field_num_rows;$j ++) - { - $tablename = $adb->query_result($fieldname_result,$j,'tablename'); - $column_name = $adb->query_result($fieldname_result,$j,'columnname'); - $field_name = $adb->query_result($fieldname_result,$j,'fieldname'); - $field_lbl = $adb->query_result($fieldname_result,$j,'fieldlabel'); - $ui_type = $adb->query_result($fieldname_result,$j,'uitype'); - $table_col = $tablename.".".$column_name; - if(getFieldVisibilityPermission($module,$current_user->id,$field_name) == 0) - { - $fld_name = ($special_fld_arr[$field_name] != '')?$special_fld_arr[$field_name]:$field_name; - - $fld_arr[] = $fld_name; - $col_arr[] = $column_name; - if($fld_table_arr[$table_col] != '') - $table_col = $fld_table_arr[$table_col]; - - $field_values_array['fieldnames_list'][] = $table_col . "." . $fld_name; - $fld_labl_arr[]=$field_lbl; - $uitype[$field_name]=$ui_type; - } - } - $field_values_array['fieldnames_list']=implode(",",$field_values_array['fieldnames_list']); - $field_values=implode(",",$fld_arr); - $field_values_array['fieldnames']=$field_values; - $field_values_array["fieldnames_array"]=$fld_arr; - $field_values_array["columnnames_array"]=$col_arr; - $field_values_array['fieldlabels_array']=$fld_labl_arr; - $field_values_array['fieldname_uitype']=$uitype; - - return $field_values_array; -} - -/** To get security parameter for a particular module -- By Pavani*/ -function getSecParameterforMerge($module) -{ - global $current_user; - $tab_id = getTabid($module); - $sec_parameter=""; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - if($module == "Products" || $module == "Vendors") { - $sec_parameter = ""; - } else { - $sec_parameter=getListViewSecurityParameter($module); - if($module == "Accounts") { - $sec_parameter .= " AND (vtiger_crmentity.smownerid IN (".$current_user->id.") - OR vtiger_crmentity.smownerid IN ( - SELECT vtiger_user2role.userid - FROM vtiger_user2role - INNER JOIN vtiger_users - ON vtiger_users.id = vtiger_user2role.userid - INNER JOIN vtiger_role - ON vtiger_role.roleid = vtiger_user2role.roleid - WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%') - OR vtiger_crmentity.smownerid IN ( - SELECT shareduserid - FROM vtiger_tmp_read_user_sharing_per - WHERE userid=".$current_user->id." - AND tabid=".$tab_id.") - OR (vtiger_crmentity.smownerid in (0) - AND ("; - - if(sizeof($current_user_groups) > 0) { - $sec_parameter .= " vtiger_groups.groupname IN ( - SELECT groupname - FROM vtiger_groups - WHERE groupid IN (". implode(",", getCurrentUserGroupList()) .")) - OR "; - } - $sec_parameter .= " vtiger_groups.groupname IN ( - SELECT vtiger_groups.groupname - FROM vtiger_tmp_read_group_sharing_per - INNER JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_tmp_read_group_sharing_per.sharedgroupid - WHERE userid=".$current_user->id." - AND tabid=".$tab_id.")))) "; - } - } - } - return $sec_parameter; -} - -// 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; - $log->debug("Entering function transferUserCurrency..."); - - $sql = "update vtiger_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; - $log->debug("Entering function updateProductCurrency..."); - $prod_res = $adb->pquery("select productid from vtiger_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 = 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; - $log->debug("Entering function updatePriceBookCurrency..."); - $pb_res = $adb->pquery("select pricebookid from vtiger_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) { - require_once('modules/PriceBooks/PriceBooks.php'); - - 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 = "$callerName$callerModule"; - }else{ - $caller = $caller."
- ".getTranslatedString('LBL_CREATE_LEAD')."
- ".getTranslatedString('LBL_CREATE_CONTACT')."
- ".getTranslatedString('LBL_CREATE_ACCOUNT')."
- ".getTranslatedString('LBL_CREATE_TICKET').""; - } - return $caller; -} - -/** - * this function searches for a given number in vtiger 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 - $name['Contacts'] = "select contactid as id,concat(firstname,' ',lastname) as name from vtiger_contactdetails inner join vtiger_crmentity on crmid=contactid where deleted=0 and (phone = ? or mobile = ? or fax = ?)";//array('name'=>"concat(firstname,' ',lastname)", 'table'=>'vtiger_contactdetails', 'field'=>"phone,mobile,fax", 'id'=>'contactid'); - $name['Accounts'] = "select accountid as id, accountname as name from vtiger_account inner join vtiger_crmentity on crmid=accountid where deleted =0 and (phone = ? or otherphone = ? or fax = ?)";//array('name'=>"accountname", 'table'=>"vtiger_account", 'field'=>"phone, otherphone, fax", 'id'=>'accountid'); - $name['Leads'] = "select leadid as id,concat(firstname,' ',lastname) as name from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid inner join vtiger_leadaddress on vtiger_leaddetails.leadid = vtiger_leadaddress.leadaddressid where vtiger_crmentity.deleted =0 and (vtiger_leadaddress.phone = ? or vtiger_leadaddress.mobile = ? or vtiger_leadaddress.fax = ?)";//array('name'=>"concat(firstname,' ',lastname)", 'table'=>"vtiger_leaddetails inner join vtiger_leadaddress on vtiger_leaddetails.leadid = vtiger_leadaddress.leadaddressid", 'field'=>"phone,mobile,fax", 'id'=>'leadid'); - foreach ($name as $module => $query) { - $result = $adb->pquery($query,array($number,$number,$number)); - 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 searches the given record in the result for the given fields - * @param integer $record - the value to search - * @param array $fields - the fields to search - * @param object $result - the adodb result set in which to search - * @param integer $flag - if on, it removes the non-integers from the fields before comparison - 1 to set - */ -function searchPhoneNumber($record, $fields, $result, $flag=0){ - global $adb; - $count = $adb->num_rows($result); - - for($i=0;$i<$count;$i++){ - foreach($fields as $field){ - $number = $adb->query_result($result, $i, $field); - if($flag == 1){ - $number = getStrippedNumber($number); - } - if($number === $record){ - return $i; - } - } - } - return false; -} - -/** - * this function removes any pre-codes like SIP:, PSTN:, etc added to a number - * it also removes any braces or spaces present in a number - * @param string $number - the number to be processed - */ -function getStrippedNumber($number){ - $number = preg_replace("/[^\d]/i","",$number); - return $number; -} - -/** - * 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){ - $tabid = getTabid($module); - $sql = "select * from vtiger_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 - */ -function get_use_asterisk($id){ - global $adb; - if(!vtlib_isModuleActive('PBXManager')){ - return false; - } - $sql = "select * from vtiger_asteriskextensions where userid = ?"; - $result = $adb->pquery($sql, array($id)); - if($adb->num_rows($result)>0){ - $use_asterisk = $adb->query_result($result, 0, "use_asterisk"); - $asterisk_extension = $adb->query_result($result, 0, "asterisk_extension"); - if($use_asterisk == 0 || empty($asterisk_extension)){ - return 'false'; - }else{ - return 'true'; - } - }else{ - return 'false'; - } -} - -/** - * 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){ - $sql = "select * from vtiger_asteriskextensions where asterisk_extension=".$userExtension; - $result = $adb->pquery($sql,array()); - $userID = $adb->query_result($result, 0, "userid"); - - $crmID = $adb->getUniqueID('vtiger_crmentity'); - $timeOfCall = date('Y-m-d H:i:s'); - - $sql = "insert into vtiger_crmentity values (?,?,?,?,?,?,?,?,?,?,?,?,?)"; - $params = array($crmID, $userID, $userID, 0, "PBXManager", "", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0); - $adb->pquery($sql, $params); - - if(empty($callfrom)){ - $callfrom = "Unknown"; - } - if(empty($callto)){ - $callto = "Unknown"; - } - - if($status == 'outgoing'){ - //call is from user to record - $sql = "select * from vtiger_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 = getCallerInfo($callto); - if($receiver == false){ - $receiver = getCallerInfo(getStrippedNumber($callto)); - } - if(empty($receiver)){ - $receiver = "Unknown"; - }else{ - $receiver = "".$receiver[name].""; - } - }else{ - //call is from record to user - $sql = "select * from vtiger_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 = getCallerInfo($callfrom); - if($callerName == false){ - $callerName = getCallerInfo(getStrippedNumber($callfrom)); - } - if(empty($callerName)){ - $callerName = "Unknown"; - }else{ - $callerName = "".decode_html($callerName[name]).""; - } - } - - $sql = "insert into vtiger_pbxmanager (pbxmanagerid,callfrom,callto,timeofcall,status)values (?,?,?,?,?)"; - $params = array($crmID, $callerName, $receiver, $timeOfCall, $status); - $adb->pquery($sql, $params); -} -//functions for asterisk integration end - -//functions for settings page -/** - * this function returns the blocks for the settings page - */ -function getSettingsBlocks(){ - global $adb; - $sql = "select * from vtiger_settings_blocks order by sequence"; - $result = $adb->query($sql); - $count = $adb->num_rows($result); - $blocks = array(); - - if($count>0){ - for($i=0;$i<$count;$i++){ - $blockid = $adb->query_result($result, $i, "blockid"); - $label = $adb->query_result($result, $i, "label"); - $blocks[$blockid] = $label; - } - } - return $blocks; -} - -/** - * this function returns the fields for the settings page - */ -function getSettingsFields(){ - global $adb; - $sql = "select * from vtiger_settings_field where blockid!=? and active=0 order by blockid,sequence"; - $result = $adb->pquery($sql, array(getSettingsBlockId('LBL_MODULE_MANAGER'))); - $count = $adb->num_rows($result); - $fields = array(); - - if($count>0){ - for($i=0;$i<$count;$i++){ - $blockid = $adb->query_result($result, $i, "blockid"); - $iconpath = $adb->query_result($result, $i, "iconpath"); - $description = $adb->query_result($result, $i, "description"); - $linkto = $adb->query_result($result, $i, "linkto"); - $action = getPropertiesFromURL($linkto, "action"); - $module = getPropertiesFromURL($linkto, "module"); - $name = $adb->query_result($result, $i, "name"); - - $fields[$blockid][] = array("icon"=>$iconpath, "description"=>$description, "link"=>$linkto, "name"=>$name, "action"=>$action, "module"=>$module); - } - - //add blanks for 4-column layout - foreach($fields as $blockid=>&$field){ - if(count($field)>0 && count($field)<4){ - for($i=count($field);$i<4;$i++){ - $field[$i] = array(); - } - } - } - } - return $fields; -} - -/** - * this function takes an url and returns the module name from it - */ -function getPropertiesFromURL($url, $action){ - $result = array(); - preg_match("/$action=([^&]+)/",$url,$result); - return $result[1]; -} - -//functions for settings page end - -/* 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; - $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 FROM vtiger_field WHERE uitype=? AND tabid=? and vtiger_field.presence in (0,2)", array('4', getTabid($module))); - 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'); - - $field = array(); - $field['name'] = $fieldname; - $field['column'] = $columnname; - $field['label'] = $fieldlabel; - } - } else { - - foreach($cachedModuleFields as $fieldinfo) { - if($fieldinfo['uitype'] == '4') { - $field = array(); - - $field['name'] = $fieldinfo['fieldname']; - $field['column'] = $fieldinfo['columnname']; - $field['label'] = $fieldinfo['fieldlabel']; - - 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; - $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('update_log','filename','comments'), - ); - - $nonmergable_displaytypes = Array(4); - $nonmergable_uitypes = Array('70','69','4'); - - $sql = "SELECT fieldid,typeofdata FROM vtiger_field WHERE tabid = ? and vtiger_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; -} - -/* 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; - $primary_obj = CRMEntity::getInstance($module); - $secondary_obj = CRMEntity::getInstance($secmodule); - - $ui10_query = $adb->pquery("SELECT vtiger_field.tabid AS tabid,vtiger_field.tablename AS tablename, vtiger_field.columnname AS columnname FROM vtiger_field INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid WHERE (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?) OR (vtiger_fieldmodulerel.module=? AND vtiger_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 { - if(method_exists($primary_obj,setRelationTables)){ - $reltables = $primary_obj->setRelationTables($secmodule); - } else { - $reltables = ''; - } - } - if(is_array($reltables) && !empty($reltables)){ - $rel_array = $reltables; - } else { - $rel_array = array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"".$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; - $log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)"); - - if ($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 - */ -function installVtlibModule($packagename, $packagepath, $customized=false) { - global $log; - require_once('vtlib/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - $Vtiger_Utils_Log = true; - $package = new Vtiger_Package(); - - $module = $package->getModuleNameFromZip($packagepath); - $module_exists = false; - $module_dir_exists = false; - if($module == null) { - $log->fatal("$packagename Module zipfile is not valid!"); - } else if(Vtiger_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 = Vtiger_Module::getInstance($module); - if (empty($moduleInstance)) { - $log->fatal("$module module installation failed!"); - } - } -} - -/* 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/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - $Vtiger_Utils_Log = true; - $package = new Vtiger_Package(); - - if($module == null) { - $log->fatal("Module name is invalid"); - } else { - $moduleInstance = Vtiger_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/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - $Vtiger_Utils_Log = true; - $package = new Vtiger_Package(); - - if($module == null) { - $log->fatal("Module name is invalid"); - } else { - $moduleInstance = Vtiger_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!"); - } - } -} - -// Function to install Vtlib Compliant - Optional Modules -function installOptionalModules($selected_modules){ - global $log; - require_once('vtlib/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - - $selected_modules = split(":",$selected_modules); - - if ($handle = opendir('packages/5.1.0/optional')) { - - while (false !== ($file = readdir($handle))) { - $filename_arr = explode(".", $file); - $packagename = $filename_arr[0]; - if (!empty($packagename)) { - $packagepath = "packages/5.1.0/optional/$file"; - $package = new Vtiger_Package(); - $module = $package->getModuleNameFromZip($packagepath); - if($module != null) { - $moduleInstance = Vtiger_Module::getInstance($module); - if(in_array($packagename,$selected_modules)) { - if($moduleInstance) { - initUpdateVtlibModule($module, $packagepath); - } else { - installVtlibModule($packagename, $packagepath); - } - } elseif ($moduleInstance) { - initUpdateVtlibModule($module, $packagepath); - vtlib_toggleModuleAccess((string)$module, false); - } - } - } - } - closedir($handle); - } -} - -/** - * 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) { - $sql="select distinct vtiger_field.tabid, name - from vtiger_field - inner join vtiger_tab - on vtiger_field.tabid=vtiger_tab.tabid - where vtiger_field.tabid not in(9,10,16,15,8,29) and vtiger_tab.presence = 0 and vtiger_tab.isentitytype=1"; - $it = new SqlResultIterator($adb, $adb->query($sql)); - $modules = array(); - foreach($it as $row) { - if(isPermitted($row->name,'index') == "yes") { - $modules[$row->name] = getTranslatedString($row->name); - } - } - 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; - $data = array(); - $sql = "select related_to from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($id)); - if($adb->num_rows($result)>0){ - $relID = $adb->query_result($result, 0, "related_to"); - $sql = "select setype from vtiger_crmentity where crmid=?"; - $result = $adb->pquery($sql, array($relID)); - if($adb->num_rows($result)>0){ - $setype = $adb->query_result($result, 0, "setype"); - } - $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; - $data = array(); - $sql = "select setype from vtiger_crmentity where crmid=?"; - $result = $adb->pquery($sql, array($id)); - if($adb->num_rows($result)>0){ - $setype = $adb->query_result($result, 0, "setype"); - $data = getEntityName($setype, $id); - } - $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; - $fields = array(); - $result = $adb->pquery("SELECT tablename,fieldlabel,fieldname FROM vtiger_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 check if a given record exists (not deleted) - * @param integer $recordId - record id - */ -function isRecordExists($recordId) { - global $adb; - $query = "SELECT crmid FROM vtiger_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; - list($y,$m,$d) = split('-',$value); - - if(strlen($y)<4){ - $insert_date = getDBInsertDateValue($value); - } else { - $insert_date = $value; - } - $log->debug("Exiting getDBInsertDateValue method ..."); - return $insert_date; -} - -/** 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 sanitize the upload file name when the file name is detected to have bad extensions - * @param String -- $fileName - File name to be sanitized - * @return String - Sanitized file name - */ -function sanitizeUploadFileName($fileName, $badFileExtensions) { - - $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename - - $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; -} +debug("Entering return_name(".$row.",".$first_column.",".$last_column.") method ..."); + $first_name = ""; + $last_name = ""; + $full_name = ""; + + if(isset($row[$first_column])) + { + $first_name = stripslashes($row[$first_column]); + } + + if(isset($row[$last_column])) + { + $last_name = stripslashes($row[$last_column]); + } + + $full_name = $first_name; + + // If we have a first name and we have a last name + if($full_name != "" && $last_name != "") + { + // append a space, then the last name + $full_name .= " ".$last_name; + } + // If we have no first name, but we have a last name + else if($last_name != "") + { + // append the last name without the space. + $full_name .= $last_name; + } + + $log->debug("Exiting return_name method ..."); + return $full_name; +} + +/** Function to return language + * @returns $languages -- languages:: Type string + * +*/ + +function get_languages() +{ + global $log; + $log->debug("Entering get_languages() method ..."); + global $languages; + $log->debug("Exiting get_languages method ..."); + return $languages; +} + +/** Function to return language + * @param $key -- key:: Type string + * @returns $languages -- languages:: Type string + * +*/ + +//seems not used +function get_language_display($key) +{ + global $log; + $log->debug("Entering get_language_display(".$key.") method ..."); + global $languages; + $log->debug("Exiting get_language_display method ..."); + return $languages[$key]; +} + +/** Function returns the user array + * @param $assigned_user_id -- assigned_user_id:: Type string + * @returns $user_list -- user list:: Type array + * +*/ + +function get_assigned_user_name(&$assigned_user_id) +{ + global $log; + $log->debug("Entering get_assigned_user_name(".$assigned_user_id.") method ..."); + $user_list = &get_user_array(false,""); + if(isset($user_list[$assigned_user_id])) + { + $log->debug("Exiting get_assigned_user_name method ..."); + return $user_list[$assigned_user_id]; + } + + $log->debug("Exiting get_assigned_user_name method ..."); + return ""; +} + +/** Function returns the user key in user array + * @param $add_blank -- boolean:: Type boolean + * @param $status -- user status:: Type string + * @param $assigned_user -- user id:: Type string + * @param $private -- sharing type:: Type string + * @returns $user_array -- user array:: Type array + * +*/ + +//used in module file +function get_user_array($add_blank=true, $status="Active", $assigned_user="",$private="") +{ + global $log; + $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); + global $current_user; + if(isset($current_user) && $current_user->id != '') + { + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + } + static $user_array = null; + $module=$_REQUEST['module']; + + if($user_array == null) + { + require_once('include/database/PearDatabase.php'); + $db = PearDatabase::getInstance(); + $temp_result = Array(); + // Including deleted vtiger_users for now. + if (empty($status)) { + $query = "SELECT id, user_name from vtiger_users"; + $params = array(); + } + else { + if($private == 'private') + { + $log->debug("Sharing is Private. Only the current user should be listed"); + $query = "select id as id,user_name as user_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ? and status='Active' union select shareduserid as id,vtiger_users.user_name as user_name from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=?"; + $params = array($current_user->id, $current_user_parent_role_seq."::%", $current_user->id, getTabid($module)); + } + else + { + $log->debug("Sharing is Public. All vtiger_users should be listed"); + $query = "SELECT id, user_name from vtiger_users WHERE status=?"; + $params = array($status); + } + } + if (!empty($assigned_user)) { + $query .= " OR id=?"; + array_push($params, $assigned_user); + } + + $query .= " order by user_name ASC"; + + $result = $db->pquery($query, $params, true, "Error filling in user array: "); + + if ($add_blank==true){ + // Add in a blank row + $temp_result[''] = ''; + } + + // Get the id and the name. + while($row = $db->fetchByAssoc($result)) + { + $temp_result[$row['id']] = $row['user_name']; + } + + $user_array = &$temp_result; + } + + $log->debug("Exiting get_user_array method ..."); + + return $user_array; +} + +function get_group_array($add_blank=true, $status="Active", $assigned_user="",$private="") +{ + global $log; + $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); + global $current_user; + if(isset($current_user) && $current_user->id != '') + { + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + } + static $group_array = null; + $module=$_REQUEST['module']; + + if($group_array == null) + { + require_once('include/database/PearDatabase.php'); + $db = PearDatabase::getInstance(); + $temp_result = Array(); + // Including deleted vtiger_users for now. + $log->debug("Sharing is Public. All vtiger_users should be listed"); + $query = "SELECT groupid, groupname from vtiger_groups"; + $params = array(); + + if($private == 'private'){ + + $query .= " WHERE groupid=?"; + $params = array( $current_user->id); + + if(count($current_user_groups) != 0) { + $query .= " OR vtiger_groups.groupid in (".generateQuestionMarks($current_user_groups).")"; + array_push($params, $current_user_groups); + } + $log->debug("Sharing is Private. Only the current user should be listed"); + $query .= " union select vtiger_group2role.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_group2role inner join vtiger_groups on vtiger_groups.groupid=vtiger_group2role.groupid inner join vtiger_role on vtiger_role.roleid=vtiger_group2role.roleid where vtiger_role.parentrole like ?"; + array_push($params, $current_user_parent_role_seq."::%"); + + if(count($current_user_groups) != 0) { + $query .= " union select vtiger_groups.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_groups inner join vtiger_group2rs on vtiger_groups.groupid=vtiger_group2rs.groupid where vtiger_group2rs.roleandsubid in (".generateQuestionMarks($parent_roles).")"; + array_push($params, $parent_roles); + } + + $query .= " union select sharedgroupid as groupid,vtiger_groups.groupname as groupname from vtiger_tmp_write_group_sharing_per inner join vtiger_groups on vtiger_groups.groupid=vtiger_tmp_write_group_sharing_per.sharedgroupid where vtiger_tmp_write_group_sharing_per.userid=?"; + array_push($params, $current_user->id); + + $query .= " and vtiger_tmp_write_group_sharing_per.tabid=?"; + array_push($params, getTabid($module)); + } + $query .= " order by groupname ASC"; + + $result = $db->pquery($query, $params, true, "Error filling in user array: "); + + if ($add_blank==true){ + // Add in a blank row + $temp_result[''] = ''; + } + + // Get the id and the name. + while($row = $db->fetchByAssoc($result)) + { + $temp_result[$row['groupid']] = $row['groupname']; + } + + $group_array = &$temp_result; + } + + $log->debug("Exiting get_user_array method ..."); + return $group_array; +} +/** Function skips executing arbitary commands given in a string + * @param $string -- string:: Type string + * @param $maxlength -- maximun length:: Type integer + * @returns $string -- escaped string:: Type string + * +*/ + +function clean($string, $maxLength) +{ + global $log; + $log->debug("Entering clean(".$string.",". $maxLength.") method ..."); + $string = substr($string, 0, $maxLength); + $log->debug("Exiting clean method ..."); + return escapeshellcmd($string); +} + +/** + * Copy the specified request variable to the member variable of the specified object. + * Do no copy if the member variable is already set. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function safe_map($request_var, & $focus, $always_copy = false) +{ + global $log; + $log->debug("Entering safe_map(".$request_var.",".get_class($focus).",".$always_copy.") method ..."); + safe_map_named($request_var, $focus, $request_var, $always_copy); + $log->debug("Exiting safe_map method ..."); +} + +/** + * Copy the specified request variable to the member variable of the specified object. + * Do no copy if the member variable is already set. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function safe_map_named($request_var, & $focus, $member_var, $always_copy) +{ + global $log; + $log->debug("Entering safe_map_named(".$request_var.",".get_class($focus).",".$member_var.",".$always_copy.") method ..."); + if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) { + $log->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var"); + $focus->$member_var = $_REQUEST[$request_var]; + } + $log->debug("Exiting safe_map_named method ..."); +} + +/** This function retrieves an application language file and returns the array of strings included in the $app_list_strings var. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are using the current language, do not call this function unless you are loading it for the first time */ + +function return_app_list_strings_language($language) +{ + global $log; + $log->debug("Entering return_app_list_strings_language(".$language.") method ..."); + global $app_list_strings, $default_language, $log, $translation_string_prefix; + $temp_app_list_strings = $app_list_strings; + $language_used = $language; + + @include("include/language/$language.lang.php"); + if(!isset($app_list_strings)) + { + $log->warn("Unable to find the application language file for language: ".$language); + require("include/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($app_list_strings)) + { + $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_app_list_strings_language method ..."); + return null; + } + + + $return_value = $app_list_strings; + $app_list_strings = $temp_app_list_strings; + + $log->debug("Exiting return_app_list_strings_language method ..."); + return $return_value; +} + +/** + * Retrieve the app_currency_strings for the required language. + */ +function return_app_currency_strings_language($language) { + global $log; + $log->debug("Entering return_app_currency_strings_language(".$language.") method ..."); + global $app_currency_strings, $default_language, $log, $translation_string_prefix; + // Backup the value first + $temp_app_currency_strings = $app_currency_strings; + @include("include/language/$language.lang.php"); + if(!isset($app_currency_strings)) + { + $log->warn("Unable to find the application language file for language: ".$language); + require("include/language/$default_language.lang.php"); + $language_used = $default_language; + } + if(!isset($app_currency_strings)) + { + $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_app_currency_strings_language method ..."); + return null; + } + $return_value = $app_currency_strings; + + // Restore the value back + $app_currency_strings = $temp_app_currency_strings; + + $log->debug("Exiting return_app_currency_strings_language method ..."); + return $return_value; +} + +/** This function retrieves an application language file and returns the array of strings included. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are using the current language, do not call this function unless you are loading it for the first time */ +function return_application_language($language) +{ + global $log; + $log->debug("Entering return_application_language(".$language.") method ..."); + global $app_strings, $default_language, $log, $translation_string_prefix; + $temp_app_strings = $app_strings; + $language_used = $language; + + @include("include/language/$language.lang.php"); + if(!isset($app_strings)) + { + $log->warn("Unable to find the application language file for language: ".$language); + require("include/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($app_strings)) + { + $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_application_language method ..."); + return null; + } + + // If we are in debug mode for translating, turn on the prefix now! + if($translation_string_prefix) + { + foreach($app_strings as $entry_key=>$entry_value) + { + $app_strings[$entry_key] = $language_used.' '.$entry_value; + } + } + + $return_value = $app_strings; + $app_strings = $temp_app_strings; + + $log->debug("Exiting return_application_language method ..."); + return $return_value; +} + +/** This function retrieves a module's language file and returns the array of strings included. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are in the current module, do not call this function unless you are loading it for the first time */ +function return_module_language($language, $module) +{ + global $log; + $log->debug("Entering return_module_language(".$language.",". $module.") method ..."); + global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; + static $cachedModuleStrings = array(); + + if(!empty($cachedModuleStrings[$module])) { + $log->debug("Exiting return_module_language method ..."); + return $cachedModuleStrings[$module]; + } + + $temp_mod_strings = $mod_strings; + $language_used = $language; + + @include("modules/$module/language/$language.lang.php"); + if(!isset($mod_strings)) + { + $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); + require("modules/$module/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($mod_strings)) + { + $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_module_language method ..."); + return null; + } + + // If we are in debug mode for translating, turn on the prefix now! + if($translation_string_prefix) + { + foreach($mod_strings as $entry_key=>$entry_value) + { + $mod_strings[$entry_key] = $language_used.' '.$entry_value; + } + } + + $return_value = $mod_strings; + $mod_strings = $temp_mod_strings; + + $log->debug("Exiting return_module_language method ..."); + $cachedModuleStrings[$module] = $return_value; + return $return_value; +} + +/*This function returns the mod_strings for the current language and the specified module +*/ + +function return_specified_module_language($language, $module) +{ + global $log; + global $default_language, $translation_string_prefix; + + @include("modules/$module/language/$language.lang.php"); + if(!isset($mod_strings)) + { + $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); + require("modules/$module/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($mod_strings)) + { + $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_module_language method ..."); + return null; + } + + $return_value = $mod_strings; + + $log->debug("Exiting return_module_language method ..."); + return $return_value; +} + +/** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are using the current language, do not call this function unless you are loading it for the first time */ +function return_mod_list_strings_language($language,$module) +{ + global $log; + $log->debug("Entering return_mod_list_strings_language(".$language.",".$module.") method ..."); + global $mod_list_strings, $default_language, $log, $currentModule,$translation_string_prefix; + + $language_used = $language; + $temp_mod_list_strings = $mod_list_strings; + + if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null) + { + $log->debug("Exiting return_mod_list_strings_language method ..."); + return $mod_list_strings; + } + + @include("modules/$module/language/$language.lang.php"); + + if(!isset($mod_list_strings)) + { + $log->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_mod_list_strings_language method ..."); + return null; + } + + $return_value = $mod_list_strings; + $mod_list_strings = $temp_mod_list_strings; + + $log->debug("Exiting return_mod_list_strings_language method ..."); + return $return_value; +} + +/** This function retrieves a theme's language file and returns the array of strings included. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function return_theme_language($language, $theme) +{ + global $log; + $log->debug("Entering return_theme_language(".$language.",". $theme.") method ..."); + global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; + + $language_used = $language; + + @include("themes/$theme/language/$current_language.lang.php"); + if(!isset($theme_strings)) + { + $log->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme); + require("themes/$theme/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($theme_strings)) + { + $log->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_theme_language method ..."); + return null; + } + + // If we are in debug mode for translating, turn on the prefix now! + if($translation_string_prefix) + { + foreach($theme_strings as $entry_key=>$entry_value) + { + $theme_strings[$entry_key] = $language_used.' '.$entry_value; + } + } + + $log->debug("Exiting return_theme_language method ..."); + return $theme_strings; +} + + + +/** If the session variable is defined and is not equal to "" then return it. Otherwise, return the default value. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. +*/ +function return_session_value_or_default($varname, $default) +{ + global $log; + $log->debug("Entering return_session_value_or_default(".$varname.",". $default.") method ..."); + if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "") + { + $log->debug("Exiting return_session_value_or_default method ..."); + return $_SESSION[$varname]; + } + + $log->debug("Exiting return_session_value_or_default method ..."); + return $default; +} + +/** + * Creates an array of where restrictions. These are used to construct a where SQL statement on the query + * It looks for the variable in the $_REQUEST array. If it is set and is not "" it will create a where clause out of it. + * @param &$where_clauses - The array to append the clause to + * @param $variable_name - The name of the variable to look for an add to the where clause if found + * @param $SQL_name - [Optional] If specified, this is the SQL column name that is used. If not specified, the $variable_name is used as the SQL_name. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null) +{ + global $log; + $log->debug("Entering append_where_clause(".$where_clauses.",".$variable_name.",".$SQL_name.") method ..."); + if($SQL_name == null) + { + $SQL_name = $variable_name; + } + + if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "") + { + array_push($where_clauses, "$SQL_name like '$_REQUEST[$variable_name]%'"); + } + $log->debug("Exiting append_where_clause method ..."); +} + +/** + * Generate the appropriate SQL based on the where clauses. + * @param $where_clauses - An Array of individual where clauses stored as strings + * @returns string where_clause - The final SQL where clause to be executed. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function generate_where_statement($where_clauses) +{ + global $log; + $log->debug("Entering generate_where_statement(".$where_clauses.") method ..."); + $where = ""; + foreach($where_clauses as $clause) + { + if($where != "") + $where .= " and "; + $where .= $clause; + } + + $log->info("Here is the where clause for the list view: $where"); + $log->debug("Exiting generate_where_statement method ..."); + return $where; +} + +/** + * A temporary method of generating GUIDs of the correct format for our DB. + * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee + * + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. +*/ +function create_guid() +{ + global $log; + $log->debug("Entering create_guid() method ..."); + $microTime = microtime(); + list($a_dec, $a_sec) = explode(" ", $microTime); + + $dec_hex = sprintf("%x", $a_dec* 1000000); + $sec_hex = sprintf("%x", $a_sec); + + ensure_length($dec_hex, 5); + ensure_length($sec_hex, 6); + + $guid = ""; + $guid .= $dec_hex; + $guid .= create_guid_section(3); + $guid .= '-'; + $guid .= create_guid_section(4); + $guid .= '-'; + $guid .= create_guid_section(4); + $guid .= '-'; + $guid .= create_guid_section(4); + $guid .= '-'; + $guid .= $sec_hex; + $guid .= create_guid_section(6); + + $log->debug("Exiting create_guid method ..."); + return $guid; + +} + +/** Function to create guid section for a given character + * @param $characters -- characters:: Type string + * @returns $return -- integer:: Type integer`` + */ +function create_guid_section($characters) +{ + global $log; + $log->debug("Entering create_guid_section(".$characters.") method ..."); + $return = ""; + for($i=0; $i<$characters; $i++) + { + $return .= sprintf("%x", rand(0,15)); + } + $log->debug("Exiting create_guid_section method ..."); + return $return; +} + +/** Function to ensure length + * @param $string -- string:: Type string + * @param $length -- length:: Type string + */ + +function ensure_length(&$string, $length) +{ + global $log; + $log->debug("Entering ensure_length(".$string.",". $length.") method ..."); + $strlen = strlen($string); + if($strlen < $length) + { + $string = str_pad($string,$length,"0"); + } + else if($strlen > $length) + { + $string = substr($string, 0, $length); + } + $log->debug("Exiting ensure_length method ..."); +} +/* +function microtime_diff($a, $b) { + global $log; + $log->debug("Entering microtime_diff(".$a.",". $b.") method ..."); + list($a_dec, $a_sec) = explode(" ", $a); + list($b_dec, $b_sec) = explode(" ", $b); + $log->debug("Exiting microtime_diff method ..."); + return $b_sec - $a_sec + $b_dec - $a_dec; +} + */ + +/** + * Return the display name for a theme if it exists. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_theme_display($theme) { + global $log; + $log->debug("Entering get_theme_display(".$theme.") method ..."); + global $theme_name, $theme_description; + $temp_theme_name = $theme_name; + $temp_theme_description = $theme_description; + + if (is_file("./themes/$theme/config.php")) { + @include("./themes/$theme/config.php"); + $return_theme_value = $theme_name; + } + else { + $return_theme_value = $theme; + } + $theme_name = $temp_theme_name; + $theme_description = $temp_theme_description; + + $log->debug("Exiting get_theme_display method ..."); + return $return_theme_value; +} + +/** + * Return an array of directory names. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_themes() { + global $log; + $log->debug("Entering get_themes() method ..."); + if ($dir = @opendir("./themes")) { + while (($file = readdir($dir)) !== false) { + if ($file != ".." && $file != "." && $file != "CVS" && $file != "Attic" && $file != "akodarkgem" && $file != "bushtree" && $file != "coolblue" && $file != "Amazon" && $file != "busthree" && $file != "Aqua" && $file != "nature" && $file != "orange" && $file != "blue") { + if(is_dir("./themes/".$file)) { + if(!($file[0] == '.')) { + // set the initial theme name to the filename + $name = $file; + + // if there is a configuration class, load that. + if(is_file("./themes/$file/config.php")) + { + require_once("./themes/$file/config.php"); + } + + if(is_file("./themes/$file/header.php")) + { + $filelist[$file] = $name; + } + } + } + } + } + closedir($dir); + } + + ksort($filelist); + $log->debug("Exiting get_themes method ..."); + return $filelist; +} + + + +/** + * Create javascript to clear values of all elements in a form. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_clear_form_js () { +global $log; +$log->debug("Entering get_clear_form_js () method ..."); +$the_script = << + + +EOQ; + +$log->debug("Exiting get_clear_form_js method ..."); +return $the_script; +} + +/** + * Create javascript to set the cursor focus to specific vtiger_field in a form + * when the screen is rendered. The vtiger_field name is currently hardcoded into the + * the function. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_set_focus_js () { +global $log; +$log->debug("Entering set_focus() method ..."); +//TODO Clint 5/20 - Make this function more generic so that it can take in the target form and vtiger_field names as variables +$the_script = << + + +EOQ; + +$log->debug("Exiting get_set_focus_js method ..."); +return $the_script; +} + +/** + * Very cool algorithm for sorting multi-dimensional arrays. Found at http://us2.php.net/manual/en/function.array-multisort.php + * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...); + * Explanation: $array is the array you want to sort, 'col1' is the name of the column + * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING + * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to + * the first - so the array is sorted by the last given column first, then the one before ... + * Example: $array = array_csort($array,'town','age',SORT_DESC,'name'); + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function array_csort() { + global $log; + $log->debug("Entering array_csort() method ..."); + $args = func_get_args(); + $marray = array_shift($args); + $i = 0; + + $msortline = "return(array_multisort("; + foreach ($args as $arg) { + $i++; + if (is_string($arg)) { + foreach ($marray as $row) { + $sortarr[$i][] = $row[$arg]; + } + } else { + $sortarr[$i] = $arg; + } + $msortline .= "\$sortarr[".$i."],"; + } + $msortline .= "\$marray));"; + + eval($msortline); + $log->debug("Exiting array_csort method ..."); + return $marray; +} + +/** Function to set default varibles on to the global variable + * @param $defaults -- default values:: Type array + */ +function set_default_config(&$defaults) +{ + global $log; + $log->debug("Entering set_default_config(".$defaults.") method ..."); + + foreach ($defaults as $name=>$value) + { + if ( ! isset($GLOBALS[$name]) ) + { + $GLOBALS[$name] = $value; + } + } + $log->debug("Exiting set_default_config method ..."); +} + +$toHtml = array( + '"' => '"', + '<' => '<', + '>' => '>', + '& ' => '& ', + "'" => ''', + '' => '\r', + '\r\n'=>'\n', + +); + +/** Function to convert the given string to html + * @param $string -- string:: Type string + * @param $ecnode -- boolean:: Type boolean + * @returns $string -- string:: Type string + * + */ +function to_html($string, $encode=true) +{ + global $log,$default_charset; + //$log->debug("Entering to_html(".$string.",".$encode.") method ..."); + global $toHtml; + $action = $_REQUEST['action']; + $search = $_REQUEST['search']; + + $doconvert = false; + + if($_REQUEST['module'] != 'Settings' && $_REQUEST['file'] != 'ListView' && $_REQUEST['module'] != 'Portal' && $_REQUEST['module'] != "Reports")// && $_REQUEST['module'] != 'Emails') + $ajax_action = $_REQUEST['module'].'Ajax'; + + if(is_string($string)) + { + if($action != 'CustomView' && $action != 'Export' && $action != $ajax_action && $action != 'LeadConvertToEntities' && $action != 'CreatePDF' && $action != 'ConvertAsFAQ' && $_REQUEST['module'] != 'Dashboard' && $action != 'CreateSOPDF' && $action != 'SendPDFMail' && (!isset($_REQUEST['submode'])) ) + { + $doconvert = true; + } + else if($search == true) + { + // Fix for tickets #4647, #4648. Conversion required in case of search results also. + $doconvert = true; + } + if ($doconvert == true) + { + if(strtolower($default_charset) == 'utf-8') + $string = htmlentities($string, ENT_QUOTES, $default_charset); + else + $string = preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); + } + } + + //$log->debug("Exiting to_html method ..."); + return $string; +} + +/** Function to get the tablabel for a given id + * @param $tabid -- tab id:: Type integer + * @returns $string -- string:: Type string +*/ + +function getTabname($tabid) +{ + global $log; + $log->debug("Entering getTabname(".$tabid.") method ..."); + $log->info("tab id is ".$tabid); + global $adb; + $sql = "select tablabel from vtiger_tab where tabid=?"; + $result = $adb->pquery($sql, array($tabid)); + $tabname= $adb->query_result($result,0,"tablabel"); + $log->debug("Exiting getTabname method ..."); + return $tabname; + +} + +/** Function to get the tab module name for a given id + * @param $tabid -- tab id:: Type integer + * @returns $string -- string:: Type string + * + */ + +function getTabModuleName($tabid) +{ + global $log; + $log->debug("Entering getTabModuleName(".$tabid.") method ..."); + + // Lookup information in cache first + $tabname = VTCacheUtils::lookupModulename($tabid); + if($tabname === false) { + if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { + include('tabdata.php'); + $tabname = array_search($tabid,$tab_info_array); + + // Update information to cache for re-use + VTCacheUtils::updateTabidInfo($tabid, $tabname); + + } else { + $log->info("tab id is ".$tabid); + global $adb; + $sql = "select name from vtiger_tab where tabid=?"; + $result = $adb->pquery($sql, array($tabid)); + $tabname= $adb->query_result($result,0,"name"); + + // Update information to cache for re-use + VTCacheUtils::updateTabidInfo($tabid, $tabname); + } + } + $log->debug("Exiting getTabModuleName method ..."); + return $tabname; +} + +/** Function to get column fields for a given module + * @param $module -- module:: Type string + * @returns $column_fld -- column field :: Type array + * + */ + +function getColumnFields($module) +{ + global $log; + $log->debug("Entering getColumnFields(".$module.") method ..."); + $log->debug("in getColumnFields ".$module); + + // Lookup in cache for information + $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); + + if($cachedModuleFields === false) { + global $adb; + $tabid = getTabid($module); + if ($module == 'Calendar') { + $tabid = array('9','16'); + } + + // Let us pick up all the fields first so that we can cache information + $sql = "SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence + FROM vtiger_field WHERE tabid in (" . generateQuestionMarks($tabid) . ")"; + + $result = $adb->pquery($sql, array($tabid)); + $noofrows = $adb->num_rows($result); + + if($noofrows) { + while($resultrow = $adb->fetch_array($result)) { + // Update information to cache for re-use + VTCacheUtils::updateFieldInfo( + $resultrow['tabid'], $resultrow['fieldname'], $resultrow['fieldid'], + $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], + $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence'] + ); + } + } + + // For consistency get information from cache + $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); + } + + if($module == 'Calendar') { + $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events'); + if($cachedModuleFields == false) $cachedModuleFields = $cachedEventsFields; + else $cachedModuleFields = array_merge($cachedModuleFields, $cachedEventsFields); + } + + $column_fld = array(); + if($cachedModuleFields) { + foreach($cachedModuleFields as $fieldinfo) { + $column_fld[$fieldinfo['fieldname']] = ''; + } + } + + $log->debug("Exiting getColumnFields method ..."); + return $column_fld; +} + +/** Function to get a users's mail id + * @param $userid -- userid :: Type integer + * @returns $email -- email :: Type string + * + */ + +function getUserEmail($userid) +{ + global $log; + $log->debug("Entering getUserEmail(".$userid.") method ..."); + $log->info("in getUserEmail ".$userid); + + global $adb; + if($userid != '') + { + $sql = "select email1 from vtiger_users where id=?"; + $result = $adb->pquery($sql, array($userid)); + $email = $adb->query_result($result,0,"email1"); + } + $log->debug("Exiting getUserEmail method ..."); + return $email; +} + +/** Function to get a userid for outlook + * @param $username -- username :: Type string + * @returns $user_id -- user id :: Type integer + */ + +//outlook security +function getUserId_Ol($username) +{ + global $log; + $log->debug("Entering getUserId_Ol(".$username.") method ..."); + $log->info("in getUserId_Ol ".$username); + + global $adb; + $sql = "select id from vtiger_users where user_name=?"; + $result = $adb->pquery($sql, array($username)); + $num_rows = $adb->num_rows($result); + if($num_rows > 0) + { + $user_id = $adb->query_result($result,0,"id"); + } + else + { + $user_id = 0; + } + $log->debug("Exiting getUserId_Ol method ..."); + return $user_id; +} + + +/** Function to get a action id for a given action name + * @param $action -- action name :: Type string + * @returns $actionid -- action id :: Type integer + */ + +//outlook security + +function getActionid($action) +{ + global $log; + $log->debug("Entering getActionid(".$action.") method ..."); + global $adb; + $log->info("get Actionid ".$action); + $actionid = ''; + if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) + { + include('tabdata.php'); + $actionid= $action_id_array[$action]; + } + else + { + $query="select * from vtiger_actionmapping where actionname=?"; + $result =$adb->pquery($query, array($action)); + $actionid=$adb->query_result($result,0,'actionid'); + + } + $log->info("action id selected is ".$actionid ); + $log->debug("Exiting getActionid method ..."); + return $actionid; +} + +/** Function to get a action for a given action id + * @param $action id -- action id :: Type integer + * @returns $actionname-- action name :: Type string + */ + + +function getActionname($actionid) +{ + global $log; + $log->debug("Entering getActionname(".$actionid.") method ..."); + global $adb; + + $actionname=''; + + if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) + { + include('tabdata.php'); + $actionname= $action_name_array[$actionid]; + } + else + { + + $query="select * from vtiger_actionmapping where actionid=? and securitycheck=0"; + $result =$adb->pquery($query, array($actionid)); + $actionname=$adb->query_result($result,0,"actionname"); + } + $log->debug("Exiting getActionname method ..."); + return $actionname; +} + +/** Function to get a assigned user id for a given entity + * @param $record -- entity id :: Type integer + * @returns $user_id -- user id :: Type integer + */ + +function getUserId($record) +{ + global $log; + $log->debug("Entering getUserId(".$record.") method ..."); + $log->info("in getUserId ".$record); + + global $adb; + $user_id=$adb->query_result($adb->pquery("select * from vtiger_crmentity where crmid = ?", array($record)),0,'smownerid'); + $log->debug("Exiting getUserId method ..."); + return $user_id; +} + +/** Function to get a user id or group id for a given entity + * @param $record -- entity id :: Type integer + * @returns $ownerArr -- owner id :: Type array + */ + +function getRecordOwnerId($record) +{ + global $log; + $log->debug("Entering getRecordOwnerId(".$record.") method ..."); + global $adb; + $ownerArr=Array(); + $query="select smownerid from vtiger_crmentity where crmid = ?"; + $result=$adb->pquery($query, array($record)); + if($adb->num_rows($result) > 0) + { + $ownerId=$adb->query_result($result,0,'smownerid'); + $sql_result = $adb->pquery("select count(*) as count from vtiger_users where id = ?",array($ownerId)); + if($adb->query_result($sql_result,0,'count') > 0) + $ownerArr['Users'] = $ownerId; + else + $ownerArr['Groups'] = $ownerId; + } + $log->debug("Exiting getRecordOwnerId method ..."); + return $ownerArr; + +} + +/** Function to insert value to profile2field table + * @param $profileid -- profileid :: Type integer + */ + + +function insertProfile2field($profileid) +{ + global $log; + $log->debug("Entering insertProfile2field(".$profileid.") method ..."); + $log->info("in insertProfile2field ".$profileid); + + global $adb; + $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); + $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); + $num_rows = $adb->num_rows($fld_result); + for($i=0; $i<$num_rows; $i++) + { + $tab_id = $adb->query_result($fld_result,$i,'tabid'); + $field_id = $adb->query_result($fld_result,$i,'fieldid'); + $params = array($profileid, $tab_id, $field_id, 0, 1); + $adb->pquery("insert into vtiger_profile2field values (?,?,?,?,?)", $params); + } + $log->debug("Exiting insertProfile2field method ..."); +} + +/** Function to insert into default org field + */ + +function insert_def_org_field() +{ + global $log; + $log->debug("Entering insert_def_org_field() method ..."); + global $adb; + $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); + $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); + $num_rows = $adb->num_rows($fld_result); + for($i=0; $i<$num_rows; $i++) + { + $tab_id = $adb->query_result($fld_result,$i,'tabid'); + $field_id = $adb->query_result($fld_result,$i,'fieldid'); + $params = array($tab_id, $field_id, 0, 1); + $adb->pquery("insert into vtiger_def_org_field values (?,?,?,?)", $params); + } + $log->debug("Exiting insert_def_org_field() method ..."); +} + +/** Function to insert value to profile2field table + * @param $fld_module -- field module :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $result -- result :: Type string + */ + +function getProfile2FieldList($fld_module, $profileid) +{ + global $log; + $log->debug("Entering getProfile2FieldList(".$fld_module.",". $profileid.") method ..."); + $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "select vtiger_profile2field.visible,vtiger_field.* from vtiger_profile2field inner join vtiger_field on vtiger_field.fieldid=vtiger_profile2field.fieldid where vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($query, array($profileid, $tabid)); + $log->debug("Exiting getProfile2FieldList method ..."); + return $result; +} + +/** Function to insert value to profile2fieldPermissions table + * @param $fld_module -- field module :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $return_data -- return_data :: Type string + */ + +//added by jeri + +function getProfile2FieldPermissionList($fld_module, $profileid) +{ + global $log; + $log->debug("Entering getProfile2FieldPermissionList(".$fld_module.",". $profileid.") method ..."); + $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); + + // Cache information to re-use + static $_module_fieldpermission_cache = array(); + + if(!isset($_module_fieldpermission_cache[$fld_module])) { + $_module_fieldpermission_cache[$fld_module] = array(); + } + + // Lookup cache first + $return_data = VTCacheUtils::lookupProfile2FieldPermissionList($fld_module, $profileid); + + if($return_data === false) { + + $return_data = array(); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "SELECT vtiger_profile2field.visible, vtiger_field.fieldlabel, vtiger_field.uitype, + vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata + FROM vtiger_profile2field INNER JOIN vtiger_field ON vtiger_field.fieldid=vtiger_profile2field.fieldid + WHERE vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)"; + + $qparams = array($profileid, $tabid); + $result = $adb->pquery($query, $qparams); + + for($i=0; $i<$adb->num_rows($result); $i++) { + $return_data[]=array( + $adb->query_result($result,$i,"fieldlabel"), + $adb->query_result($result,$i,"visible"), // From vtiger_profile2field.visible + $adb->query_result($result,$i,"uitype"), + $adb->query_result($result,$i,"visible"), + $adb->query_result($result,$i,"fieldid"), + $adb->query_result($result,$i,"displaytype"), + $adb->query_result($result,$i,"typeofdata") + ); + } + + // Update information to cache for re-use + VTCacheUtils::updateProfile2FieldPermissionList($fld_module, $profileid, $return_data); + } + + + $log->debug("Exiting getProfile2FieldPermissionList method ..."); + return $return_data; +} + +/** Function to getProfile2allfieldsListinsert value to profile2fieldPermissions table + * @param $mod_array -- mod_array :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $profilelist -- profilelist :: Type string + */ + +function getProfile2AllFieldList($mod_array,$profileid) +{ + global $log; + $log->debug("Entering getProfile2AllFieldList(".$mod_array.",".$profileid.") method ..."); + $log->info("in getProfile2AllFieldList vtiger_profile id is " .$profileid); + + global $adb; + $profilelist=array(); + for($i=0;$idebug("Exiting getProfile2AllFieldList method ..."); + return $profilelist; +} + +/** Function to getdefaultfield organisation list for a given module + * @param $fld_module -- module name :: Type string + * @returns $result -- string :: Type object + */ + +//end of fn added by jeri + +function getDefOrgFieldList($fld_module) +{ + global $log; + $log->debug("Entering getDefOrgFieldList(".$fld_module.") method ..."); + $log->info("in getDefOrgFieldList ".$fld_module); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "select vtiger_def_org_field.visible,vtiger_field.* from vtiger_def_org_field inner join vtiger_field on vtiger_field.fieldid=vtiger_def_org_field.fieldid where vtiger_def_org_field.tabid=? and vtiger_field.presence in (0,2)"; + $qparams = array($tabid); + $result = $adb->pquery($query, $qparams); + $log->debug("Exiting getDefOrgFieldList method ..."); + return $result; +} + +/** Function to getQuickCreate for a given tabid + * @param $tabid -- tab id :: Type string + * @param $actionid -- action id :: Type integer + * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean + */ + +function getQuickCreate($tabid,$actionid) +{ + global $log; + $log->debug("Entering getQuickCreate(".$tabid.",".$actionid.") method ..."); + $module=getTabModuleName($tabid); + $actionname=getActionname($actionid); + $QuickCreateForm= 'true'; + + $perr=isPermitted($module,$actionname); + if($perr = 'no') + { + $QuickCreateForm= 'false'; + } + $log->debug("Exiting getQuickCreate method ..."); + return $QuickCreateForm; + +} + +/** Function to getQuickCreate for a given tabid + * @param $tabid -- tab id :: Type string + * @param $actionid -- action id :: Type integer + * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean + */ + +function ChangeStatus($status,$activityid,$activity_mode='') + { + global $log; + $log->debug("Entering ChangeStatus(".$status.",".$activityid.",".$activity_mode."='') method ..."); + $log->info("in ChangeStatus ".$status. ' vtiger_activityid is '.$activityid); + + global $adb; + if ($activity_mode == 'Task') + { + $query = "Update vtiger_activity set status=? where activityid = ?"; + } + elseif ($activity_mode == 'Events') + { + $query = "Update vtiger_activity set eventstatus=? where activityid = ?"; + } + if($query) { + $adb->pquery($query, array($status, $activityid)); + } + $log->debug("Exiting ChangeStatus method ..."); + } + +/** Function to set date values compatible to database (YY_MM_DD) + * @param $value -- value :: Type string + * @returns $insert_date -- insert_date :: Type string + */ + +function getDBInsertDateValue($value) +{ + global $log; + $log->debug("Entering getDBInsertDateValue(".$value.") method ..."); + global $current_user; + $dat_fmt = $current_user->date_format; + if($dat_fmt == '') { + $dat_fmt = 'dd-mm-yyyy'; + } + $insert_date=''; + if($dat_fmt == 'dd-mm-yyyy') + { + list($d,$m,$y) = explode('-',$value); + } + elseif($dat_fmt == 'mm-dd-yyyy') + { + list($m,$d,$y) = explode('-',$value); + } + elseif($dat_fmt == 'yyyy-mm-dd') + { + list($y,$m,$d) = explode('-',$value); + } + + if(!$y && !$m && !$d) { + $insert_date = ''; + } else { + $insert_date=$y.'-'.$m.'-'.$d; + } + $log->debug("Exiting getDBInsertDateValue method ..."); + return $insert_date; +} + +/** Function to get unitprice for a given product id + * @param $productid -- product id :: Type integer + * @returns $up -- up :: Type string + */ + +function getUnitPrice($productid, $module='Products') +{ + global $log, $adb; + $log->debug("Entering getUnitPrice($productid,$module) method ..."); + + if($module == 'Services') { + $query = "select unit_price from vtiger_service where serviceid=?"; + } else { + $query = "select unit_price from vtiger_products where productid=?"; + } + $result = $adb->pquery($query, array($productid)); + $unitpice = $adb->query_result($result,0,'unit_price'); + $log->debug("Exiting getUnitPrice method ..."); + return $unitpice; +} + +/** Function to upload product image file + * @param $mode -- mode :: Type string + * @param $id -- id :: Type integer + * @returns $ret_array -- return array:: Type array + */ + +function upload_product_image_file($mode,$id) +{ + global $log; + $log->debug("Entering upload_product_image_file(".$mode.",".$id.") method ..."); + global $root_directory; + $log->debug("Inside upload_product_image_file. The id is ".$id); + $uploaddir = $root_directory ."/test/product/"; + + $file_path_name = $_FILES['imagename']['name']; + if (isset($_REQUEST['imagename_hidden'])) { + $file_name = $_REQUEST['imagename_hidden']; + } else { + //allowed file pathname like UTF-8 Character + $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name); + } + $file_name = $id.'_'.$file_name; + $filetype= $_FILES['imagename']['type']; + $filesize = $_FILES['imagename']['size']; + + $ret_array = Array(); + + if($filesize > 0) + { + + if(move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$file_name)) + { + + $upload_status = "yes"; + $ret_array["status"] = $upload_status; + $ret_array["file_name"] = $file_name; + + + } + else + { + $errorCode = $_FILES['imagename']['error']; + $upload_status = "no"; + $ret_array["status"] = $upload_status; + $ret_array["errorcode"] = $errorCode; + + + } + + } + else + { + $upload_status = "no"; + $ret_array["status"] = $upload_status; + } + $log->debug("Exiting upload_product_image_file method ..."); + return $ret_array; + +} + +/** Function to upload product image file + * @param $id -- id :: Type integer + * @param $deleted_array -- images to be deleted :: Type array + * @returns $imagename -- imagelist:: Type array + */ + +function getProductImageName($id,$deleted_array='') +{ + global $log; + $log->debug("Entering getProductImageName(".$id.",".$deleted_array."='') method ..."); + global $adb; + $image_array=array(); + $query = "select imagename from vtiger_products where productid=?"; + $result = $adb->pquery($query, array($id)); + $image_name = $adb->query_result($result,0,"imagename"); + $image_array=explode("###",$image_name); + $log->debug("Inside getProductImageName. The image_name is ".$image_name); + if($deleted_array!='') + { + $resultant_image = array(); + $resultant_image=array_merge(array_diff($image_array,$deleted_array)); + $imagelists=implode('###',$resultant_image); + $log->debug("Exiting getProductImageName method ..."); + return $imagelists; + } + else + { + $log->debug("Exiting getProductImageName method ..."); + return $image_name; + } +} + +/** Function to get Contact images + * @param $id -- id :: Type integer + * @returns $imagename -- imagename:: Type string + */ + +function getContactImageName($id) +{ + global $log; + $log->debug("Entering getContactImageName(".$id.") method ..."); + global $adb; + $query = "select imagename from vtiger_contactdetails where contactid=?"; + $result = $adb->pquery($query, array($id)); + $image_name = $adb->query_result($result,0,"imagename"); + $log->debug("Inside getContactImageName. The image_name is ".$image_name); + $log->debug("Exiting getContactImageName method ..."); + return $image_name; + +} + +/** Function to update sub total in inventory + * @param $module -- module name :: Type string + * @param $tablename -- tablename :: Type string + * @param $colname -- colname :: Type string + * @param $colname1 -- coluname1 :: Type string + * @param $entid_fld -- entity field :: Type string + * @param $entid -- entid :: Type integer + * @param $prod_total -- totalproduct :: Type integer + */ + +function updateSubTotal($module,$tablename,$colname,$colname1,$entid_fld,$entid,$prod_total) +{ + global $log; + $log->debug("Entering updateSubTotal(".$module.",".$tablename.",".$colname.",".$colname1.",".$entid_fld.",".$entid.",".$prod_total.") method ..."); + global $adb; + //getting the subtotal + $query = "select ".$colname.",".$colname1." from ".$tablename." where ".$entid_fld."=?"; + $result1 = $adb->pquery($query, array($entid)); + $subtot = $adb->query_result($result1,0,$colname); + $subtot_upd = $subtot - $prod_total; + + $gdtot = $adb->query_result($result1,0,$colname1); + $gdtot_upd = $gdtot - $prod_total; + + //updating the subtotal + $sub_query = "update $tablename set $colname=?, $colname1=? where $entid_fld=?"; + $adb->pquery($sub_query, array($subtot_upd, $gdtot_upd, $entid)); + $log->debug("Exiting updateSubTotal method ..."); +} + +/** Function to get Inventory Total + * @param $return_module -- return module :: Type string + * @param $id -- entity id :: Type integer + * @returns $total -- total:: Type integer + */ + +function getInventoryTotal($return_module,$id) +{ + global $log; + $log->debug("Entering getInventoryTotal(".$return_module.",".$id.") method ..."); + global $adb; + if($return_module == "Potentials") + { + $query ="select vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?"; + } + elseif($return_module == "Products") + { + $query="select vtiger_products.productid,vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?"; + } + $result = $adb->pquery($query, array($id)); + $num_rows=$adb->num_rows($result); + $total=0; + for($i=1;$i<=$num_rows;$i++) + { + $unitprice=$adb->query_result($result,$i-1,'unit_price'); + $qty=$adb->query_result($result,$i-1,'quantity'); + $listprice=$adb->query_result($result,$i-1,'listprice'); + if($listprice == '') + $listprice = $unitprice; + if($qty =='') + $qty = 1; + $total = $total+($qty*$listprice); + } + $log->debug("Exiting getInventoryTotal method ..."); + return $total; +} + +/** Function to update product quantity + * @param $product_id -- product id :: Type integer + * @param $upd_qty -- quantity :: Type integer + */ + +function updateProductQty($product_id, $upd_qty) +{ + global $log; + $log->debug("Entering updateProductQty(".$product_id.",". $upd_qty.") method ..."); + global $adb; + $query= "update vtiger_products set qtyinstock=? where productid=?"; + $adb->pquery($query, array($upd_qty, $product_id)); + $log->debug("Exiting updateProductQty method ..."); + +} + +/** Function to get account information + * @param $parent_id -- parent id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function get_account_info($parent_id) +{ + global $log; + $log->debug("Entering get_account_info(".$parent_id.") method ..."); + global $adb; + $query = "select related_to from vtiger_potential where potentialid=?"; + $result = $adb->pquery($query, array($parent_id)); + $accountid=$adb->query_result($result,0,'related_to'); + $log->debug("Exiting get_account_info method ..."); + return $accountid; +} + +/** Function to get quick create form fields + * @param $fieldlabel -- field label :: Type string + * @param $uitype -- uitype :: Type integer + * @param $fieldname -- field name :: Type string + * @param $tabid -- tabid :: Type integer + * @returns $return_field -- return field:: Type string + */ + +//for Quickcreate-Form + +function get_quickcreate_form($fieldlabel,$uitype,$fieldname,$tabid) +{ + global $log; + $log->debug("Entering get_quickcreate_form(".$fieldlabel.",".$uitype.",".$fieldname.",".$tabid.") method ..."); + $return_field =''; + switch($uitype) + { + case 1: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 2: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 6: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 11: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 13: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 15: $return_field .=get_textcomboField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 16: $return_field .=get_textcomboField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 17: $return_field .=get_textwebField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 19: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 22: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 23: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 50: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 51: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 55: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 63: $return_field .=get_textdurationField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 71: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + } +} + +/** Function to get quick create form fields + * @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_textmanField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textmanField(".$label.",".$name.",".$tid.") method ..."); + $form_field=''; + if($tid == 9) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textmanField method ..."); + return $form_field; + } + if($tid == 16) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textmanField method ..."); + return $form_field; + } + else + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $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 .=''; + $form_field .= $label.':
http://
'; + $form_field .=''; + $log->debug("Exiting get_textwebField method ..."); + return $form_field; + +} + +/** Function to get textfield + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @returns $form_field -- return field:: Type string + */ + +function get_textField($label,$name) +{ + global $log; + $log->debug("Entering get_textField(".$label.",".$name.") method ..."); + $form_field=''; + if($name == "amount") + { + $form_field .=''; + $form_field .= $label.':(U.S Dollar:$)
'; + $form_field .=''; + $log->debug("Exiting get_textField method ..."); + return $form_field; + } + else + { + + $form_field .=''; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textField method ..."); + return $form_field; + } + +} + +/** Function to get account textfield + * @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_textaccField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textaccField(".$label.",".$name.",".$tid.") method ..."); + + global $app_strings; + + $form_field=''; + if($tid == 2) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .='
'; + $form_field .=' '; + $log->debug("Exiting get_textaccField method ..."); + return $form_field; + } + else + { + $form_field .=''; + $form_field .= $label.':
'; + $form_field .='
'; + $form_field .=' '; + $log->debug("Exiting get_textaccField method ..."); + return $form_field; + } + +} + +/** Function to get combo field values + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @returns $form_field -- return field:: Type string + */ + +function get_textcomboField($label,$name) +{ + global $log; + $log->debug("Entering get_textcomboField(".$label.",".$name.") method ..."); + $form_field=''; + if($name == "sales_stage") + { + $comboFieldNames = Array('leadsource'=>'leadsource_dom' + ,'opportunity_type'=>'opportunity_type_dom' + ,'sales_stage'=>'sales_stage_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + } + if($name == "productcategory") + { + $comboFieldNames = Array('productcategory'=>'productcategory_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + } + if($name == "ticketpriorities") + { + $comboFieldNames = Array('ticketpriorities'=>'ticketpriorities_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + } + if($name == "activitytype") + { + $comboFieldNames = Array('activitytype'=>'activitytype_dom', + 'duration_minutes'=>'duration_minutes_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + + } + if($name == "eventstatus") + { + $comboFieldNames = Array('eventstatus'=>'eventstatus_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + + } + if($name == "taskstatus") + { + $comboFieldNames = Array('taskstatus'=>'taskstatus_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.'
'; + $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 .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .='('.$current_user->date_format.')
'; + $form_field .=' '; + $form_field .=''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + + } + if($tid == 9) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=' '; + $form_field.= ' '; + $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + } + if($tid == 16) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=' '; + $form_field.= ' '; + $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + } + + else + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=' '; + $form_field.= ' '; + $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + } + +} + +/** Function to get duration text field in activity + * @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_textdurationField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textdurationField(".$label.",".$name.",".$tid.") method ..."); + $form_field=''; + if($tid == 16) + { + + $comboFieldNames = Array('activitytype'=>'activitytype_dom', + 'duration_minutes'=>'duration_minutes_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=' '; + $form_field .='
(hours/minutes)
'; + $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; + // If the information is not sent then read it + if($focus === false) { + if($module == 'Contacts') + $focus = new Contacts(); + if($module == 'Leads') + $focus = new 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 vtiger_field where tabid = ? and fieldname= ? and vtiger_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; + $sql = "select postatus from vtiger_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; + $qtyInStck=getProductQtyInStock($productId); + $updQty=$qtyInStck + $qty; + $sql = "UPDATE vtiger_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; + $qtyInStck=getProductQtyInDemand($productId); + $updQty=$qtyInStck + $qty; + $sql = "UPDATE vtiger_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; + $qtyInStck=getProductQtyInStock($productId); + $updQty=$qtyInStck - $qty; + $sql = "UPDATE vtiger_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; + $qtyInStck=getProductQtyInDemand($productId); + $updQty=$qtyInStck - $qty; + $sql = "UPDATE vtiger_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; + $query1 = "select qtyinstock from vtiger_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; + $query1 = "select qtyindemand from vtiger_products where productid=?"; + $result = $adb->pquery($query1, array($product_id)); + $qtyInDemand = $adb->query_result($result,0,"qtyindemand"); + $log->debug("Exiting getProductQtyInDemand method ..."); + return $qtyInDemand; +} + +/** Function to seperate the Date and Time + * This function accepts a sting with date and time and + * returns an array of two elements.The first element + * contains the date and the second one contains the time + */ +function getDateFromDateAndtime($date_time) +{ + global $log; + $log->debug("Entering getDateFromDateAndtime(".$date_time.") method ..."); + $result = explode(" ",$date_time); + $log->debug("Exiting getDateFromDateAndtime method ..."); + return $result; +} + + +/** Function to get header for block in edit/create and detailview + * @param $header_label -- header label :: Type string + * @returns $output -- output:: Type string + */ + +function getBlockTableHeader($header_label) +{ + global $log; + $log->debug("Entering getBlockTableHeader(".$header_label.") method ..."); + global $mod_strings; + $label = $mod_strings[$header_label]; + $output = $label; + $log->debug("Exiting getBlockTableHeader method ..."); + return $output; + +} + + + +/** Function to get the vtiger_table name from 'field' vtiger_table for the input vtiger_field based on the module + * @param : string $module - current module value + * @param : string $fieldname - vtiger_fieldname to which we want the vtiger_tablename + * @return : string $tablename - vtiger_tablename in which $fieldname is a column, which is retrieved from 'field' vtiger_table per $module basis + */ +function getTableNameForField($module,$fieldname) +{ + global $log; + $log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ..."); + global $adb; + $tabid = getTabid($module); + //Asha + if($module == 'Calendar') { + $tabid = array('9','16'); + } + $sql = "select tablename from vtiger_field where tabid in (". generateQuestionMarks($tabid) .") and vtiger_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; +} + +/** Function to get parent record owner + * @param $tabid -- tabid :: Type integer + * @param $parModId -- parent module id :: Type integer + * @param $record_id -- record id :: Type integer + * @returns $parentRecOwner -- parentRecOwner:: Type integer + */ + +function getParentRecordOwner($tabid,$parModId,$record_id) +{ + global $log; + $log->debug("Entering getParentRecordOwner(".$tabid.",".$parModId.",".$record_id.") method ..."); + $parentRecOwner=Array(); + $parentTabName=getTabname($parModId); + $relTabName=getTabname($tabid); + $fn_name="get".$relTabName."Related".$parentTabName; + $ent_id=$fn_name($record_id); + if($ent_id != '') + { + $parentRecOwner=getRecordOwnerId($ent_id); + } + $log->debug("Exiting getParentRecordOwner method ..."); + return $parentRecOwner; +} + +/** Function to get potential related accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getPotentialsRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getPotentialsRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select related_to from vtiger_potential where potentialid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'related_to'); + $log->debug("Exiting getPotentialsRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get email related accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ +function getEmailsRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getEmailsRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Accounts' and activityid=?"; + $result = $adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'crmid'); + $log->debug("Exiting getEmailsRelatedAccounts method ..."); + return $accountid; +} +/** Function to get email related Leads + * @param $record_id -- record id :: Type integer + * @returns $leadid -- leadid:: Type integer + */ + +function getEmailsRelatedLeads($record_id) +{ + global $log; + $log->debug("Entering getEmailsRelatedLeads(".$record_id.") method ..."); + global $adb; + $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Leads' and activityid=?"; + $result = $adb->pquery($query, array($record_id)); + $leadid=$adb->query_result($result,0,'crmid'); + $log->debug("Exiting getEmailsRelatedLeads method ..."); + return $leadid; +} + +/** Function to get HelpDesk related Accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getHelpDeskRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getHelpDeskRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select parent_id from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.parent_id where ticketid=? and vtiger_crmentity.setype='Accounts'"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'parent_id'); + $log->debug("Exiting getHelpDeskRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get Quotes related Accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getQuotesRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getQuotesRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select accountid from vtiger_quotes where quoteid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'accountid'); + $log->debug("Exiting getQuotesRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get Quotes related Potentials + * @param $record_id -- record id :: Type integer + * @returns $potid -- potid:: Type integer + */ + +function getQuotesRelatedPotentials($record_id) +{ + global $log; + $log->debug("Entering getQuotesRelatedPotentials(".$record_id.") method ..."); + global $adb; + $query="select potentialid from vtiger_quotes where quoteid=?"; + $result=$adb->pquery($query, array($record_id)); + $potid=$adb->query_result($result,0,'potentialid'); + $log->debug("Exiting getQuotesRelatedPotentials method ..."); + return $potid; +} + +/** Function to get Quotes related Potentials + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getSalesOrderRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getSalesOrderRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select accountid from vtiger_salesorder where salesorderid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'accountid'); + $log->debug("Exiting getSalesOrderRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get SalesOrder related Potentials + * @param $record_id -- record id :: Type integer + * @returns $potid -- potid:: Type integer + */ + +function getSalesOrderRelatedPotentials($record_id) +{ + global $log; + $log->debug("Entering getSalesOrderRelatedPotentials(".$record_id.") method ..."); + global $adb; + $query="select potentialid from vtiger_salesorder where salesorderid=?"; + $result=$adb->pquery($query, array($record_id)); + $potid=$adb->query_result($result,0,'potentialid'); + $log->debug("Exiting getSalesOrderRelatedPotentials method ..."); + return $potid; +} +/** Function to get SalesOrder related Quotes + * @param $record_id -- record id :: Type integer + * @returns $qtid -- qtid:: Type integer + */ + +function getSalesOrderRelatedQuotes($record_id) +{ + global $log; + $log->debug("Entering getSalesOrderRelatedQuotes(".$record_id.") method ..."); + global $adb; + $query="select quoteid from vtiger_salesorder where salesorderid=?"; + $result=$adb->pquery($query, array($record_id)); + $qtid=$adb->query_result($result,0,'quoteid'); + $log->debug("Exiting getSalesOrderRelatedQuotes method ..."); + return $qtid; +} + +/** Function to get Invoice related Accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getInvoiceRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getInvoiceRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select accountid from vtiger_invoice where invoiceid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'accountid'); + $log->debug("Exiting getInvoiceRelatedAccounts method ..."); + return $accountid; +} +/** Function to get Invoice related SalesOrder + * @param $record_id -- record id :: Type integer + * @returns $soid -- soid:: Type integer + */ + +function getInvoiceRelatedSalesOrder($record_id) +{ + global $log; + $log->debug("Entering getInvoiceRelatedSalesOrder(".$record_id.") method ..."); + global $adb; + $query="select salesorderid from vtiger_invoice where invoiceid=?"; + $result=$adb->pquery($query, array($record_id)); + $soid=$adb->query_result($result,0,'salesorderid'); + $log->debug("Exiting getInvoiceRelatedSalesOrder method ..."); + return $soid; +} + + +/** Function to get Days and Dates in between the dates specified + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +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 + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +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 vtiger_table format for a particular date + based upon the period + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +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 vtiger_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; + $image_lists=array(); + $query="select imagename from vtiger_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; + $query = "select imagename from vtiger_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; + $query = "select imagename from vtiger_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 remove the script tag in the contents + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function strip_selected_tags($text, $tags = array()) +{ + $args = func_get_args(); + $text = array_shift($args); + $tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags; + foreach ($tags as $tag){ + if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){ + $text = str_replace($found[0],$found[1],$text); + } + } + + return $text; +} + +/** Function to check whether user has opted for internal mailer + * @returns $int_mailer -- int mailer:: Type boolean + */ +function useInternalMailer() { + global $current_user,$adb; + return $adb->query_result($adb->pquery("select int_mailer from vtiger_mail_accounts where user_id=?", array($current_user->id)),0,"int_mailer"); +} + +/** +* 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("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data); +} + +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; +} + +// Return Question mark +function _questionify($v){ + return "?"; +} + +/** +* Function to generate question marks for a given list of items +*/ +function generateQuestionMarks($items_list) { + // array_map will call the function specified in the first parameter for every element of the list in second parameter + if (is_array($items_list)) { + return implode(",", array_map("_questionify", $items_list)); + } else { + return implode(",", array_map("_questionify", explode(",", $items_list))); + } +} + +/** +* 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(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') + { + $current_language = $_SESSION['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; + $log->debug("Entering into function getAccessPickListValues($module)"); + + $id = getTabid($module); + $query = "select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid = ? and uitype in ('15','33','55') and vtiger_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"); + + $keyvalue = $columnname; + $fieldvalues = Array(); + if (count($roleids) > 1) + { + $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; + } + else + { + $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; + } + if($fieldname != 'firstname') + $mulselresult = $adb->query($mulsel); + for($j=0;$j < $adb->num_rows($mulselresult);$j++) + { + $fieldvalues[] = $adb->query_result($mulselresult,$j,$fieldname); + } + $field_count = count($fieldvalues); + if($uitype == 15 && $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 == 15) + $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; +} + +function getMigrationCharsetFlag() { + global $adb; + + if(!$adb->isPostgres()) + $db_status=check_db_utf8_support($adb); + $config_status=get_config_status(); + + if ($db_status == $config_status) { + if ($db_status == 1) { // Both are UTF-8 + $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_UTF8; + } else { // Both are Non UTF-8 + $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8; + } + } else { + if ($db_status == 1) { // Database charset is UTF-8 and CRM charset is Non UTF-8 + $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_UTF8; + } else { // Database charset is Non UTF-8 and CRM charset is UTF-8 + $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_NONUTF8; + } + } + return $db_migration_status; +} + +/** Function to convert a given time string to Minutes */ +function ConvertToMinutes($time_string) +{ + $interval = split(' ', $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; +} + +//added to find duplicates +/** To get the converted record values which have to be display in duplicates merging tpl*/ +function getRecordValues($id_array,$module) { + global $adb,$current_user; + global $app_strings; + $tabid=getTabid($module); + $query="select fieldname,fieldlabel,uitype from vtiger_field where tabid=? and fieldname not in ('createdtime','modifiedtime') and vtiger_field.presence in (0,2) and uitype not in('4')"; + $result=$adb->pquery($query, array($tabid)); + $no_rows=$adb->num_rows($result); + + $focus = new $module(); + if(isset($id_array) && $id_array !='') { + foreach($id_array as $value) { + $focus->id=$value; + $focus->retrieve_entity_info($value,$module); + $field_values[]=$focus->column_fields; + } + } + $labl_array=array(); + $value_pair = array(); + $c = 0; + for($i=0;$i<$no_rows;$i++) { + $fld_name=$adb->query_result($result,$i,"fieldname"); + $fld_label=$adb->query_result($result,$i,"fieldlabel"); + $ui_type=$adb->query_result($result,$i,"uitype"); + + if(getFieldVisibilityPermission($module,$current_user->id,$fld_name) == '0') { + $fld_array []= $fld_name; + $record_values[$c][$fld_label] = Array(); + $ui_value[]=$ui_type; + for($j=0;$j < count($field_values);$j++) { + + if($ui_type ==56) { + if($field_values[$j][$fld_name] == 0) + $value_pair['disp_value']=$app_strings['no']; + else + $value_pair['disp_value']=$app_strings['yes']; + } elseif($ui_type == 51 || $ui_type == 50) { + $entity_id=$field_values[$j][$fld_name]; + if($module !='Products') + $entity_name=getAccountName($entity_id); + else + $entity_name=getProductName($entity_id); + $value_pair['disp_value']=$entity_name; + } elseif($ui_type == 53) { + $owner_id=$field_values[$j][$fld_name]; + $ownername=getOwnerName($owner_id); + $value_pair['disp_value']=$ownername; + } elseif($ui_type ==57) { + $contact_id= $field_values[$j][$fld_name]; + if($contact_id != '') { + $contactname=getContactName($contact_id); + } + $value_pair['disp_value']=$contactname; + } elseif($ui_type == 75 || $ui_type ==81) { + $vendor_id=$field_values[$j][$fld_name]; + if($vendor_id != '') { + $vendor_name=getVendorName($vendor_id); + } + $value_pair['disp_value']=$vendor_name; + } elseif($ui_type == 52) { + $user_id = $field_values[$j][$fld_name]; + $user_name=getUserName($user_id); + $value_pair['disp_value']=$user_name; + } elseif($ui_type ==68) { + $parent_id = $field_values[$j][$fld_name]; + $value_pair['disp_value'] = getAccountName($parent_id); + if($value_pair['disp_value'] == '' || $value_pair['disp_value'] == NULL) + $value_pair['disp_value'] = getContactName($parent_id); + } elseif($ui_type ==59) { + $product_name=getProductName($field_values[$j][$fld_name]); + if($product_name != '') + $value_pair['disp_value']=$product_name; + else $value_pair['disp_value']=''; + } elseif($ui_type==58) { + $campaign_name=getCampaignName($field_values[$j][$fld_name]); + if($campaign_name != '') + $value_pair['disp_value']=$campaign_name; + else $value_pair['disp_value']=''; + } elseif($ui_type == 10) { + $value_pair['disp_value'] = getRecordInfoFromID($field_values[$j][$fld_name]); + }elseif($ui_type == 5 || $ui_type == 6 || $ui_type == 23){ + $value_pair['disp_value'] = getDisplayDate($field_values[$j][$fld_name]); + }else { + $value_pair['disp_value']=$field_values[$j][$fld_name]; + } + $value_pair['org_value'] = $field_values[$j][$fld_name]; + + array_push($record_values[$c][$fld_label],$value_pair); + } + $c++; + } + + } + $parent_array[0]=$record_values; + $parent_array[1]=$fld_array; + $parent_array[2]=$fld_array; + return $parent_array; +} + +/** Function to check whether the relationship entries are exist or not on elationship tables */ +function is_related($relation_table,$crm_field,$related_module_id,$crmid) +{ + global $adb; + $check_res = $adb->query("select * from $relation_table where $crm_field=$related_module_id and crmid=$crmid"); + $count = $adb->num_rows($check_res); + if($count > 0) + return true; + else + return false; +} + +/** Function to get a to find duplicates in a particular module*/ +function getDuplicateQuery($module,$field_values,$ui_type_arr) +{ + global $current_user; + $tbl_col_fld = explode(",", $field_values); + $i=0; + foreach($tbl_col_fld as $val) { + list($tbl[$i], $cols[$i], $fields[$i]) = explode(".", $val); + $tbl_cols[$i] = $tbl[$i]. "." . $cols[$i]; + $i++; + } + $table_cols = implode(",",$tbl_cols); + $sec_parameter = getSecParameterforMerge($module); + if( stristr($_REQUEST['action'],'ImportStep') || ($_REQUEST['action'] == $_REQUEST['module'].'Ajax' && $_REQUEST['current_action'] == 'ImportSteplast')) + { + if($module == 'Contacts') + { + $ret_arr = get_special_on_clause($table_cols); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $nquery="select vtiger_contactdetails.contactid as recordid,vtiger_users_last_import.deleted,$table_cols + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid + LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (select $select_clause from vtiger_contactdetails t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.contactid + INNER JOIN vtiger_contactaddress addr ON t.contactid = addr.contactaddressid + INNER JOIN vtiger_contactsubdetails subd ON addr.contactaddressid = subd.contactsubscriptionid + LEFT JOIN vtiger_contactscf tcf ON t.contactid = tcf.contactid + LEFT JOIN vtiger_account acc ON acc.accountid=t.accountid + LEFT JOIN vtiger_customerdetails custd ON custd.customerid=t.contactid + WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC"; + + } + + else if($module == 'Accounts') + { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $nquery="SELECT vtiger_account.accountid AS recordid,vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (select $select_clause from vtiger_account t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.accountid + INNER JOIN vtiger_accountbillads badd ON t.accountid = badd.accountaddressid + INNER JOIN vtiger_accountshipads sadd ON t.accountid = sadd.accountaddressid + LEFT JOIN vtiger_accountscf tcf ON t.accountid = tcf.accountid + WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC"; + + } + else if($module == 'Leads') + { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $nquery="select vtiger_leaddetails.leadid as recordid, vtiger_users_last_import.deleted,$table_cols + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid + INNER JOIN (select $select_clause from vtiger_leaddetails t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.leadid + INNER JOIN vtiger_leadsubdetails subd ON subd.leadsubscriptionid = t.leadid + INNER JOIN vtiger_leadaddress addr ON addr.leadaddressid = subd.leadsubscriptionid + LEFT JOIN vtiger_leadscf tcf ON tcf.leadid=t.leadid + WHERE crm.deleted=0 and t.converted = 0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC"; + + } + else if($module == 'Products') + { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + + $nquery="SELECT vtiger_products.productid AS recordid,vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + INNER JOIN (select $select_clause from vtiger_products t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.productid + LEFT JOIN vtiger_productcf tcf ON tcf.productid=t.productid + WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_products.productid ASC"; + + } + else if($module == 'HelpDesk') + { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $nquery="SELECT vtiger_troubletickets.ticketid AS recordid,vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_troubletickets + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid + LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid + LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid + LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid + INNER JOIN (select $select_clause from vtiger_troubletickets t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.ticketid + LEFT JOIN vtiger_account acc ON acc.accountid = t.parent_id + LEFT JOIN vtiger_contactdetails contd ON contd.contactid = t.parent_id + LEFT JOIN vtiger_ticketcf tcf ON tcf.ticketid = t.ticketid + WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0". $sec_parameter ." ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC"; + + } + else if($module == 'Potentials') + { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $nquery="SELECT vtiger_potential.potentialid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_potential + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid + LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid + INNER JOIN (select $select_clause from vtiger_potential t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.potentialid + LEFT JOIN vtiger_potentialscf tcf ON tcf.potentialid=t.potentialid + WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC"; + + } + else if($module == 'Vendors') + { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $nquery="SELECT vtiger_vendor.vendorid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid + INNER JOIN (select $select_clause from vtiger_vendor t + INNER JOIN vtiger_crmentity crm ON crm.crmid=t.vendorid + LEFT JOIN vtiger_vendorcf tcf ON tcf.vendorid=t.vendorid + WHERE crm.deleted=0 group by $select_clause HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module)." + WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC"; + + } else { + $ret_arr = get_special_on_clause($field_values); + $select_clause = $ret_arr['sel_clause']; + $on_clause = $ret_arr['on_clause']; + $modObj = CRMEntity::getInstance($module); + if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) { + $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr,$select_clause); + } + } + } + else + { + + if($module == 'Contacts') + { + $nquery = "SELECT vtiger_contactdetails.contactid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid + LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC"; + + } + else if($module == 'Accounts') + { + $nquery="SELECT vtiger_account.accountid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC"; + } + else if($module == 'Leads') + { + $nquery = "SELECT vtiger_leaddetails.leadid AS recordid, vtiger_users_last_import.deleted,$table_cols + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid + INNER JOIN (SELECT $table_cols + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter + GROUP BY $table_cols HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC"; + + } + else if($module == 'Products') + { + $nquery = "SELECT vtiger_products.productid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + INNER JOIN (SELECT $table_cols + FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + WHERE vtiger_crmentity.deleted=0 + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_products.productid ASC"; + } + else if($module == "HelpDesk") + { + $nquery = "SELECT vtiger_troubletickets.ticketid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_troubletickets + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid + LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid + LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid + INNER JOIN (SELECT $table_cols FROM vtiger_troubletickets + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid + LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_contactdetails contd ON contd.contactid = vtiger_troubletickets.parent_id + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC"; + } + else if($module == "Potentials") + { + $nquery = "SELECT vtiger_potential.potentialid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_potential + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid + LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_potential + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid + LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC"; + } + else if($module == "Vendors") + { + $nquery = "SELECT vtiger_vendor.vendorid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid + INNER JOIN (SELECT $table_cols + FROM vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid + WHERE vtiger_crmentity.deleted=0 + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC"; + } else { + $modObj = CRMEntity::getInstance($module); + if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) { + $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr); + } + } + } + return $nquery; +} + +/** Function to return the duplicate records data as a formatted array */ +function getDuplicateRecordsArr($module) +{ + global $adb,$app_strings,$list_max_entries_per_page,$theme; + $field_values_array=getFieldValues($module); + $field_values=$field_values_array['fieldnames_list']; + $fld_arr=$field_values_array['fieldnames_array']; + $col_arr=$field_values_array['columnnames_array']; + $fld_labl_arr=$field_values_array['fieldlabels_array']; + $ui_type=$field_values_array['fieldname_uitype']; + + $dup_query = getDuplicateQuery($module,$field_values,$ui_type); + // added for page navigation + $dup_count_query = substr($dup_query, stripos($dup_query,'FROM'),strlen($dup_query)); + $dup_count_query = "SELECT count(*) as count ".$dup_count_query; + $count_res = $adb->query($dup_count_query); + $no_of_rows = $adb->query_result($count_res,0,"count"); + + if($no_of_rows <= $list_max_entries_per_page) + $_SESSION['dup_nav_start'.$module] = 1; + else if(isset($_REQUEST["start"]) && $_REQUEST["start"] != "" && $_SESSION['dup_nav_start'.$module] != $_REQUEST["start"]) + $_SESSION['dup_nav_start'.$module] = ListViewSession::getRequestStartPage(); + $start = ($_SESSION['dup_nav_start'.$module] != "")?$_SESSION['dup_nav_start'.$module]:1; + $navigation_array = getNavigationValues($start, $no_of_rows, $list_max_entries_per_page); + $start_rec = $navigation_array['start']; + $end_rec = $navigation_array['end_val']; + $navigationOutput = getTableHeaderNavigation($navigation_array, "",$module,"FindDuplicate",""); + if ($start_rec == 0) + $limit_start_rec = 0; + else + $limit_start_rec = $start_rec -1; + $dup_query .= " LIMIT $limit_start_rec, $list_max_entries_per_page"; + //ends + + $nresult=$adb->query($dup_query); + $no_rows=$adb->num_rows($nresult); + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + require_once($theme_path.'layout_utils.php'); + if($no_rows == 0) + { + if ($_REQUEST['action'] == 'FindDuplicateRecords') + { + //echo "

".$app_strings['LBL_NO_DUPLICATE']." ".$app_strings['LBL_GO_BACK'].".
"; + //die; + echo ""; + echo "
"; + echo "
+ + + + + + + + + +
$app_strings[LBL_NO_DUPLICATE]
+ $app_strings[LBL_GO_BACK]
+
"; + echo "
"; + exit(); + } + else + { + echo "

".$app_strings['LBL_NO_DUPLICATE']."
"; + die; + } + } + + $rec_cnt = 0; + $temp = Array(); + $sl_arr = Array(); + $grp = "group0"; + $gcnt = 0; + $ii = 0; //ii'th record in group + while ( $rec_cnt < $no_rows ) + { + $result = $adb->fetchByAssoc($nresult); + //echo '
';print_r($result);echo '
'; + if($rec_cnt != 0) + { + $sl_arr = array_slice($result,2); + array_walk($temp,'lower_array'); + array_walk($sl_arr,'lower_array'); + $arr_diff = array_diff($temp,$sl_arr); + if(count($arr_diff) > 0) + { + $gcnt++; + $temp = $sl_arr; + $ii = 0; + } + $grp = "group".$gcnt; + } + $fld_values[$grp][$ii]['recordid'] = $result['recordid']; + for($k=0;$k"accountid","Contacts"=>"contactid","Leads"=>"leadid","Products"=>"productid","HelpDesk"=>"ticketid","Potentials"=>"potentialid","Vendors"=>"vendorid"); + $id = ($module_id_array[$_REQUEST['modulename']] != '')?$module_id_array[$_REQUEST['modulename']]:$module_id_array[$_REQUEST['module']]; + $sub_res = ''; + $sub_result = $adb->query($sub_query); + $row_count = $adb->num_rows($sub_result); + $sub_res = ''; + if($row_count > 0) + { + while($rows = $adb->fetchByAssoc($sub_result)) + { + $sub_res .= $rows[$id].","; + } + $sub_res = trim($sub_res,","); + } + else + $sub_res .= "''"; + return $sub_res; +} + +/** Function to get tablename, columnname, fieldname, fieldlabel and uitypes of fields of merge criteria for a particular module*/ +function getFieldValues($module) +{ + global $adb,$current_user; + + //In future if we want to change a id mapping to name or other string then we can add that elements in this array. + //$fld_table_arr = Array("vtiger_contactdetails.account_id"=>"vtiger_account.accountname"); + //$special_fld_arr = Array("account_id"=>"accountname"); + + $fld_table_arr = Array(); + $special_fld_arr = Array(); + $tabid = getTabid($module); + + $fieldname_query="select fieldname,fieldlabel,uitype,tablename,columnname from vtiger_field where fieldid in + (select fieldid from vtiger_user2mergefields WHERE tabid=? AND userid=? AND visible = ?) and vtiger_field.presence in (0,2)"; + $fieldname_result = $adb->pquery($fieldname_query, array($tabid, $current_user->id, 1)); + + $field_num_rows = $adb->num_rows($fieldname_result); + + $fld_arr = array(); + $col_arr = array(); + for($j=0;$j< $field_num_rows;$j ++) + { + $tablename = $adb->query_result($fieldname_result,$j,'tablename'); + $column_name = $adb->query_result($fieldname_result,$j,'columnname'); + $field_name = $adb->query_result($fieldname_result,$j,'fieldname'); + $field_lbl = $adb->query_result($fieldname_result,$j,'fieldlabel'); + $ui_type = $adb->query_result($fieldname_result,$j,'uitype'); + $table_col = $tablename.".".$column_name; + if(getFieldVisibilityPermission($module,$current_user->id,$field_name) == 0) + { + $fld_name = ($special_fld_arr[$field_name] != '')?$special_fld_arr[$field_name]:$field_name; + + $fld_arr[] = $fld_name; + $col_arr[] = $column_name; + if($fld_table_arr[$table_col] != '') + $table_col = $fld_table_arr[$table_col]; + + $field_values_array['fieldnames_list'][] = $table_col . "." . $fld_name; + $fld_labl_arr[]=$field_lbl; + $uitype[$field_name]=$ui_type; + } + } + $field_values_array['fieldnames_list']=implode(",",$field_values_array['fieldnames_list']); + $field_values=implode(",",$fld_arr); + $field_values_array['fieldnames']=$field_values; + $field_values_array["fieldnames_array"]=$fld_arr; + $field_values_array["columnnames_array"]=$col_arr; + $field_values_array['fieldlabels_array']=$fld_labl_arr; + $field_values_array['fieldname_uitype']=$uitype; + + return $field_values_array; +} + +/** To get security parameter for a particular module -- By Pavani*/ +function getSecParameterforMerge($module) +{ + global $current_user; + $tab_id = getTabid($module); + $sec_parameter=""; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) + { + if($module == "Products" || $module == "Vendors") { + $sec_parameter = ""; + } else { + $sec_parameter=getListViewSecurityParameter($module); + if($module == "Accounts") { + $sec_parameter .= " AND (vtiger_crmentity.smownerid IN (".$current_user->id.") + OR vtiger_crmentity.smownerid IN ( + SELECT vtiger_user2role.userid + FROM vtiger_user2role + INNER JOIN vtiger_users + ON vtiger_users.id = vtiger_user2role.userid + INNER JOIN vtiger_role + ON vtiger_role.roleid = vtiger_user2role.roleid + WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%') + OR vtiger_crmentity.smownerid IN ( + SELECT shareduserid + FROM vtiger_tmp_read_user_sharing_per + WHERE userid=".$current_user->id." + AND tabid=".$tab_id.") + OR (vtiger_crmentity.smownerid in (0) + AND ("; + + if(sizeof($current_user_groups) > 0) { + $sec_parameter .= " vtiger_groups.groupname IN ( + SELECT groupname + FROM vtiger_groups + WHERE groupid IN (". implode(",", getCurrentUserGroupList()) .")) + OR "; + } + $sec_parameter .= " vtiger_groups.groupname IN ( + SELECT vtiger_groups.groupname + FROM vtiger_tmp_read_group_sharing_per + INNER JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_tmp_read_group_sharing_per.sharedgroupid + WHERE userid=".$current_user->id." + AND tabid=".$tab_id.")))) "; + } + } + } + return $sec_parameter; +} + +// 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; + $log->debug("Entering function transferUserCurrency..."); + + $sql = "update vtiger_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; + $log->debug("Entering function updateProductCurrency..."); + $prod_res = $adb->pquery("select productid from vtiger_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 = 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; + $log->debug("Entering function updatePriceBookCurrency..."); + $pb_res = $adb->pquery("select pricebookid from vtiger_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) { + require_once('modules/PriceBooks/PriceBooks.php'); + + 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 vtiger 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'); + foreach ($name as $module) { + $focus = CRMEntity::getInstance($module); + $query = $focus->buildSearchQueryForFieldTypes(11, $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){ + $tabid = getTabid($module); + $sql = "select * from vtiger_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 + */ +function get_use_asterisk($id){ + global $adb; + if(!vtlib_isModuleActive('PBXManager')){ + return false; + } + $sql = "select * from vtiger_asteriskextensions where userid = ?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result)>0){ + $use_asterisk = $adb->query_result($result, 0, "use_asterisk"); + $asterisk_extension = $adb->query_result($result, 0, "asterisk_extension"); + if($use_asterisk == 0 || empty($asterisk_extension)){ + return 'false'; + }else{ + return 'true'; + } + }else{ + return 'false'; + } +} + +/** + * 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){ + $sql = "select * from vtiger_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 Vtiger will returns NULL + return; + } + $crmID = $adb->getUniqueID('vtiger_crmentity'); + $timeOfCall = date('Y-m-d H:i:s'); + + $sql = "insert into vtiger_crmentity values (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $params = array($crmID, $userID, $userID, 0, "PBXManager", "", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0); + $adb->pquery($sql, $params); + + if(empty($callfrom)){ + $callfrom = "Unknown"; + } + if(empty($callto)){ + $callto = "Unknown"; + } + + if($status == 'outgoing'){ + //call is from user to record + $sql = "select * from vtiger_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 vtiger_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 vtiger_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 + +//functions for settings page +/** + * this function returns the blocks for the settings page + */ +function getSettingsBlocks(){ + global $adb; + $sql = "select * from vtiger_settings_blocks order by sequence"; + $result = $adb->query($sql); + $count = $adb->num_rows($result); + $blocks = array(); + + if($count>0){ + for($i=0;$i<$count;$i++){ + $blockid = $adb->query_result($result, $i, "blockid"); + $label = $adb->query_result($result, $i, "label"); + $blocks[$blockid] = $label; + } + } + return $blocks; +} + +/** + * this function returns the fields for the settings page + */ +function getSettingsFields(){ + global $adb; + $sql = "select * from vtiger_settings_field where blockid!=? and active=0 order by blockid,sequence"; + $result = $adb->pquery($sql, array(getSettingsBlockId('LBL_MODULE_MANAGER'))); + $count = $adb->num_rows($result); + $fields = array(); + + if($count>0){ + for($i=0;$i<$count;$i++){ + $blockid = $adb->query_result($result, $i, "blockid"); + $iconpath = $adb->query_result($result, $i, "iconpath"); + $description = $adb->query_result($result, $i, "description"); + $linkto = $adb->query_result($result, $i, "linkto"); + $action = getPropertiesFromURL($linkto, "action"); + $module = getPropertiesFromURL($linkto, "module"); + $name = $adb->query_result($result, $i, "name"); + + $fields[$blockid][] = array("icon"=>$iconpath, "description"=>$description, "link"=>$linkto, "name"=>$name, "action"=>$action, "module"=>$module); + } + + //add blanks for 4-column layout + foreach($fields as $blockid=>&$field){ + if(count($field)>0 && count($field)<4){ + for($i=count($field);$i<4;$i++){ + $field[$i] = array(); + } + } + } + } + return $fields; +} + +/** + * this function takes an url and returns the module name from it + */ +function getPropertiesFromURL($url, $action){ + $result = array(); + preg_match("/$action=([^&]+)/",$url,$result); + return $result[1]; +} + +//functions for settings page end + +/* 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; + $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 FROM vtiger_field WHERE uitype=? AND tabid=? and vtiger_field.presence in (0,2)", array('4', getTabid($module))); + 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'); + + $field = array(); + $field['name'] = $fieldname; + $field['column'] = $columnname; + $field['label'] = $fieldlabel; + } + } else { + + foreach($cachedModuleFields as $fieldinfo) { + if($fieldinfo['uitype'] == '4') { + $field = array(); + + $field['name'] = $fieldinfo['fieldname']; + $field['column'] = $fieldinfo['columnname']; + $field['label'] = $fieldinfo['fieldlabel']; + + 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; + $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('update_log','filename','comments'), + ); + + $nonmergable_displaytypes = Array(4); + $nonmergable_uitypes = Array('70','69','4'); + + $sql = "SELECT fieldid,typeofdata FROM vtiger_field WHERE tabid = ? and vtiger_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; +} + +/* 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; + $primary_obj = CRMEntity::getInstance($module); + $secondary_obj = CRMEntity::getInstance($secmodule); + + $ui10_query = $adb->pquery("SELECT vtiger_field.tabid AS tabid,vtiger_field.tablename AS tablename, vtiger_field.columnname AS columnname FROM vtiger_field INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid WHERE (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?) OR (vtiger_fieldmodulerel.module=? AND vtiger_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 { + if(method_exists($primary_obj,setRelationTables)){ + $reltables = $primary_obj->setRelationTables($secmodule); + } else { + $reltables = ''; + } + } + if(is_array($reltables) && !empty($reltables)){ + $rel_array = $reltables; + } else { + $rel_array = array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"".$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; + $log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)"); + + if ($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 + */ +function installVtlibModule($packagename, $packagepath, $customized=false) { + global $log; + require_once('vtlib/Vtiger/Package.php'); + require_once('vtlib/Vtiger/Module.php'); + $Vtiger_Utils_Log = true; + $package = new Vtiger_Package(); + + if($package->isLanguageType($packagepath)) { + $package = new Vtiger_Language(); + $package->import($packagepath, true); + return; + } + $module = $package->getModuleNameFromZip($packagepath); + $module_exists = false; + $module_dir_exists = false; + if($module == null) { + $log->fatal("$packagename Module zipfile is not valid!"); + } else if(Vtiger_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 = Vtiger_Module::getInstance($module); + if (empty($moduleInstance)) { + $log->fatal("$module module installation failed!"); + } + } +} + +/* 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/Vtiger/Package.php'); + require_once('vtlib/Vtiger/Module.php'); + $Vtiger_Utils_Log = true; + $package = new Vtiger_Package(); + + if($module == null) { + $log->fatal("Module name is invalid"); + } else { + $moduleInstance = Vtiger_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/Vtiger/Package.php'); + require_once('vtlib/Vtiger/Module.php'); + $Vtiger_Utils_Log = true; + $package = new Vtiger_Package(); + + if($module == null) { + $log->fatal("Module name is invalid"); + } else { + $moduleInstance = Vtiger_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) { + $sql="select distinct vtiger_field.tabid, name + from vtiger_field + inner join vtiger_tab + on vtiger_field.tabid=vtiger_tab.tabid + where vtiger_field.tabid not in(9,10,16,15,8,29) and vtiger_tab.presence = 0 and vtiger_tab.isentitytype=1"; + $it = new SqlResultIterator($adb, $adb->query($sql)); + $modules = array(); + foreach($it as $row) { + if(isPermitted($row->name,'index') == "yes") { + $modules[$row->name] = getTranslatedString($row->name); + } + } + 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; + $data = array(); + $sql = "select related_to from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result)>0){ + $relID = $adb->query_result($result, 0, "related_to"); + $sql = "select setype from vtiger_crmentity where crmid=?"; + $result = $adb->pquery($sql, array($relID)); + if($adb->num_rows($result)>0){ + $setype = $adb->query_result($result, 0, "setype"); + } + $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; + $data = array(); + $sql = "select setype from vtiger_crmentity where crmid=?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result)>0){ + $setype = $adb->query_result($result, 0, "setype"); + $data = getEntityName($setype, $id); + } + $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; + $fields = array(); + $result = $adb->pquery("SELECT tablename,fieldlabel,fieldname FROM vtiger_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 check if a given record exists (not deleted) + * @param integer $recordId - record id + */ +function isRecordExists($recordId) { + global $adb; + $query = "SELECT crmid FROM vtiger_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 ..."); + $delim = array('/','.'); + foreach ($delim as $delimiter){ + $x = strpos($value, $delimiter); + if($x === false) continue; + else{ + $value=str_replace($delimiter, '-', $value); + break; + } + } + global $current_user; + list($y,$m,$d) = explode('-',$value); + + if(strlen($y)<4){ + $insert_date = getDBInsertDateValue($value); + } else { + $insert_date = $value; + } + $log->debug("Exiting getDBInsertDateValue method ..."); + return $insert_date; +} + +/** 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 sanitize the upload file name when the file name is detected to have bad extensions + * @param String -- $fileName - File name to be sanitized + * @return String - Sanitized file name + */ +function sanitizeUploadFileName($fileName, $badFileExtensions) { + + $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename + $fileName = rtrim($fileName, '\\/<>?*:"<>|'); + + $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; +} + +/** 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; + + $tabInfoResult = $adb->pquery('SELECT prefname, prefvalue FROM vtiger_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; + } +} + +/** Function to return block name + * @param Integer -- $blockid + * @return String - Block Name + */ +function getBlockName($blockid) { + global $adb; + if(!empty($blockid)){ + $block_res = $adb->pquery('SELECT blocklabel FROM vtiger_blocks WHERE blockid = ?',array($blockid)); + if($adb->num_rows($block_res)){ + $blockname = $adb->query_result($block_res,0,'blocklabel'); + return $blockname; + } + } + return ''; +} ?> \ No newline at end of file