Exemplo n.º 1
0
    function replaceProductTableNP($content, $pdftype, $id)
    {
        $current_language = Users_Record_Model::getCurrentUserModel()->get('language');
        require_once 'include/utils/utils.php';
        include "modules/OSSPdf/language/" . $current_language . ".lang.php";
        require_once 'include/utils/CommonUtils.php';
        require_once 'include/fields/CurrencyField.php';
        require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
        $db = PearDatabase::getInstance();
        $focus = new $pdftype();
        $focus->retrieve_entity_info($id, $pdftype);
        $focus->id = $focus->column_fields["record_id"];
        $associated_products = getAssociatedProducts($pdftype, $focus);
        $num_products = count($associated_products);
        $currency_id = $focus->column_fields['currency_id'];
        $pobierz = $db->query("select currency_symbol from vtiger_currency_info where id = '{$currency_id}'", true);
        $symbol_waluty = $db->query_result($pobierz, 0, "currency_symbol");
        //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
        $final_details = $associated_products[1]['final_details'];
        //getting the Net Total
        $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
        //Final discount amount/percentage
        $discount_amount = $final_details["discount_amount_final"];
        $discount_percent = $final_details["discount_percentage_final"];
        if ($discount_amount != "") {
            $price_discount = number_format($discount_amount, 2, '.', ',');
        } else {
            if ($discount_percent != "") {
                //This will be displayed near Discount label - used in include/fpdf/templates/body.php
                $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
                $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
            } else {
                $price_discount = "0.00";
            }
        }
        //Grand Total
        $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
        //To calculate the group tax amount
        if ($final_details['taxtype'] == 'group') {
            $group_tax_total = $final_details['tax_totalamount'];
            $price_salestax = number_format($group_tax_total, 2, '.', ',');
            $group_total_tax_percent = '0.00';
            $group_tax_details = $final_details['taxes'];
            for ($i = 0; $i < count($group_tax_details); $i++) {
                $group_total_tax_percent = $group_total_tax_percent + $group_tax_details[$i]['percentage'];
            }
        }
        $prod_line = array();
        $lines = 0;
        //This is to get all prodcut details as row basis
        for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
            $product_name[$i] = $associated_products[$i]['productName' . $i];
            $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
            //$prod_description[$i] = $associated_products[$i]['productDescription'.$i];
            $comment[$i] = $associated_products[$i]['comment' . $i];
            $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
            $qty[$i] = $associated_products[$i]['qty' . $i];
            $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
            $list_price[$i] = $associated_products[$i]['listPrice' . $i];
            // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
            $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
            $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
            //aded for 5.0.3 pdf changes
            $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
            $taxable_total = $qty[$i] * $list_pricet[$i] - $discount_total[$i];
            $producttotal = $taxable_total;
            $total_taxes = '0.00';
            if ($focus->column_fields["hdnTaxType"] == "individual") {
                $total_tax_percent = '0.00';
                //This loop is to get all tax percentage and then calculate the total of all taxes
                for ($tax_count = 0; $tax_count < count($associated_products[$i]['taxes']); $tax_count++) {
                    $tax_percent = $associated_products[$i]['taxes'][$tax_count]['percentage'];
                    $total_tax_percent = $total_tax_percent + $tax_percent;
                    $tax_amount = $taxable_total * $tax_percent / 100;
                    $total_taxes = $total_taxes + $tax_amount;
                }
                $producttotal = $taxable_total + $total_taxes;
                $product_line[$j]["tax_percentage"] = $total_tax_percent;
                $product_line[$j]["Tax"] = $total_taxes;
                $price_salestax += $total_taxes;
            }
            $prod_total[$i] = $producttotal;
            $product_line[$j]["Product Code"] = $product_code[$i];
            $product_line[$j]["Qty"] = $qty[$i];
            $product_line[$j]["Price"] = $list_price[$i];
            $product_line[$j]["Discount"] = $discount_total[$i];
            $product_line[$j]["Total"] = $prod_total[$i];
            $lines++;
            $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
            $prod_line[$j] = 1;
            for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
                if ($lines % 12 != 0) {
                    $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                    $prod_line[$j]++;
                } else {
                    $j++;
                    $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                    $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                    $prod_line[$j] = 2;
                    $lines++;
                }
                $lines++;
            }
            if ($comment[$i] != '') {
                $product_line[$j]["Product Name"] .= "\n" . decode_html($comment[$i]);
                $prod_line[$j]++;
                $lines++;
            }
        }
        $price_salestax = number_format($price_salestax, 2, '.', ',');
        $header = array($mod_strings['LBL_nr'], $mod_strings['LBL_productname'], $mod_strings['LBL_Quantity'], $mod_strings['LBL_price'], $mod_strings['LBL_netto'], $mod_strings['LBL_rabat'], $mod_strings['LBL_vat'], $mod_strings['LBL_brutto']);
        $data = array();
        $i = 0;
        foreach ($product_line as $item) {
            $data[$i++] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Price'] * $item['Qty'], $item['Discount'], 'NP', $item['Total']);
        }
        $width = array(30, 245, 35, 45, 45, 45, 45, 45);
        $align = array("center", "center", "center", "center", "center", "center", "center", "center");
        $format = array(0, "s", 0, 2, 2, 2, "np", 2);
        $product_table = '<table border="1" cellpadding="2">';
        $product_table .= '<tr valign="middle">';
        for ($i = 0; $i < count($header); $i++) {
            $product_table .= '<td width="' . $width[$i] . '" height="20" align="' . $align[$i] . '"><b><small>' . $header[$i] . '</small></b></td>';
        }
        $product_table .= '</tr>';
        $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center");
        //Data
        foreach ($data as $row) {
            $product_table .= '<tr>';
            $i = 0;
            foreach ($row as $item) {
                $sum[$i] += (double) $item;
                if ($format[$i] == 's') {
                    $itarr = explode("\n\n", $item);
                    $item = '<b>' . $itarr[0] . '</b><br/><small>' . $itarr[1] . '</small>';
                } elseif ($format[$i] == 'np') {
                } else {
                    $currfield = new CurrencyField($item);
                    $item = $currfield->getDisplayValue();
                }
                $product_table .= '<td width="' . $width[$i] . '" align="' . $align[$i++] . '"><small>' . $item . '</small></td>';
            }
            $product_table .= '</tr>';
        }
        $product_table .= "</table>";
        $i = 0;
        $mod = strtolower($pdftype);
        if ($mod == 'quotes') {
            $idcol = "quoteid";
        } else {
            $idcol = $mod . "id";
        }
        $sql = "SELECT discount_percent, discount_amount, subtotal, total FROM vtiger_{$mod} WHERE {$idcol} = " . $this->id;
        $result = $db->query($sql, true);
        $grand_total = $db->query_result($result, 0, 'total');
        $subtotal = $db->query_result($result, 0, "subtotal");
        $discount_percent = $db->query_result($result, 0, 'discount_percent');
        $discount_amount = $db->query_result($result, 0, 'discount_amount');
        if ($discount_percent != 0) {
            $discount = $subtotal * ($discount_percent / 100.0);
        } else {
            $discount = $discount_amount;
        }
        $currfield = new CurrencyField($grand_total);
        $grand_total = $currfield->getDisplayValue();
        $currfield = new CurrencyField($subtotal);
        $subtotal = $currfield->getDisplayValue();
        $currfield = new CurrencyField($discount);
        $discount = $currfield->getDisplayValue();
        $product_table .= '<table width="535px" border="1" cellpadding="2">
			<tr height="10"><td align="right" valign="middle"><small><b>' . getTranslatedString('Net Total', "OSSPdf") . '</b> : ' . $subtotal . '</small></td></tr>
			<tr valign="middle"><td align="right"><small><b>' . getTranslatedString("Discount Amount", "OSSPdf") . '</b> : ' . $discount . '</small></td></tr>
			<tr valign="middle"><td align="right"><small><b>' . getTranslatedString("Grand Total", "OSSPdf") . '</b> : ' . $grand_total . ' (' . $symbol_waluty . ')</small></td></tr>
		</table><br/>';
        $content = str_replace("#product_tableNP#", $product_table, $content);
        $currfield = new CurrencyField($grand_total);
        $grand_total = $currfield->getDBInsertedValue($grand_total);
        $kwota = $this->slownie($grand_total);
        $content = str_replace("#amount_words#", $kwota, $content);
        return $content;
    }
 function wf_formatcurrency($value)
 {
     $currencyField = new CurrencyField($value);
     return $currencyField->getDisplayValue(null, true);
 }
Exemplo n.º 3
0
 public function getPDFMakerFieldValue($report, $picklistArray, $dbField, $valueArray, $fieldName)
 {
     global $current_user, $default_charset;
     $db = PearDatabase::getInstance();
     $value = $valueArray[$fieldName];
     $fld_type = $dbField->type;
     list($module, $fieldLabel) = explode('_', $dbField->name, 2);
     $fieldInfo = $this->getFieldByPDFMakerLabel($module, $fieldLabel);
     $fieldType = null;
     $fieldvalue = $value;
     if (!empty($fieldInfo)) {
         $field = WebserviceField::fromArray($db, $fieldInfo);
         $fieldType = $field->getFieldDataType();
     }
     if ($fieldType == 'currency' && $value != '') {
         // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
         if ($field->getUIType() == '72') {
             $curid_value = explode("::", $value);
             $currency_id = $curid_value[0];
             $currency_value = $curid_value[1];
             $cur_sym_rate = getCurrencySymbolandCRate($currency_id);
             if ($value != '') {
                 if ($dbField->name == 'Products_Unit_Price') {
                     // need to do this only for Products Unit Price
                     if ($currency_id != 1) {
                         $currency_value = (double) $cur_sym_rate['rate'] * (double) $currency_value;
                     }
                 }
                 $formattedCurrencyValue = CurrencyField::convertToUserFormat($currency_value, null, true);
                 $fieldvalue = CurrencyField::appendCurrencySymbol($formattedCurrencyValue, $cur_sym_rate['symbol']);
             }
         } else {
             $currencyField = new CurrencyField($value);
             $fieldvalue = $currencyField->getDisplayValue();
         }
     } elseif ($dbField->name == "PurchaseOrder_Currency" || $dbField->name == "SalesOrder_Currency" || $dbField->name == "Invoice_Currency" || $dbField->name == "Quotes_Currency" || $dbField->name == "PriceBooks_Currency") {
         if ($value != '') {
             $fieldvalue = getTranslatedCurrencyString($value);
         }
     } elseif (in_array($dbField->name, $this->ui101_fields) && !empty($value)) {
         $entityNames = getEntityName('Users', $value);
         $fieldvalue = $entityNames[$value];
     } elseif ($fieldType == 'date' && !empty($value)) {
         if ($module == 'Calendar' && $field->getFieldName() == 'due_date') {
             $endTime = $valueArray['calendar_end_time'];
             if (empty($endTime)) {
                 $recordId = $valueArray['calendar_id'];
                 $endTime = getSingleFieldValue('vtiger_activity', 'time_end', 'activityid', $recordId);
             }
             $date = new DateTimeField($value . ' ' . $endTime);
             $fieldvalue = $date->getDisplayDate();
         } else {
             $fieldvalue = DateTimeField::convertToUserFormat($value);
         }
     } elseif ($fieldType == "datetime" && !empty($value)) {
         $date = new DateTimeField($value);
         $fieldvalue = $date->getDisplayDateTimeValue();
     } elseif ($fieldType == 'time' && !empty($value) && $field->getFieldName() != 'duration_hours') {
         if ($field->getFieldName() == "time_start" || $field->getFieldName() == "time_end") {
             $date = new DateTimeField($value);
             $fieldvalue = $date->getDisplayTime();
         } else {
             $fieldvalue = $value;
         }
     } elseif ($fieldType == "picklist" && !empty($value)) {
         if (is_array($picklistArray)) {
             if (is_array($picklistArray[$dbField->name]) && $field->getFieldName() != 'activitytype' && !in_array($value, $picklistArray[$dbField->name])) {
                 $fieldvalue = $app_strings['LBL_NOT_ACCESSIBLE'];
             } else {
                 $fieldvalue = $this->getTranslatedString($value, $module);
             }
         } else {
             $fieldvalue = $this->getTranslatedString($value, $module);
         }
     } elseif ($fieldType == "multipicklist" && !empty($value)) {
         if (is_array($picklistArray[1])) {
             $valueList = explode(' |##| ', $value);
             $translatedValueList = array();
             foreach ($valueList as $value) {
                 if (is_array($picklistArray[1][$dbField->name]) && !in_array($value, $picklistArray[1][$dbField->name])) {
                     $translatedValueList[] = $app_strings['LBL_NOT_ACCESSIBLE'];
                 } else {
                     $translatedValueList[] = $this->getTranslatedString($value, $module);
                 }
             }
         }
         if (!is_array($picklistArray[1]) || !is_array($picklistArray[1][$dbField->name])) {
             $fieldvalue = str_replace(' |##| ', ', ', $value);
         } else {
             implode(', ', $translatedValueList);
         }
     } elseif ($fieldType == 'double') {
         if ($current_user->truncate_trailing_zeros == true) {
             $fieldvalue = decimalFormat($fieldvalue);
         }
     }
     if ($fieldvalue == "") {
         return "-";
     }
     $fieldvalue = str_replace("<", "&lt;", $fieldvalue);
     $fieldvalue = str_replace(">", "&gt;", $fieldvalue);
     $fieldvalue = decode_html($fieldvalue);
     if (stristr($fieldvalue, "|##|") && empty($fieldType)) {
         $fieldvalue = str_ireplace(' |##| ', ', ', $fieldvalue);
     } elseif ($fld_type == "date" && empty($fieldType)) {
         $fieldvalue = DateTimeField::convertToUserFormat($fieldvalue);
     } elseif ($fld_type == "datetime" && empty($fieldType)) {
         $date = new DateTimeField($fieldvalue);
         $fieldvalue = $date->getDisplayDateTimeValue();
     }
     // Added to render html tag for description fields
     if ($fieldInfo['uitype'] == '19' && ($module == 'Documents' || $module == 'Emails')) {
         return $fieldvalue;
     }
     return htmlentities($fieldvalue, ENT_QUOTES, $default_charset);
 }
Exemplo n.º 4
0
/** 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_pair['disp_value']) {
            $focus->id = $value_pair['disp_value'];
            $focus->retrieve_entity_info($value_pair['disp_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, 'readwrite') == '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 != '') {
                        $displayValueArray = getEntityName('Contacts', $contact_id);
                        if (!empty($displayValueArray)) {
                            foreach ($displayValueArray as $key => $field_value) {
                                $contactname = $field_value;
                            }
                        }
                    }
                    $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 = getUserFullName($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) {
                        $displayValueArray = getEntityName('Contacts', $parent_id);
                        if (!empty($displayValueArray)) {
                            foreach ($displayValueArray as $key => $field_value) {
                                $contact_name = $field_value;
                            }
                        } else {
                            $contact_name = '';
                        }
                        $value_pair['disp_value'] = $contact_name;
                    }
                } 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) {
                    if ($field_values[$j][$fld_name] != '' && $field_values[$j][$fld_name] != '0000-00-00') {
                        $date = new DateTimeField($field_values[$j][$fld_name]);
                        $value_pair['disp_value'] = $date->getDisplayDate();
                        if (strpos($field_values[$j][$fld_name], ' ') > -1) {
                            $value_pair['disp_value'] .= ' ' . $date->getDisplayTime();
                        }
                    } elseif ($field_values[$j][$fld_name] == '0000-00-00') {
                        $value_pair['disp_value'] = '';
                    } else {
                        $value_pair['disp_value'] = $field_values[$j][$fld_name];
                    }
                } elseif ($ui_type == '71' || $ui_type == '72') {
                    $currencyField = new CurrencyField($field_values[$j][$fld_name]);
                    if ($ui_type == '72') {
                        $value_pair['disp_value'] = $currencyField->getDisplayValue(null, true);
                    } else {
                        $value_pair['disp_value'] = $currencyField->getDisplayValue();
                    }
                } 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;
}
Exemplo n.º 5
0
/**
 *
 * @global Users $current_user
 * @param ReportRun $report
 * @param Array $picklistArray
 * @param ADOFieldObject $dbField
 * @param Array $valueArray
 * @param String $fieldName
 * @return String
 */
function getReportFieldValue($report, $picklistArray, $dbField, $valueArray, $fieldName)
{
    global $current_user, $default_charset;
    $db = PearDatabase::getInstance();
    $value = $valueArray[$fieldName];
    $fld_type = $dbField->type;
    list($module, $fieldLabel) = explode('__', $dbField->name, 2);
    $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
    $fieldType = null;
    $fieldvalue = $value;
    if (!empty($fieldInfo)) {
        $field = WebserviceField::fromArray($db, $fieldInfo);
        $fieldType = $field->getFieldDataType();
    }
    if ($fieldType == 'currency' && $value != '') {
        // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
        if ($field->getUIType() == '72') {
            $curid_value = explode("::", $value);
            $currency_id = $curid_value[0];
            $currency_value = $curid_value[1];
            $cur_sym_rate = getCurrencySymbolandCRate($currency_id);
            if ($value != '') {
                if ($dbField->name == 'Products_Unit_Price') {
                    // need to do this only for Products Unit Price
                    if ($currency_id != 1) {
                        $currency_value = (double) $cur_sym_rate['rate'] * (double) $currency_value;
                    }
                }
                $formattedCurrencyValue = CurrencyField::convertToUserFormat($currency_value, null, true);
                $fieldvalue = CurrencyField::appendCurrencySymbol($formattedCurrencyValue, $cur_sym_rate['symbol']);
            }
        } else {
            $currencyField = new CurrencyField($value);
            $fieldvalue = $currencyField->getDisplayValue();
        }
    } elseif ($dbField->name == "PriceBooks_Currency") {
        if ($value != '') {
            $fieldvalue = getTranslatedCurrencyString($value);
        }
    } elseif (in_array($dbField->name, $report->ui101_fields) && !empty($value)) {
        $entityNames = getEntityName('Users', $value);
        $fieldvalue = $entityNames[$value];
    } elseif ($fieldType == 'date' && !empty($value)) {
        if ($module == 'Calendar' && $field->getFieldName() == 'due_date') {
            $endTime = $valueArray['calendar_end_time'];
            if (empty($endTime)) {
                $recordId = $valueArray['calendar_id'];
                $endTime = getSingleFieldValue('vtiger_activity', 'time_end', 'activityid', $recordId);
            }
            $date = new DateTimeField($value . ' ' . $endTime);
            $fieldvalue = $date->getDisplayDate();
        } else {
            if (!($field->getUIType() == '5')) {
                $date = new DateTimeField($fieldvalue);
                $fieldvalue = $date->getDisplayDateTimeValue();
            }
        }
    } elseif ($fieldType == "datetime" && !empty($value)) {
        $date = new DateTimeField($value);
        $fieldvalue = $date->getDisplayDateTimeValue();
    } elseif ($fieldType == 'time' && !empty($value) && $field->getFieldName() != 'duration_hours') {
        if ($field->getFieldName() == "time_start" || $field->getFieldName() == "time_end") {
            $date = new DateTimeField($value);
            $fieldvalue = $date->getDisplayTime();
        } else {
            $userModel = Users_Privileges_Model::getCurrentUserModel();
            if ($userModel->get('hour_format') == '12') {
                $value = Vtiger_Time_UIType::getTimeValueInAMorPM($value);
            }
            $fieldvalue = $value;
        }
    } elseif ($fieldType == "picklist" && !empty($value)) {
        if (is_array($picklistArray)) {
            if (is_array($picklistArray[$dbField->name]) && $field->getFieldName() != 'activitytype' && !in_array($value, $picklistArray[$dbField->name])) {
                $fieldvalue = $app_strings['LBL_NOT_ACCESSIBLE'];
            } else {
                $fieldvalue = getTranslatedString($value, $module);
            }
        } else {
            $fieldvalue = getTranslatedString($value, $module);
        }
    } elseif ($fieldType == "multipicklist" && !empty($value)) {
        if (is_array($picklistArray[1])) {
            $valueList = explode(' |##| ', $value);
            $translatedValueList = array();
            foreach ($valueList as $value) {
                if (is_array($picklistArray[1][$dbField->name]) && !in_array($value, $picklistArray[1][$dbField->name])) {
                    $translatedValueList[] = $app_strings['LBL_NOT_ACCESSIBLE'];
                } else {
                    $translatedValueList[] = getTranslatedString($value, $module);
                }
            }
        }
        if (!is_array($picklistArray[1]) || !is_array($picklistArray[1][$dbField->name])) {
            $fieldvalue = str_replace(' |##| ', ', ', $value);
        } else {
            implode(', ', $translatedValueList);
        }
    } elseif ($fieldType == 'double') {
        if ($current_user->truncate_trailing_zeros == true) {
            $fieldvalue = decimalFormat($fieldvalue);
        }
    } elseif ($fieldType == 'boolean') {
        if (strtolower($value) === 'yes' || strtolower($value) === 'on' || $value == 1) {
            $fieldvalue = vtranslate('LBL_YES');
        } else {
            $fieldvalue = vtranslate('LBL_NO');
        }
    } elseif ($field && $field->getUIType() == 117 && $value != '') {
        if ($value != '0') {
            $currencyList = Settings_Currency_Record_Model::getAll();
            $fieldvalue = $currencyList[$value]->getName() . ' (' . $currencyList[$value]->get('currency_symbol') . ')';
        } else {
            $fieldvalue = '-';
        }
    }
    if ('vtiger_crmentity' == $dbField->table && false != strpos($dbField->name, 'Share__with__users')) {
        if ($value) {
            $listId = explode(',', $value);
            $usersSqlFullName = getSqlForNameInDisplayFormat(['first_name' => 'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'], 'Users');
            $getListUserSql = "select {$usersSqlFullName} as uname from vtiger_users WHERE id IN (" . generateQuestionMarks($listId) . ') ';
            $getListUserResult = $db->pquery($getListUserSql, array($listId), TRUE);
            $fieldvalue = '';
            $finalList = array();
            $listUsers = $getListUserResult->GetAll();
            for ($i = 0; $i < count($listUsers); $i++) {
                $finalList[] = $listUsers[$i][0];
            }
            $fieldvalue = implode(', ', $finalList);
        }
    }
    if ($fieldvalue == "") {
        return "-";
    }
    $fieldvalue = str_replace("<", "&lt;", $fieldvalue);
    $fieldvalue = str_replace(">", "&gt;", $fieldvalue);
    $fieldvalue = decode_html($fieldvalue);
    if (stristr($fieldvalue, "|##|") && empty($fieldType)) {
        $fieldvalue = str_ireplace(' |##| ', ', ', $fieldvalue);
    } elseif ($fld_type == "date" && empty($fieldType)) {
        $fieldvalue = DateTimeField::convertToUserFormat($fieldvalue);
    } elseif ($fld_type == "datetime" && empty($fieldType)) {
        $date = new DateTimeField($fieldvalue);
        $fieldvalue = $date->getDisplayDateTimeValue();
    }
    // Added to render html tag for description fields
    if ($fieldInfo['uitype'] == '19' && ($module == 'Documents' || $module == 'Emails')) {
        return $fieldvalue;
    }
    return htmlentities($fieldvalue, ENT_QUOTES, $default_charset);
}
Exemplo n.º 6
0
function replaceProductList($pdftype, $id, $templateid, $content, $tcpdf)
{
    require_once 'include/utils/CommonUtils.php';
    require_once 'include/fields/CurrencyField.php';
    require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
    $focus = new $pdftype();
    $focus->retrieve_entity_info($id, $pdftype);
    $focus->id = $focus->column_fields["record_id"];
    $associated_products = getAssociatedProducts($pdftype, $focus);
    $num_products = count($associated_products);
    //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
    $final_details = $associated_products[1]['final_details'];
    //getting the Net Total
    $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
    //Final discount amount/percentage
    $discount_amount = $final_details["discount_amount_final"];
    $discount_percent = $final_details["discount_percentage_final"];
    if ($discount_amount != "") {
        $price_discount = number_format($discount_amount, 2, '.', ',');
    } else {
        if ($discount_percent != "") {
            //This will be displayed near Discount label - used in include/fpdf/templates/body.php
            $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
            $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
        } else {
            $price_discount = "0.00";
        }
    }
    //Grand Total
    $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
    //To calculate the group tax amount
    if ($final_details['taxtype'] == 'group') {
        $group_tax_total = $final_details['tax_totalamount'];
        $price_salestax = number_format($group_tax_total, 2, '.', ',');
        $group_total_tax_percent = '0.00';
        $group_tax_details = $final_details['taxes'];
        for ($i = 0; $i < count($group_tax_details); $i++) {
            $group_total_tax_percent = $group_total_tax_percent + $group_tax_details[$i]['percentage'];
        }
    }
    $prod_line = array();
    $lines = 0;
    //This is to get all prodcut details as row basis
    for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
        $product_name[$i] = $associated_products[$i]['productName' . $i];
        $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
        $comment[$i] = $associated_products[$i]['comment' . $i];
        $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
        $qty[$i] = $associated_products[$i]['qty' . $i];
        $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
        $list_price[$i] = $associated_products[$i]['listPrice' . $i];
        // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
        $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
        $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
        //aded for 5.0.3 pdf changes
        $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
        $taxable_total = $qty[$i] * $list_pricet[$i] - $discount_total[$i];
        $producttotal = $taxable_total;
        $total_taxes = '0.00';
        if ($focus->column_fields["hdnTaxType"] == "individual") {
            $total_tax_percent = '0.00';
            //This loop is to get all tax percentage and then calculate the total of all taxes
            for ($tax_count = 0; $tax_count < count($associated_products[$i]['taxes']); $tax_count++) {
                $tax_percent = $associated_products[$i]['taxes'][$tax_count]['percentage'];
                $total_tax_percent = $total_tax_percent + $tax_percent;
                $tax_amount = $taxable_total * $tax_percent / 100;
                $total_taxes = $total_taxes + $tax_amount;
            }
            $producttotal = $taxable_total + $total_taxes;
            $product_line[$j]["tax_percentage"] = $total_tax_percent;
            $product_line[$j]["Tax"] = $total_taxes;
            $price_salestax += $total_taxes;
        }
        $prod_total[$i] = $producttotal;
        // number_format($producttotal,2,'.',',');
        $product_line[$j]["Product Code"] = $product_code[$i];
        $product_line[$j]["Qty"] = $qty[$i];
        $product_line[$j]["Price"] = $list_price[$i];
        $product_line[$j]["Discount"] = $discount_total[$i];
        $product_line[$j]["Total"] = $prod_total[$i];
        $lines++;
        $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
        $prod_line[$j] = 1;
        for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
            if ($lines % 12 != 0) {
                $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j]++;
            } else {
                $j++;
                $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j] = 2;
                $lines++;
            }
            $lines++;
        }
        if ($comment[$i] != '') {
            $product_line[$j]["Product Name"] .= "\n" . decode_html($comment[$i]);
            $prod_line[$j]++;
            $lines++;
        }
    }
    $price_salestax = number_format($price_salestax, 2, '.', ',');
    $header = array(vtranslate('LBL_nr', 'OSSPdf'), vtranslate('LBL_productname', 'OSSPdf'), vtranslate('LBL_Quantity', 'OSSPdf'));
    $data = array();
    $i = 0;
    foreach ($product_line as $item) {
        $currfield = new CurrencyField($item["tax_percentage"]);
        $tax_percentage = $currfield->getDisplayValue();
        $data[$i++] = array($i, $item['Product Name'], $item['Qty']);
    }
    $width = array(35, 400, 100, 45, 45, 45, 45, 45, 45);
    $align = array("center", "center", "center", "center", "center", "center", "center", "center", "center");
    $format = array(0, "s", 0, 2, 2, 2, 2, 2, 2);
    $product_table = '<table align="center" border="1" cellpadding="2">';
    $product_table .= '<tr valign="middle">';
    for ($i = 0; $i < count($header); $i++) {
        $product_table .= '<td width="' . $width[$i] . '" height="20" align="' . $align[$i] . '"><b><small>' . $header[$i] . '</small></b></td>';
    }
    $product_table .= '</tr>';
    $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center");
    //Data
    foreach ($data as $row) {
        $product_table .= '<tr>';
        $i = 0;
        foreach ($row as $item) {
            $sum[$i] += (double) $item;
            if ($format[$i] != 's') {
                $currfield = new CurrencyField($item);
                $item = $currfield->getDisplayValue();
            } else {
                $itarr = explode("\n\n", $item);
                $item = '<b>' . $itarr[0] . '</b><br/><small>' . $itarr[1] . '</small>';
            }
            $product_table .= '<td width="' . $width[$i] . '" align="' . $align[$i++] . '"><small>' . $item . '</small></td>';
        }
        $product_table .= '</tr>';
    }
    $product_table .= "</table><br/></center>";
    $i = 0;
    return $product_table;
}
function replaceCorrectedTableProducts($pdftype, $id, $templateid, $content, $tcpdf)
{
    /* ------------------- COLUMN CONFIGURATION -------------------
    
          In this part, you can decide which columns you want to appear
                           and which are not in the table of positions and invoice summary table
    
                           If the variable responsible for this column has the value TRUE
                           will be displayed and if FALSE it will not be displayed
    
         */
    // The columns for the table from the list of items on the invoice
    $kolumnyDlaPozycjiFaktur = array();
    // column ordinal
    $enable_ordinal_column = TRUE;
    // Column name of the product
    $enable_productname_column = TRUE;
    // column number
    $enable_amount_column = TRUE;
    // unit price column
    $enable_listprice_column = TRUE;
    // net price column
    $enable_netprice_column = TRUE;
    // discount column
    $enable_discount_column = TRUE;
    // Vat column (%)
    $enable_vatpercentage_column = TRUE;
    // Vat column (currency)
    $enable_vatamount_column = TRUE;
    // Gross column
    $enable_gross_column = TRUE;
    // Taxes in PLN
    $enable_taxes_inPLN = TRUE;
    // Column for a summary in the gray box
    $wyswietlaj = array($enable_ordinal_column, $enable_productname_column, $enable_amount_column, $enable_listprice_column, $enable_netprice_column, $enable_discount_column, $enable_vatpercentage_column, $enable_vatamount_column, $enable_gross_column, $enable_taxes_inPLN);
    $kolumnyDlaPodsumowaniaFaktur = array();
    $enable_summary_before_correction = TRUE;
    $enable_summary_including = TRUE;
    $enable_summary_after_correction = TRUE;
    $enable_summary_together = TRUE;
    $db = PearDatabase::getInstance();
    require_once 'include/utils/utils.php';
    include "languages/pl_pl/OSSPdf.php";
    $tab_pl = $languageStrings;
    include "languages/en_us/OSSPdf.php";
    $tab_us = $languageStrings;
    $displays_a_summary_of_invoices = TRUE;
    require_once 'include/utils/CommonUtils.php';
    require_once 'include/fields/CurrencyField.php';
    require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
    require_once 'modules/' . $pdftype . '/utils.php';
    require_once 'modules/Invoice/Invoice.php';
    $focus = new $pdftype();
    $focus->retrieve_entity_info($id, $pdftype);
    $currency_id = $focus->column_fields['currency_id'];
    $pobierz = $db->query("select currency_symbol, currency_code from vtiger_currency_info where id = '{$currency_id}'", true);
    $kod_aktualnej_waluty = $db->query_result($pobierz, 0, "currency_code");
    $symbol_waluty = $db->query_result($pobierz, 0, "currency_symbol");
    //////////////////////////////
    // check if the module is OSSCurrencyUpdate exist
    $czyDrukowacKolumneZPrzeliczonymPodatkiem = FALSE;
    $moduleFilePath = "modules/OSSCurrencyUpdate/OSSCurrencyUpdate.php";
    $moduleFilePathTpl = "Smarty/templates/modules/OSSCurrencyUpdate/index.tpl";
    $checkInDatabaseSql = "SELECT * FROM vtiger_tab WHERE name = 'OSSCurrencyUpdate'";
    $pobierzGluwnaWaluteSql = $db->query("select currency_code from vtiger_currency_info where id = '1'", true);
    $kod_waluty = $db->query_result($pobierzGluwnaWaluteSql, 0, "currency_code");
    $checkInDatabaseResult = $db->query($checkInDatabaseSql, true);
    $numDB = $db->num_rows($checkInDatabaseResult);
    //var_dump($kod_aktualnej_waluty);
    //$log->error( 'kod waluty: '.$kod_waluty.'; $kod aktualnej: '.$kod_aktualnej_waluty );
    if (file_exists($moduleFilePath) && $numDB > 0 && $kod_waluty == 'PLN' && $kod_aktualnej_waluty != 'PLN' && vtlib_isModuleActive('OSSCurrencyUpdate')) {
        $czyDrukowacKolumneZPrzeliczonymPodatkiem = TRUE;
    }
    if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
        require_once $moduleFilePath;
    }
    $focus->id = $focus->column_fields["record_id"];
    $associated_products = OSSgetAssociatedProducts($pdftype, $focus);
    $num_products = count($associated_products);
    $vat = array();
    $sales = array();
    $service = array();
    $total_discount = 0.0;
    $suma_netto = 0.0;
    $suma_brutto = $associated_products[1]['final_details']['hdnSubTotal'];
    $rabat_calkowity = $associated_products[1]['final_details']['discount_amount_final'];
    $korekta_rabat = 0.0;
    for ($i = 1; $i <= count($associated_products); $i++) {
        $korekta_rabat += (double) $associated_products[$i]['discount_amount' . $i];
    }
    $suma_vat = 0;
    $inoice_id_sql = "SELECT vtiger_invoice.invoiceid FROM vtiger_invoice JOIN vtiger_osscorrectedinvoice ON vtiger_invoice.invoiceid = vtiger_osscorrectedinvoice.invoiceid WHERE osscorrectedinvoiceid = {$id}";
    $inoice_result = $db->query($inoice_id_sql, true);
    $invoice_id = $db->query_result($inoice_result, 0, 'invoiceid');
    $focus_invoice = new Invoice();
    $focus_invoice->retrieve_entity_info($invoice_id, 'Invoice');
    $focus_invoice->id = $focus_invoice->column_fields["record_id"];
    $associated_products_in = getAssociatedProducts('Invoice', $focus_invoice);
    $subtotal_invoice = $associated_products_in[1]['final_details']['hdnSubTotal'];
    $faktura_rabat = 0.0;
    for ($i = 1; $i <= count($associated_products_in); $i++) {
        $faktura_rabat += (double) $associated_products_in[$i]['discount_amount' . $i];
    }
    $suma_brutto = (double) $suma_brutto;
    $wartosc_korekty_brutto = $suma_brutto - $subtotal_invoice;
    $suma_netto_invoice = 0.0;
    $suma_vat_inv = 0.0;
    $suma_netto_invoice = $associated_products_in[1]['final_details']['hdnSubTotal'];
    for ($i = 1; $i <= count($associated_products_in); $i++) {
        $TotalAfterDiscount_inv = $associated_products_in[$i]['totalAfterDiscount' . $i];
        foreach ($associated_products_in[$i]['taxes'] as $podatek) {
            if ($podatek['taxlabel'] == 'VAT') {
                //$vat[$podatek['percentage']] += $TotalAfterDiscount_inv*($podatek['percentage'] / 100.0);
                $suma_vat_inv += $TotalAfterDiscount_inv * ($podatek['percentage'] / 100.0);
            }
        }
    }
    //var_dump($suma_vat_inv);
    //exit();
    /////////////////////////////
    /// Create a table summary of VAT
    if ($focus->column_fields['hdnTaxType'] == 'group') {
        for ($i = 1; $i <= count($associated_products); $i++) {
            $suma_netto += $associated_products[$i]['totalAfterDiscount' . $i];
            $total_discount += $associated_products[$i]['discountTotal' . $i];
        }
    } else {
        for ($i = 1; $i <= count($associated_products); $i++) {
            $suma_netto += $associated_products[$i]['totalAfterDiscount' . $i];
            $TotalAfterDiscount = $associated_products[$i]['totalAfterDiscount' . $i];
            foreach ($associated_products[$i]['taxes'] as $podatek) {
                if ($podatek['taxlabel'] == 'VAT') {
                    $vat[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    $suma_vat += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                }
                if ($podatek['taxlabel'] == 'Sales') {
                    $sales[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                }
                if ($podatek['taxlabel'] == 'Service') {
                    $service[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                }
            }
            // Calculating the total discount
            $total_discount += $associated_products[$i]['discountTotal' . $i];
        }
    }
    /*
          echo "<br/>vat: ".$suma_vat;
          echo "<br/>netto: ".$suma_netto;
          echo "<br/>brutto: ".$suma_brutto;
          print_r($vat);
          echo "<br /><br />";
          print_r($sales);
          echo "<br /><br />";
          print_r($service);
          echo "<br /><br />";
    
    
          print_r($associated_products);
          exit; */
    ///////////////////////////////////////////////////////////
    //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
    $final_details = $associated_products[1]['final_details'];
    //getting the Net Total
    $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
    //Final discount amount/percentage
    $discount_amount = $final_details["discount_amount_final"];
    $discount_percent = $final_details["discount_percentage_final"];
    if ($discount_amount != "") {
        $price_discount = number_format($discount_amount, 2, '.', ',');
        $price_disc = $discount_amount;
    } else {
        if ($discount_percent != "") {
            //This will be displayed near Discount label - used in include/fpdf/templates/body.php
            $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
            $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
            $price_disc = $discount_percent * $final_details["hdnSubTotal"];
        } else {
            $price_discount = "0.00";
        }
    }
    //Grand Total
    $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
    //To calculate the group tax amount
    if ($final_details['taxtype'] == 'group') {
        $group_tax_total = $final_details['tax_totalamount'];
        $price_salestax = number_format($group_tax_total, 2, '.', ',');
        $group_total_tax_percent = '0.00';
        $group_tax_details = $final_details['taxes'];
        for ($i = 0; $i < count($group_tax_details); $i++) {
            $group_total_tax_percent = $group_total_tax_percent + $group_tax_details[$i]['percentage'];
        }
    }
    $podatek_grupowy = ($final_details["hdnSubTotal"] - $price_disc) * ($group_total_tax_percent / 100.0);
    $tax_pl = 0;
    $suma_podatku_w_pln = 0.0;
    //var_dump($czyDrukowacKolumneZPrzeliczonymPodatkiem);
    //exit;
    if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
        $invoice_date_sql = "SELECT datecorrection FROM vtiger_osscorrectedinvoice WHERE osscorrectedinvoiceid = {$id}";
        $invoice_date_result = $db->query($invoice_date_sql, true);
        $invoice_date = $db->query_result($invoice_date_result, 0, 'datecorrection');
        $date_tab = explode(" ", $invoice_date);
        $date = $date_tab[0];
        $newdate = strtotime('-1 day', strtotime($date));
        $newdate = date('Y-m-d', $newdate);
        $CurrencyUpdate = Vtiger_Record_Model::getCleanInstance('OSSCurrencyUpdate');
        $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
        $num_rate = $db->num_rows($kurs_waluty_result);
        if ($num_rate == 0) {
            $CurrencyUpdate->getCurrency($newdate);
            $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
            $num_rate = $db->num_rows($kurs_waluty_result);
            if ($num_rate != 0) {
                $kurs_waluty = (double) $db->query_result($kurs_waluty_result, 0, 'kurs');
            }
        } else {
            $kurs_waluty = (double) $db->query_result($kurs_waluty_result, 0, 'kurs');
            $newdate = date('Y-m-d', strtotime($db->query_result($kurs_waluty_result, 0, "data_faktyczna_kursu")));
        }
    }
    $prod_line = array();
    $lines = 0;
    //This is to get all prodcut details as row basis
    for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
        $product_name[$i] = $associated_products[$i]['productName' . $i];
        $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
        $comment[$i] = $associated_products[$i]['comment' . $i];
        $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
        $qty[$i] = $associated_products[$i]['qty' . $i];
        $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
        $list_price[$i] = $associated_products[$i]['listPrice' . $i];
        // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
        $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
        $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
        $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
        $taxable_total = $qty[$i] * $list_pricet[$i] - $discount_total[$i];
        $producttotal = $taxable_total;
        $total_taxes = '0.00';
        if ($focus->column_fields["hdnTaxType"] == "individual") {
            $total_tax_percent = '0.00';
            //This loop is to get all tax percentage and then calculate the total of all taxes
            for ($tax_count = 0; $tax_count < count($associated_products[$i]['taxes']); $tax_count++) {
                $tax_percent = $associated_products[$i]['taxes'][$tax_count]['percentage'];
                $total_tax_percent = $total_tax_percent + $tax_percent;
                $tax_amount = $taxable_total * $tax_percent / 100;
                $total_taxes = $total_taxes + $tax_amount;
            }
            $producttotal = $taxable_total + $total_taxes;
            $product_line[$j]["tax_percentage"] = $total_tax_percent;
            $product_line[$j]["Tax"] = $total_taxes;
            $price_salestax += $total_taxes;
        }
        $prod_total[$i] = $producttotal;
        // number_format($producttotal,2,'.',',');
        $product_line[$j]["Product Code"] = $product_code[$i];
        $product_line[$j]["Qty"] = $qty[$i];
        $product_line[$j]["Price"] = $list_price[$i];
        $product_line[$j]["Discount"] = $discount_total[$i];
        $product_line[$j]["Total"] = $prod_total[$i];
        $lines++;
        $product_line[$j]["Product Name"] = '<b>' . decode_html($product_name[$i]) . '</b>';
        $prod_line[$j] = 1;
        for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
            if ($lines % 12 != 0) {
                if ($subproduct_name[$i][$count] != '') {
                    $product_line[$j]["Product Name"] .= "\n <br />" . '<font color="grey" size="-1"><em>' . decode_html($subproduct_name[$i][$count]) . '</em></font>';
                    $prod_line[$j]++;
                }
            } else {
                $j++;
                $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                $product_line[$j]["Product Name"] .= "\n <br />" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j] = 2;
                $lines++;
            }
            $lines++;
        }
        if ($comment[$i] != '') {
            $product_line[$j]["Product Name"] .= "\n <br />" . decode_html($comment[$i]);
            $prod_line[$j]++;
            $lines++;
        }
    }
    //Number
    //	print_r($product_line);
    //echo ;
    $price_salestax = number_format($price_salestax, 2, '.', ',');
    if ($final_details['taxtype'] == 'group') {
        $header = array();
        if ($enable_ordinal_column) {
            $header[0] = $mod_strings['LBL_nr'];
        }
        if ($enable_productname_column) {
            $header[1] = $mod_strings['LBL_productname'];
        }
        if ($enable_amount_column) {
            $header[2] = $mod_strings['LBL_Quantity'];
        }
        if ($enable_listprice_column) {
            $header[3] = $mod_strings['LBL_price'];
        }
        if ($enable_discount_column) {
            $header[4] = $mod_strings['LBL_rabat'];
        }
        if ($enable_netprice_column) {
            $header[5] = $mod_strings['LBL_netto'];
        }
        if ($enable_gross_column) {
            $header[6] = $mod_strings['LBL_brutto'];
        }
    } else {
        $header = array();
        if ($enable_ordinal_column) {
            $header[0] = $mod_strings['LBL_nr'];
        }
        if ($enable_productname_column) {
            $header[1] = $mod_strings['LBL_productname'];
        }
        if ($enable_amount_column) {
            $header[2] = $mod_strings['LBL_Quantity'];
        }
        if ($enable_listprice_column) {
            $header[3] = $mod_strings['LBL_price'];
        }
        if ($enable_discount_column) {
            $header[4] = $mod_strings['LBL_rabat'];
        }
        if ($enable_netprice_column) {
            $header[5] = $mod_strings['LBL_netto'];
        }
        if ($enable_vatpercentage_column) {
            $header[6] = $mod_strings['LBL_vat'];
        }
        if ($enable_vatamount_column) {
            $header[7] = $mod_strings['LBL_vat_waluta'] . " (" . $symbol_waluty . ")";
        }
        if ($enable_gross_column) {
            $header[8] = $mod_strings['LBL_brutto'];
        }
        if ($enable_taxes_inPLN && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            $header[9] = $mod_strings['TAXES_IN_PLN'];
        }
    }
    $data = array();
    $i = 1;
    foreach ($product_line as $item) {
        $currfield = new CurrencyField($item["tax_percentage"]);
        $tax_percentage = $currfield->getDisplayValue();
        if ($final_details['taxtype'] == 'group') {
            $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
            $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $item['Total']);
        } else {
            $tax_pln = $item['Tax'] * $kurs_waluty;
            $suma_podatku_w_pln += $tax_pln;
            $currfield = new CurrencyField($tax_pln);
            $tax_pln = $currfield->getDisplayValue();
            $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
            $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $tax_percentage, $item['Tax'], $item['Total'], $tax_pln);
        }
        $i++;
    }
    if ($final_details['taxtype'] == 'group') {
        $width = array(30, 290, 35, 45, 45, 45, 45);
        $align = array("center", "center", "center", "center", "center", "center", "center");
        $format = array(0, "s", 0, 2, 2, 2, 2);
    } else {
        $width = array(30, 200, 35, 40, 40, 40, 40, 40, 40, 40);
        $align = array("center", "center", "center", "center", "center", "center", "center", "center", "center", "center");
        $format = array(0, "s", 0, 2, 2, 2, 2, 2, 2);
    }
    $group_sep = ' ';
    $separatorSql = "SELECT currency_decimal_separator FROM vtiger_users WHERE id = '{$current_user->id}'";
    $separatorResult = $db->query($separatorSql, true);
    $dec_sep = $db->query_result($separatorResult, 0, 'currency_decimal_separator');
    //$group_sep = $db->query_result($separatorResult, 0, 'currency_grouping_separator');
    //var_dump($data);
    //exit;
    if ($dec_sep == '') {
        $dec_sep = ' ';
    }
    if ($group_sep == $dec_sep) {
        $dec_sep = '.';
    }
    $product_table = '<table border="1" cellpadding="2">';
    $product_table .= '<tr valign="middle">';
    foreach ($header as $key => $val) {
        $product_table .= '<td width="' . $width[$key] . '" height="20" align="' . $align[$key] . '"><b><small>' . $val . '</small></b></td>';
    }
    $product_table .= '</tr>';
    $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center", "center");
    foreach ($data as $row) {
        $product_table .= '<tr>';
        $i = 0;
        $j = 1;
        foreach ($row as $key => $item) {
            $sum[$i] += (double) $item;
            if ($format[$i] == 's') {
                $itarr = explode("\n\n", $item);
                $item = $itarr[0] . ' ' . $itarr[1];
            }
            if ($wyswietlaj[$key]) {
                if ($key == 9) {
                    if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                        $currfield = new CurrencyField(0);
                        $zero = $currfield->getDisplayValue();
                        /* echo "<br/>".$tax_percentage;
                            echo "<br/>".$zero;
                            echo "<br/>porownanie".($item != 0 );
                            echo "<br/>".$item;
                           */
                        if ($item != 0 && $kurs_waluty) {
                            $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format((double) $item, 2, $dec_sep, $group_sep) . '</small></td>';
                        } else {
                            $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>np</small></td>';
                        }
                    }
                } else {
                    if ($key != 0 && $key != 1) {
                        //var_dump($item);
                        $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format((double) $item, 2, $dec_sep, $group_sep) . '</small></td>';
                    } else {
                        $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . $item . '</small></td>';
                    }
                }
            }
            $i++;
        }
        $product_table .= '</tr>';
    }
    //exit;
    $product_table .= "</table>";
    $i = 0;
    $roznica_vat = $suma_vat - $suma_vat_inv;
    $roznica_netto = $suma_netto - (double) $suma_netto_invoice;
    $suma_netto_poz = $suma_netto;
    $suma_brutto_poz = $suma_brutto;
    /*
     $currfield = new CurrencyField( $suma_netto_poz );
     $suma_netto_poz = $currfield->getDisplayValue();
    
     $currfield = new CurrencyField( $total_discount );
     $total_discount = $currfield->getDisplayValue();
    
     $currfield = new CurrencyField( $suma_vat );
     $suma_vat = $currfield->getDisplayValue();
    
     $currfield = new CurrencyField( $suma_brutto_poz );
     $suma_brutto_poz = $currfield->getDisplayValue();
    */
    $product_table .= '<table cellpadding="0" cellspacing="0"><tr border="0">';
    if ($enable_ordinal_column) {
        $product_table .= '<td width="' . $width[0] . '"></td>';
    }
    if ($enable_productname_column) {
        $product_table .= '<td width="' . $width[1] . '"></td>';
    }
    if ($enable_amount_column) {
        $product_table .= '<td width="' . $width[2] . '"></td>';
    }
    if ($enable_listprice_column) {
        $product_table .= '<td width="' . $width[3] . '"></td>';
    }
    if ($enable_netprice_column) {
        $product_table .= '<td width="' . $width[5] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($total_discount, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_discount_column) {
        $product_table .= '<td width="' . $width[4] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_netto_poz, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_vatpercentage_column && $final_details['taxtype'] != 'group') {
        $product_table .= '<td width="' . $width[6] . '"></td>';
    }
    if ($enable_vatamount_column && $final_details['taxtype'] != 'group') {
        $product_table .= '<td width="' . $width[7] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_vat, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_gross_column) {
        $product_table .= '<td width="' . $width[8] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_brutto_poz, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_taxes_inPLN == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
        if ($suma_podatku_w_pln != 0) {
            $product_table .= '<td width="' . $width[9] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_podatku_w_pln, 2) . '</b></small></td></tr></table></td>';
        } else {
            $product_table .= '<td width="' . $width[9] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>np</b></small></td></tr></table></td>';
        }
    }
    $product_table .= '</tr></table>';
    if ($final_details['taxtype'] == 'group') {
        $grup_tax = 0.0;
        for ($i = 0; $i < 3; $i++) {
            if ($associated_products[1]['final_details']['taxes'] == $associated_products[1]['final_details']['taxes'][$i]['taxname']) {
                $grup_tax += (double) $associated_products[1]['final_details']['taxes'][$i]['amount'];
                $grup_tax_percent += (double) $associated_products[1]['final_details']['taxes'][$i]['percentage'];
            }
        }
        $currfield = new CurrencyField($grup_tax);
        $grup_tax = $currfield->getDisplayValue();
        $currfield = new CurrencyField($grup_tax_percent);
        $grup_tax_percent = $currfield->getDisplayValue();
    }
    $mod = strtolower($pdftype);
    if ($mod == 'quotes') {
        $idcol = "quoteid";
    } else {
        $idcol = $mod . "id";
    }
    $sql = "SELECT discount_percent, discount_amount, subtotal, total FROM vtiger_{$mod} WHERE {$idcol} = " . $id;
    $result = $db->query($sql, true);
    $grand_total = $db->query_result($result, 0, 'total');
    $subtotal = $db->query_result($result, 0, "subtotal");
    $discount_percent = $db->query_result($result, 0, 'discount_percent');
    $discount_amount = $db->query_result($result, 0, 'discount_amount');
    if ($discount_percent != 0) {
        $discount = $subtotal * ($discount_percent / 100.0);
    } else {
        $discount = $discount_amount;
    }
    $currfield = new CurrencyField($grand_total);
    $grand_total = $currfield->getDisplayValue();
    $currfield = new CurrencyField($subtotal);
    $subtotal = $currfield->getDisplayValue();
    $currfield = new CurrencyField($discount);
    $discount = $currfield->getDisplayValue();
    $currfield = new CurrencyField($rabat_calkowity);
    $rabat_calkowity = $currfield->getDisplayValue();
    $currfield = new CurrencyField($netto);
    $netto = $currfield->getDisplayValue();
    if ($displays_a_summary_of_invoices) {
        $product_table .= '<table width="535px" border="0" cellpadding="0" cellspacing="0">
                            <tr>
                            <td width="85px"></td>
                            <td width="220px"><br />
                            <table bgcolor="#C0C0C0">';
        $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["SUMMARY"] . ' / ' . $tab_us["SUMMARY"] . '</b></small></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_TOGETHER"] . ' / ' . $tab_us["LBL_TOGETHER"] . '</b> :</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_BEFORE_CORRECTION"] . ' / ' . $tab_us["LBL_BEFORE_CORRECTION"] . '</b> :</small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_AFTER_CORRECTION"] . ' / ' . $tab_us["LBL_AFTER_CORRECTION"] . '</b> :</small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_INCLUDING"] . ' / ' . $tab_us["LBL_INCLUDING"] . '</b> :</small></td></tr>';
        }
        $razem_rabat = $faktura_rabat - $korekta_rabat;
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($razem_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($faktura_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($korekta_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($razem_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_netto, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            //$suma_netto_invoice = $suma_netto_invoice - $faktura_rabat;
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_netto_invoice, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_netto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_netto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_vat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_vat_inv, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_vat, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_vat, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($wartosc_korekty_brutto, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($subtotal_invoice, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_brutto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($wartosc_korekty_brutto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        $product_table .= '         
                            </table>
                    </td>
                    </tr></table>
                    <br/>';
    }
    //		$currfield = new CurrencyField( $grand_total );
    //$grand_total = $currfield->getDBInsertedValue( $grand_total );
    //$kwota = $this->slownie( $grand_total );
    //$content = str_replace( "#amount_words#",  $kwota , $content );
    return $product_table;
}
 function formatPrice($value, $decimal = 2)
 {
     $currencyField = new CurrencyField($value);
     return $currencyField->getDisplayValue(null, true);
 }
Exemplo n.º 9
0
 private function formatFldNumberValue($fld_value, $currency_id = "", $dec_number = "3")
 {
     global $log;
     $log->debug("Entering ./modules/ITS4YouReports/GenerateObj.php::formatFldNumberValue");
     global $log;
     $log->debug("Entering ./modules/ITS4YouReports/GenerateObj.php::formatFldNumberValue");
     global $log;
     $log->debug("Entering ./modules/ITS4YouReports/GenerateObj.php::formatFldNumberValue");
     global $log;
     $log->debug("Entering ./modules/ITS4YouReports/GenerateObj.php::formatFldNumberValue");
     if ($fld_value != "") {
         $fld_value = number_format($fld_value, $dec_number, ".", "");
         if ($currency_id != "" && isset($this->currency_symbols[$currency_id])) {
             $currencyField = new CurrencyField($fld_value);
             $fld_value = $currencyField->getDisplayValue(null, true);
             $fld_value = CurrencyField::appendCurrencySymbol($fld_value, $this->currency_symbols[$currency_id]);
         } else {
             $currencyField = new CurrencyField($fld_value);
             $fld_value = $currencyField->getDisplayValue(null, true);
         }
     }
     return $fld_value;
 }
Exemplo n.º 10
0
 function sanitizeCurrencyFieldsForDisplay($row, $meta)
 {
     global $current_user;
     $moduleFields = $meta->getModuleFields();
     foreach ($moduleFields as $fieldName => $fieldObj) {
         if (($fieldObj->getFieldDataType() == "currency" || $fieldObj->getFieldDataType() == "double") && !empty($row[$fieldName])) {
             $uitype = $fieldObj->getUIType();
             $cryFields = new CurrencyField($row[$fieldName]);
             $cryFields->initialize($current_user);
             if ($uitype == '71') {
                 $row[$fieldName] = $cryFields->getDisplayValue($current_user, false, true);
             } else {
                 if ($uitype == '72' || $uitype == '7' || $uitype == '9') {
                     $row[$fieldName] = $cryFields->getDisplayValue($current_user, true, true);
                 }
             }
         }
     }
     return $row;
 }
Exemplo n.º 11
0
/** This function returns the vtiger_field details for a given vtiger_fieldname.
 * Param $uitype - UI type of the vtiger_field
 * Param $fieldname - Form vtiger_field name
 * Param $fieldlabel - Form vtiger_field label name
 * Param $maxlength - maximum length of the vtiger_field
 * Param $col_fields - array contains the vtiger_fieldname and values
 * Param $generatedtype - Field generated type (default is 1)
 * Param $module_name - module name
 * Return type is an array
 */
function getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields, $generatedtype, $module_name, $mode = '', $typeofdata = null)
{
    global $log, $app_strings, $adb, $default_charset, $theme, $mod_strings, $current_user;
    $log->debug("Entering getOutputHtml(" . $uitype . "," . $fieldname . "," . $fieldlabel . "," . $maxlength . "," . print_r($col_fields, true) . "," . $generatedtype . "," . $module_name . ") method ...");
    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)) order by sequence', 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)) {
            if ($adb->num_rows($fldmod_result) == 1) {
                $valueType = $adb->query_result($fldmod_result, 0, 0);
            } else {
                $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);
    } else {
        if ($uitype == 5 || $uitype == 6 || $uitype == 23) {
            $log->info("uitype is " . $uitype);
            if ($value == '') {
                //modified to fix the issue in trac(http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/1469)
                if ($fieldname != 'birthday' && $generatedtype != 2 && getTabid($module_name) != 14) {
                    $disp_value = getNewDisplayDate();
                }
                if (($module_name == 'Events' || $module_name == 'Calendar') && $uitype == 6) {
                    $curr_time = date('H:i', strtotime('+5 minutes'));
                }
                if (($module_name == 'Events' || $module_name == 'Calendar') && $uitype == 23) {
                    $curr_time = date('H:i', strtotime('+10 minutes'));
                }
                //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");
                    $disp_value = DateTimeField::convertToUserFormat(date('Y-m-d', $addyear));
                } elseif ($fieldname == 'validtill' && $_REQUEST['module'] == 'Quotes') {
                    $disp_value = '';
                }
            } else {
                if ($uitype == 6) {
                    if ($col_fields['time_start'] != '' && ($module_name == 'Events' || $module_name == 'Calendar')) {
                        $curr_time = $col_fields['time_start'];
                        $value = $value . ' ' . $curr_time;
                    } else {
                        $curr_time = date('H:i', strtotime('+5 minutes'));
                    }
                }
                if (($module_name == 'Events' || $module_name == 'Calendar') && $uitype == 23) {
                    if ($col_fields['time_end'] != '') {
                        $curr_time = $col_fields['time_end'];
                        $value = $value . ' ' . $curr_time;
                    } else {
                        $curr_time = date('H:i', strtotime('+10 minutes'));
                    }
                }
                $disp_value = getValidDisplayDate($value);
            }
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']);
            if (!empty($curr_time)) {
                if (($module_name == 'Events' || $module_name == 'Calendar') && ($uitype == 23 || $uitype == 6)) {
                    $curr_time = DateTimeField::convertToUserTimeZone($curr_time);
                    $curr_time = $curr_time->format('H:i');
                }
            } else {
                $curr_time = '';
            }
            if (empty($disp_value)) {
                $disp_value = '';
            }
            $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 == 1613) {
            require_once 'modules/PickList/PickListUtils.php';
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $fieldname = $adb->sql_escape_string($fieldname);
            $pickListResult = getAllowedPicklistModules();
            $options = array();
            $options[] = "";
            $pickcount = 0;
            $found = false;
            foreach ($pickListResult as $pKey => $pValue) {
                $value = decode_html($value);
                $pickListValue = decode_html($pValue);
                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, $pickListValue), ENT_QUOTES, $default_charset), $pickListValue, $chk_val);
                } else {
                    $options[] = array(getTranslatedString($pickListValue, $pickListValue), $pickListValue, $chk_val);
                }
            }
            uasort($options, function ($a, $b) {
                return strtolower($a[0]) < strtolower($b[0]) ? -1 : 1;
            });
            $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);
            foreach ($valueArr as $key => $value) {
                $valueArr[$key] = trim(html_entity_decode($value, ENT_QUOTES, $default_charset));
            }
            $pickcount = 0;
            if (!empty($picklistValues)) {
                foreach ($picklistValues as $order => $pickListValue) {
                    if (in_array(trim($pickListValue), $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 == 3313) {
            require_once 'modules/PickList/PickListUtils.php';
            $picklistValues = getAllowedPicklistModules();
            $valueArr = explode("|##|", $value);
            foreach ($valueArr as $key => $value) {
                $valueArr[$key] = trim(html_entity_decode($value, ENT_QUOTES, $default_charset));
            }
            $pickcount = 0;
            if (!empty($picklistValues)) {
                foreach ($picklistValues as $order => $pickListValue) {
                    if (in_array(trim($pickListValue), $valueArr)) {
                        $chk_val = "selected";
                        $pickcount++;
                    } else {
                        $chk_val = '';
                    }
                    if (isset($_REQUEST['file']) && $_REQUEST['file'] == 'QuickCreate') {
                        $options[] = array(htmlentities(getTranslatedString($pickListValue, $pickListValue), ENT_QUOTES, $default_charset), $pickListValue, $chk_val);
                    } else {
                        $options[] = array(getTranslatedString($pickListValue, $pickListValue), $pickListValue, $chk_val);
                    }
                }
                if ($pickcount == 0 && !empty($value)) {
                    $options[] = array($app_strings['LBL_NOT_ACCESSIBLE'], $value, 'selected');
                }
            }
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            uasort($options, function ($a, $b) {
                return strtolower($a[0]) < strtolower($b[0]) ? -1 : 1;
            });
            $fieldvalue[] = $options;
        } elseif ($uitype == 1024) {
            $options = array();
            $arr_evo = explode(' |##| ', $value);
            $roleid = $current_user->roleid;
            $subrole = getRoleSubordinates($roleid);
            $uservalues = array_merge($subrole, array($roleid));
            for ($i = 0; $i < sizeof($uservalues); $i++) {
                $currentValId = $uservalues[$i];
                $currentValName = getRoleName($currentValId);
                if (in_array(trim($currentValId), $arr_evo)) {
                    $chk_val = 'selected';
                } else {
                    $chk_val = '';
                }
                $options[] = array($currentValName, $currentValId, $chk_val);
            }
            $fieldvalue[] = $options;
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
        } elseif ($uitype == 17) {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $fieldvalue[] = $value;
        } elseif ($uitype == 85) {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $fieldvalue[] = $value;
        } elseif ($uitype == 14) {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $fieldvalue[] = $value;
        } elseif ($uitype == 19 || $uitype == 20) {
            if (isset($_REQUEST['body'])) {
                $value = $_REQUEST['body'];
            }
            if ($fieldname == '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 ($fieldname == 'assigned_user_id' && $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);
            }
            $assigned_user_id = empty($value) ? $current_user->id : $value;
            if ($fieldname == 'assigned_user_id' && $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 ($fieldname == 'assigned_user_id' && $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 (!isset($_REQUEST['convertmode']) || $_REQUEST['convertmode'] != 'update_quote_val' && $_REQUEST['convertmode'] != 'update_so_val') {
                if (isset($_REQUEST['account_id']) && $_REQUEST['account_id'] != '') {
                    $value = vtlib_purify($_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', 'readwrite');
            }
            if ($uitype == 255 && $fieldpermission == '0') {
                $fieldvalue[] = '';
            } else {
                $fieldpermission = getFieldVisibilityPermission($module_name, $current_user->id, 'salutationtype', 'readwrite');
                if ($fieldpermission == '0') {
                    $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;
                } else {
                    $fieldvalue[] = '';
                }
            }
            $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 = vtlib_purify($_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 != '') {
                $displayValueArray = getEntityName('Contacts', $value);
                if (!empty($displayValueArray)) {
                    foreach ($displayValueArray as $key => $field_value) {
                        $contact_name = $field_value;
                    }
                }
            } elseif (isset($_REQUEST['contact_id']) && $_REQUEST['contact_id'] != '') {
                if ($_REQUEST['module'] == 'Contacts' && ($fieldname = 'contact_id')) {
                    $contact_name = '';
                } else {
                    $value = $_REQUEST['contact_id'];
                    $displayValueArray = getEntityName('Contacts', $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $contact_name = $field_value;
                        }
                    } else {
                        $contact_name = '';
                    }
                }
            }
            //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'] != "") {
                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=?';
                    $params = array($col_fields['record_id']);
                } else {
                    if ($module_name == 'Contacts') {
                        $imageattachment = 'Image';
                    } else {
                        $imageattachment = 'Attachment';
                    }
                    $query = "select vtiger_attachments.*,vtiger_crmentity.setype\n\t\t\t\t from vtiger_attachments\n\t\t\t\t inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid\n\t\t\t\t inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_attachments.attachmentsid\n\t\t\t\t where vtiger_crmentity.setype='{$module_name} {$imageattachment}'\n\t\t\t\t  and vtiger_attachments.name = ?\n\t\t\t\t  and vtiger_seattachmentsrel.crmid=?";
                    $params = array($col_fields[$fieldname], $col_fields['record_id']);
                }
                $result_image = $adb->pquery($query, $params);
                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 < count($image_array); $img_itr++) {
                        $fieldvalue[] = array('name' => $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 = vtlib_purify($_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") {
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $parent_name = $field_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 (!empty($_REQUEST['parent_id'])) {
                $value = vtlib_purify($_REQUEST['parent_id']);
            }
            if (!empty($value)) {
                $parent_module = getSalesEntityType($value);
                if ($parent_module != "Contacts") {
                    $entity_names = getEntityName($parent_module, $value);
                    $parent_name = $entity_names[$value];
                    $fieldvalue[] = $parent_name;
                    $fieldvalue[] = $value;
                }
            }
            // Check for vtiger_activity type if task orders to be added in select option
            $act_mode = $_REQUEST['activity_mode'];
            $parentModulesList = array('Leads' => $app_strings['COMBO_LEADS'], 'Accounts' => $app_strings['COMBO_ACCOUNTS'], 'Potentials' => $app_strings['COMBO_POTENTIALS'], 'HelpDesk' => $app_strings['COMBO_HELPDESK'], 'Campaigns' => $app_strings['COMBO_CAMPAIGNS'], 'Vendors' => $app_strings['COMBO_VENDORS']);
            if ($act_mode == "Task") {
                $parentModulesList['Quotes'] = $app_strings['COMBO_QUOTES'];
                $parentModulesList['PurchaseOrder'] = $app_strings['COMBO_PORDER'];
                $parentModulesList['SalesOrder'] = $app_strings['COMBO_SORDER'];
                $parentModulesList['Invoice'] = $app_strings['COMBO_INVOICES'];
            }
            $parentModuleNames = array_keys($parentModulesList);
            $parentModuleLabels = array_values($parentModulesList);
            $editview_label[0] = $parentModuleLabels;
            $editview_label[1] = array_fill(0, count($parentModulesList), '');
            $selectedModuleIndex = array_search($parent_module, $parentModuleNames);
            if ($selectedModuleIndex > -1) {
                $editview_label[1][$selectedModuleIndex] = 'selected';
            }
            $parentModulePopupUrl = array();
            foreach ($parentModuleNames as $parentModule) {
                $parentModulePopupUrl[] = $parentModule . '&action=Popup';
            }
            $editview_label[2] = $parentModulePopupUrl;
        } 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';
            } elseif ($pmodule == 'Project') {
                $project_selected = 'selected';
            } elseif ($pmodule == 'ProjectTask') {
                $projecttask_selected = 'selected';
            } elseif ($pmodule == 'Potentials') {
                $potentials_selected = 'selected';
            } elseif ($pmodule == 'HelpDesk') {
                $helpdesk_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';
                    } elseif ($pmodule == 'Project') {
                        require_once 'modules/Project/Project.php';
                        $myfocus = new Project();
                        $myfocus->retrieve_entity_info($entityid, "Project");
                        $fname = br2nl($myfocus->column_fields['projectname']);
                        $lname = br2nl($myfocus->column_fields['projectid']);
                        $fullname = $fname;
                        $project_selected = 'selected';
                    } elseif ($pmodule == 'ProjectTask') {
                        require_once 'modules/ProjectTask/ProjectTask.php';
                        $myfocus = new ProjectTask();
                        $myfocus->retrieve_entity_info($entityid, "ProjectTask");
                        $fname = br2nl($myfocus->column_fields['projecttaskname']);
                        $lname = br2nl($myfocus->column_fields['projecttaskid']);
                        $fullname = $fname;
                        $projecttask_selected = 'selected';
                    } elseif ($pmodule == 'Potentials') {
                        require_once 'modules/Potentials/Potentials.php';
                        $myfocus = new Potentials();
                        $myfocus->retrieve_entity_info($entityid, "Potentials");
                        $fname = br2nl($myfocus->column_fields['potentialname']);
                        $lname = br2nl($myfocus->column_fields['potentialid']);
                        $fullname = $fname;
                        $potentials_selected = 'selected';
                    } elseif ($pmodule == 'HelpDesk') {
                        require_once 'modules/HelpDesk/HelpDesk.php';
                        $myfocus = new HelpDesk();
                        $myfocus->retrieve_entity_info($entityid, "HelpDesk");
                        $fname = br2nl($myfocus->column_fields['title']);
                        $lname = br2nl($myfocus->column_fields['ticketid']);
                        $fullname = $fname;
                        $helpdesk_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 .= '<br>';
                            $temp_parent_name = '';
                        }
                        if ($temp1 != '') {
                            $parent_name .= $fullname . '&lt;' . $temp1 . '&gt;; ';
                            $temp_parent_name .= $fullname . '&lt;' . $temp1 . '&gt;; ';
                        } else {
                            $parent_name .= "<b style='color:red'>" . $fullname . '&lt;' . $temp1 . '&gt;; ' . "</b>";
                            $temp_parent_name .= "<b style='color:red'>" . $fullname . '&lt;' . $temp1 . '&gt;; ' . "</b>";
                        }
                    }
                }
            } 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 .= '<td width="20%" class="dataLabel">' . $app_strings['To'] . '&nbsp;</td>';
                $custfld .= '<td width="90%" colspan="3"><input name="parent_id" type="hidden" value="' . $parent_id . '"><textarea readonly name="parent_name" cols="70" rows="2">' . $parent_name . '</textarea>&nbsp;<select name="parent_type" >';
                $custfld .= '<OPTION value="Contacts" selected>' . $app_strings['COMBO_CONTACTS'] . '</OPTION>';
                $custfld .= '<OPTION value="Accounts" >' . $app_strings['COMBO_ACCOUNTS'] . '</OPTION>';
                $custfld .= '<OPTION value="Leads" >' . $app_strings['COMBO_LEADS'] . '</OPTION>';
                $custfld .= '<OPTION value="Vendors" >' . $app_strings['COMBO_VENDORS'] . '</OPTION></select><img src="' . vtiger_imageurl('select.gif', $theme) . '" alt="Select" title="Select" LANGUAGE=javascript onclick=\'$log->debug("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\'>&nbsp;<input type="image" src="' . vtiger_imageurl('clear_field.gif', $theme) . '" alt="Clear" title="Clear" LANGUAGE=javascript onClick="this.form.parent_id.value=\'\';this.form.parent_name.value=\'\';$log->debug("Exiting getOutputHtml method ..."); return false;" align="absmiddle" style=\'cursor:hand;cursor:pointer\'></td>';
                $editview_label[] = array('Contacts' => $contact_selected, 'Accounts' => $account_selected, 'Vendors' => $vendor_selected, 'Leads' => $lead_selected, 'Users' => $user_selected);
                $fieldvalue[] = $parent_name;
                $fieldvalue[] = $parent_id;
            }
        } elseif ($uitype == 68) {
            if (empty($value) && isset($_REQUEST['parent_id']) && $_REQUEST['parent_id'] != '') {
                $value = vtlib_purify($_REQUEST['parent_id']);
            }
            if ($value != '') {
                $parent_module = getSalesEntityType($value);
                if ($parent_module == "Contacts") {
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $parent_name = $field_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[0] = array();
            $editview_label[1] = array();
            $editview_label[2] = array();
            if (vtlib_isModuleActive('Accounts')) {
                array_push($editview_label[0], $app_strings['COMBO_ACCOUNTS']);
                array_push($editview_label[1], $account_selected);
                array_push($editview_label[2], "Accounts");
            }
            if (vtlib_isModuleActive('Contacts')) {
                array_push($editview_label[0], $app_strings['COMBO_CONTACTS']);
                array_push($editview_label[1], $contact_selected);
                array_push($editview_label[2], "Contacts");
            }
            $fieldvalue[] = $parent_name;
            $fieldvalue[] = $value;
        } elseif ($uitype == 9 || $uitype == 7) {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $fldrs = $adb->pquery('select typeofdata from vtiger_field
			where vtiger_field.fieldname=? and vtiger_field.tabid=?', array($fieldname, getTabid($module_name)));
            $typeofdata = $adb->query_result($fldrs, 0, 0);
            $typeinfo = explode('~', $typeofdata);
            if ($typeinfo[0] == 'I') {
                $fieldvalue[] = $value;
            } else {
                $currencyField = new CurrencyField($value);
                $decimals = CurrencyField::getDecimalsFromTypeOfData($typeofdata);
                $currencyField->initialize($current_user);
                $currencyField->setNumberofDecimals(min($decimals, $currencyField->getCurrencyDecimalPlaces()));
                $fieldvalue[] = $currencyField->getDisplayValue(null, false, true);
            }
        } elseif ($uitype == 71 || $uitype == 72) {
            $currencyField = new CurrencyField($value);
            // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
            if ($col_fields['record_id'] != '' && $uitype == 72) {
                if ($fieldname == 'unit_price') {
                    $rate_symbol = getCurrencySymbolandCRate(getProductBaseCurrency($col_fields['record_id'], $module_name));
                    $currencySymbol = $rate_symbol['symbol'];
                } else {
                    $currency_info = getInventoryCurrencyInfo($module, $col_fields['record_id']);
                    $currencySymbol = $currency_info['currency_symbol'];
                }
                $fieldvalue[] = $currencyField->getDisplayValue(null, true);
            } else {
                $decimals = CurrencyField::getDecimalsFromTypeOfData($typeofdata);
                $currencyField->initialize($current_user);
                $currencyField->setNumberofDecimals(min($decimals, $currencyField->getCurrencyDecimalPlaces()));
                $fieldvalue[] = $currencyField->getDisplayValue(null, false, true);
                $currencySymbol = $currencyField->getCurrencySymbol();
            }
            $editview_label[] = getTranslatedString($fieldlabel, $module_name) . ': (' . $currencySymbol . ')';
        } 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';
            } else {
                $SET_REM = '';
            }
            $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(10, 59, 'remmin', $rem_min);
            $fieldvalue[] = array(array(0, 32, 'remdays', getTranslatedString('LBL_DAYS', 'Calendar'), $rem_days), array(0, 24, 'remhrs', getTranslatedString('LBL_HOURS', 'Calendar'), $rem_hrs), array(10, 60, 'remmin', getTranslatedString('LBL_MINUTES', 'Calendar') . '&nbsp;&nbsp;' . getTranslatedString('LBL_BEFORE_EVENT', 'Calendar'), $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 < count($image_array); $img_itr++) {
                    $fieldvalue[] = array('name' => $image_array[$img_itr], 'path' => $image_path_array[$img_itr]);
                }
            } else {
                $fieldvalue[] = '';
            }
        } elseif ($uitype == 101) {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $fieldvalue[] = getOwnerName($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 == 'E') {
                $external_selected = "selected";
                $filename = $col_fields['filename'];
            } else {
                $internal_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;
        } elseif ($uitype == '31') {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $options = array();
            $themeList = get_themes();
            foreach ($themeList as $theme) {
                if ($value == $theme) {
                    $selected = 'selected';
                } else {
                    $selected = '';
                }
                $options[] = array(getTranslatedString($theme), $theme, $selected);
            }
            $fieldvalue[] = $options;
        } elseif ($uitype == '32') {
            $editview_label[] = getTranslatedString($fieldlabel, $module_name);
            $options = array();
            $languageList = Vtiger_Language::getAll();
            foreach ($languageList as $prefix => $label) {
                if ($value == $prefix) {
                    $selected = 'selected';
                } else {
                    $selected = '';
                }
                $options[] = array(getTranslatedString($label), $prefix, $selected);
            }
            $fieldvalue[] = $options;
        } 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 ($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("/<input/iS", "<input id='{$fieldname}' ", $custfld);
    }
    if (in_array($uitype, array(71, 72, 7, 9, 90))) {
        $custfld = preg_replace("/<input/iS", "<input align=right ", $custfld);
    }
    $final_arr[] = $ui_type;
    $final_arr[] = $editview_label;
    $final_arr[] = $editview_fldname;
    $final_arr[] = $fieldvalue;
    $type_of_data = explode('~', $typeofdata);
    $final_arr[] = $type_of_data[1];
    $log->debug('Exiting getOutputHtml method ...');
    return $final_arr;
}
Exemplo n.º 12
0
    public function process()
    {
        global $site_URL;
        $imagefound = false;
        $variableList = $this->getTemplateVariableListForModule($this->module);
        $handler = vtws_getModuleHandlerFromName($this->module, $this->user);
        $meta = $handler->getMeta();
        $referenceFields = $meta->getReferenceFieldDetails();
        $fieldColumnMapping = $meta->getFieldColumnMapping();
        $columnTableMapping = $meta->getColumnTableMapping();
        $tableList = array();
        $columnList = array();
        $columnList_full = array();
        $allColumnList = $meta->getUserAccessibleColumns();
        if (count($variableList) > 0) {
            foreach ($variableList as $column) {
                if (in_array($column, $allColumnList)) {
                    $columnList[] = $column;
                    $columnList_full[] = $columnTableMapping[$column] . '.' . $column;
                }
            }
            foreach ($columnList as $column) {
                if (!empty($columnTableMapping[$column])) {
                    $tableList[$columnTableMapping[$column]] = '';
                }
            }
            $tableList = array_keys($tableList);
            $defaultTableList = $meta->getEntityDefaultTableList();
            $tableList = array_merge($tableList, $defaultTableList);
            $leadtables = array('vtiger_leadsubdetails', 'vtiger_leadaddress', 'vtiger_leadscf');
            $leadmerge = array_intersect($tableList, $leadtables);
            if (count($leadmerge) > 0 and !in_array('vtiger_leaddetails', $tableList)) {
                // we need this one because the where condition for Leads uses the converted column from the main table
                $tableList[] = 'vtiger_leaddetails';
            }
            // right now this is will be limited to module type, entities.
            // need to extend it to non-module entities when we have a reliable way of getting
            // record type from the given record id. non webservice id.
            // can extend to non-module entity without many changes as long as the reference field
            // refers to one type of entity, either module entities or non-module entities.
            if (count($tableList) > 0) {
                $sql = 'select ' . implode(', ', $columnList_full) . ' from ' . $tableList[0];
                $moduleTableIndexList = $meta->getEntityTableIndexList();
                foreach ($tableList as $index => $tableName) {
                    if ($tableName != $tableList[0]) {
                        $sql .= ' INNER JOIN ' . $tableName . ' ON ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=' . $tableName . '.' . $moduleTableIndexList[$tableName];
                    }
                }
                $sql .= ' WHERE';
                $deleteQuery = $meta->getEntityDeletedQuery();
                if (!empty($deleteQuery)) {
                    $sql .= " {$deleteQuery} AND";
                }
                $sql .= ' ' . $tableList[0] . '.' . $moduleTableIndexList[$tableList[0]] . '=?';
                $params = array($this->recordId);
                $db = PearDatabase::getInstance();
                $result = $db->pquery($sql, $params);
                $it = new SqlResultIterator($db, $result);
                //assuming there can only be one row.
                $values = array();
                foreach ($it as $row) {
                    foreach ($columnList as $column) {
                        $values[$column] = $row->get($column);
                    }
                }
                $moduleFields = $meta->getModuleFields();
                foreach ($moduleFields as $fieldName => $webserviceField) {
                    if (isset($values[$fieldColumnMapping[$fieldName]]) && $values[$fieldColumnMapping[$fieldName]] !== null) {
                        $fieldtype = $webserviceField->getFieldDataType();
                        if (strcasecmp($fieldtype, 'reference') === 0) {
                            $details = $webserviceField->getReferenceList();
                            if (count($details) == 1) {
                                $referencedObjectHandler = vtws_getModuleHandlerFromName($details[0], $this->user);
                            } else {
                                $type = getSalesEntityType($values[$fieldColumnMapping[$fieldName]]);
                                $referencedObjectHandler = vtws_getModuleHandlerFromName($type, $this->user);
                            }
                            $referencedObjectMeta = $referencedObjectHandler->getMeta();
                            $values[$fieldColumnMapping[$fieldName]] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldColumnMapping[$fieldName]]));
                        } elseif (strcasecmp($fieldtype, 'owner') === 0) {
                            $referencedObjectHandler = vtws_getModuleHandlerFromName(vtws_getOwnerType($values[$fieldColumnMapping[$fieldName]]), $this->user);
                            $referencedObjectMeta = $referencedObjectHandler->getMeta();
                            $values[$fieldColumnMapping[$fieldName]] = $referencedObjectMeta->getName(vtws_getId($referencedObjectMeta->getEntityId(), $values[$fieldColumnMapping[$fieldName]]));
                        } elseif (strcasecmp($fieldtype, 'picklist') === 0 or $fieldName == 'salutationtype') {
                            $values[$fieldColumnMapping[$fieldName]] = getTranslatedString($values[$fieldColumnMapping[$fieldName]], $this->module);
                        } elseif (strcasecmp($fieldtype, 'datetime') === 0) {
                            $values[$fieldColumnMapping[$fieldName]] = $values[$fieldColumnMapping[$fieldName]] . ' ' . DateTimeField::getDBTimeZone();
                        } elseif (strcasecmp($fieldtype, 'currency') === 0 or strcasecmp($fieldtype, 'double') === 0) {
                            $currencyField = new CurrencyField($values[$fieldColumnMapping[$fieldName]]);
                            $values[$fieldColumnMapping[$fieldName]] = $currencyField->getDisplayValue(null, true);
                        } elseif ($webserviceField->getUIType() == 69) {
                            $query = 'select vtiger_attachments.name, vtiger_attachments.type, vtiger_attachments.attachmentsid, vtiger_attachments.path
									from vtiger_attachments
									inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid
									inner join vtiger_seattachmentsrel on vtiger_attachments.attachmentsid=vtiger_seattachmentsrel.attachmentsid
									where (vtiger_crmentity.setype LIKE "%Image" or vtiger_crmentity.setype LIKE "%Attachment")
									  and deleted=0 and vtiger_seattachmentsrel.crmid=?';
                            $params = array($this->recordId);
                            if (!empty($values[$fieldColumnMapping[$fieldName]])) {
                                $query .= ' and vtiger_attachments.name = ?';
                                $params[] = $values[$fieldColumnMapping[$fieldName]];
                            }
                            $result_image = $db->pquery($query, $params);
                            if ($db->num_rows($result_image) > 0) {
                                $img = $db->fetch_array($result_image);
                                $fullpath = $site_URL . '/' . $img['path'] . $img['attachmentsid'] . '_' . $img['name'];
                                $values[$fieldColumnMapping[$fieldName] . '_fullpath'] = $fullpath;
                                $values[$fieldColumnMapping[$fieldName]] = $img['name'];
                                $imagefound = true;
                            }
                        }
                    }
                }
                foreach ($columnList as $column) {
                    if ($imagefound) {
                        $needle = '$' . strtolower($this->module) . "-{$column}" . '_fullpath$';
                        $this->processedDescription = str_replace($needle, $values[$column . '_fullpath'], $this->processedDescription);
                    }
                    $needle = '$' . strtolower($this->module) . "-{$column}\$";
                    $this->processedDescription = str_replace($needle, $values[$column], $this->processedDescription);
                }
            }
        }
        $this->processed = true;
    }
Exemplo n.º 13
0
function replaceProductTable($pdftype, $id, $templateid, $content, $tcpdf)
{
    $permitted_modules = vglobal('permitted_modules');
    if (in_array($pdftype, $permitted_modules)) {
        /* ------------------- COLUMN CONFIGURATION -------------------
        
              In this part, you can decide which columns you want to appear
                               and which are not in the table of positions and invoice summary table
        
                               If the variable responsible for this column has the value TRUE
                               will be displayed and if FALSE it will not be displayed
        
             */
        // The columns for the table from the list of items on the invoice
        $kolumnyDlaPozycjiFaktur = array();
        // column ordinal
        $enable_ordinal_column = TRUE;
        // Column name of the product
        $enable_productname_column = TRUE;
        // column number
        $enable_amount_column = TRUE;
        // unit price column
        $enable_listprice_column = TRUE;
        // net price column
        $enable_netprice_column = TRUE;
        // discount column
        $enable_discount_column = TRUE;
        // Vat column (%)
        $enable_vatpercentage_column = TRUE;
        // Vat column (currency)
        $enable_vatamount_column = TRUE;
        // Gross column
        $enable_gross_column = TRUE;
        // Taxes in PLN
        $enable_taxes_inPLN = TRUE;
        // Column for a summary in the gray box
        $wyswietlaj = array($enable_ordinal_column, $enable_productname_column, $enable_amount_column, $enable_listprice_column, $enable_netprice_column, $enable_discount_column, $enable_vatpercentage_column, $enable_vatamount_column, $enable_gross_column, $enable_taxes_inPLN);
        $kolumnyDlaPodsumowaniaFaktur = array();
        // shipping costs
        $enable_summary_shipping = TRUE;
        // tax on shipping costs
        $enable_summary_shippingtax = TRUE;
        // correction
        $enable_summary_correction = TRUE;
        // to pay
        $enable_summary_topay = TRUE;
        // total rebate
        $enable_summary_rebate = TRUE;
        // the percentage of tax column
        $enable_summary_taxpercentage = TRUE;
        // tax amount column
        $enable_summary_taxamount = TRUE;
        //show the date of the course
        $enable_date_of_the_course = TRUE;
        //----------------------------------------------------
        $newdate = vglobal('newdate');
        $current_user = vglobal('current_user');
        $adb = PearDatabase::getInstance();
        $currentModule = vglobal('currentModule');
        require_once 'include/utils/utils.php';
        $current_language = Users_Record_Model::getCurrentUserModel()->get('language');
        include "languages/" . $current_language . "/OSSPdf.php";
        include_once "languages/" . $current_language . "/Vtiger.php";
        require_once 'include/utils/CommonUtils.php';
        require_once 'include/fields/CurrencyField.php';
        require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
        $displays_a_summary_of_invoices = TRUE;
        if ($pdftype == 'OSSCorrectedInvoice') {
            require_once 'modules/' . $pdftype . '/utils.php';
            $displays_a_summary_of_invoices = FALSE;
            $pdftype = 'Invoice';
            $id_sql = "SELECT invoiceid FROM vtiger_osscorrectedinvoice WHERE osscorrectedinvoiceid = {$id}";
            $id_result = $adb->query($id_sql, true);
            $id = $adb->query_result($id_result, 0, 'invoiceid');
        }
        $focus = new $pdftype();
        $focus->retrieve_entity_info($id, $pdftype);
        $currency_id = $focus->column_fields['currency_id'];
        $pobierz = $adb->query("select currency_symbol, currency_code from vtiger_currency_info where id = '{$currency_id}'", true);
        $symbol_waluty = $adb->query_result($pobierz, 0, "currency_symbol");
        $kod_aktualnej_waluty = $adb->query_result($pobierz, 0, "currency_code");
        $focus->id = $focus->column_fields["record_id"];
        if ($pdftype == 'OSSInvoiceCost') {
            $associated_products = OSSgetAssociatedProducts($pdftype, $focus);
        } else {
            $associated_products = getAssociatedProducts($pdftype, $focus);
        }
        $czyDrukowacKolumneZPrzeliczonymPodatkiem = FALSE;
        $moduleFilePath = "modules/OSSCurrencyUpdate/OSSCurrencyUpdate.php";
        $moduleFilePathTpl = "Smarty/templates/modules/OSSCurrencyUpdate/index.tpl";
        $checkInDatabaseSql = "SELECT * FROM vtiger_tab WHERE name = 'OSSCurrencyUpdate'";
        $pobierzGluwnaWaluteSql = $adb->query("select currency_code from vtiger_currency_info where id = '1'", true);
        $kod_waluty = $adb->query_result($pobierzGluwnaWaluteSql, 0, "currency_code");
        $checkInDatabaseResult = $adb->query($checkInDatabaseSql, true);
        $numDB = $adb->num_rows($checkInDatabaseResult);
        if (file_exists($moduleFilePath) && file_exists($moduleFilePathTpl) && $numDB > 0 && $kod_waluty == 'PLN' && $kod_aktualnej_waluty != 'PLN' && vtlib_isModuleActive('OSSCurrencyUpdate')) {
            $czyDrukowacKolumneZPrzeliczonymPodatkiem = TRUE;
        }
        if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            require_once $moduleFilePath;
        }
        $num_products = count($associated_products);
        $vat = array();
        $sales = array();
        $service = array();
        $total_discount = 0.0;
        $suma_netto = 0.0;
        $suma_brutto = $associated_products[1]['final_details']['grandTotal'];
        $rabat_calkowity = $associated_products[1]['final_details']['discountTotal_final'];
        $suma_vat = 0;
        /////////////////////////////
        /// Create a table summary of VAT
        if ($focus->column_fields['hdnTaxType'] == 'group') {
            for ($i = 1; $i <= count($associated_products); $i++) {
                $total_discount += $associated_products[$i]['discountTotal' . $i];
                $suma_netto += $associated_products[$i]['listPrice' . $i] - $total_discount;
            }
        } else {
            for ($i = 1; $i <= count($associated_products); $i++) {
                $TotalAfterDiscount = $associated_products[$i]['totalAfterDiscount' . $i];
                $suma_netto += $TotalAfterDiscount;
                foreach ($associated_products[$i]['taxes'] as $podatek) {
                    if ($podatek['taxlabel'] == 'VAT') {
                        $vat[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                        $suma_vat += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    }
                    if ($podatek['taxlabel'] == 'Sales') {
                        $sales[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    }
                    if ($podatek['taxlabel'] == 'Service') {
                        $service[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    }
                }
                // Calculating the total discount
                $total_discount += $associated_products[$i]['discountTotal' . $i];
            }
        }
        ///////////////////////////////////////////////////////////
        //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
        $final_details = $associated_products[1]['final_details'];
        //getting the Net Total
        $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
        //Final discount amount/percentage
        $discount_amount = $final_details["discount_amount_final"];
        $discount_percent = $final_details["discount_percentage_final"];
        if ($discount_amount != "") {
            $price_discount = number_format($discount_amount, 2, '.', ',');
            $price_disc = $discount_amount;
        } else {
            if ($discount_percent != "") {
                //This will be displayed near Discount label - used in include/fpdf/templates/body.php
                $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
                $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
                $price_disc = $discount_percent * $final_details["hdnSubTotal"];
            } else {
                $price_discount = "0.00";
            }
        }
        //Grand Total
        $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
        //To calculate the group tax amount
        if ($final_details['taxtype'] == 'group') {
            $group_tax_total = $final_details['tax_totalamount'];
            $price_salestax = number_format($group_tax_total, 2, '.', ',');
            $group_total_tax_percent = '0.00';
            $group_tax_details = $final_details['taxes'];
            for ($i = 0; $i < count($group_tax_details); $i++) {
                $group_total_tax_percent = $group_total_tax_percent + $group_tax_details[$i]['percentage'];
            }
        }
        $podatek_grupowy = ($final_details["hdnSubTotal"] - $price_disc) * ($group_total_tax_percent / 100.0);
        $prod_line = array();
        $lines = 0;
        //This is to get all prodcut details as row basis
        for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
            $product_name[$i] = $associated_products[$i]['productName' . $i];
            $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
            $comment[$i] = $associated_products[$i]['comment' . $i];
            $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
            $qty[$i] = $associated_products[$i]['qty' . $i];
            $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
            $list_price[$i] = $associated_products[$i]['listPrice' . $i];
            // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
            $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
            $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
            $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
            $taxable_total = $qty[$i] * $list_pricet[$i] - $discount_total[$i];
            $producttotal = $taxable_total;
            $total_taxes = '0.00';
            if ($focus->column_fields["hdnTaxType"] == "individual") {
                $total_tax_percent = '0.00';
                //This loop is to get all tax percentage and then calculate the total of all taxes
                for ($tax_count = 0; $tax_count < count($associated_products[$i]['taxes']); $tax_count++) {
                    $tax_percent = $associated_products[$i]['taxes'][$tax_count]['percentage'];
                    $total_tax_percent = $total_tax_percent + $tax_percent;
                    $tax_amount = $taxable_total * $tax_percent / 100;
                    $total_taxes = $total_taxes + $tax_amount;
                }
                $producttotal = $taxable_total + $total_taxes;
                $product_line[$j]["tax_percentage"] = $total_tax_percent;
                $product_line[$j]["Tax"] = $total_taxes;
                $price_salestax += $total_taxes;
            }
            $prod_total[$i] = $producttotal;
            // number_format($producttotal,2,'.',',');
            $product_line[$j]["Product Code"] = $product_code[$i];
            $product_line[$j]["Qty"] = $qty[$i];
            $product_line[$j]["Price"] = $list_price[$i];
            $product_line[$j]["Discount"] = $discount_total[$i];
            $product_line[$j]["Total"] = $prod_total[$i];
            $lines++;
            $product_line[$j]["Product Name"] = '<b>' . decode_html($product_name[$i]) . '</b>';
            $prod_line[$j] = 1;
            for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
                if ($lines % 12 != 0) {
                    if ($subproduct_name[$i][$count] != '') {
                        $product_line[$j]["Product Name"] .= "\n <br />" . '<font color="grey" size="-1"><em>' . decode_html($subproduct_name[$i][$count]) . '</em></font>';
                        $prod_line[$j]++;
                    }
                } else {
                    $j++;
                    $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                    $product_line[$j]["Product Name"] .= "\n <br />" . decode_html($subproduct_name[$i][$count]);
                    $prod_line[$j] = 2;
                    $lines++;
                }
                $lines++;
            }
            if ($comment[$i] != '') {
                $product_line[$j]["Product Name"] .= "\n" . '<br />' . decode_html($comment[$i]);
                $prod_line[$j]++;
                $lines++;
            }
        }
        $tax_pl = 0;
        if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            //invoicedate
            $invoice_date_sql = "SELECT invoicedate FROM `vtiger_invoice` WHERE invoiceid = {$id}";
            $invoice_date_result = $adb->query($invoice_date_sql, true);
            $invoice_date = $adb->query_result($invoice_date_result, 0, 'invoicedate');
            $date = $invoice_date;
            $newdate = strtotime('-1 day', strtotime($date));
            $newdate = date('Y-m-d', $newdate);
            $CurrencyUpdate = Vtiger_Record_Model::getCleanInstance('OSSCurrencyUpdate');
            $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
            $num_rate = $adb->num_rows($kurs_waluty_result, true);
            $kurs_waluty = '0.00';
            if ($num_rate != 0) {
                $kurs_waluty = (double) $adb->query_result($kurs_waluty_result, 0, 'kurs');
                $newdate = date('Y-m-d', strtotime($adb->query_result($kurs_waluty_result, 0, "data_faktyczna_kursu")));
            } else {
                $CurrencyUpdate->getCurrency($newdate);
                $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
                $num_rate = $adb->num_rows($kurs_waluty_result);
                if ($num_rate != 0) {
                    $kurs_waluty = (double) $adb->query_result($kurs_waluty_result, 0, 'kurs');
                }
            }
        }
        $price_salestax = number_format($price_salestax, 2, '.', ',');
        if ($final_details['taxtype'] == 'group') {
            $header = array();
            if ($enable_ordinal_column) {
                $header[0] = vtranslate('LBL_nr', 'OSSPdf');
            }
            if ($enable_productname_column) {
                $header[1] = vtranslate('LBL_productname', 'OSSPdf');
            }
            if ($enable_amount_column) {
                $header[2] = vtranslate('LBL_Quantity', 'OSSPdf');
            }
            if ($enable_listprice_column) {
                $header[3] = vtranslate('LBL_price', 'OSSPdf');
            }
            if ($enable_netprice_column) {
                $header[4] = vtranslate('LBL_rabat', 'OSSPdf');
            }
            if ($enable_discount_column) {
                $header[5] = vtranslate('LBL_netto', 'OSSPdf');
            }
            if ($enable_gross_column) {
                $header[6] = vtranslate('LBL_brutto', 'OSSPdf');
            }
        } else {
            $header = array();
            if ($enable_ordinal_column) {
                $header[0] = vtranslate('LBL_nr', 'OSSPdf');
            }
            if ($enable_productname_column) {
                $header[1] = vtranslate('LBL_productname', 'OSSPdf');
            }
            if ($enable_amount_column) {
                $header[2] = vtranslate('LBL_Quantity', 'OSSPdf');
            }
            if ($enable_listprice_column) {
                $header[3] = vtranslate('LBL_price', 'OSSPdf');
            }
            if ($enable_netprice_column) {
                $header[4] = vtranslate('LBL_rabat', 'OSSPdf');
            }
            if ($enable_discount_column) {
                $header[5] = vtranslate('LBL_netto', 'OSSPdf');
            }
            if ($enable_vatpercentage_column) {
                $header[6] = vtranslate('LBL_vat', 'OSSPdf');
            }
            if ($enable_vatamount_column) {
                $header[7] = vtranslate('LBL_vat_waluta', 'OSSPdf') . " (" . $symbol_waluty . ")";
            }
            if ($enable_gross_column) {
                $header[8] = vtranslate('LBL_brutto', 'OSSPdf');
            }
            if ($enable_taxes_inPLN == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                $header[9] = vtranslate('TAXES_IN_PLN', 'OSSPdf');
            }
        }
        $data = array();
        $i = 1;
        $suma_podatku_w_pln = 0.0;
        $tax_percentage_array = array();
        foreach ($product_line as $item) {
            $currfield = new CurrencyField($item["tax_percentage"]);
            $tax_percentage = $currfield->getDisplayValue();
            $tax_percentage_array[$i] = $tax_percentage;
            if ($final_details['taxtype'] == 'group') {
                $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
                // $currfield = new CurrencyField($netto);
                // $currfield->getDBInsertedValue();
                // $netto = $currfield->getDisplayValue();
                // $currfield = new CurrencyField((float) $item['Price']);
                // $currfield->getDBInsertedValue();
                $item['Price'] = (double) $item['Price'];
                // $currfield = new CurrencyField((float) $item['Discount']);
                // $currfield->getDBInsertedValue();
                $item['Discount'] = (double) $item['Discount'];
                // $currfield = new CurrencyField((float) $item['Total']);
                // $currfield->getDBInsertedValue();
                $item['Total'] = (double) $item['Total'];
                $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $item['Total']);
            } else {
                $tax_pln = $item['Tax'] * $kurs_waluty;
                $suma_podatku_w_pln += $tax_pln;
                //$currfield = new CurrencyField( $tax_pln );
                //$tax_pln = $currfield->getDisplayValue();
                $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
                //$currfield = new CurrencyField( $netto );
                //$currfield->getDBInsertedValue();
                //$netto = $currfield->getDisplayValue();
                ////////
                //$currfield = new CurrencyField( (float)$item['Price'] );
                //$currfield->getDBInsertedValue();
                $item['Price'] = (double) $item['Price'];
                //$currfield->getDisplayValue();
                ////////
                $currfield = new CurrencyField((double) $item['Discount']);
                $currfield->getDBInsertedValue();
                $item['Discount'] = (double) $item['Discount'];
                //$currfield->getDisplayValue();
                /////////
                //$currfield = new CurrencyField( (float)$item['tax_percentage'] );
                //$currfield->getDBInsertedValue();
                $tax_percentage = (double) $item['tax_percentage'];
                //$currfield->getDisplayValue();
                //////////
                //$currfield = new CurrencyField( (float)$item['Tax'] );
                //$currfield->getDBInsertedValue();
                $item['Tax'] = (double) $item['Tax'];
                //$currfield->getDisplayValue();
                ///////////
                //$currfield = new CurrencyField( (float)$item['Total'] );
                //$currfield->getDBInsertedValue();
                $item['Total'] = (double) $item['Total'];
                //$currfield->getDisplayValue();
                ////////////
                $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $tax_percentage, $item['Tax'], $item['Total'], $tax_pln);
            }
            $i++;
        }
        if ($final_details['taxtype'] == 'group') {
            $width = array(30, 200, 50, 60, 50, 70, 70);
            $align = array("center", "center", "center", "center", "center", "center", "center");
            $format = array(0, "s", 0, 2, 2, 2, 2);
        } else {
            $width = array(30, 180, 50, 60, 50, 40, 40, 40, 40, 40);
            $align = array("center", "center", "center", "center", "center", "center", "center", "center", "center", "center");
            $format = array(0, "s", 0, 2, 2, 2, 2, 2, 2);
        }
        $product_table = '<table cellpadding="2">';
        $product_table .= '<tr style="background-color: #c8c8c8;" >';
        foreach ($header as $lastKey => $val) {
            $product_table .= '<td style="border:0.2mm solid black;" width="' . $width[$lastKey] . '" height="20" align="' . $align[$lastKey] . '"><b><small>' . $val . '</small></b></td>';
        }
        $product_table .= '</tr>';
        $group_sep = ' ';
        $separatorSql = "SELECT currency_decimal_separator FROM vtiger_users WHERE id = '{$current_user->id}'";
        $separatorResult = $adb->query($separatorSql, true);
        $dec_sep = $adb->query_result($separatorResult, 0, 'currency_decimal_separator');
        $group_sep = $adb->query_result($separatorResult, 0, 'currency_grouping_separator');
        if ($dec_sep == '') {
            $dec_sep = ' ';
        }
        $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center", "center");
        $i = 0;
        foreach ($data as $row) {
            $product_table .= '<tr>';
            $tax_percentage = $tax_percentage_array[$i];
            foreach ($row as $key => $item) {
                if ($format[$i] != 's') {
                    //echo $item;
                } else {
                    $itarr = explode("\n\n", $item);
                    $item = $itarr[0] . ' ' . $itarr[1];
                }
                if ($wyswietlaj[$key]) {
                    if ($key == 9) {
                        if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                            $currfield = new CurrencyField(0);
                            $zero = $currfield->getDisplayValue();
                            if ($item != 0 && $kurs_waluty) {
                                //var_dump($item);
                                //exit();
                                $product_table .= '<td style="border: 0.2mm solid black;" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format((double) $item, 2, $dec_sep, $group_sep) . '</small></td>';
                            } else {
                                $product_table .= '<td style="border: 0.2mm solid black;" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>np</small></td>';
                            }
                        }
                    } else {
                        if ($key != 0 && $key != 1) {
                            $product_table .= '<td style="border: 0.2mm solid black;' . ($lastKey == 7 ? ' border-right: 0.2mm solid black;' : '') . '" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format($item, 2, $dec_sep, $group_sep) . '</small></td>';
                        } else {
                            $product_table .= '<td style="border: 0.2mm solid black;" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . $item . '</small></td>';
                        }
                    }
                }
            }
            $product_table .= '</tr>';
            $i++;
        }
        $product_table .= "</table>";
        $i = 0;
        $product_table .= '<table cellpadding="0" cellspacing="0"><tr border="0">';
        if ($enable_ordinal_column) {
            $product_table .= '<td width="' . $width[0] . '"></td>';
        }
        if ($enable_productname_column) {
            $product_table .= '<td width="' . $width[1] . '"></td>';
        }
        if ($enable_amount_column) {
            $product_table .= '<td width="' . $width[2] . '"></td>';
        }
        if ($enable_listprice_column) {
            $product_table .= '<td width="' . $width[3] . '"></td>';
        }
        if ($enable_netprice_column) {
            $product_table .= '<td width="' . $width[4] . '" align="center" valign="middle" style="border: 0.2mm solid black;" ><small><b>' . number_format($total_discount, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_discount_column) {
            $product_table .= '<td width="' . $width[5] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_netto, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_vatpercentage_column && $final_details['taxtype'] != 'group') {
            $product_table .= '<td width="' . $width[6] . '"></td>';
        }
        if ($enable_vatamount_column && $final_details['taxtype'] != 'group') {
            $product_table .= '<td width="' . $width[7] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_vat, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_gross_column) {
            $product_table .= '<td width="' . $width[5] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_brutto, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_gross_column && $suma_podatku_w_pln != 0 && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            $product_table .= '<td width="' . $width[9] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_podatku_w_pln, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        $product_table .= '</tr></table><br/>';
        if ($final_details['taxtype'] == 'group') {
            $grup_tax = 0.0;
            for ($i = 0; $i < 3; $i++) {
                if ($associated_products[1]['final_details']['tax'] == $associated_products[1]['final_details']['taxes'][$i]['taxname']) {
                    $grup_tax = (double) $associated_products[1]['final_details']['taxes'][$i]['amount'];
                    $grup_tax_percent = (double) $associated_products[1]['final_details']['taxes'][$i]['percentage'];
                }
            }
            $currfield = new CurrencyField($grup_tax);
            $grup_tax = $currfield->getDisplayValue();
            $currfield = new CurrencyField($grup_tax_percent);
            $grup_tax_percent = $currfield->getDisplayValue();
        }
        $mod = strtolower($pdftype);
        if ($mod == 'quotes') {
            $idcol = "quoteid";
        } else {
            $idcol = $mod . "id";
        }
        $sql = "SELECT discount_percent, discount_amount, subtotal, total FROM vtiger_{$mod} WHERE {$idcol} = " . $id;
        $result = $adb->query($sql, true);
        $grand_total = $adb->query_result($result, 0, 'total');
        $subtotal = $adb->query_result($result, 0, "subtotal");
        $discount_percent = $adb->query_result($result, 0, 'discount_percent');
        $discount_amount = $adb->query_result($result, 0, 'discount_amount');
        if ($discount_percent != 0) {
            $discount = $subtotal * ($discount_percent / 100.0);
        } else {
            $discount = $discount_amount;
        }
        //$currfield = new CurrencyField( $grand_total );
        //$grand_total = $currfield->getDisplayValue();
        $currfield = new CurrencyField($subtotal);
        $subtotal = $currfield->getDisplayValue();
        $currfield = new CurrencyField($discount);
        $discount = $currfield->getDisplayValue();
        $currfield = new CurrencyField($netto);
        $netto = $currfield->getDisplayValue();
        if ($displays_a_summary_of_invoices == TRUE) {
            $product_table .= '<table width="535px" border="0" cellpadding="2">
                            <tr>
                            <td width="85px"></td>
                            <td width="270px"><br /><br />
                            <table bgcolor="#e8e8e8">';
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["SUMMARY"] . '</b></small></td></tr>';
            if ($enable_summary_rebate) {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["Discount Amount"] . '</b> :</small></td></tr>';
            }
            if ($enable_summary_taxpercentage && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["The percentage of tax"] . '</b> :</small></td></tr>';
            }
            if ($enable_summary_taxamount && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["The amount of tax"] . '</b> :</small></td></tr>';
            }
            if ($enable_summary_topay) {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["Grand Total"] . '</b> :</small></td></tr>';
            }
            if ($enable_date_of_the_course == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                $product_table .= '<tr valign="middle"><td align="right"><small></small></td></tr>';
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["rate"] . ' ' . $kod_aktualnej_waluty . ' ' . $languageStrings["on"] . ': ' . $CurrencyUpdate->getCorrectDate($newdate) . '</b> </small></td></tr>';
            }
            $product_table .= '</table>
			</td>
			<td width="160px" ><br />
                <table>';
            $product_table .= '<tr valign="middle"><td align="left"> </td></tr><tr valign="middle"><td align="left"> </td></tr>';
            if ($enable_summary_rebate) {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . number_format($rabat_calkowity, 2, $dec_sep, $group_sep) . ' (' . $symbol_waluty . ')</small></td></tr>';
            }
            if ($enable_summary_taxpercentage && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . $grup_tax_percent . ' (%)</small></td></tr>';
            }
            if ($enable_summary_taxpercentage && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . number_format($grup_tax, 2, $dec_sep, $group_sep) . ' (' . $symbol_waluty . ')</small></td></tr>';
            }
            if ($enable_summary_topay) {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . number_format($grand_total, 2, $dec_sep, $group_sep) . ' (' . $symbol_waluty . ')</small></td></tr>';
            }
            if ($enable_date_of_the_course == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                if ($kurs_waluty != 0) {
                    $product_table .= '<tr valign="middle"><td align="left"><small></small></td></tr>';
                    $product_table .= '<tr valign="middle"><td align="left"><small>' . $kurs_waluty . '</small></td></tr>';
                } else {
                    $product_table .= '<tr valign="middle"><td align="left"><small></small></td></tr>';
                    $product_table .= '<tr valign="middle"><td align="left"><small>np</small></td></tr>';
                }
            }
            $product_table .= '         
				</table>
			</td>
		</tr></table>
		<br/>';
        }
        return $product_table;
    }
}
Exemplo n.º 14
0
    function GenerateReport($outputformat, $filtersql, $directOutput = false)
    {
        global $adb, $current_user, $php_max_execution_time;
        global $modules, $app_strings;
        global $mod_strings, $current_language;
        require 'user_privileges/user_privileges_' . $current_user->id . '.php';
        $modules_selected = array();
        $modules_selected[] = $this->primarymodule;
        if (!empty($this->secondarymodule)) {
            $sec_modules = explode(":", $this->secondarymodule);
            for ($i = 0; $i < count($sec_modules); $i++) {
                $modules_selected[] = $sec_modules[$i];
            }
        }
        // Update Reference fields list list
        $referencefieldres = $adb->pquery("SELECT tabid, fieldlabel, uitype from vtiger_field WHERE uitype in (10,101)", array());
        if ($referencefieldres) {
            foreach ($referencefieldres as $referencefieldrow) {
                $uiType = $referencefieldrow['uitype'];
                $modprefixedlabel = getTabModuleName($referencefieldrow['tabid']) . ' ' . $referencefieldrow['fieldlabel'];
                $modprefixedlabel = str_replace(' ', '_', $modprefixedlabel);
                if ($uiType == 10 && !in_array($modprefixedlabel, $this->ui10_fields)) {
                    $this->ui10_fields[] = $modprefixedlabel;
                } elseif ($uiType == 101 && !in_array($modprefixedlabel, $this->ui101_fields)) {
                    $this->ui101_fields[] = $modprefixedlabel;
                }
            }
        }
        if ($outputformat == "HTML") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, $outputformat);
            $result = $adb->query($sSQL);
            $error_msg = $adb->database->ErrorMsg();
            if (!$result && $error_msg != '') {
                // Performance Optimization: If direct output is requried
                if ($directOutput) {
                    echo getTranslatedString('LBL_REPORT_GENERATION_FAILED', $currentModule) . "<br>" . $error_msg;
                    $error_msg = false;
                }
                // END
                return $error_msg;
            }
            // Performance Optimization: If direct output is required
            if ($directOutput) {
                echo '<table cellpadding="5" cellspacing="0" align="center" class="rptTable"><tr>';
            }
            // END
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                $picklistarray = $this->getAccessPickListValues();
            }
            if ($result) {
                $y = $adb->num_fields($result);
                $arrayHeaders = array();
                for ($x = 0; $x < $y; $x++) {
                    $fld = $adb->field_name($result, $x);
                    if (in_array($this->getLstringforReportHeaders($fld->name), $arrayHeaders)) {
                        $headerLabel = str_replace("_", " ", $fld->name);
                        $arrayHeaders[] = $headerLabel;
                    } else {
                        $headerLabel = str_replace($modules, " ", $this->getLstringforReportHeaders($fld->name));
                        $headerLabel = str_replace("_", " ", $this->getLstringforReportHeaders($fld->name));
                        $arrayHeaders[] = $headerLabel;
                    }
                    /*STRING TRANSLATION starts */
                    $mod_name = explode(' ', $headerLabel, 2);
                    $moduleLabel = '';
                    if (in_array($mod_name[0], $modules_selected)) {
                        $moduleLabel = getTranslatedString($mod_name[0], $mod_name[0]);
                    }
                    if (!empty($this->secondarymodule)) {
                        if ($moduleLabel != '') {
                            $headerLabel_tmp = $moduleLabel . " " . getTranslatedString($mod_name[1], $mod_name[0]);
                        } else {
                            $headerLabel_tmp = getTranslatedString($mod_name[0] . " " . $mod_name[1]);
                        }
                    } else {
                        if ($moduleLabel != '') {
                            $headerLabel_tmp = getTranslatedString($mod_name[1], $mod_name[0]);
                        } else {
                            $headerLabel_tmp = getTranslatedString($mod_name[0] . " " . $mod_name[1]);
                        }
                    }
                    if ($headerLabel == $headerLabel_tmp) {
                        $headerLabel = getTranslatedString($headerLabel_tmp);
                    } else {
                        $headerLabel = $headerLabel_tmp;
                    }
                    /*STRING TRANSLATION ends */
                    $header .= "<td class='rptCellLabel'>" . $headerLabel . "</td>";
                    // Performance Optimization: If direct output is required
                    if ($directOutput) {
                        echo $header;
                        $header = '';
                    }
                    // END
                }
                // Performance Optimization: If direct output is required
                if ($directOutput) {
                    echo '</tr><tr>';
                }
                // END
                $noofrows = $adb->num_rows($result);
                $custom_field_values = $adb->fetch_array($result);
                $groupslist = $this->getGroupingList($this->reportid);
                $column_definitions = $adb->getFieldsDefinition($result);
                do {
                    $arraylists = array();
                    if (count($groupslist) == 1) {
                        $newvalue = $custom_field_values[0];
                    } elseif (count($groupslist) == 2) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                    } elseif (count($groupslist) == 3) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                        $tnewvalue = $custom_field_values[2];
                    }
                    if ($newvalue == "") {
                        $newvalue = "-";
                    }
                    if ($snewvalue == "") {
                        $snewvalue = "-";
                    }
                    if ($tnewvalue == "") {
                        $tnewvalue = "-";
                    }
                    $valtemplate .= "<tr>";
                    // Performance Optimization
                    if ($directOutput) {
                        echo $valtemplate;
                        $valtemplate = '';
                    }
                    // END
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $fld_type = $column_definitions[$i]->type;
                        $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                        //check for Roll based pick list
                        $temp_val = $fld->name;
                        if ($fieldvalue == "") {
                            $fieldvalue = "-";
                        } else {
                            if ($fld->name == 'LBL_ACTION' && $fieldvalue != '-') {
                                $fieldvalue = "<a href='index.php?module={$this->primarymodule}&action=DetailView&record={$fieldvalue}' target='_blank'>" . getTranslatedString('LBL_VIEW_DETAILS') . "</a>";
                            }
                        }
                        if ($lastvalue == $fieldvalue && $this->reporttype == "summary") {
                            if ($this->reporttype == "summary") {
                                $valtemplate .= "<td class='rptEmptyGrp'>&nbsp;</td>";
                            } else {
                                $valtemplate .= "<td class='rptData'>" . $fieldvalue . "</td>";
                            }
                        } else {
                            if ($secondvalue === $fieldvalue && $this->reporttype == "summary") {
                                if ($lastvalue === $newvalue) {
                                    $valtemplate .= "<td class='rptEmptyGrp'>&nbsp;</td>";
                                } else {
                                    $valtemplate .= "<td class='rptGrpHead'>" . $fieldvalue . "</td>";
                                }
                            } else {
                                if ($thirdvalue === $fieldvalue && $this->reporttype == "summary") {
                                    if ($secondvalue === $snewvalue) {
                                        $valtemplate .= "<td class='rptEmptyGrp'>&nbsp;</td>";
                                    } else {
                                        $valtemplate .= "<td class='rptGrpHead'>" . $fieldvalue . "</td>";
                                    }
                                } else {
                                    if ($this->reporttype == "tabular") {
                                        $valtemplate .= "<td class='rptData'>" . $fieldvalue . "</td>";
                                    } else {
                                        $valtemplate .= "<td class='rptGrpHead'>" . $fieldvalue . "</td>";
                                    }
                                }
                            }
                        }
                        // Performance Optimization: If direct output is required
                        if ($directOutput) {
                            echo $valtemplate;
                            $valtemplate = '';
                        }
                        // END
                    }
                    $valtemplate .= "</tr>";
                    // Performance Optimization: If direct output is required
                    if ($directOutput) {
                        echo $valtemplate;
                        $valtemplate = '';
                    }
                    // END
                    $lastvalue = $newvalue;
                    $secondvalue = $snewvalue;
                    $thirdvalue = $tnewvalue;
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                // Performance Optimization
                if ($directOutput) {
                    echo "</tr></table>";
                    echo "<script type='text/javascript' id='__reportrun_directoutput_recordcount_script'>\n\t\t\t\t\t\tif(\$('_reportrun_total')) \$('_reportrun_total').innerHTML={$noofrows};</script>";
                } else {
                    $sHTML = '<table cellpadding="5" cellspacing="0" align="center" class="rptTable">
					<tr>' . $header . '<!-- BEGIN values -->
					<tr>' . $valtemplate . '</tr>
					</table>';
                }
                //<<<<<<<<construct HTML>>>>>>>>>>>>
                $return_data[] = $sHTML;
                $return_data[] = $noofrows;
                $return_data[] = $sSQL;
                return $return_data;
            }
        } elseif ($outputformat == "PDF") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql);
            $result = $adb->query($sSQL);
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                $picklistarray = $this->getAccessPickListValues();
            }
            if ($result) {
                $y = $adb->num_fields($result);
                $noofrows = $adb->num_rows($result);
                $custom_field_values = $adb->fetch_array($result);
                $column_definitions = $adb->getFieldsDefinition($result);
                do {
                    $arraylists = array();
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $fld_type = $column_definitions[$i]->type;
                        list($module, $fieldLabel) = explode('_', $fld->name, 2);
                        $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
                        $fieldType = null;
                        if (!empty($fieldInfo)) {
                            $field = WebserviceField::fromArray($adb, $fieldInfo);
                            $fieldType = $field->getFieldDataType();
                        }
                        if (!empty($fieldInfo)) {
                            $translatedLabel = getTranslatedString($field->getFieldLabelKey(), $module);
                        } else {
                            $translatedLabel = getTranslatedString(str_replace('_', " ", $fieldLabel), $module);
                        }
                        /*STRING TRANSLATION starts */
                        $moduleLabel = '';
                        if (in_array($module, $modules_selected)) {
                            $moduleLabel = getTranslatedString($module, $module);
                        }
                        if (empty($translatedLabel)) {
                            $translatedLabel = getTranslatedString(str_replace('_', " ", $fld->name));
                        }
                        $headerLabel = $translatedLabel;
                        if (!empty($this->secondarymodule)) {
                            if ($moduleLabel != '') {
                                $headerLabel = $moduleLabel . " " . $translatedLabel;
                            }
                        }
                        // Check for role based pick list
                        $temp_val = $fld->name;
                        if ($fieldType == 'currency') {
                            // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
                            $cur_value = $custom_field_values[$i];
                            if ($field->getUIType() == '72') {
                                $curid_value = explode("::", $cur_value);
                                if (count($curid_value) == 2) {
                                    $currency_id = $curid_value[0];
                                    $currency_value = $curid_value[1];
                                    $cur_sym_rate = getCurrencySymbolandCRate($currency_id);
                                } else {
                                    $currency_value = $curid_value[0];
                                    $cur_sym_rate['symbol'] = '';
                                }
                                $arraylists[$headerLabel] = number_format($currency_value, 2, '.', '');
                                $arraylists[getTranslatedString('LBL_CURRENCY') . ' ' . $headerLabel] = $cur_sym_rate['symbol'];
                            } else {
                                $currencyField = new CurrencyField($cur_value);
                                $fieldvalue = $currencyField->getDisplayValue();
                                $arraylists[$headerLabel] = number_format($fieldvalue, 2, '.', '');
                            }
                        } else {
                            $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                            $arraylists[$headerLabel] = $fieldvalue;
                        }
                    }
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                return $arr_val;
            }
        } elseif ($outputformat == "TOTALXLS") {
            $escapedchars = array('_SUM', '_AVG', '_MIN', '_MAX');
            $totalpdf = array();
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, "COLUMNSTOTOTAL");
            if (isset($this->totallist)) {
                if ($sSQL != "") {
                    $result = $adb->query($sSQL);
                    $y = $adb->num_fields($result);
                    $custom_field_values = $adb->fetch_array($result);
                    foreach ($this->totallist as $key => $value) {
                        $fieldlist = explode(":", $key);
                        $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?", array($fieldlist[1], $fieldlist[2]));
                        if ($adb->num_rows($mod_query) > 0) {
                            $module_name = getTabModuleName($adb->query_result($mod_query, 0, 'tabid'));
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("_", " ", $fieldlabel);
                            if ($module_name) {
                                $field = getTranslatedString($module_name, $module_name) . " " . getTranslatedString($fieldlabel, $module_name);
                            } else {
                                $field = getTranslatedString($fieldlabel);
                            }
                        }
                        $uitype_arr[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $adb->query_result($mod_query, 0, "uitype");
                        $totclmnflds[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $field;
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $keyhdr[$fld->name] = $custom_field_values[$i];
                    }
                    $rowcount = 0;
                    foreach ($totclmnflds as $key => $value) {
                        $col_header = trim(str_replace($modules, " ", $value));
                        $fld_name_1 = $this->primarymodule . "_" . trim($value);
                        $fld_name_2 = $this->secondarymodule . "_" . trim($value);
                        if ($uitype_arr[$key] == 71 || $uitype_arr[$key] == 72 || in_array($fld_name_1, $this->append_currency_symbol_to_value) || in_array($fld_name_2, $this->append_currency_symbol_to_value)) {
                            $col_header .= " (" . $app_strings['LBL_IN'] . " " . $current_user->currency_symbol . ")";
                            $convert_price = true;
                        } else {
                            $convert_price = false;
                        }
                        $value = trim($key);
                        $arraykey = $value . '_SUM';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $arraykey = $value . '_AVG';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $arraykey = $value . '_MIN';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $arraykey = $value . '_MAX';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $totalpdf[$rowcount][$arraykey] = $conv_value;
                        } else {
                            $totalpdf[$rowcount][$arraykey] = '';
                        }
                        $rowcount++;
                    }
                }
            }
            return $totalpdf;
        } elseif ($outputformat == "TOTALHTML") {
            $escapedchars = array('_SUM', '_AVG', '_MIN', '_MAX');
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, "COLUMNSTOTOTAL");
            if (isset($this->totallist)) {
                if ($sSQL != "") {
                    $result = $adb->query($sSQL);
                    $y = $adb->num_fields($result);
                    $custom_field_values = $adb->fetch_array($result);
                    $coltotalhtml .= "<table align='center' width='60%' cellpadding='3' cellspacing='0' border='0' class='rptTable'><tr><td class='rptCellLabel'>" . $mod_strings[Totals] . "</td><td class='rptCellLabel'>" . $mod_strings[SUM] . "</td><td class='rptCellLabel'>" . $mod_strings[AVG] . "</td><td class='rptCellLabel'>" . $mod_strings[MIN] . "</td><td class='rptCellLabel'>" . $mod_strings[MAX] . "</td></tr>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                    // END
                    foreach ($this->totallist as $key => $value) {
                        $fieldlist = explode(":", $key);
                        $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?", array($fieldlist[1], $fieldlist[2]));
                        if ($adb->num_rows($mod_query) > 0) {
                            $module_name = getTabModuleName($adb->query_result($mod_query, 0, 'tabid'));
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("_", " ", $fieldlabel);
                            if ($module_name) {
                                $field = getTranslatedString($module_name, $module_name) . " " . getTranslatedString($fieldlabel, $module_name);
                            } else {
                                $field = getTranslatedString($fieldlabel);
                            }
                        }
                        $uitype_arr[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $adb->query_result($mod_query, 0, "uitype");
                        $totclmnflds[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $field;
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $keyhdr[$fld->name] = $custom_field_values[$i];
                    }
                    foreach ($totclmnflds as $key => $value) {
                        $coltotalhtml .= '<tr class="rptGrpHead" valign=top>';
                        $col_header = trim(str_replace($modules, " ", $value));
                        $fld_name_1 = $this->primarymodule . "_" . trim($value);
                        $fld_name_2 = $this->secondarymodule . "_" . trim($value);
                        if ($uitype_arr[$key] == 71 || $uitype_arr[$key] == 72 || in_array($fld_name_1, $this->append_currency_symbol_to_value) || in_array($fld_name_2, $this->append_currency_symbol_to_value)) {
                            $col_header .= " (" . $app_strings['LBL_IN'] . " " . $current_user->currency_symbol . ")";
                            $convert_price = true;
                        } else {
                            $convert_price = false;
                        }
                        $coltotalhtml .= '<td class="rptData">' . $col_header . '</td>';
                        $value = trim($key);
                        $arraykey = $value . '_SUM';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $arraykey = $value . '_AVG';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $arraykey = $value . '_MIN';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $arraykey = $value . '_MAX';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            if (substr($arraykey, 0, 21) == 'Timecontrol_TotalTime' or substr($arraykey, 0, 18) == 'TCTotals_TotalTime') {
                                $conv_value = $keyhdr[$arraykey];
                            }
                            $coltotalhtml .= '<td class="rptTotal">' . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= '<td class="rptTotal">&nbsp;</td>';
                        }
                        $coltotalhtml .= '<tr>';
                        // Performation Optimization: If Direct output is desired
                        if ($directOutput) {
                            echo $coltotalhtml;
                            $coltotalhtml = '';
                        }
                        // END
                    }
                    $coltotalhtml .= "</table>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                    // END
                }
            }
            return $coltotalhtml;
        } elseif ($outputformat == "PRINT") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql);
            $result = $adb->query($sSQL);
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) {
                $picklistarray = $this->getAccessPickListValues();
            }
            if ($result) {
                $y = $adb->num_fields($result);
                $arrayHeaders = array();
                for ($x = 0; $x < $y; $x++) {
                    $fld = $adb->field_name($result, $x);
                    if (in_array($this->getLstringforReportHeaders($fld->name), $arrayHeaders)) {
                        $headerLabel = str_replace("_", " ", $fld->name);
                        $arrayHeaders[] = $headerLabel;
                    } else {
                        $headerLabel = str_replace($modules, " ", $this->getLstringforReportHeaders($fld->name));
                        $headerLabel = str_replace("_", " ", $this->getLstringforReportHeaders($fld->name));
                        $arrayHeaders[] = $headerLabel;
                    }
                    /*STRING TRANSLATION starts */
                    $mod_name = explode(' ', $headerLabel, 2);
                    $moduleLabel = '';
                    if (in_array($mod_name[0], $modules_selected)) {
                        $moduleLabel = getTranslatedString($mod_name[0], $mod_name[0]);
                    }
                    if (!empty($this->secondarymodule)) {
                        if ($moduleLabel != '') {
                            $headerLabel_tmp = $moduleLabel . " " . getTranslatedString($mod_name[1], $mod_name[0]);
                        } else {
                            $headerLabel_tmp = getTranslatedString($mod_name[0] . " " . $mod_name[1]);
                        }
                    } else {
                        if ($moduleLabel != '') {
                            $headerLabel_tmp = getTranslatedString($mod_name[1], $mod_name[0]);
                        } else {
                            $headerLabel_tmp = getTranslatedString($mod_name[0] . " " . $mod_name[1]);
                        }
                    }
                    if ($headerLabel == $headerLabel_tmp) {
                        $headerLabel = getTranslatedString($headerLabel_tmp);
                    } else {
                        $headerLabel = $headerLabel_tmp;
                    }
                    /*STRING TRANSLATION ends */
                    $header .= "<th>" . $headerLabel . "</th>";
                }
                $noofrows = $adb->num_rows($result);
                $custom_field_values = $adb->fetch_array($result);
                $groupslist = $this->getGroupingList($this->reportid);
                $column_definitions = $adb->getFieldsDefinition($result);
                do {
                    $arraylists = array();
                    if (count($groupslist) == 1) {
                        $newvalue = $custom_field_values[0];
                    } elseif (count($groupslist) == 2) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                    } elseif (count($groupslist) == 3) {
                        $newvalue = $custom_field_values[0];
                        $snewvalue = $custom_field_values[1];
                        $tnewvalue = $custom_field_values[2];
                    }
                    if ($newvalue == "") {
                        $newvalue = "-";
                    }
                    if ($snewvalue == "") {
                        $snewvalue = "-";
                    }
                    if ($tnewvalue == "") {
                        $tnewvalue = "-";
                    }
                    $valtemplate .= "<tr>";
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $fld_type = $column_definitions[$i]->type;
                        $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                        if ($lastvalue == $fieldvalue && $this->reporttype == "summary") {
                            if ($this->reporttype == "summary") {
                                $valtemplate .= "<td style='border-top:1px dotted #FFFFFF;'>&nbsp;</td>";
                            } else {
                                $valtemplate .= "<td>" . $fieldvalue . "</td>";
                            }
                        } else {
                            if ($secondvalue == $fieldvalue && $this->reporttype == "summary") {
                                if ($lastvalue == $newvalue) {
                                    $valtemplate .= "<td style='border-top:1px dotted #FFFFFF;'>&nbsp;</td>";
                                } else {
                                    $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                }
                            } else {
                                if ($thirdvalue == $fieldvalue && $this->reporttype == "summary") {
                                    if ($secondvalue == $snewvalue) {
                                        $valtemplate .= "<td style='border-top:1px dotted #FFFFFF;'>&nbsp;</td>";
                                    } else {
                                        $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                    }
                                } else {
                                    if ($this->reporttype == "tabular") {
                                        $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                    } else {
                                        $valtemplate .= "<td>" . $fieldvalue . "</td>";
                                    }
                                }
                            }
                        }
                    }
                    $valtemplate .= "</tr>";
                    $lastvalue = $newvalue;
                    $secondvalue = $snewvalue;
                    $thirdvalue = $tnewvalue;
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                $sHTML = '<tr>' . $header . '</tr>' . $valtemplate;
                $return_data[] = $sHTML;
                $return_data[] = $noofrows;
                return $return_data;
            }
        } elseif ($outputformat == "PRINT_TOTAL") {
            $escapedchars = array('_SUM', '_AVG', '_MIN', '_MAX');
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, "COLUMNSTOTOTAL");
            if (isset($this->totallist)) {
                if ($sSQL != "") {
                    $result = $adb->query($sSQL);
                    $y = $adb->num_fields($result);
                    $custom_field_values = $adb->fetch_array($result);
                    $coltotalhtml .= "<br /><table align='center' width='60%' cellpadding='3' cellspacing='0' border='1' class='printReport'><tr><td class='rptCellLabel'>" . $mod_strings['Totals'] . "</td><td><b>" . $mod_strings['SUM'] . "</b></td><td><b>" . $mod_strings['AVG'] . "</b></td><td><b>" . $mod_strings['MIN'] . "</b></td><td><b>" . $mod_strings['MAX'] . "</b></td></tr>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                    // END
                    foreach ($this->totallist as $key => $value) {
                        $fieldlist = explode(":", $key);
                        $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?", array($fieldlist[1], $fieldlist[2]));
                        if ($adb->num_rows($mod_query) > 0) {
                            $module_name = getTabModuleName($adb->query_result($mod_query, 0, 'tabid'));
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("_", " ", $fieldlabel);
                            if ($module_name) {
                                $field = getTranslatedString($module_name, $module_name) . " " . getTranslatedString($fieldlabel, $module_name);
                            } else {
                                $field = getTranslatedString($fieldlabel);
                            }
                        }
                        $uitype_arr[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $adb->query_result($mod_query, 0, "uitype");
                        $totclmnflds[str_replace($escapedchars, " ", $module_name . "_" . $fieldlist[3])] = $field;
                    }
                    for ($i = 0; $i < $y; $i++) {
                        $fld = $adb->field_name($result, $i);
                        $keyhdr[$fld->name] = $custom_field_values[$i];
                    }
                    foreach ($totclmnflds as $key => $value) {
                        $coltotalhtml .= '<tr class="rptGrpHead">';
                        $col_header = getTranslatedString(trim(str_replace($modules, " ", $value)));
                        $fld_name_1 = $this->primarymodule . "_" . trim($value);
                        $fld_name_2 = $this->secondarymodule . "_" . trim($value);
                        if ($uitype_arr[$key] == 71 || $uitype_arr[$key] == 72 || in_array($fld_name_1, $this->append_currency_symbol_to_value) || in_array($fld_name_2, $this->append_currency_symbol_to_value)) {
                            $col_header .= " (" . $app_strings['LBL_IN'] . " " . $current_user->currency_symbol . ")";
                            $convert_price = true;
                        } else {
                            $convert_price = false;
                        }
                        $coltotalhtml .= '<td class="rptData">' . $col_header . '</td>';
                        $value = trim($key);
                        $arraykey = $value . '_SUM';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $arraykey = $value . '_AVG';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $arraykey = $value . '_MIN';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $arraykey = $value . '_MAX';
                        if (isset($keyhdr[$arraykey])) {
                            if ($convert_price) {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey]);
                            } else {
                                $conv_value = CurrencyField::convertToUserFormat($keyhdr[$arraykey], null, true);
                            }
                            $coltotalhtml .= "<td class='rptTotal'>" . $conv_value . '</td>';
                        } else {
                            $coltotalhtml .= "<td class='rptTotal'>&nbsp;</td>";
                        }
                        $coltotalhtml .= '</tr>';
                        // Performation Optimization: If Direct output is desired
                        if ($directOutput) {
                            echo $coltotalhtml;
                            $coltotalhtml = '';
                        }
                        // END
                    }
                    $coltotalhtml .= "</table>";
                    // Performation Optimization: If Direct output is desired
                    if ($directOutput) {
                        echo $coltotalhtml;
                        $coltotalhtml = '';
                    }
                    // END
                }
            }
            return $coltotalhtml;
        }
    }
Exemplo n.º 15
0
/**
 *
 * @global Users $current_user
 * @param ReportRun $report
 * @param Array $picklistArray
 * @param ADOFieldObject $dbField
 * @param Array $valueArray
 * @param String $fieldName
 * @return String
 */
function getReportFieldValue($report, $picklistArray, $dbField, $valueArray, $fieldName)
{
    global $current_user;
    $db = PearDatabase::getInstance();
    $value = $valueArray[$fieldName];
    $fld_type = $dbField->type;
    list($module, $fieldLabel) = explode('_', $dbField->name, 2);
    $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
    $fieldType = null;
    $fieldvalue = $value;
    if (!empty($fieldInfo)) {
        $field = WebserviceField::fromArray($db, $fieldInfo);
        $fieldType = $field->getFieldDataType();
    }
    if ($fieldType == 'currency' && $value != '') {
        // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
        if ($field->getUIType() == '72') {
            $curid_value = explode("::", $value);
            $currency_id = $curid_value[0];
            $currency_value = $curid_value[1];
            $cur_sym_rate = getCurrencySymbolandCRate($currency_id);
            if ($value != '') {
                $formattedCurrencyValue = CurrencyField::convertToUserFormat($currency_value, null, true);
                $fieldvalue = CurrencyField::appendCurrencySymbol($formattedCurrencyValue, $cur_sym_rate['symbol']);
            }
        } else {
            $currencyField = new CurrencyField($value);
            $fieldvalue = $currencyField->getDisplayValue();
        }
    } elseif ($dbField->name == "PurchaseOrder_Currency" || $dbField->name == "SalesOrder_Currency" || $dbField->name == "Invoice_Currency" || $dbField->name == "Quotes_Currency" || $dbField->name == "PriceBooks_Currency") {
        if ($value != '') {
            $fieldvalue = getTranslatedCurrencyString($value);
        }
    } elseif (in_array($dbField->name, $report->ui101_fields) && !empty($value)) {
        if (is_numeric($value)) {
            $entityNames = getEntityName('Users', $value);
            $fieldvalue = $entityNames[$value];
        } else {
            $fieldvalue = $value;
        }
    } elseif ($fieldType == 'date' && !empty($value)) {
        if ($module == 'Calendar' && $field->getFieldName() == 'due_date') {
            $endTime = $valueArray['calendar_end_time'];
            if (empty($endTime)) {
                $recordId = $valueArray['calendar_id'];
                $endTime = getSingleFieldValue('vtiger_activity', 'time_end', 'activityid', $recordId);
            }
            $date = new DateTimeField($value . ' ' . $endTime);
            $fieldvalue = $date->getDisplayDate();
        } else {
            $fieldvalue = DateTimeField::convertToUserFormat($value);
        }
    } elseif ($fieldType == "datetime" && !empty($value)) {
        $date = new DateTimeField($value);
        $fieldvalue = $date->getDisplayDateTimeValue();
    } elseif ($fieldType == 'time' && !empty($value) && $field->getFieldName() != 'duration_hours' && $field->getFieldName() != 'totaltime') {
        $date = new DateTimeField($value);
        $fieldvalue = $date->getDisplayTime();
    } elseif ($fieldType == "picklist" && !empty($value)) {
        if (is_array($picklistArray)) {
            if (is_array($picklistArray[$dbField->name]) && $field->getFieldName() != 'activitytype' && !in_array($value, $picklistArray[$dbField->name])) {
                $fieldvalue = $app_strings['LBL_NOT_ACCESSIBLE'];
            } else {
                $fieldvalue = getTranslatedString($value, $module);
            }
        } else {
            $fieldvalue = getTranslatedString($value, $module);
        }
    } elseif ($fieldType == "multipicklist" && !empty($value)) {
        if (is_array($picklistArray[1])) {
            $valueList = explode(' |##| ', $value);
            $translatedValueList = array();
            foreach ($valueList as $value) {
                if (is_array($picklistArray[1][$dbField->name]) && !in_array($value, $picklistArray[1][$dbField->name])) {
                    $translatedValueList[] = $app_strings['LBL_NOT_ACCESSIBLE'];
                } else {
                    $translatedValueList[] = getTranslatedString($value, $module);
                }
            }
        }
        if (!is_array($picklistArray[1]) || !is_array($picklistArray[1][$dbField->name])) {
            $fieldvalue = str_replace(' |##| ', ', ', $value);
        } else {
            implode(', ', $translatedValueList);
        }
    }
    if ($fieldvalue == "") {
        return "-";
    }
    $fieldvalue = str_replace("<", "&lt;", $fieldvalue);
    $fieldvalue = str_replace(">", "&gt;", $fieldvalue);
    $fieldvalue = decode_html($fieldvalue);
    if (stristr($fieldvalue, "|##|") && empty($fieldType)) {
        $fieldvalue = str_ireplace(' |##| ', ', ', $fieldvalue);
    } elseif ($fld_type == "date" && empty($fieldType)) {
        $fieldvalue = DateTimeField::convertToUserFormat($fieldvalue);
    } elseif ($fld_type == "datetime" && empty($fieldType)) {
        $date = new DateTimeField($fieldvalue);
        $fieldvalue = $date->getDisplayDateTimeValue();
    }
    return $fieldvalue;
}
Exemplo n.º 16
-1
/** This function returns the detail view form vtiger_field and and its properties in array format.
 * Param $uitype - UI type of the vtiger_field
 * Param $fieldname - Form vtiger_field name
 * Param $fieldlabel - Form vtiger_field label name
 * Param $col_fields - array contains the vtiger_fieldname and values
 * Param $generatedtype - Field generated type (default is 1)
 * Param $tabid - vtiger_tab id to which the Field belongs to (default is "")
 * Return type is an array
 */
function getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields, $generatedtype, $tabid = '', $module = '')
{
    global $log;
    $log->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 = getTranslatedString($parent_module, $parent_module);
            $displayValueArray = getEntityName($parent_module, $parent_id);
            if (!empty($displayValueArray)) {
                foreach ($displayValueArray as $key => $value) {
                    $displayValue = $value;
                }
            }
            // vtlib customization: For listview javascript triggers
            $modMetaInfo = getEntityFieldNames($parent_module);
            $modEName = is_array($modMetaInfo['fieldname']) ? $modMetaInfo['fieldname'][0] : $modMetaInfo['fieldname'];
            $vtlib_metainfo = "<span type='vtlib_metainfo' vtrecordid='{$parent_id}' vtfieldname=" . "'{$modEName}' vtmodule='{$parent_module}' style='display:none;'></span>";
            // END
            $label_fld = array($fieldlabel, "<a href='index.php?module={$parent_module}&action=DetailView&record={$parent_id}' title='{$valueTitle}'>{$displayValue}</a>{$vtlib_metainfo}");
        } else {
            $moduleSpecificMessage = 'MODULE_NOT_SELECTED';
            if ($mod_strings[$moduleSpecificMessage] != "") {
                $moduleSpecificMessage = $mod_strings[$moduleSpecificMessage];
            }
            $label_fld = array($fieldlabel, '');
        }
    } 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[] = getTranslatedString($col_fields[$fieldname], $module);
            $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;
            $valueArr = explode("|##|", $col_fields[$fieldname]);
            $picklistValues = getAssignedPicklistValues($fieldname, $roleid, $adb);
            //Mikecrowe fix to correctly default for custom pick lists
            $options = array();
            $count = 0;
            $found = false;
            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');
                }
            }
            $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;
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $label_fld[] = str_ireplace(' |##| ', ', ', $col_fields[$fieldname]);
            $picklistValues = getAssignedPicklistValues($fieldname, $roleid, $adb);
            $options = array();
            $selected_entries = array();
            $selected_entries = explode(' |##| ', $col_fields[$fieldname]);
            if (!empty($picklistValues)) {
                foreach ($picklistValues as $order => $pickListValue) {
                    foreach ($selected_entries as $selected_entries_value) {
                        if (trim($selected_entries_value) == trim(htmlentities($pickListValue, ENT_QUOTES, $default_charset))) {
                            $chk_val = 'selected';
                            $pickcount++;
                            break;
                        } 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)) {
                    $not_access_lbl = "<font color='red'>" . $app_strings['LBL_NOT_ACCESSIBLE'] . "</font>";
                    $options[] = array($not_access_lbl, trim($selected_entries_value), 'selected');
                }
            }
            $label_fld["options"] = $options;
        } elseif ($uitype == 17) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $matchPattern = "^[\\w]+:\\/\\/^";
            $value = $col_fields[$fieldname];
            preg_match($matchPattern, $value, $matches);
            if (!empty($matches[0])) {
                $fieldValue = str_replace($matches, "", $value);
                $label_fld[] = $value;
            } else {
                if ($value != null) {
                    $label_fld[] = 'http://' . $value;
                } else {
                    $label_fld[] = '';
                }
            }
        } elseif ($uitype == 19) {
            if ($fieldname == 'notecontent' or $module == 'Timecontrol') {
                $col_fields[$fieldname] = decode_html($col_fields[$fieldname]);
            } else {
                $col_fields[$fieldname] = str_replace("&lt;br /&gt;", "<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<scher 11.08.2005 -> 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 = getOwnerName($user_id);
            if ($user_id != '') {
                $assigned_user_id = $user_id;
            } else {
                $assigned_user_id = $current_user->id;
            }
            if (is_admin($current_user)) {
                $label_fld[] = '<a href="index.php?module=Users&action=DetailView&record=' . $user_id . '">' . $user_name . '</a>';
            } 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 = '******';
            $result = $adb->pquery("SELECT count(*) as count from vtiger_users where id = ?", array($owner_id));
            if ($adb->query_result($result, 0, 'count') > 0) {
                $user = '******';
            }
            $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 ($fieldname == 'assigned_user_id' && $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 ($fieldname == 'assigned_user_id' && $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'), $assigned_user_id);
            } else {
                $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $current_user->id), $assigned_user_id);
            }
            if ($noof_group_rows != 0) {
                if ($fieldname == 'assigned_user_id' && $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..
                $displayValue = $app_strings['yes'];
            } else {
                $displayValue = $app_strings['no'];
            }
            $label_fld[] = $displayValue;
        } elseif ($uitype == 156) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $value = $col_fields[$fieldname];
            if ($value == 'on') {
                //Since "yes" is not been translated it is given as app strings here..
                $displayValue = $app_strings['yes'];
            } else {
                $displayValue = $app_strings['no'];
            }
            $label_fld[] = $displayValue;
        } elseif ($uitype == 57) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $contact_id = $col_fields[$fieldname];
            if ($contact_id != '') {
                $displayValueArray = getEntityName('Contacts', $contact_id);
                if (!empty($displayValueArray)) {
                    foreach ($displayValueArray as $key => $field_value) {
                        $contact_name = $field_value;
                    }
                } else {
                    $contact_name = '';
                }
            }
            $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 = '<a href = "index.php?module=uploads&action=downloadfile&return_module=' . $col_fields['record_module'] . '&fileid=' . $attachmentid . '&entityid=' . $col_fields['record_id'] . '">' . $attachmentsname . '</a>';
                        } 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 = '<a target="_blank" href =' . $col_fields['filename'] . ' onclick=\'javascript:dldCntIncrease(' . $col_fields['record_id'] . ');\'>' . $col_fields[$fieldname] . '</a>';
                        } else {
                            $custfldval = $col_fields[$fieldname];
                        }
                    } elseif ($col_fields['filelocationtype'] == 'I') {
                        if ($col_fields['filestatus'] == 1) {
                            $custfldval = '<a href = "index.php?module=uploads&action=downloadfile&return_module=' . $col_fields['record_module'] . '&fileid=' . $attachmentid . '&entityid=' . $col_fields['record_id'] . '" onclick=\'javascript:dldCntIncrease(' . $col_fields['record_id'] . ');\'>' . $col_fields[$fieldname] . '</a>';
                        } 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 = '<a target="_blank" href =' . $col_fields['filename'] . ' onclick=\'javascript:dldCntIncrease(' . $col_fields['record_id'] . ');\'>' . $col_fields[$fieldname] . '</a>';
                    } else {
                        $custfldval = $col_fields[$fieldname];
                    }
                } elseif ($col_fields['filelocationtype'] == 'I') {
                    if ($col_fields['filestatus'] == 1) {
                        $custfldval = '<a href = "index.php?module=uploads&action=downloadfile&return_module=' . $col_fields['record_module'] . '&fileid=' . $attachmentid . '&entityid=' . $col_fields['record_id'] . '" onclick=\'javascript:dldCntIncrease(' . $col_fields['record_id'] . ');\'>' . $col_fields[$fieldname] . '</a>';
                    } 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 = '<div id="Carousel" style="position:relative;vertical-align: middle;">
					<img src="modules/Products/placeholder.gif" width="571" height="117" style="position:relative;">
					</div><script>var Car_NoOfSides=' . $sides . '; Car_Image_Sources=new Array(';
                    for ($image_iter = 0; $image_iter < count($image_array); $image_iter++) {
                        $images[] = '"' . $imagepath_array[$image_iter] . $image_id_array[$image_iter] . "_" . $image_array[$image_iter] . '","' . $imagepath_array[$image_iter] . $image_id_array[$image_iter] . "_" . $image_array[$image_iter] . '"';
                    }
                    $image_lists .= implode(',', $images) . ');</script><script language="JavaScript" type="text/javascript" src="modules/Products/Productsslide.js"></script><script language="JavaScript" type="text/javascript">Carousel();</script>';
                    $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[] = '<img src="' . $imagepath_array[0] . $image_id_array[0] . "_" . $image_array[0] . '" border="0" width="450" height="300">';
                    } else {
                        $label_fld[] = '<img src="' . $imagepath_array[0] . $image_id_array[0] . "_" . $image_array[0] . '" border="0" width="' . $pro_image_width . '" height="' . $pro_image_height . '">';
                    }
                } else {
                    $label_fld[] = '';
                }
            } else {
                if ($module == 'Contacts') {
                    $imageattachment = 'Image';
                } else {
                    $imageattachment = 'Attachment';
                }
                //$imgpath = getModuleFileStoragePath('Contacts').$col_fields[$fieldname];
                $sql = "select vtiger_attachments.*,vtiger_crmentity.setype\n\t\t\t from vtiger_attachments\n\t\t\t inner join vtiger_seattachmentsrel on vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid\n\t\t\t inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid\n\t\t\t where vtiger_crmentity.setype='{$module} {$imageattachment}'\n\t\t\t  and vtiger_attachments.name = ?\n\t\t\t  and vtiger_seattachmentsrel.crmid=?";
                $image_res = $adb->pquery($sql, array($col_fields[$fieldname], $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 != '') {
                    $ftype = $adb->query_result($image_res, 0, 'type');
                    $isimage = stripos($ftype, 'image') !== false;
                    if ($isimage) {
                        $imgtxt = getTranslatedString('SINGLE_' . $module, $module) . ' ' . getTranslatedString('Image');
                        $label_fld[] = '<img src="' . $imgpath . '" alt="' . $imgtxt . '" title= "' . $imgtxt . '" style="max-width: 500px;">';
                    } else {
                        $imgtxt = getTranslatedString('SINGLE_' . $module, $module) . ' ' . getTranslatedString('SINGLE_Documents');
                        $label_fld[] = '<a href="' . $imgpath . '" alt="' . $imgtxt . '" title= "' . $imgtxt . '">' . $image_name . '</a>';
                    }
                } 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'];
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $lead_name = $field_value;
                        }
                    }
                    $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $lead_name . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $account_name . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $potentialname . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $productname . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $pordername . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $sordername . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $invoicename . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $quotename . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $title . '</a>';
                }
            } 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[] = '<a href="' . $imgpath . '" target="_blank"><img src="' . $imgpath . '" width="' . $pro_image_width . '" height="' . $pro_image_height . '" alt="' . $col_fields['user_name'] . '" title="' . $col_fields['user_name'] . '" border="0"></a>';
            } 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'];
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $lead_name = $field_value;
                        }
                    }
                    $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $lead_name . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $account_name . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $potentialname . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $quotename . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $pordername . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $sordername . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $invoicename . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $campaignname . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $tickettitle . '</a>';
                } elseif ($parent_module == "Vendors") {
                    //MSL
                    $label_fld[] = $app_strings['LBL_VENDOR_NAME'];
                    $sql = "select vendorname from  vtiger_vendor where vendorid=?";
                    $result = $adb->pquery($sql, array($value));
                    $vendor_name = $adb->query_result($result, 0, "vendorname");
                    $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $vendor_name . '</a>';
                }
                //MSL -------------------------------------------
            } 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'];
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $lead_name = $field_value;
                        }
                    }
                    $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $lead_name . '</a>';
                } elseif ($parent_module == "Contacts") {
                    $label_fld[] = $app_strings['LBL_CONTACT_NAME'];
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $contact_name = $field_value;
                        }
                    } else {
                        $contact_name = '';
                    }
                    $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $contact_name . '</a>';
                }
            } else {
                $label_fld[] = getTranslatedString($fieldlabel, $module);
                $label_fld[] = $value;
            }
        } 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'];
                        $displayValueArray = getEntityName($parent_module, $value);
                        if (!empty($displayValueArray)) {
                            foreach ($displayValueArray as $key => $field_value) {
                                $lead_name = $field_value;
                            }
                        }
                        $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $lead_name . '</a>';
                    } elseif ($parent_module == "Contacts") {
                        $label_fld[] = $app_strings['LBL_CONTACT_NAME'];
                        $displayValueArray = getEntityName($parent_module, $value);
                        if (!empty($displayValueArray)) {
                            foreach ($displayValueArray as $key => $field_value) {
                                $contact_name = $field_value;
                            }
                        } else {
                            $contact_name = '';
                        }
                        $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $contact_name . '</a>';
                    } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $accountname . '</a>';
                    }
                }
            } else {
                $label_fld[] = getTranslatedString($fieldlabel, $module);
                $label_fld[] = $value;
            }
        } elseif ($uitype == 68) {
            $value = $col_fields[$fieldname];
            if ($value != '') {
                $parent_module = getSalesEntityType($value);
                if ($parent_module == "Contacts") {
                    $label_fld[] = $app_strings['LBL_CONTACT_NAME'];
                    $displayValueArray = getEntityName($parent_module, $value);
                    if (!empty($displayValueArray)) {
                        foreach ($displayValueArray as $key => $field_value) {
                            $contact_name = $field_value;
                        }
                    } else {
                        $contact_name = '';
                    }
                    $label_fld[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $contact_name . '</a>';
                } 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[] = '<a href="index.php?module=' . $parent_module . '&action=DetailView&record=' . $value . '">' . $account_name . '</a>';
                } 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&nbsp; ' . $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'];
            }
            $dateValue = $col_fields[$fieldname];
            if ($col_fields[$fieldname] == '0000-00-00' || empty($dateValue)) {
                $displayValue = '';
            } else {
                if (empty($start_time) && strpos($col_fields[$fieldname], ' ') == false) {
                    $displayValue = DateTimeField::convertToUserFormat($col_fields[$fieldname]);
                } else {
                    if (!empty($start_time)) {
                        $date = new DateTimeField($col_fields[$fieldname] . ' ' . $start_time);
                    } else {
                        $date = new DateTimeField($col_fields[$fieldname]);
                    }
                    $displayValue = $date->getDisplayDateTimeValue();
                }
            }
            $label_fld[] = $displayValue;
        } elseif ($uitype == 5 || $uitype == 23 || $uitype == 70) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $dateValue = $col_fields[$fieldname];
            if ($col_fields['time_end'] != '' && ($tabid == 9 || $tabid == 16) && $uitype == 23) {
                $end_time = $col_fields['time_end'];
            }
            if ($dateValue == '0000-00-00' || empty($dateValue)) {
                $displayValue = '';
            } else {
                if (empty($end_time) && strpos($dateValue, ' ') == false) {
                    $displayValue = DateTimeField::convertToUserFormat($col_fields[$fieldname]);
                } else {
                    if (!empty($end_time)) {
                        $date = new DateTimeField($col_fields[$fieldname] . ' ' . $end_time);
                    } else {
                        $date = new DateTimeField($col_fields[$fieldname]);
                    }
                    $displayValue = $date->getDisplayDateTimeValue();
                }
            }
            $label_fld[] = $displayValue;
        } elseif ($uitype == 71 || $uitype == 72) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $currencyField = new CurrencyField($col_fields[$fieldname]);
            if ($uitype == 72) {
                // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
                if ($fieldname == 'unit_price') {
                    $rate_symbol = getCurrencySymbolandCRate(getProductBaseCurrency($col_fields['record_id'], $module));
                    $label_fld[] = $currencyField->getDisplayValue(null, true);
                    $label_fld["cursymb"] = $rate_symbol['symbol'];
                } else {
                    $currency_info = getInventoryCurrencyInfo($module, $col_fields['record_id']);
                    $label_fld[] = $currencyField->getDisplayValue(null, true);
                    $label_fld["cursymb"] = $currency_info['currency_symbol'];
                }
            } else {
                $label_fld[] = $currencyField->getDisplayValue();
                $label_fld["cursymb"] = $currencyField->getCurrencySymbol();
            }
        } 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 . '&nbsp;' . $mod_strings['LBL_DAYS'] . '&nbsp;' . $rem_hrs . '&nbsp;' . $mod_strings['LBL_HOURS'] . '&nbsp;' . $rem_min . '&nbsp;' . $mod_strings['LBL_MINUTES'] . '&nbsp;&nbsp;' . $mod_strings['LBL_BEFORE_EVENT'];
            }
            $label_fld[] = '&nbsp;' . $reminder_str;
        } elseif ($uitype == 98) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            if (is_admin($current_user)) {
                $label_fld[] = '<a href="index.php?module=Settings&action=RoleDetailView&roleid=' . $col_fields[$fieldname] . '">' . getRoleName($col_fields[$fieldname]) . '</a>';
            } 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'];
            }
        } elseif ($uitype == 31) {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $label_fld[] = $col_fields[$fieldname];
            $options = array();
            $themeList = get_themes();
            foreach ($themeList as $theme) {
                if ($current_user->theme == $theme) {
                    $selected = 'selected';
                } else {
                    $selected = '';
                }
                $options[] = array(getTranslatedString($theme), $theme, $selected);
            }
            $label_fld["options"] = $options;
        } elseif ($uitype == 32) {
            $options = array();
            $languageList = Vtiger_Language::getAll();
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            $label_fld[] = isset($languageList[$col_fields[$fieldname]]) ? $languageList[$col_fields[$fieldname]] : $col_fields[$fieldname];
            foreach ($languageList as $prefix => $label) {
                if ($current_user->language == $prefix) {
                    $selected = 'selected';
                } else {
                    $selected = '';
                }
                $options[] = array(getTranslatedString($label), $prefix, $selected);
            }
            $label_fld["options"] = $options;
        } else {
            $label_fld[] = getTranslatedString($fieldlabel, $module);
            if ($col_fields[$fieldname] == '0' && $fieldname != 'filedownloadcount' && $fieldname != 'filestatus' && $fieldname != 'filesize') {
                $col_fields[$fieldname] = '';
            }
            //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 = "<img src='" . vtiger_imageurl('fExeBin.gif', $theme) . "' hspace='3' align='absmiddle' border='0'>";
                        } elseif ($ext == 'jpg' || $ext == 'gif' || $ext == 'bmp') {
                            $fileicon = "<img src='" . vtiger_imageurl('fbImageFile.gif', $theme) . "' hspace='3' align='absmiddle' border='0'>";
                        } elseif ($ext == 'txt' || $ext == 'doc' || $ext == 'xls') {
                            $fileicon = "<img src='" . vtiger_imageurl('fbTextFile.gif', $theme) . "' hspace='3' align='absmiddle' border='0'>";
                        } elseif ($ext == 'zip' || $ext == 'gz' || $ext == 'rar') {
                            $fileicon = "<img src='" . vtiger_imageurl('fbZipFile.gif', $theme) . "' hspace='3' align='absmiddle'\tborder='0'>";
                        } else {
                            $fileicon = "<img src='" . vtiger_imageurl('fbUnknownFile.gif', $theme) . "' hspace='3' align='absmiddle' border='0'>";
                        }
                    } else {
                        $fld_value = $col_fields['filename'];
                        $fileicon = "<img src='" . vtiger_imageurl('fbLink.gif', $theme) . "' alt='" . $mod_strings['LBL_EXTERNAL_LNK'] . "' title='" . $mod_strings['LBL_EXTERNAL_LNK'] . "' hspace='3' align='absmiddle' border='0'>";
                    }
                    $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;
}