function amount_in_words($module, $id, $templateid, $content, $tcpdf)
{
    $db = PearDatabase::getInstance();
    $current_language = Users_Record_Model::getCurrentUserModel()->get('language');
    if (!file_exists("languages/" . $current_language . "/OSSPdf.php")) {
        $current_language = "en_us";
    }
    $mod = $module;
    $module = strtolower($module);
    if ($module == 'quotes') {
        $idcol = "quoteid";
    } else {
        $idcol = $module . "id";
    }
    $sql = "SELECT total FROM vtiger_{$module} WHERE {$idcol} = " . $id;
    $result = $db->query($sql, true);
    $grand_total = $db->query_result($result, 0, 'total');
    $currfield = new CurrencyField($grand_total);
    $grand_total = $currfield->getDBInsertedValue($grand_total);
    require_once 'include/utils/utils.php';
    require_once 'include/utils/CommonUtils.php';
    require_once 'modules/' . $mod . '/' . $mod . '.php';
    $focus = new $mod();
    $focus->retrieve_entity_info($id, $mod);
    $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");
    $recordModel = Vtiger_Record_Model::getCleanInstance('OSSPdf');
    $kwota = $recordModel->slownie($grand_total, $kod_aktualnej_waluty);
    return $kwota;
}
Example #2
0
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->removeByName('PageBuilder');
     /* =========================================
        * Images
        =========================================*/
     $fields->addFieldToTab('Root.Main', new UploadField('Image'), 'Content');
     /* =========================================
        * Menu Item Details
        =========================================*/
     $fields->addFieldToTab('Root.Main', $price = new CurrencyField('Price'), 'Content');
     $price->setRightTitle('To add extra price options e.g Small, Large please add a variation under the "Variations" tab above');
     $fields->addFieldToTab('Root.Main', $ingredients = new HtmlEditorField('Ingredients'), 'Metadata');
     $ingredients->setRows(15);
     /* =========================================
        * Variations
        =========================================*/
     $config = GridFieldConfig_RelationEditor::create(10);
     $config->addComponent(new GridFieldSortableRows('SortOrder'))->addComponent(new GridFieldDeleteAction());
     $config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array('Title' => 'Title', 'Price' => 'Price'));
     $gridField = new GridField('Variations', 'Variations', $this->owner->MenuVariations(), $config);
     $fields->addFieldToTab('Root.Variations', $gridField);
     return $fields;
 }
 public function Form()
 {
     $form = parent::Form();
     if ($this->VariableAmount) {
         $form->setSaveableFields(array("UnitPrice"));
         $form->Fields()->push($giftamount = new CurrencyField("UnitPrice", "Amount", $this->BasePrice));
         $giftamount->setForm($form);
     }
     $form->setValidator($validator = new GiftVoucherFormValidator(array("Quantity", "UnitPrice")));
     return $form;
 }
 public function getCMSFields($params = null)
 {
     //fields that shouldn't be changed once coupon is used
     $fields = new FieldList(array($tabset = new TabSet("Root", $maintab = new Tab("Main", TextField::create("Title"), CheckboxField::create("Active", "Active")->setDescription("Enable/disable all use of this discount."), HeaderField::create("ActionTitle", "Action", 3), $typefield = SelectionGroup::create("Type", array(new SelectionGroup_Item("Percent", $percentgroup = FieldGroup::create($percentfield = NumericField::create("Percent", "Percentage", "0.00")->setDescription("e.g. 0.05 = 5%, 0.5 = 50%, and 5 = 500%"), $maxamountfield = CurrencyField::create("MaxAmount", _t("MaxAmount", "Maximum Amount"))->setDescription("The total allowable discount. 0 means unlimited.")), "Discount by percentage"), new SelectionGroup_Item("Amount", $amountfield = CurrencyField::create("Amount", "Amount", "\$0.00"), "Discount by fixed amount")))->setTitle("Type"), OptionSetField::create("For", "Applies to", array("Order" => "Entire Order", "Cart" => "Cart Subtotal", "Shipping" => "Shipping Subtotal", "Items" => "Each Individual Item")), new Tab("Main", HeaderField::create("ConstraintsTitle", "Constraints", 3), LabelField::create("ConstraintsDescription", "Configure the requirements an order must meet for this discount to be valid:")), new TabSet("Constraints")))));
     if (!$this->isInDB()) {
         $fields->addFieldToTab("Root.Main", LiteralField::create("SaveNote", "<p class=\"message good\">More constraints will show up after you save for the first time.</p>"), "Constraints");
     }
     $this->extend("updateCMSFields", $fields, $params);
     if ($count = $this->getUseCount()) {
         $fields->addFieldsToTab("Root.Usage", array(HeaderField::create("UseCount", sprintf("This discount has been used {$count} time%s.", $count > 1 ? "s" : "")), HeaderField::create("TotalSavings", sprintf("A total of %s has been saved by customers using this discount.", $this->SavingsTotal), "3"), GridField::create("Orders", "Orders", $this->getAppliedOrders(), GridFieldConfig_RecordViewer::create()->removeComponentsByType("GridFieldViewButton"))));
     }
     if ($params && isset($params['forcetype'])) {
         $valuefield = $params['forcetype'] == "Percent" ? $percentfield : $amountfield;
         $fields->insertAfter($valuefield, "Type");
         $fields->removeByName("Type");
     } elseif ($this->Type && (double) $this->{$this->Type}) {
         $valuefield = $this->Type == "Percent" ? $percentfield : $amountfield;
         $fields->removeByName("Type");
         $fields->insertAfter($valuefield, "ActionTitle");
         $fields->replaceField($this->Type, $valuefield->performReadonlyTransformation());
         if ($this->Type == "Percent") {
             $fields->insertAfter($maxamountfield, "Percent");
         }
     }
     return $fields;
 }
Example #5
0
function getTopPotentials($maxval, $calCnt)
{
    $log = LoggerManager::getLogger('top opportunity_list');
    $log->debug("Entering getTopPotentials() method ...");
    require_once "data/Tracker.php";
    require_once 'modules/Potentials/Potentials.php';
    require_once 'include/logging.php';
    require_once 'include/ListView/ListView.php';
    global $app_strings;
    global $adb;
    global $current_language;
    global $current_user;
    $current_module_strings = return_module_language($current_language, "Potentials");
    $title = array();
    $title[] = 'myTopOpenPotentials.gif';
    $title[] = $current_module_strings['LBL_TOP_OPPORTUNITIES'];
    $title[] = 'home_mypot';
    $where = "AND vtiger_potential.potentialid > 0 AND vtiger_potential.sales_stage not in ('Closed Won','Closed Lost','" . $current_module_strings['Closed Won'] . "','" . $current_module_strings['Closed Lost'] . "') AND vtiger_crmentity.smownerid='" . $current_user->id . "' AND vtiger_potential.amount > 0";
    $header = array();
    $header[] = $current_module_strings['LBL_LIST_OPPORTUNITY_NAME'];
    //$header[]=$current_module_strings['LBL_LIST_ACCOUNT_NAME'];
    $currencyid = fetchCurrency($current_user->id);
    $rate_symbol = getCurrencySymbolandCRate($currencyid);
    $rate = $rate_symbol['rate'];
    $curr_symbol = $rate_symbol['symbol'];
    $header[] = $current_module_strings['LBL_LIST_AMOUNT'] . '(' . $curr_symbol . ')';
    $list_query = "SELECT vtiger_crmentity.crmid, vtiger_potential.potentialname,\n\t\t\tvtiger_potential.amount, potentialid\n\t\t\tFROM vtiger_potential\n\t\t\tIGNORE INDEX(PRIMARY) INNER JOIN vtiger_crmentity\n\t\t\t\tON vtiger_crmentity.crmid = vtiger_potential.potentialid";
    $list_query .= getNonAdminAccessControlQuery('Potentials', $current_user);
    $list_query .= "WHERE vtiger_crmentity.deleted = 0 " . $where;
    $list_query .= " ORDER BY amount DESC";
    $list_query .= " LIMIT " . $adb->sql_escape_string($maxval);
    if ($calCnt == 'calculateCnt') {
        $list_result_rows = $adb->query(mkCountQuery($list_query));
        return $adb->query_result($list_result_rows, 0, 'count');
    }
    $list_result = $adb->query($list_query);
    $open_potentials_list = array();
    $noofrows = $adb->num_rows($list_result);
    $entries = array();
    if ($noofrows) {
        for ($i = 0; $i < $noofrows; $i++) {
            $open_potentials_list[] = array('name' => $adb->query_result($list_result, $i, 'potentialname'), 'id' => $adb->query_result($list_result, $i, 'potentialid'), 'amount' => $adb->query_result($list_result, $i, 'amount'));
            $potentialid = $adb->query_result($list_result, $i, 'potentialid');
            $potentialname = $adb->query_result($list_result, $i, 'potentialname');
            $Top_Potential = strlen($potentialname) > 20 ? substr($potentialname, 0, 20) . '...' : $potentialname;
            $value = array();
            $value[] = '<a href="index.php?action=DetailView&module=Potentials&record=' . $potentialid . '">' . $Top_Potential . '</a>';
            $value[] = CurrencyField::convertToUserFormat($adb->query_result($list_result, $i, 'amount'));
            $entries[$potentialid] = $value;
        }
    }
    $advft_criteria_groups = array('1' => array('groupcondition' => null));
    $advft_criteria = array(array('groupid' => 1, 'columnname' => 'vtiger_potential:sales_stage:sales_stage:Potentials_Sales_Stage:V', 'comparator' => 'k', 'value' => 'closed', 'columncondition' => 'and'), array('groupid' => 1, 'columnname' => 'vtiger_potential:amount:amount:Potentials_Amount:N', 'comparator' => 'g', 'value' => '0', 'columncondition' => 'and'), array('groupid' => 1, 'columnname' => 'vtiger_crmentity:smownerid:assigned_user_id:Leads_Assigned_To:V', 'comparator' => 'e', 'value' => getFullNameFromArray('Users', $current_user->column_fields), 'columncondition' => null));
    $search_qry = '&advft_criteria=' . Zend_Json::encode($advft_criteria) . '&advft_criteria_groups=' . Zend_Json::encode($advft_criteria_groups) . '&searchtype=advance&query=true';
    $values = array('ModuleName' => 'Potentials', 'Title' => $title, 'Header' => $header, 'Entries' => $entries, 'search_qry' => $search_qry);
    if (count($open_potentials_list) == 0 || count($open_potentials_list) > 0) {
        $log->debug("Exiting getTopPotentials method ...");
        return $values;
    }
}
 public function getCreateViewUrl()
 {
     $createViewUrl = parent::getCreateViewUrl();
     $currentUserModel = Users_Record_Model::getCurrentUserModel();
     $parentRecordModel = $this->getParentRecordModel();
     $currencyValue = $parentRecordModel->get('hdnGrandTotal');
     $parentRecordModelCurrencyId = $parentRecordModel->get('currency_id');
     if ($parentRecordModelCurrencyId == $currentUserModel->get('currency_id')) {
         $amount = CurrencyField::convertToUserFormat($currencyValue, null, true);
     } else {
         $baseCurrencyId = CurrencyField::getDBCurrencyId();
         $allCurrencies = getAllCurrencies();
         foreach ($allCurrencies as $currencyInfo) {
             if ($parentRecordModelCurrencyId == $currencyInfo['currency_id']) {
                 $currencyValue = CurrencyField::convertToDollar($currencyValue, $currencyInfo['conversionrate']);
             }
         }
         foreach ($allCurrencies as $currencyInfo) {
             if ($baseCurrencyId == $currencyInfo['currency_id']) {
                 $currencyValue = CurrencyField::convertFromMasterCurrency($currencyValue, $currencyInfo['conversionrate']);
             }
         }
         $amount = CurrencyField::convertToUserFormat($currencyValue);
     }
     return $createViewUrl . '&relatedcontact=' . $parentRecordModel->get('contact_id') . '&relatedorganization=' . $parentRecordModel->get('account_id') . '&amount=' . $amount;
 }
Example #7
0
function getTopAccounts($maxval, $calCnt)
{
    $log = LoggerManager::getLogger('top accounts_list');
    $log->debug("Entering getTopAccounts() method ...");
    require_once "data/Tracker.php";
    require_once 'modules/Potentials/Potentials.php';
    require_once 'include/logging.php';
    require_once 'include/ListView/ListView.php';
    global $app_strings;
    global $adb;
    global $current_language;
    global $current_user;
    $current_module_strings = return_module_language($current_language, "Accounts");
    require 'user_privileges/user_privileges_' . $current_user->id . '.php';
    require 'user_privileges/sharing_privileges_' . $current_user->id . '.php';
    $list_query = "select vtiger_potential.potentialname,vtiger_account.accountid, vtiger_account.accountname, " . "vtiger_account.tickersymbol, sum(vtiger_potential.amount) as amount from vtiger_potential " . "inner join vtiger_crmentity on (vtiger_potential.potentialid=vtiger_crmentity.crmid) " . "inner join vtiger_account on (vtiger_potential.related_to=vtiger_account.accountid) ";
    $list_query .= " WHERE vtiger_crmentity.deleted = 0 " . $where . " AND vtiger_potential.potentialid>0";
    $list_query .= " AND vtiger_crmentity.smownerid='" . $current_user->id . "' " . "and vtiger_potential.sales_stage not in ('Closed Won', 'Closed Lost','" . $app_strings['LBL_CLOSE_WON'] . "','" . $app_strings['LBL_CLOSE_LOST'] . "')";
    $list_query .= " group by vtiger_account.accountid, vtiger_account.tickersymbol order by amount desc";
    $list_query .= " LIMIT 0," . $adb->sql_escape_string($maxval);
    if ($calCnt == 'calculateCnt') {
        $list_result_rows = $adb->query(mkCountQuery($list_query));
        return $adb->query_result($list_result_rows, 0, 'count');
    }
    $list_result = $adb->query($list_query);
    $open_accounts_list = array();
    $noofrows = $adb->num_rows($list_result);
    if ($noofrows) {
        for ($i = 0; $i < $noofrows; $i++) {
            $open_accounts_list[] = array('accountid' => $adb->query_result($list_result, $i, 'accountid'), 'accountname' => $adb->query_result($list_result, $i, 'accountname'), 'amount' => $adb->query_result($list_result, $i, 'amount'), 'tickersymbol' => $adb->query_result($list_result, $i, 'tickersymbol'));
        }
    }
    $title = array();
    $title[] = 'myTopAccounts.gif';
    $title[] = $current_module_strings['LBL_TOP_ACCOUNTS'];
    $title[] = 'home_myaccount';
    $header = array();
    $header[] = $current_module_strings['LBL_LIST_ACCOUNT_NAME'];
    $currencyid = fetchCurrency($current_user->id);
    $rate_symbol = getCurrencySymbolandCRate($currencyid);
    $rate = $rate_symbol['rate'];
    $curr_symbol = $rate_symbol['symbol'];
    $header[] = $current_module_strings['LBL_LIST_AMOUNT'] . '(' . $curr_symbol . ')';
    $header[] = $current_module_strings['LBL_POTENTIAL_TITLE'];
    $entries = array();
    foreach ($open_accounts_list as $account) {
        $value = array();
        $account_fields = array('ACCOUNT_ID' => $account['accountid'], 'ACCOUNT_NAME' => $account['accountname'], 'AMOUNT' => $account['amount']);
        $Top_Accounts = strlen($account['accountname']) > 20 ? substr($account['accountname'], 0, 20) . '...' : $account['accountname'];
        $value[] = '<a href="index.php?action=DetailView&module=Accounts&record=' . $account['accountid'] . '">' . $Top_Accounts . '</a>';
        $value[] = CurrencyField::convertToUserFormat($account['amount']);
        $entries[$account['accountid']] = $value;
    }
    $values = array('ModuleName' => 'Accounts', 'Title' => $title, 'Header' => $header, 'Entries' => $entries);
    $log->debug("Exiting getTopAccounts method ...");
    if ($display_empty_home_blocks && count($entries) == 0 || count($entries) > 0) {
        return $values;
    }
}
 function TypoForm()
 {
     $array = array('green', 'yellow', 'blue', 'pink', 'orange');
     $form = new Form($this, 'TestForm', $fields = FieldList::create(HeaderField::create('HeaderField1', 'HeaderField Level 1', 1), LiteralField::create('LiteralField', '<p>All fields up to EmailField are required and should be marked as such</p>'), TextField::create('TextField1', 'Text Field Example 1'), TextField::create('TextField2', 'Text Field Example 2'), TextField::create('TextField3', 'Text Field Example 3'), TextField::create('TextField4', ''), HeaderField::create('HeaderField2b', 'Field with right title', 2), $textAreaField = new TextareaField('TextareaField', 'Textarea Field'), EmailField::create('EmailField', 'Email address'), HeaderField::create('HeaderField2c', 'HeaderField Level 2', 2), DropdownField::create('DropdownField', 'Dropdown Field', array(0 => '-- please select --', 1 => 'test AAAA', 2 => 'test BBBB')), OptionsetField::create('OptionSF', 'Optionset Field', $array), CheckboxSetField::create('CheckboxSF', 'Checkbox Set Field', $array), CountryDropdownField::create('CountryDropdownField', 'Countries'), CurrencyField::create('CurrencyField', 'Bling bling', '$123.45'), HeaderField::create('HeaderField3', 'Other Fields', 3), NumericField::create('NumericField', 'Numeric Field '), DateField::create('DateField', 'Date Field'), DateField::create('DateTimeField', 'Date and Time Field'), CheckboxField::create('CheckboxField', 'Checkbox Field')), $actions = FieldList::create(FormAction::create('submit', 'Submit Button')), $requiredFields = RequiredFields::create('TextField1', 'TextField2', 'TextField3', 'ErrorField1', 'ErrorField2', 'EmailField', 'TextField3', 'RightTitleField', 'CheckboxField', 'CheckboxSetField'));
     $textAreaField->setColumns(45);
     $form->setMessage('warning message', 'warning');
     return $form;
 }
 public function getCMSFields()
 {
     $fields = FieldList::create(TabSet::create('Root'));
     $fields->addFieldsToTab('Root.Main', array(TextField::create('Title'), TextareaField::create('Description'), CurrencyField::create('PricePerNight', 'Price (per night)'), DropdownField::create('Bedrooms')->setSource(ArrayLib::valuekey(range(1, 10))), DropdownField::create('Bathrooms')->setSource(ArrayLib::valuekey(range(1, 10))), DropdownField::create('RegionID', 'Region')->setSource(Region::get()->map('ID', 'Title'))->setEmptyString('-- Select a region --'), CheckboxField::create('FeaturedOnHomepage', 'Feature on homepage')));
     $fields->addFieldToTab('Root.Photos', $upload = UploadField::create('PrimaryPhoto', 'Primary photo'));
     $upload->getValidator()->setAllowedExtensions(array('png', 'jpeg', 'jpg', 'gif'));
     $upload->setFolderName('property-photos');
     return $fields;
 }
    public function process($module, $id, Vtiger_PDF_Model $pdf)
    {
        $html = '';
        $recordId = $id;
        $record = Vtiger_Record_Model::getInstanceById($recordId);
        $moduleModel = $record->getModule();
        if (!$moduleModel->isInventory()) {
            return $html;
        }
        $inventoryField = Vtiger_InventoryField_Model::getInstance($module);
        $fields = $inventoryField->getFields(true);
        if ($fields[0] != 0) {
            $columns = $inventoryField->getColumns();
            $inventoryRows = $record->getInventoryData();
            $mainParams = $inventoryField->getMainParams($fields[1]);
            $countFields0 = count($fields[0]);
            $countFields1 = count($fields[1]);
            $countFields2 = count($fields[2]);
            $baseCurrency = Vtiger_Util_Helper::getBaseCurrency();
        }
        if (in_array("currency", $columns)) {
            if (count($inventoryRows) > 0 && $inventoryRows[0]['currency'] != NULL) {
                $currency = $inventoryRows[0]['currency'];
            } else {
                $currency = $baseCurrency['id'];
            }
            $currencySymbolRate = Vtiger_Functions::getCurrencySymbolandRate($currency);
        }
        $html .= '<style>' . '.productTable{color:#000; font-size:10px}' . '.productTable th {text-transform: uppercase;font-weight:normal}' . '.productTable tbody tr:nth-child(odd){background:#eee}' . '.productTable tbody tr td{border-bottom: 1px solid #ddd; padding:5px}' . '.colapseBorder {border-collapse: collapse;}' . '.productTable td, th {padding-left: 5px; padding-right: 5px;}' . '.productTable .summaryContainer{background:#ccc;}' . '</style>';
        if (count($fields[0]) != 0) {
            $discount = 0;
            foreach ($inventoryRows as $key => &$inventoryRow) {
                $taxes = $inventoryField->getTaxParam($inventoryRow['taxparam'], $inventoryRow['net'], $taxes);
            }
            if (in_array('discount', $columns) && in_array('discountmode', $columns)) {
                $html .= '<table class="productTable colapseBorder">
							<thead>
								<tr>
									<th class="tBorder noBottomBorder tHeader">
										<strong>' . vtranslate('LBL_DISCOUNTS_SUMMARY', $module) . '</strong>
									</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td class="textAlignRight tBorder">' . CurrencyField::convertToUserFormat($discount, null, true) . ' ' . $currencySymbolRate['symbol'] . '</td>
								</tr>
							</tbody>
						</table>';
            }
        }
        return $html;
    }
 function testDataValue()
 {
     $f = new CurrencyField('TestField');
     $f->setValue('$123.45');
     $this->assertEquals($f->dataValue(), 123.45);
     $f->setValue('-$123.45');
     $this->assertEquals($f->dataValue(), -123.45);
     $f->setValue('$-123.45');
     $this->assertEquals($f->dataValue(), -123.45);
 }
Example #12
0
 /**
  * Function adds Products/Services-PriceBooks Relation
  * @param type $request
  */
 function addListPrice($request)
 {
     $sourceModule = $request->getModule();
     $sourceRecordId = $request->get('src_record');
     $relatedModule = $request->get('related_module');
     $relInfos = $request->get('relinfo');
     $sourceModuleModel = Vtiger_Module_Model::getInstance($sourceModule);
     $relatedModuleModel = Vtiger_Module_Model::getInstance($relatedModule);
     $relationModel = Vtiger_Relation_Model::getInstance($sourceModuleModel, $relatedModuleModel);
     foreach ($relInfos as $relInfo) {
         $price = CurrencyField::convertToDBFormat($relInfo['price'], null, true);
         $relationModel->addListPrice($sourceRecordId, $relInfo['id'], $price);
     }
 }
 public function getEntries($pagingModel)
 {
     $db = PearDatabase::getInstance();
     $parentModule = $this->getParentRecordModel()->getModule();
     $relationModel = $this->getRelationModel();
     $relationModule = $relationModel->getRelationModuleModel();
     $relatedColumnFieldMapping = $relationModel->getRelationFields(true, true);
     if (count($relatedColumnFieldMapping) <= 0) {
         $relatedColumnFieldMapping = $relationModule->getConfigureRelatedListFields();
     }
     if (count($relatedColumnFieldMapping) <= 0) {
         $relatedColumnFieldMapping = $relationModule->getRelatedListFields();
     }
     $query = $this->getRelationQuery();
     $startIndex = $pagingModel->getStartIndex();
     $pageLimit = $pagingModel->getPageLimit();
     $orderBy = $this->getForSql('orderby');
     $sortOrder = $this->getForSql('sortorder');
     if ($orderBy) {
         $query = "{$query} ORDER BY {$orderBy} {$sortOrder}";
     }
     $limitQuery = $query . ' LIMIT ' . $startIndex . ',' . $pageLimit;
     $result = $db->pquery($limitQuery, array());
     $relatedRecordList = array();
     for ($i = 0; $i < $db->num_rows($result); $i++) {
         $row = $db->fetch_row($result, $i);
         $newRow = array();
         foreach ($row as $col => $val) {
             if (array_key_exists($col, $relatedColumnFieldMapping)) {
                 $newRow[$relatedColumnFieldMapping[$col]] = $val;
             }
         }
         $recordId = $row['crmid'];
         $newRow['id'] = $recordId;
         //Added to support List Price
         $newRow['listprice'] = CurrencyField::convertToUserFormat($row['listprice'], null, true);
         $record = Vtiger_Record_Model::getCleanInstance($relationModule->get('name'));
         $relatedRecordList[$recordId] = $record->setData($newRow)->setModuleFromInstance($relationModule);
     }
     $pagingModel->calculatePageRange($relatedRecordList);
     $nextLimitQuery = $query . ' LIMIT ' . ($startIndex + $pageLimit) . ' , 1';
     $nextPageLimitResult = $db->pquery($nextLimitQuery, array());
     if ($db->num_rows($nextPageLimitResult) > 0) {
         $pagingModel->set('nextPageExists', true);
     } else {
         $pagingModel->set('nextPageExists', false);
     }
     return $relatedRecordList;
 }
 public function getCMSFields()
 {
     $fields = FieldList::create(new Tabset('Root', new Tab('Main'), new Tab('Modifiers')));
     // set variables from Product
     $productID = $this->ProductID != 0 ? $this->ProductID : Session::get('CMSMain.currentPage');
     $product = ProductPage::get()->byID($productID);
     $parentPrice = $product->obj('Price')->Nice();
     $parentWeight = $product->Weight;
     $parentCode = $product->Code;
     // ProductOptionGroup Dropdown field w/ add new
     $groups = function () {
         return OptionGroup::get()->map()->toArray();
     };
     $groupFields = singleton('OptionGroup')->getCMSFields();
     $groupField = DropdownField::create('ProductOptionGroupID', _t("OptionItem.Group", "Group"), $groups())->setEmptyString('')->setDescription(_t('OptionItem.GroupDescription', 'Name of this group of options. Managed in <a href="admin/settings">Settings > FoxyStripe > Option Groups</a>'));
     if (class_exists('QuickAddNewExtension')) {
         $groupField->useAddNew('OptionGroup', $groups, $groupFields);
     }
     $fields->addFieldsToTab('Root.Main', array(HeaderField::create('DetailsHD', _t("OptionItem.DetailsHD", "Product Option Details"), 2), Textfield::create('Title')->setTitle(_t("OptionItem.Title", "Product Option Name")), CheckboxField::create('Available')->setTitle(_t("OptionItem.Available", "Available for purchase"))->setDescription(_t('OptionItem.AvailableDescription', "If unchecked, will disable this option in the drop down menu")), $groupField));
     $fields->addFieldsToTab('Root.Modifiers', array(HeaderField::create('ModifyHD', _t('OptionItem.ModifyHD', 'Product Option Modifiers'), 2), HeaderField::create('WeightHD', _t('OptionItem.WeightHD', 'Modify Weight'), 3), NumericField::create('WeightModifier')->setTitle(_t('OptionItem.WeightModifier', 'Weight')), DropdownField::create('WeightModifierAction', _t('OptionItem.WeightModifierAction', 'Weight Modification'), array('Add' => _t('OptionItem.WeightAdd', "Add to Base Weight ({weight})", 'Add to weight', array('weight' => $parentWeight)), 'Subtract' => _t('OptionItem.WeightSubtract', "Subtract from Base Weight ({weight})", 'Subtract from weight', array('weight' => $parentWeight)), 'Set' => _t('OptionItem.WeightSet', 'Set as a new Weight')))->setEmptyString('')->setDescription(_t('OptionItem.WeightDescription', 'Does weight modify or replace base weight?')), HeaderField::create('PriceHD', _t('OptionItem.PriceHD', 'Modify Price'), 3), CurrencyField::create('PriceModifier')->setTitle(_t('OptionItem.PriceModifier', 'Price')), DropdownField::create('PriceModifierAction', _t('OptionItem.PriceModifierAction', 'Price Modification'), array('Add' => _t('OptionItem.PriceAdd', "Add to Base Price ({price})", 'Add to price', array('price' => $parentPrice)), 'Subtract' => _t('OptionItem.PriceSubtract', "Subtract from Base Price ({price})", 'Subtract from price', array('price' => $parentPrice)), 'Set' => _t('OptionItem.PriceSet', 'Set as a new Price')))->setEmptyString('')->setDescription(_t('OptionItem.PriceDescription', 'Does price modify or replace base price?')), HeaderField::create('CodeHD', _t('OptionItem.CodeHD', 'Modify Code'), 3), TextField::create('CodeModifier')->setTitle(_t('OptionItem.CodeModifier', 'Code')), DropdownField::create('CodeModifierAction', _t('OptionItem.CodeModifierAction', 'Code Modification'), array('Add' => _t('OptionItem.CodeAdd', "Add to Base Code ({code})", 'Add to code', array('code' => $parentCode)), 'Subtract' => _t('OptionItem.CodeSubtract', 'Subtract from Base Code ({code})', 'Subtract from code', array('code' => $parentCode)), 'Set' => _t('OptionItem.CodeSet', 'Set as a new Code')))->setEmptyString('')->setDescription(_t('OptionItem.CodeDescription', 'Does code modify or replace base code?'))));
     /*
     // Cateogry Dropdown field w/ add new
     // removed until relevance determined
     $categories = function(){
         return ProductCategory::get()->map()->toArray();
     };
     
     // to do - have OptionItem category override set ProductPage category if selected: issue #155
     $categoryField = DropdownField::create('CategoryID', 'Category', $categories())
         ->setEmptyString('')
         ->setDescription('Categories can be managed in <a href="admin/settings">Settings > FoxyStripe > Categories</a>');
     if (class_exists('QuickAddNewExtension')) $categoryField->useAddNew('ProductCategory', $categories);
     
     $fields->insertAfter($categoryField, 'ProductOptionGroupID');
     */
     // allow CMS fields to be extended
     $this->extend('getCMSFields', $fields);
     return $fields;
 }
 function wf_formatcurrency($value)
 {
     $currencyField = new CurrencyField($value);
     return $currencyField->getDisplayValue(null, true);
 }
Example #16
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;
    }
Example #17
0
 /**
  * this function takes in an array of values for an user and sanitizes it for export
  * @param array $arr - the array of values
  */
 function sanitizeValues($arr)
 {
     global $current_user, $adb;
     $roleid = fetchUserRole($current_user->id);
     $decimal = $current_user->currency_decimal_separator;
     $numsep = $current_user->currency_grouping_separator;
     foreach ($arr as $fieldlabel => &$value) {
         $fieldInfo = $this->fieldsArr[$fieldlabel];
         $uitype = $fieldInfo['uitype'];
         $fieldname = $fieldInfo['fieldname'];
         if ($uitype == 15 || $uitype == 16 || $uitype == 33) {
             //picklists
             if (empty($this->picklistValues[$fieldname])) {
                 $this->picklistValues[$fieldname] = getAssignedPicklistValues($fieldname, $roleid, $adb);
             }
             $value = trim($value);
         } elseif ($uitype == 10) {
             //have to handle uitype 10
             $value = trim($value);
             if (!empty($value)) {
                 $parent_module = getSalesEntityType($value);
                 $displayValueArray = getEntityName($parent_module, $value);
                 if (!empty($displayValueArray)) {
                     foreach ($displayValueArray as $k => $v) {
                         $displayValue = $v;
                     }
                 }
                 if (!empty($parent_module) && !empty($displayValue)) {
                     $value = $parent_module . "::::" . $displayValue;
                 } else {
                     $value = "";
                 }
             } else {
                 $value = '';
             }
         } elseif ($uitype == 71 || $uitype == 72) {
             $value = CurrencyField::convertToUserFormat($value, null, true);
         } elseif ($uitype == 7 || $fieldInfo['typeofdata'] == 'N~O' || $uitype == 9) {
             $value = number_format($value, 2, $decimal, $numsep);
         }
     }
     return $arr;
 }
$list_body = '';
for ($i = 0; $i < count($new_prod_array); $i++) {
    $log->info("Products :: Showing the List of products to be added in price book");
    $entity_id = $new_prod_array[$i];
    $list_body .= '<tr class="lvtColData" onmouseover="this.className=\'lvtColDataHover\'" onmouseout="this.className=\'lvtColData\'" bgcolor="white">';
    $unit_price = $prod_price_list[$entity_id];
    $field_name = $entity_id . "_listprice";
    $unit_price_array[] = '"' . CurrencyField::convertToUserFormat($unit_price, null, true) . '"';
    $field_name_array[] = "'" . $field_name . "'";
    $list_body .= '<td><INPUT type=checkbox NAME="selected_id" id="check_' . $entity_id . '" value= ' . $entity_id . ' onClick=\'toggleSelectAll(this.name,"selectall");updateListPriceForField("' . $field_name . '",this)\'></td>';
    $list_body .= '<td>' . $adb->query_result($list_result, $entity_id_array[$entity_id], "productname") . '</td>';
    if (getFieldVisibilityPermission('Products', $current_user->id, 'productcode') == '0') {
        $list_body .= '<td>' . $adb->query_result($list_result, $entity_id_array[$entity_id], "productcode") . '</td>';
    }
    if (getFieldVisibilityPermission('Products', $current_user->id, 'unit_price') == '0') {
        $list_body .= '<td>' . CurrencyField::convertToUserFormat($unit_price, null, true) . '</td>';
    }
    $list_body .= '<td>';
    if (isPermitted("PriceBooks", "EditView", "") == 'yes') {
        $list_body .= '<input type="text" name="' . $field_name . '" style="visibility:hidden;" id="' . $field_name . '">';
    } else {
        $list_body .= '<input type="text" name="' . $field_name . '" style="visibility:hidden;" readonly id="' . $field_name . '">';
    }
    $list_body .= '</td></tr>';
}
$smarty->assign("UNIT_PRICE_ARRAY", implode(",", $unit_price_array));
$smarty->assign("FIELD_NAME_ARRAY", implode(",", $field_name_array));
if ($order_by != '') {
    $url_string .= "&order_by=" . $order_by;
}
if ($sorder != '') {
Example #19
0
/**	Function used to get all the price details for different currencies which are associated to the given product
 *	@param int $productid - product id to which we want to get all the associated prices
 *  @param decimal $unit_price - Unit price of the product
 *  @param string $available - available or available_associated where as default is available, if available then the prices in the currencies which are available now will be returned, otherwise if the value is available_associated then prices of all the associated currencies will be retruned
 *	@return array $price_details - price details as a array with productid, curid, curname
 */
function getPriceDetailsForProduct($productid, $unit_price, $available = 'available', $itemtype = 'Products')
{
    global $log, $adb;
    $log->debug("Entering into function getPriceDetailsForProduct({$productid})");
    if ($productid != '') {
        $product_currency_id = getProductBaseCurrency($productid, $itemtype);
        $product_base_conv_rate = getBaseConversionRateForProduct($productid, 'edit', $itemtype);
        // Detail View
        if ($available == 'available_associated') {
            $query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price\n\t\t\t\t\tfrom vtiger_currency_info\n\t\t\t\t\tinner join vtiger_productcurrencyrel on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid\n\t\t\t\t\twhere vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0\n\t\t\t\t\tand vtiger_productcurrencyrel.productid = ? and vtiger_currency_info.id != ?";
            $params = array($productid, $product_currency_id);
        } else {
            // Edit View
            $query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price\n\t\t\t\t\tfrom vtiger_currency_info\n\t\t\t\t\tleft join vtiger_productcurrencyrel\n\t\t\t\t\ton vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid and vtiger_productcurrencyrel.productid = ?\n\t\t\t\t\twhere vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0";
            $params = array($productid);
        }
        //Postgres 8 fixes
        if ($adb->dbType == "pgsql") {
            $query = fixPostgresQuery($query, $log, 0);
        }
        $res = $adb->pquery($query, $params);
        for ($i = 0; $i < $adb->num_rows($res); $i++) {
            $price_details[$i]['productid'] = $productid;
            $price_details[$i]['currencylabel'] = $adb->query_result($res, $i, 'currency_name');
            $price_details[$i]['currencycode'] = $adb->query_result($res, $i, 'currency_code');
            $price_details[$i]['currencysymbol'] = $adb->query_result($res, $i, 'currency_symbol');
            $currency_id = $adb->query_result($res, $i, 'id');
            $price_details[$i]['curid'] = $currency_id;
            $price_details[$i]['curname'] = 'curname' . $adb->query_result($res, $i, 'id');
            $cur_value = $adb->query_result($res, $i, 'actual_price');
            // Get the conversion rate for the given currency, get the conversion rate of the product currency to base currency.
            // Both together will be the actual conversion rate for the given currency.
            $conversion_rate = $adb->query_result($res, $i, 'conversion_rate');
            $actual_conversion_rate = $product_base_conv_rate * $conversion_rate;
            if ($cur_value == null || $cur_value == '') {
                $price_details[$i]['check_value'] = false;
                if ($unit_price != null) {
                    $cur_value = convertFromMasterCurrency($unit_price, $actual_conversion_rate);
                } else {
                    $cur_value = '0';
                }
            } else {
                $price_details[$i]['check_value'] = true;
            }
            $price_details[$i]['curvalue'] = CurrencyField::convertToUserFormat($cur_value, null, true);
            $price_details[$i]['conversionrate'] = $actual_conversion_rate;
            $is_basecurrency = false;
            if ($currency_id == $product_currency_id) {
                $is_basecurrency = true;
            }
            $price_details[$i]['is_basecurrency'] = $is_basecurrency;
        }
    } else {
        if ($available == 'available') {
            // Create View
            global $current_user;
            $user_currency_id = fetchCurrency($current_user->id);
            $query = "select vtiger_currency_info.* from vtiger_currency_info\n\t\t\t\t\twhere vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0";
            $params = array();
            $res = $adb->pquery($query, $params);
            for ($i = 0; $i < $adb->num_rows($res); $i++) {
                $price_details[$i]['currencylabel'] = $adb->query_result($res, $i, 'currency_name');
                $price_details[$i]['currencycode'] = $adb->query_result($res, $i, 'currency_code');
                $price_details[$i]['currencysymbol'] = $adb->query_result($res, $i, 'currency_symbol');
                $currency_id = $adb->query_result($res, $i, 'id');
                $price_details[$i]['curid'] = $currency_id;
                $price_details[$i]['curname'] = 'curname' . $adb->query_result($res, $i, 'id');
                // Get the conversion rate for the given currency, get the conversion rate of the product currency(logged in user's currency) to base currency.
                // Both together will be the actual conversion rate for the given currency.
                $conversion_rate = $adb->query_result($res, $i, 'conversion_rate');
                $user_cursym_convrate = getCurrencySymbolandCRate($user_currency_id);
                $product_base_conv_rate = 1 / $user_cursym_convrate['rate'];
                $actual_conversion_rate = $product_base_conv_rate * $conversion_rate;
                $price_details[$i]['check_value'] = false;
                $price_details[$i]['curvalue'] = '0';
                $price_details[$i]['conversionrate'] = $actual_conversion_rate;
                $is_basecurrency = false;
                if ($currency_id == $user_currency_id) {
                    $is_basecurrency = true;
                }
                $price_details[$i]['is_basecurrency'] = $is_basecurrency;
            }
        } else {
            $log->debug("Product id is empty. we cannot retrieve the associated prices.");
        }
    }
    $log->debug("Exit from function getPriceDetailsForProduct({$productid})");
    return $price_details;
}
Example #20
0
 /**	Function to display the Services which are related to the PriceBook
  *	@param string $query - query to get the list of products which are related to the current PriceBook
  *	@param object $focus - PriceBook object which contains all the information of the current PriceBook
  *	@param string $returnset - return_module, return_action and return_id which are sequenced with & to pass to the URL which is optional
  *	return array $return_data which will be formed like array('header'=>$header,'entries'=>$entries_list) where as $header contains all the header columns and $entries_list will contain all the Service entries
  */
 function getPriceBookRelatedServices($query, $focus, $returnset = '')
 {
     global $log;
     $log->debug("Entering getPriceBookRelatedServices(" . $query . "," . get_class($focus) . "," . $returnset . ") method ...");
     global $adb;
     global $app_strings;
     global $current_language, $current_user;
     $current_module_strings = return_module_language($current_language, 'Services');
     global $list_max_entries_per_page;
     global $urlPrefix;
     global $theme;
     $pricebook_id = $_REQUEST['record'];
     $theme_path = "themes/" . $theme . "/";
     $image_path = $theme_path . "images/";
     $computeCount = $_REQUEST['withCount'];
     if (PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true || (bool) $computeCount == true) {
         $noofrows = $adb->query_result($adb->query(mkCountQuery($query)), 0, 'count');
     } else {
         $noofrows = null;
     }
     $module = 'PriceBooks';
     $relatedmodule = 'Services';
     if (!$_SESSION['rlvs'][$module][$relatedmodule]) {
         $modObj = new ListViewSession();
         $modObj->sortby = $focus->default_order_by;
         $modObj->sorder = $focus->default_sort_order;
         $_SESSION['rlvs'][$module][$relatedmodule] = get_object_vars($modObj);
     }
     if (isset($_REQUEST['relmodule']) && $_REQUEST['relmodule'] != '' && $_REQUEST['relmodule'] == $relatedmodule) {
         $relmodule = vtlib_purify($_REQUEST['relmodule']);
         if ($_SESSION['rlvs'][$module][$relmodule]) {
             setSessionVar($_SESSION['rlvs'][$module][$relmodule], $noofrows, $list_max_entries_per_page, $module, $relmodule);
         }
     }
     global $relationId;
     $start = RelatedListViewSession::getRequestCurrentPage($relationId, $query);
     $navigation_array = VT_getSimpleNavigationValues($start, $list_max_entries_per_page, $noofrows);
     $limit_start_rec = ($start - 1) * $list_max_entries_per_page;
     if ($adb->dbType == "pgsql") {
         $list_result = $adb->pquery($query . " OFFSET {$limit_start_rec} LIMIT {$list_max_entries_per_page}", array());
     } else {
         $list_result = $adb->pquery($query . " LIMIT {$limit_start_rec}, {$list_max_entries_per_page}", array());
     }
     $header = array();
     $header[] = $current_module_strings['LBL_LIST_SERVICE_NAME'];
     if (getFieldVisibilityPermission('Services', $current_user->id, 'unit_price') == '0') {
         $header[] = $current_module_strings['LBL_SERVICE_UNIT_PRICE'];
     }
     $header[] = $current_module_strings['LBL_PB_LIST_PRICE'];
     if (isPermitted("PriceBooks", "EditView", "") == 'yes' || isPermitted("PriceBooks", "Delete", "") == 'yes') {
         $header[] = $app_strings['LBL_ACTION'];
     }
     $currency_id = $focus->column_fields['currency_id'];
     $numRows = $adb->num_rows($list_result);
     for ($i = 0; $i < $numRows; $i++) {
         $entity_id = $adb->query_result($list_result, $i, "crmid");
         $unit_price = $adb->query_result($list_result, $i, "unit_price");
         if ($currency_id != null) {
             $prod_prices = getPricesForProducts($currency_id, array($entity_id), 'Services');
             $unit_price = $prod_prices[$entity_id];
         }
         $listprice = $adb->query_result($list_result, $i, "listprice");
         $field_name = $entity_id . "_listprice";
         $entries = array();
         $entries[] = textlength_check($adb->query_result($list_result, $i, "servicename"));
         if (getFieldVisibilityPermission('Services', $current_user->id, 'unit_price') == '0') {
             $entries[] = CurrencyField::convertToUserFormat($unit_price, null, true);
         }
         $entries[] = CurrencyField::convertToUserFormat($listprice, null, true);
         $action = "";
         if (isPermitted("PriceBooks", "EditView", "") == 'yes' && isPermitted('Services', 'EditView', $entity_id) == 'yes') {
             $action .= '<img style="cursor:pointer;" src="themes/images/editfield.gif" border="0" onClick="fnvshobj(this,\'editlistprice\'),editProductListPrice(\'' . $entity_id . '\',\'' . $pricebook_id . '\',\'' . $listprice . '\')" alt="' . $app_strings["LBL_EDIT_BUTTON"] . '" title="' . $app_strings["LBL_EDIT_BUTTON"] . '"/>';
         } else {
             $action .= '<img src="' . vtiger_imageurl('blank.gif', $theme) . '" border="0" />';
         }
         if (isPermitted("PriceBooks", "Delete", "") == 'yes' && isPermitted('Services', 'Delete', $entity_id) == 'yes') {
             if ($action != "") {
                 $action .= '&nbsp;|&nbsp;';
             }
             $action .= '<img src="themes/images/delete.gif" onclick="if(confirm(\'' . $app_strings['ARE_YOU_SURE'] . '\')) deletePriceBookProductRel(' . $entity_id . ',' . $pricebook_id . ');" alt="' . $app_strings["LBL_DELETE"] . '" title="' . $app_strings["LBL_DELETE"] . '" style="cursor:pointer;" border="0">';
         }
         if ($action != "") {
             $entries[] = $action;
         }
         $entries_list[] = $entries;
     }
     $navigationOutput[] = getRecordRangeMessage($list_result, $limit_start_rec, $noofrows);
     $navigationOutput[] = getRelatedTableHeaderNavigation($navigation_array, '', $module, $relatedmodule, $focus->id);
     $return_data = array('header' => $header, 'entries' => $entries_list, 'navigation' => $navigationOutput);
     $log->debug("Exiting getPriceBookRelatedServices method ...");
     return $return_data;
 }
 /** Function to insert values in the specifed table for the specified module
  * @param $table_name -- table name:: Type varchar
  * @param $module -- module:: Type varchar
  */
 function insertIntoEntityTable($table_name, $module, $fileid = '')
 {
     global $log;
     global $current_user, $app_strings;
     $log->info("function insertIntoEntityTable " . $module . ' vtiger_table name ' . $table_name);
     global $adb;
     $insertion_mode = $this->mode;
     //Checkin whether an entry is already is present in the vtiger_table to update
     if ($insertion_mode == 'edit') {
         $tablekey = $this->tab_name_index[$table_name];
         // Make selection on the primary key of the module table to check.
         $check_query = "select {$tablekey} from {$table_name} where {$tablekey}=?";
         $check_result = $adb->pquery($check_query, array($this->id));
         $num_rows = $adb->num_rows($check_result);
         if ($num_rows <= 0) {
             $insertion_mode = '';
         }
     }
     $tabid = getTabid($module);
     if ($module == 'Calendar' && $this->column_fields["activitytype"] != null && $this->column_fields["activitytype"] != 'Task') {
         $tabid = getTabid('Events');
     }
     if ($insertion_mode == 'edit') {
         $update = array();
         $update_params = array();
         checkFileAccessForInclusion('user_privileges/user_privileges_' . $current_user->id . '.php');
         require 'user_privileges/user_privileges_' . $current_user->id . '.php';
         if ($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) {
             $sql = "select * from vtiger_field where tabid in (" . generateQuestionMarks($tabid) . ") and tablename=? and displaytype in (1,3) and presence in (0,2) group by columnname";
             $params = array($tabid, $table_name);
         } else {
             $profileList = getCurrentUserProfileList();
             if (count($profileList) > 0) {
                 $sql = "SELECT *\n\t\t\t  \t\t\tFROM vtiger_field\n\t\t\t  \t\t\tINNER JOIN vtiger_profile2field\n\t\t\t  \t\t\tON vtiger_profile2field.fieldid = vtiger_field.fieldid\n\t\t\t  \t\t\tINNER JOIN vtiger_def_org_field\n\t\t\t  \t\t\tON vtiger_def_org_field.fieldid = vtiger_field.fieldid\n\t\t\t  \t\t\tWHERE vtiger_field.tabid = ?\n\t\t\t  \t\t\tAND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0\n\t\t\t  \t\t\tAND vtiger_profile2field.profileid IN (" . generateQuestionMarks($profileList) . ")\n\t\t\t  \t\t\tAND vtiger_def_org_field.visible = 0 and vtiger_field.tablename=? and vtiger_field.displaytype in (1,3) and vtiger_field.presence in (0,2) group by columnname";
                 $params = array($tabid, $profileList, $table_name);
             } else {
                 $sql = "SELECT *\n\t\t\t  \t\t\tFROM vtiger_field\n\t\t\t  \t\t\tINNER JOIN vtiger_profile2field\n\t\t\t  \t\t\tON vtiger_profile2field.fieldid = vtiger_field.fieldid\n\t\t\t  \t\t\tINNER JOIN vtiger_def_org_field\n\t\t\t  \t\t\tON vtiger_def_org_field.fieldid = vtiger_field.fieldid\n\t\t\t  \t\t\tWHERE vtiger_field.tabid = ?\n\t\t\t  \t\t\tAND vtiger_profile2field.visible = 0 AND vtiger_profile2field.readonly = 0\n\t\t\t  \t\t\tAND vtiger_def_org_field.visible = 0 and vtiger_field.tablename=? and vtiger_field.displaytype in (1,3) and vtiger_field.presence in (0,2) group by columnname";
                 $params = array($tabid, $table_name);
             }
         }
     } else {
         $table_index_column = $this->tab_name_index[$table_name];
         if ($table_index_column == 'id' && $table_name == 'vtiger_users') {
             $currentuser_id = $adb->getUniqueID("vtiger_users");
             $this->id = $currentuser_id;
         }
         $column = array($table_index_column);
         $value = array($this->id);
         $sql = "select * from vtiger_field where tabid=? and tablename=? and displaytype in (1,3,4) and vtiger_field.presence in (0,2)";
         $params = array($tabid, $table_name);
     }
     // Attempt to re-use the quer-result to avoid reading for every save operation
     // TODO Need careful analysis on impact ... MEMORY requirement might be more
     static $_privatecache = array();
     $cachekey = "{$insertion_mode}-" . implode(',', $params);
     if (!isset($_privatecache[$cachekey])) {
         $result = $adb->pquery($sql, $params);
         $noofrows = $adb->num_rows($result);
         if (CRMEntity::isBulkSaveMode()) {
             $cacheresult = array();
             for ($i = 0; $i < $noofrows; ++$i) {
                 $cacheresult[] = $adb->fetch_array($result);
             }
             $_privatecache[$cachekey] = $cacheresult;
         }
     } else {
         // Useful when doing bulk save
         $result = $_privatecache[$cachekey];
         $noofrows = count($result);
     }
     for ($i = 0; $i < $noofrows; $i++) {
         $fieldname = $this->resolve_query_result_value($result, $i, "fieldname");
         $columname = $this->resolve_query_result_value($result, $i, "columnname");
         $uitype = $this->resolve_query_result_value($result, $i, "uitype");
         $generatedtype = $this->resolve_query_result_value($result, $i, "generatedtype");
         $typeofdata = $this->resolve_query_result_value($result, $i, "typeofdata");
         $typeofdata_array = explode("~", $typeofdata);
         $datatype = $typeofdata_array[0];
         $ajaxSave = false;
         if ($_REQUEST['file'] == 'DetailViewAjax' && $_REQUEST['ajxaction'] == 'DETAILVIEW' && isset($_REQUEST["fldName"]) && $_REQUEST["fldName"] != $fieldname || $_REQUEST['action'] == 'MassEditSave' && !isset($_REQUEST[$fieldname . "_mass_edit_check"])) {
             $ajaxSave = true;
         }
         if ($uitype == 4 && $insertion_mode != 'edit') {
             $fldvalue = '';
             // Bulk Save Mode: Avoid generation of module sequence number, take care later.
             // SalesPlatform.ru begin: Added separate numbering for self organizations
             if (!CRMEntity::isBulkSaveMode()) {
                 $modules = array('Invoice', 'Act', 'Consignment');
                 if (in_array($module, $modules) && isset($this->column_fields['spcompany'])) {
                     $fldvalue = $this->setModuleSeqNumber("increment", $module, '', '', $this->column_fields['spcompany']);
                 } else {
                     $fldvalue = $this->setModuleSeqNumber("increment", $module);
                 }
                 //$fldvalue = $this->setModuleSeqNumber("increment", $module);
             }
             // SalesPlatform.ru end
             $this->column_fields[$fieldname] = $fldvalue;
         }
         if (isset($this->column_fields[$fieldname])) {
             if ($uitype == 56) {
                 if ($this->column_fields[$fieldname] == 'on' || $this->column_fields[$fieldname] == 1) {
                     $fldvalue = '1';
                 } else {
                     $fldvalue = '0';
                 }
             } elseif ($uitype == 15 || $uitype == 16) {
                 if ($this->column_fields[$fieldname] == $app_strings['LBL_NOT_ACCESSIBLE']) {
                     //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
                     $sql = "select {$columname} from  {$table_name} where " . $this->tab_name_index[$table_name] . "=?";
                     $res = $adb->pquery($sql, array($this->id));
                     $pick_val = $adb->query_result($res, 0, $columname);
                     $fldvalue = $pick_val;
                 } else {
                     $fldvalue = $this->column_fields[$fieldname];
                 }
             } elseif ($uitype == 33) {
                 if (is_array($this->column_fields[$fieldname])) {
                     $field_list = implode(' |##| ', $this->column_fields[$fieldname]);
                 } else {
                     $field_list = $this->column_fields[$fieldname];
                 }
                 if ($field_list == '') {
                     $fldvalue = NULL;
                 } else {
                     $fldvalue = $field_list;
                 }
             } elseif ($uitype == 5 || $uitype == 6 || $uitype == 23) {
                 //Added to avoid function call getDBInsertDateValue in ajax save
                 if (isset($current_user->date_format) && !$ajaxSave) {
                     $fldvalue = getValidDBInsertDateValue($this->column_fields[$fieldname]);
                 } else {
                     $fldvalue = $this->column_fields[$fieldname];
                 }
             } elseif ($uitype == 7) {
                 //strip out the spaces and commas in numbers if given ie., in amounts there may be ,
                 $fldvalue = str_replace(",", "", $this->column_fields[$fieldname]);
                 //trim($this->column_fields[$fieldname],",");
             } elseif ($uitype == 26) {
                 if (empty($this->column_fields[$fieldname])) {
                     $fldvalue = 1;
                     //the documents will stored in default folder
                 } else {
                     $fldvalue = $this->column_fields[$fieldname];
                 }
             } elseif ($uitype == 28) {
                 if ($this->column_fields[$fieldname] == null) {
                     $fileQuery = $adb->pquery("SELECT filename from vtiger_notes WHERE notesid = ?", array($this->id));
                     $fldvalue = null;
                     if (isset($fileQuery)) {
                         $rowCount = $adb->num_rows($fileQuery);
                         if ($rowCount > 0) {
                             $fldvalue = decode_html($adb->query_result($fileQuery, 0, 'filename'));
                         }
                     }
                 } else {
                     $fldvalue = decode_html($this->column_fields[$fieldname]);
                 }
             } elseif ($uitype == 8) {
                 $this->column_fields[$fieldname] = rtrim($this->column_fields[$fieldname], ',');
                 $ids = explode(',', $this->column_fields[$fieldname]);
                 $json = new Zend_Json();
                 $fldvalue = $json->encode($ids);
             } elseif ($uitype == 12) {
                 // Bulk Sae Mode: Consider the FROM email address as specified, if not lookup
                 $fldvalue = $this->column_fields[$fieldname];
                 if (empty($fldvalue)) {
                     $query = "SELECT email1 FROM vtiger_users WHERE id = ?";
                     $res = $adb->pquery($query, array($current_user->id));
                     $rows = $adb->num_rows($res);
                     if ($rows > 0) {
                         $fldvalue = $adb->query_result($res, 0, 'email1');
                     }
                 }
                 // END
             } elseif ($uitype == 72 && !$ajaxSave) {
                 // Some of the currency fields like Unit Price, Totoal , Sub-total - doesn't need currency conversion during save
                 $fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname], null, true);
             } elseif ($uitype == 71 && !$ajaxSave) {
                 $fldvalue = CurrencyField::convertToDBFormat($this->column_fields[$fieldname]);
             } else {
                 $fldvalue = $this->column_fields[$fieldname];
             }
             if ($uitype != 33 && $uitype != 8) {
                 $fldvalue = from_html($fldvalue, $insertion_mode == 'edit' ? true : false);
             }
         } else {
             $fldvalue = '';
         }
         if ($fldvalue == '') {
             $fldvalue = $this->get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
         }
         if ($insertion_mode == 'edit') {
             if ($table_name != 'vtiger_ticketcomments' && $uitype != 4) {
                 array_push($update, $columname . "=?");
                 array_push($update_params, $fldvalue);
             }
         } else {
             array_push($column, $columname);
             array_push($value, $fldvalue);
         }
     }
     if ($insertion_mode == 'edit') {
         if ($module == 'Potentials') {
             $dbquery = 'select sales_stage from vtiger_potential where potentialid = ?';
             $sales_stage = $adb->query_result($adb->pquery($dbquery, array($this->id)), 0, 'sales_stage');
             if ($sales_stage != $_REQUEST['sales_stage'] && $_REQUEST['sales_stage'] != '') {
                 $date_var = date("Y-m-d H:i:s");
                 $closingDateField = new DateTimeField($this->column_fields['closingdate']);
                 $closingdate = $_REQUEST['ajxaction'] == 'DETAILVIEW' ? $this->column_fields['closingdate'] : $closingDateField->getDBInsertDateValue();
                 $sql = "insert into vtiger_potstagehistory values(?,?,?,?,?,?,?,?)";
                 $params = array('', $this->id, $this->column_fields['amount'], decode_html($sales_stage), $this->column_fields['probability'], 0, $adb->formatDate($closingdate, true), $adb->formatDate($date_var, true));
                 $adb->pquery($sql, $params);
             }
         } elseif ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice' || $module == 'Act' || $module == 'Consignment') {
             //elseif ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
             // SalesPlatform.ru end
             //added to update the history for PO, SO, Quotes and Invoice
             $history_field_array = array("Act" => "sp_actstatus", "Consignment" => "sp_consignmentstatus", "PurchaseOrder" => "postatus", "SalesOrder" => "sostatus", "Quotes" => "quotestage", "Invoice" => "invoicestatus");
             $inventory_module = $module;
             if ($_REQUEST['ajxaction'] == 'DETAILVIEW') {
                 //if we use ajax edit
                 if ($inventory_module == "PurchaseOrder") {
                     $relatedname = getVendorName($this->column_fields['vendor_id']);
                 } else {
                     $relatedname = getAccountName($this->column_fields['account_id']);
                 }
                 $total = $this->column_fields['hdnGrandTotal'];
             } else {
                 //using edit button and save
                 if ($inventory_module == "PurchaseOrder") {
                     $relatedname = $_REQUEST["vendor_name"];
                 } else {
                     $relatedname = $_REQUEST["account_name"];
                 }
                 $total = $_REQUEST['total'];
             }
             if ($this->column_fields["{$history_field_array[$inventory_module]}"] == $app_strings['LBL_NOT_ACCESSIBLE']) {
                 //If the value in the request is Not Accessible for a picklist, the existing value will be replaced instead of Not Accessible value.
                 $his_col = $history_field_array[$inventory_module];
                 $his_sql = "select {$his_col} from  {$this->table_name} where " . $this->table_index . "=?";
                 $his_res = $adb->pquery($his_sql, array($this->id));
                 $status_value = $adb->query_result($his_res, 0, $his_col);
                 $stat_value = $status_value;
             } else {
                 $stat_value = $this->column_fields["{$history_field_array[$inventory_module]}"];
             }
             $oldvalue = getSingleFieldValue($this->table_name, $history_field_array[$inventory_module], $this->table_index, $this->id);
             if ($this->column_fields["{$history_field_array[$inventory_module]}"] != '' && $oldvalue != $stat_value) {
                 addInventoryHistory($inventory_module, $this->id, $relatedname, $total, $stat_value);
             }
         }
         //Check done by Don. If update is empty the the query fails
         if (count($update) > 0) {
             $sql1 = "update {$table_name} set " . implode(",", $update) . " where " . $this->tab_name_index[$table_name] . "=?";
             array_push($update_params, $this->id);
             $adb->pquery($sql1, $update_params);
         }
     } else {
         $sql1 = "insert into {$table_name}(" . implode(",", $column) . ") values(" . generateQuestionMarks($value) . ")";
         $adb->pquery($sql1, $value);
     }
 }
Example #22
0
    function getAdvancedFilterList($reportid)
    {
        global $adb;
        global $modules;
        global $log;
        global $current_user;
        $advft_criteria = array();
        $sql = 'SELECT * FROM vtiger_relcriteria_grouping WHERE queryid = ? ORDER BY groupid';
        $groupsresult = $adb->pquery($sql, array($reportid));
        $i = 1;
        $j = 0;
        while ($relcriteriagroup = $adb->fetch_array($groupsresult)) {
            $groupId = $relcriteriagroup["groupid"];
            $groupCondition = $relcriteriagroup["group_condition"];
            $ssql = 'select vtiger_relcriteria.* from vtiger_report
						inner join vtiger_relcriteria on vtiger_relcriteria.queryid = vtiger_report.queryid
						left join vtiger_relcriteria_grouping on vtiger_relcriteria.queryid = vtiger_relcriteria_grouping.queryid
								and vtiger_relcriteria.groupid = vtiger_relcriteria_grouping.groupid';
            $ssql .= " where vtiger_report.reportid = ? AND vtiger_relcriteria.groupid = ? order by vtiger_relcriteria.columnindex";
            $result = $adb->pquery($ssql, array($reportid, $groupId));
            $noOfColumns = $adb->num_rows($result);
            if ($noOfColumns <= 0) {
                continue;
            }
            while ($relcriteriarow = $adb->fetch_array($result)) {
                $columnIndex = $relcriteriarow["columnindex"];
                $criteria = array();
                $criteria['columnname'] = $relcriteriarow["columnname"];
                $criteria['comparator'] = $relcriteriarow["comparator"];
                $advfilterval = $relcriteriarow["value"];
                $col = explode(":", $relcriteriarow["columnname"]);
                $moduleFieldLabel = $col[2];
                $fieldName = $col[3];
                list($module, $fieldLabel) = explode('__', $moduleFieldLabel, 2);
                $fieldInfo = getFieldByReportLabel($module, $fieldLabel);
                $fieldType = null;
                if (!empty($fieldInfo)) {
                    $field = WebserviceField::fromArray($adb, $fieldInfo);
                    $fieldType = $field->getFieldDataType();
                }
                if ($fieldType == 'currency') {
                    if ($field->getUIType() == '71') {
                        $advfilterval = CurrencyField::convertToUserFormat($advfilterval, $current_user);
                    } else {
                        if ($field->getUIType() == '72') {
                            $advfilterval = CurrencyField::convertToUserFormat($advfilterval, $current_user, true);
                        }
                    }
                }
                $temp_val = explode(",", $relcriteriarow["value"]);
                if ($col[4] == 'D' || $col[4] == 'T' && $col[1] != 'time_start' && $col[1] != 'time_end' || $col[4] == 'DT') {
                    $val = array();
                    for ($x = 0; $x < count($temp_val); $x++) {
                        if ($col[4] == 'D') {
                            $date = new DateTimeField(trim($temp_val[$x]));
                            $val[$x] = $date->getDisplayDate();
                        } elseif ($col[4] == 'DT') {
                            $date = new DateTimeField(trim($temp_val[$x]));
                            $val[$x] = $date->getDisplayDateTimeValue();
                        } else {
                            $date = new DateTimeField(trim($temp_val[$x]));
                            $val[$x] = $date->getDisplayTime();
                        }
                    }
                    $advfilterval = implode(",", $val);
                }
                //In vtiger6 report filter conditions, if the value has "(double quotes) then it is failed.
                $criteria['value'] = Vtiger_Util_Helper::toSafeHTML(decode_html($advfilterval));
                $criteria['column_condition'] = $relcriteriarow["column_condition"];
                $advft_criteria[$relcriteriarow['groupid']]['columns'][$j] = $criteria;
                $advft_criteria[$relcriteriarow['groupid']]['condition'] = $groupCondition;
                $j++;
            }
            $i++;
        }
        // Clear the condition (and/or) for last group, if any.
        if (!empty($advft_criteria[$i - 1]['condition'])) {
            $advft_criteria[$i - 1]['condition'] = '';
        }
        $this->advft_criteria = $advft_criteria;
        $log->info("Reports :: Successfully returned getAdvancedFilterList");
        return true;
    }
Example #23
0
/** This function returns a HTML output of associated vtiger_products for a given entity (Quotes,Invoice,Sales order or Purchase order)
 * Param $module - module name
 * Param $focus - module object
 * Return type string
 */
function getDetailAssociatedProducts($module, $focus)
{
    global $log;
    $log->debug("Entering getDetailAssociatedProducts(" . $module . "," . get_class($focus) . ") method ...");
    global $adb;
    global $mod_strings;
    global $theme;
    global $log;
    global $app_strings, $current_user;
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    if (vtlib_isModuleActive("Products")) {
        $hide_stock = 'no';
    } else {
        $hide_stock = 'yes';
    }
    if ($module != 'PurchaseOrder') {
        if (GlobalVariable::getVariable('B2B', '1') == '1') {
            $acvid = $focus->column_fields['account_id'];
        } else {
            $acvid = $focus->column_fields['contact_id'];
        }
        if ($hide_stock == 'no') {
            $colspan = '2';
        } else {
            $colspan = '1';
        }
    } else {
        $acvid = $focus->column_fields['vendor_id'];
        $colspan = '1';
    }
    //Get the taxtype of this entity
    $taxtype = getInventoryTaxType($module, $focus->id);
    $currencytype = getInventoryCurrencyInfo($module, $focus->id);
    $output = '';
    //Header Rows
    $output .= '

	<table width="100%"  border="0" align="center" cellpadding="5" cellspacing="0" class="crmTable" id="proTab">
	   <tr valign="top">
	   	<td colspan="' . $colspan . '" class="dvInnerHeader"><b>' . $app_strings['LBL_ITEM_DETAILS'] . '</b></td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_CURRENCY'] . ' : </b>' . getTranslatedCurrencyString($currencytype['currency_name']) . ' (' . $currencytype['currency_symbol'] . ')
		</td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_TAX_MODE'] . ' : </b>' . $app_strings[$taxtype] . '
		</td>
	   </tr>
	   <tr valign="top">
		<td width=40% class="lvtCol"><font color="red">*</font>
			<b>' . $app_strings['LBL_ITEM_NAME'] . '</b>
		</td>';
    //Add Quantity in Stock column for SO, Quotes and Invoice
    if (($module == 'Quotes' || $module == 'SalesOrder' || $module == 'Invoice') && $hide_stock == 'no') {
        $output .= '<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY_IN_STOCK'] . '</b></td>';
    }
    $output .= '

		<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY'] . '</b></td>
		<td width=10% class="lvtCol" align="right"><b>' . $app_strings['LBL_LIST_PRICE'] . '</b></td>
		<td width=12% nowrap class="lvtCol" align="right"><b>' . $app_strings['LBL_TOTAL'] . '</b></td>
		<td width=13% valign="top" class="lvtCol" align="right"><b>' . $app_strings['LBL_NET_PRICE'] . '</b></td>
	   </tr>
	   	';
    // DG 15 Aug 2006
    // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, vtiger_inventoryproductrel.* " . " from vtiger_inventoryproductrel" . " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . " where id=? ORDER BY sequence_no";
    }
    $result = $adb->pquery($query, array($focus->id));
    $num_rows = $adb->num_rows($result);
    $netTotal = '0.00';
    for ($i = 1; $i <= $num_rows; $i++) {
        $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        $subprodname_str = '';
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'productid');
                $sprod_name = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodname_str .= $str_sep . " - " . $sprod_name;
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $productid = $adb->query_result($result, $i - 1, 'productid');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        $productname = '<a href="index.php?action=DetailView&record=' . $productid . '&module=' . $entitytype . '">' . $productname . '</a>';
        if ($subprodname_str != '') {
            $productname .= "<br/><span style='color:#C0C0C0;font-style:italic;'>" . $subprodname_str . "</span>";
        }
        $comment = $adb->query_result($result, $i - 1, 'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $qty = number_format($qty, 2, '.', '');
        //Convert to 2 decimals
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $total = $qty * $listprice;
        $listprice = number_format($listprice, 2, '.', '');
        //Convert to 2 decimals
        //Product wise Discount calculation - starts
        $discount_percent = $adb->query_result($result, $i - 1, 'discount_percent');
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $totalAfterDiscount = $total;
        $productDiscount = '0.00';
        if ($discount_percent != 'NULL' && $discount_percent != '') {
            $productDiscount = $total * $discount_percent / 100;
            $productDiscount = number_format($productDiscount, 2, '.', '');
            $totalAfterDiscount = $total - $productDiscount;
            //if discount is percent then show the percentage
            $discount_info_message = "{$discount_percent} % of " . CurrencyField::convertToUserFormat($total, null, true) . " = " . CurrencyField::convertToUserFormat($productDiscount, null, true);
        } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
            $productDiscount = $discount_amount;
            $productDiscount = number_format($productDiscount, 2, '.', '');
            $totalAfterDiscount = $total - $productDiscount;
            $discount_info_message = $app_strings['LBL_DIRECT_AMOUNT_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($productDiscount, null, true);
        } else {
            $discount_info_message = $app_strings['LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM'];
        }
        //Product wise Discount calculation - ends
        $totalAfterDiscount = number_format($totalAfterDiscount, 2, '.', '');
        //Convert to 2 decimals
        $netprice = $totalAfterDiscount;
        //Calculate the individual tax if taxtype is individual
        if ($taxtype == 'individual') {
            $taxtotal = '0.00';
            $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($totalAfterDiscount, null, true) . " \\n";
            $tax_details = getTaxDetailsForProduct($productid, 'all', $acvid);
            for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                $tax_name = $tax_details[$tax_count]['taxname'];
                $tax_label = $tax_details[$tax_count]['taxlabel'];
                $tax_value = getInventoryProductTaxValue($focus->id, $productid, $tax_name);
                $individual_taxamount = $totalAfterDiscount * $tax_value / 100;
                $individual_taxamount = number_format($individual_taxamount, 2, '.', '');
                //Convert to 2 decimals
                $taxtotal = $taxtotal + $individual_taxamount;
                $taxtotal = number_format($taxtotal, 2, '.', '');
                //Convert to 2 decimals
                $tax_info_message .= "{$tax_label} : {$tax_value} % = " . CurrencyField::convertToUserFormat($individual_taxamount, null, true) . " \\n";
            }
            $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($taxtotal, null, true);
            $netprice = $netprice + $taxtotal;
            $netprice = number_format($netprice, 2, '.', '');
            //Convert to 2 decimals
        }
        $sc_image_tag = '';
        if ($module == 'Invoice') {
            switch ($entitytype) {
                case 'Services':
                    if (vtlib_isModuleActive('ServiceContracts')) {
                        $sc_image_tag = '<a href="index.php?module=ServiceContracts&action=EditView&service_id=' . $productid . '&sc_related_to=' . $focus->column_fields['account_id'] . '&start_date=' . DateTimeField::convertToUserFormat($focus->column_fields['invoicedate']) . '&return_module=' . $module . '&return_id=' . $focus->id . '">' . '<img border="0" src="' . vtiger_imageurl('handshake.gif', $theme) . '" title="' . getTranslatedString('LBL_ADD_NEW', $module) . " " . getTranslatedString('ServiceContracts', 'ServiceContracts') . '" style="cursor: pointer;" align="absmiddle" />' . '</a>';
                    }
                    break;
                case 'Products':
                    if (vtlib_isModuleActive('Assets')) {
                        $sc_image_tag = '<a href="index.php?module=Assets&action=EditView&invoiceid=' . $focus->id . '&product=' . $productid . '&account=' . $focus->column_fields['account_id'] . '&datesold=' . DateTimeField::convertToUserFormat($focus->column_fields['invoicedate']) . '&return_module=' . $module . '&return_id=' . $focus->id . '" onmouseout="vtlib_listview.trigger(\'invoiceasset.onmouseout\', $(this))" onmouseover="vtlib_listview.trigger(\'cell.onmouseover\', $(this))">' . '<img border="0" src="' . vtiger_imageurl('barcode.png', $theme) . '" title="' . getTranslatedString('LBL_ADD_NEW', $module) . " " . getTranslatedString('Assets', 'Assets') . '" style="cursor: pointer;" align="absmiddle" />' . '<span style="display:none;" vtmodule="Assets" vtfieldname="invoice_product" vtrecordid="' . $focus->id . '::' . $productid . '::' . $i . '" type="vtlib_metainfo"></span>' . '</a>';
                    }
                    break;
                default:
                    $sc_image_tag = '';
            }
        }
        //For Product Name
        $output .= '
			   <tr valign="top">
				<td class="crmTableRow small lineOnTop">
					' . $productname . '&nbsp;' . $sc_image_tag . '
					<br>' . $comment . '
				</td>';
        //Upto this added to display the Product name and comment
        if ($module != 'PurchaseOrder' && $hide_stock == 'no') {
            $output .= '<td class="crmTableRow small lineOnTop">' . $qtyinstock . '</td>';
        }
        $output .= '<td class="crmTableRow small lineOnTop">' . $qty . '</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr>
				   	<td align="right">' . CurrencyField::convertToUserFormat($listprice, null, true) . '</td>
				   </tr>
				   <tr>
					   <td align="right">(-)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $discount_info_message . '\'); ">' . $app_strings['LBL_DISCOUNT'] . ' : </a></b></td>
				   </tr>
				   <tr>
				   	<td align="right" nowrap>' . $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . ' : </td>
				   </tr>';
        if ($taxtype == 'individual') {
            $output .= '
				   <tr>
					   <td align="right" nowrap>(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . ' : </a></b></td>
				   </tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr><td align="right">' . CurrencyField::convertToUserFormat($total, null, true) . '</td></tr>
				   <tr><td align="right">' . CurrencyField::convertToUserFormat($productDiscount, null, true) . '</td></tr>
				   <tr><td align="right" nowrap>' . CurrencyField::convertToUserFormat($totalAfterDiscount, null, true) . '</td></tr>';
        if ($taxtype == 'individual') {
            $output .= '<tr><td align="right" nowrap>' . CurrencyField::convertToUserFormat($taxtotal, null, true) . '</td></tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '<td class="crmTableRow small lineOnTop" valign="bottom" align="right">' . CurrencyField::convertToUserFormat($netprice, null, true) . '</td>';
        $output .= '</tr>';
        $netTotal = $netTotal + $netprice;
    }
    $output .= '</table>';
    //$netTotal should be equal to $focus->column_fields['hdnSubTotal']
    $netTotal = $focus->column_fields['hdnSubTotal'];
    $netTotal = number_format($netTotal, 2, '.', '');
    //Convert to 2 decimals
    //Display the total, adjustment, S&H details
    $output .= '<table width="100%" border="0" cellspacing="0" cellpadding="5" class="crmTable">';
    $output .= '<tr>';
    $output .= '<td width="88%" class="crmTableRow small" align="right"><b>' . $app_strings['LBL_NET_TOTAL'] . '</td>';
    $output .= '<td width="12%" class="crmTableRow small" align="right"><b>' . CurrencyField::convertToUserFormat($netTotal, null, true) . '</b></td>';
    $output .= '</tr>';
    //Decide discount
    $finalDiscount = '0.00';
    $final_discount_info = '0';
    //if($focus->column_fields['hdnDiscountPercent'] != '') - previously (before changing to prepared statement) the selected option (either percent or amount) will have value and the other remains empty. So we can find the non selected item by empty check. But now with prepared statement, the non selected option stored as 0
    if ($focus->column_fields['hdnDiscountPercent'] != '0') {
        $finalDiscount = $netTotal * $focus->column_fields['hdnDiscountPercent'] / 100;
        $finalDiscount = number_format($finalDiscount, 2, '.', '');
        $final_discount_info = $focus->column_fields['hdnDiscountPercent'] . " % of " . CurrencyField::convertToUserFormat($netTotal, null, true) . " = " . CurrencyField::convertToUserFormat($finalDiscount, null, true);
    } elseif ($focus->column_fields['hdnDiscountAmount'] != '0') {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $finalDiscount = number_format($finalDiscount, 2, '.', '');
        $final_discount_info = CurrencyField::convertToUserFormat($finalDiscount, null, true);
    }
    //Alert the Final Discount amount even it is zero
    $final_discount_info = $app_strings['LBL_FINAL_DISCOUNT_AMOUNT'] . " = {$final_discount_info}";
    $final_discount_info = 'onclick="alert(\'' . $final_discount_info . '\');"';
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">(-)&nbsp;<b><a href="javascript:;" ' . $final_discount_info . '>' . $app_strings['LBL_DISCOUNT'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . CurrencyField::convertToUserFormat($finalDiscount, null, true) . '</td>';
    $output .= '</tr>';
    if ($taxtype == 'group') {
        $taxtotal = '0.00';
        $final_totalAfterDiscount = $netTotal - $finalDiscount;
        $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($final_totalAfterDiscount, null, true) . " \\n";
        //First we should get all available taxes and then retrieve the corresponding tax values
        $tax_details = getAllTaxes('available', '', 'edit', $focus->id);
        $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
        //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
            $tax_name = $tax_details[$tax_count]['taxname'];
            $tax_label = $tax_details[$tax_count]['taxlabel'];
            if (in_array($tax_name, $ipr_cols)) {
                $tax_value = $adb->query_result($result, 0, $tax_name);
            } else {
                $tax_value = $tax_details[$tax_count]['percentage'];
            }
            if ($tax_value == '' || $tax_value == 'NULL') {
                $tax_value = '0.00';
            }
            $taxamount = ($netTotal - $finalDiscount) * $tax_value / 100;
            $taxtotal = $taxtotal + $taxamount;
            $tax_info_message .= "{$tax_label} : {$tax_value} % = " . CurrencyField::convertToUserFormat($taxtotal, null, true) . " \\n";
        }
        $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($taxtotal, null, true);
        $output .= '<tr>';
        $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . '</a></b></td>';
        $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($taxtotal, null, true) . '</td>';
        $output .= '</tr>';
    }
    $shAmount = $focus->column_fields['hdnS_H_Amount'] != '' ? $focus->column_fields['hdnS_H_Amount'] : '0.00';
    $shAmount = number_format($shAmount, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b>' . $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGES'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($shAmount, null, true) . '</td>';
    $output .= '</tr>';
    //calculate S&H tax
    $shtaxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $shtax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
    //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
    $shtax_info_message = $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGE'] . " = " . CurrencyField::convertToUserFormat($shAmount, null, true) . "\\n";
    for ($shtax_count = 0; $shtax_count < count($shtax_details); $shtax_count++) {
        $shtax_name = $shtax_details[$shtax_count]['taxname'];
        $shtax_label = $shtax_details[$shtax_count]['taxlabel'];
        $shtax_percent = getInventorySHTaxPercent($focus->id, $shtax_name);
        $shtaxamount = $shAmount * $shtax_percent / 100;
        $shtaxamount = number_format($shtaxamount, 2, '.', '');
        $shtaxtotal = $shtaxtotal + $shtaxamount;
        $shtax_info_message .= "{$shtax_label} : {$shtax_percent} % = " . CurrencyField::convertToUserFormat($shtaxamount, null, true) . " \\n";
    }
    $shtax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($shtaxtotal, null, true);
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $shtax_info_message . '\')">' . $app_strings['LBL_TAX_FOR_SHIPPING_AND_HANDLING'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($shtaxtotal, null, true) . '</td>';
    $output .= '</tr>';
    $adjustment = $focus->column_fields['txtAdjustment'] != '' ? $focus->column_fields['txtAdjustment'] : '0.00';
    $adjustment = number_format($adjustment, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">&nbsp;<b>' . $app_strings['LBL_ADJUSTMENT'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($adjustment, null, true) . '</td>';
    $output .= '</tr>';
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
    $grandTotal = number_format($grandTotal, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop"><b>' . $app_strings['LBL_GRAND_TOTAL'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . CurrencyField::convertToUserFormat($grandTotal, null, true) . '</td>';
    $output .= '</tr>';
    $output .= '</table>';
    $log->debug("Exiting getDetailAssociatedProducts method ...");
    return $output;
}
 function getListViewRecords($focus, $module, $result)
 {
     global $listview_max_textlength, $theme, $default_charset;
     require 'user_privileges/user_privileges_' . $this->user->id . '.php';
     $fields = $this->queryGenerator->getFields();
     $meta = $this->queryGenerator->getMeta($this->queryGenerator->getModule());
     $moduleFields = $this->queryGenerator->getModuleFields();
     $accessibleFieldList = array_keys($moduleFields);
     $listViewFields = array_intersect($fields, $accessibleFieldList);
     $referenceFieldList = $this->queryGenerator->getReferenceFieldList();
     foreach ($referenceFieldList as $fieldName) {
         if (in_array($fieldName, $listViewFields)) {
             $field = $moduleFields[$fieldName];
             $this->fetchNameList($field, $result);
         }
     }
     $db = PearDatabase::getInstance();
     $rowCount = $db->num_rows($result);
     $ownerFieldList = $this->queryGenerator->getOwnerFieldList();
     foreach ($ownerFieldList as $fieldName) {
         if (in_array($fieldName, $listViewFields)) {
             $field = $moduleFields[$fieldName];
             $idList = array();
             for ($i = 0; $i < $rowCount; $i++) {
                 $id = $this->db->query_result($result, $i, $field->getColumnName());
                 if (!isset($this->ownerNameList[$fieldName][$id])) {
                     $idList[] = $id;
                 }
             }
             if (count($idList) > 0) {
                 if (!is_array($this->ownerNameList[$fieldName])) {
                     $this->ownerNameList[$fieldName] = getOwnerNameList($idList);
                 } else {
                     //array_merge API loses key information so need to merge the arrays
                     // manually.
                     $newOwnerList = getOwnerNameList($idList);
                     foreach ($newOwnerList as $id => $name) {
                         $this->ownerNameList[$fieldName][$id] = $name;
                     }
                 }
             }
         }
     }
     foreach ($listViewFields as $fieldName) {
         $field = $moduleFields[$fieldName];
         if (!$is_admin && ($field->getFieldDataType() == 'picklist' || $field->getFieldDataType() == 'multipicklist')) {
             $this->setupAccessiblePicklistValueList($fieldName);
         }
     }
     $useAsterisk = get_use_asterisk($this->user->id);
     $data = array();
     for ($i = 0; $i < $rowCount; ++$i) {
         //Getting the recordId
         if ($module != 'Users') {
             $baseTable = $meta->getEntityBaseTable();
             $moduleTableIndexList = $meta->getEntityTableIndexList();
             $baseTableIndex = $moduleTableIndexList[$baseTable];
             $recordId = $db->query_result($result, $i, $baseTableIndex);
         } else {
             $recordId = $db->query_result($result, $i, "id");
         }
         $row = array();
         foreach ($listViewFields as $fieldName) {
             $field = $moduleFields[$fieldName];
             $uitype = $field->getUIType();
             $rawValue = $this->db->query_result($result, $i, $field->getColumnName());
             if (in_array($uitype, array(15, 33, 16))) {
                 $value = html_entity_decode($rawValue, ENT_QUOTES, $default_charset);
             } else {
                 $value = $rawValue;
             }
             if ($module == 'Documents' && $fieldName == 'filename') {
                 $downloadtype = $db->query_result($result, $i, 'filelocationtype');
                 $fileName = $db->query_result($result, $i, 'filename');
                 $downloadType = $db->query_result($result, $i, 'filelocationtype');
                 $status = $db->query_result($result, $i, 'filestatus');
                 $fileIdQuery = "select attachmentsid from vtiger_seattachmentsrel where crmid=?";
                 $fileIdRes = $db->pquery($fileIdQuery, array($recordId));
                 $fileId = $db->query_result($fileIdRes, 0, 'attachmentsid');
                 if ($fileName != '' && $status == 1) {
                     if ($downloadType == 'I') {
                         $value = '<a onclick="Javascript:Documents_Index_Js.updateDownloadCount(\'index.php?module=Documents&action=UpdateDownloadCount&record=' . $recordId . '\');"' . ' href="index.php?module=Documents&action=DownloadFile&record=' . $recordId . '&fileid=' . $fileId . '"' . ' title="' . getTranslatedString('LBL_DOWNLOAD_FILE', $module) . '" >' . textlength_check($value) . '</a>';
                     } elseif ($downloadType == 'E') {
                         $value = '<a onclick="Javascript:Documents_Index_Js.updateDownloadCount(\'index.php?module=Documents&action=UpdateDownloadCount&record=' . $recordId . '\');"' . ' href="' . $fileName . '" target="_blank"' . ' title="' . getTranslatedString('LBL_DOWNLOAD_FILE', $module) . '" >' . textlength_check($value) . '</a>';
                     } else {
                         $value = ' --';
                     }
                 }
                 $value = $fileicon . $value;
             } elseif ($module == 'Documents' && $fieldName == 'filesize') {
                 $downloadType = $db->query_result($result, $i, 'filelocationtype');
                 if ($downloadType == 'I') {
                     $filesize = $value;
                     if ($filesize < 1024) {
                         $value = $filesize . ' B';
                     } elseif ($filesize > 1024 && $filesize < 1048576) {
                         $value = round($filesize / 1024, 2) . ' KB';
                     } else {
                         if ($filesize > 1048576) {
                             $value = round($filesize / (1024 * 1024), 2) . ' MB';
                         }
                     }
                 } else {
                     $value = ' --';
                 }
             } elseif ($module == 'Documents' && $fieldName == 'filestatus') {
                 if ($value == 1) {
                     $value = getTranslatedString('yes', $module);
                 } elseif ($value == 0) {
                     $value = getTranslatedString('no', $module);
                 } else {
                     $value = '--';
                 }
             } elseif ($module == 'Documents' && $fieldName == 'filetype') {
                 $downloadType = $db->query_result($result, $i, 'filelocationtype');
                 if ($downloadType == 'E' || $downloadType != 'I') {
                     $value = '--';
                 }
             } elseif ($module == 'OSSTimeControl' && $fieldName == 'sum_time') {
                 $value = Vtiger_Functions::decimalTimeFormat($value);
                 $value = $value['short'];
             } elseif ($field->getUIType() == '27') {
                 if ($value == 'I') {
                     $value = getTranslatedString('LBL_INTERNAL', $module);
                 } elseif ($value == 'E') {
                     $value = getTranslatedString('LBL_EXTERNAL', $module);
                 } else {
                     $value = ' --';
                 }
                 $value = Vtiger_Functions::textLength($value);
             } elseif ($field->getFieldDataType() == 'picklist') {
                 $value = Vtiger_Language_Handler::getTranslatedString($value, $module);
                 $value = textlength_check($value);
             } elseif ($field->getFieldDataType() == 'date' || $field->getFieldDataType() == 'datetime') {
                 if ($value != '' && $value != '0000-00-00') {
                     $fieldDataType = $field->getFieldDataType();
                     if ($module == 'Calendar' && ($fieldName == 'date_start' || $fieldName == 'due_date')) {
                         if ($fieldName == 'date_start') {
                             $timeField = 'time_start';
                         } else {
                             if ($fieldName == 'due_date') {
                                 $timeField = 'time_end';
                             }
                         }
                         $timeFieldValue = $this->db->query_result($result, $i, $timeField);
                         if (!empty($timeFieldValue)) {
                             $value .= ' ' . $timeFieldValue;
                             //TO make sure it takes time value as well
                             $fieldDataType = 'datetime';
                         }
                     }
                     if ($fieldDataType == 'datetime') {
                         $value = Vtiger_Datetime_UIType::getDateTimeValue($value);
                     } else {
                         if ($fieldDataType == 'date') {
                             $date = new DateTimeField($value);
                             $value = $date->getDisplayDate();
                         }
                     }
                 } elseif ($value == '0000-00-00') {
                     $value = '';
                 }
             } elseif ($field->getFieldDataType() == 'time') {
                 if (!empty($value)) {
                     $userModel = Users_Privileges_Model::getCurrentUserModel();
                     if ($userModel->get('hour_format') == '12') {
                         $value = Vtiger_Time_UIType::getTimeValueInAMorPM($value);
                     }
                 }
             } elseif ($field->getFieldDataType() == 'currency') {
                 if ($value != '') {
                     if ($field->getUIType() == 72) {
                         if ($fieldName == 'unit_price') {
                             $currencyId = getProductBaseCurrency($recordId, $module);
                             $cursym_convrate = getCurrencySymbolandCRate($currencyId);
                             $currencySymbol = $cursym_convrate['symbol'];
                         } else {
                             $currencyInfo = getInventoryCurrencyInfo($module, $recordId);
                             $currencySymbol = $currencyInfo['currency_symbol'];
                         }
                         $value = CurrencyField::convertToUserFormat($value, null, true);
                         $row['currencySymbol'] = $currencySymbol;
                         $value = CurrencyField::appendCurrencySymbol($value, $currencySymbol);
                     } else {
                         if (!empty($value)) {
                             $value = CurrencyField::convertToUserFormat($value);
                             $currencyModal = new CurrencyField($value);
                             $currencyModal->initialize();
                             $value = $currencyModal->appendCurrencySymbol($value, $currencyModal->currencySymbol);
                         }
                     }
                 }
             } elseif ($field->getFieldDataType() == 'url') {
                 $matchPattern = "^[\\w]+:\\/\\/^";
                 preg_match($matchPattern, $rawValue, $matches);
                 if (!empty($matches[0])) {
                     $value = '<a class="urlField cursorPointer" title="' . $rawValue . '" href="' . $rawValue . '" target="_blank">' . textlength_check($value) . '</a>';
                 } else {
                     $value = '<a class="urlField cursorPointer" title="' . $rawValue . '" href="http://' . $rawValue . '" target="_blank">' . textlength_check($value) . '</a>';
                 }
             } elseif ($field->getFieldDataType() == 'email') {
                 $current_user = vglobal('current_user');
                 if ($current_user->internal_mailer == 1) {
                     //check added for email link in user detailview
                     $value = "<a class='emailField' onclick=\"Vtiger_Helper_Js.getInternalMailer({$recordId}," . "'{$fieldName}','{$module}');\">" . textlength_check($value) . "</a>";
                 } else {
                     $value = '<a class="emailField" href="mailto:' . $rawValue . '">' . textlength_check($value) . '</a>';
                 }
             } elseif ($field->getFieldDataType() == 'boolean') {
                 if ($value === 'on') {
                     $value = 1;
                 } else {
                     if ($value == 'off') {
                         $value = 0;
                     }
                 }
                 if ($value == 1) {
                     $value = getTranslatedString('yes', $module);
                 } elseif ($value == 0) {
                     $value = getTranslatedString('no', $module);
                 } else {
                     $value = '--';
                 }
             } elseif ($field->getUIType() == 98) {
                 $value = '<a href="index.php?module=Roles&parent=Settings&view=Edit&record=' . $value . '">' . textlength_check(getRoleName($value)) . '</a>';
             } elseif ($field->getFieldDataType() == 'multipicklist') {
                 $value = $value != "" ? str_replace(' |##| ', ', ', $value) : "";
                 if (!$is_admin && $value != '') {
                     $valueArray = $rawValue != "" ? explode(' |##| ', $rawValue) : array();
                     $tmp = '';
                     $tmpArray = array();
                     foreach ($valueArray as $index => $val) {
                         if (!$listview_max_textlength || !(strlen(preg_replace("/(<\\/?)(\\w+)([^>]*>)/i", "", $tmp)) > $listview_max_textlength)) {
                             $tmpArray[] = $val;
                             $tmp .= ', ' . $val;
                         } else {
                             $tmpArray[] = '...';
                             $tmp .= '...';
                         }
                     }
                     $value = implode(', ', $tmpArray);
                     $value = textlength_check($value);
                 }
             } elseif ($field->getFieldDataType() == 'skype') {
                 $value = $value != "" ? "<a href='skype:{$value}?call'>" . textlength_check($value) . "</a>" : "";
             } elseif ($field->getUIType() == 11) {
                 $outgoingCallPermission = Vtiger_Mobile_Model::checkPermissionForOutgoingCall();
                 if ($outgoingCallPermission && !empty($value)) {
                     $phoneNumber = preg_replace('/[-()\\s]/', '', $value);
                     $value = '<a class="phoneField" data-phoneNumber="' . $phoneNumber . '" record="' . $recordId . '" onclick="Vtiger_Mobile_Js.registerOutboundCall(\'' . $phoneNumber . '\', ' . $recordId . ')">' . textlength_check($value) . '</a>';
                     $callUsers = Vtiger_Mobile_Model::getPrivilegesUsers();
                     if ($callUsers) {
                         $value .= '  <a class="btn btn-xs noLinkBtn" onclick="Vtiger_Mobile_Js.registerOutboundCallToUser(this,\'' . $phoneNumber . '\',' . $recordId . ')" data-placement="right" data-original-title="' . vtranslate('LBL_SELECT_USER_TO_CALL', $module) . '" data-content=\'<select class="select sesectedUser" name="sesectedUser">';
                         foreach ($callUsers as $key => $item) {
                             $value .= '<option value="' . $key . '">' . $item . '</option>';
                         }
                         $value .= '</select><br /><a class="btn btn-success popoverCallOK">' . vtranslate('LBL_BTN_CALL', $module) . '</a>   <a class="btn btn-inverse popoverCallCancel">' . vtranslate('LBL_CANCEL', $module) . '</a>\' data-trigger="manual"><i class="icon-user"></i></a>';
                     }
                 } else {
                     $value = textlength_check($value);
                 }
             } elseif ($field->getFieldDataType() == 'reference') {
                 $referenceFieldInfoList = $this->queryGenerator->getReferenceFieldInfoList();
                 $moduleList = $referenceFieldInfoList[$fieldName];
                 if (count($moduleList) == 1) {
                     $parentModule = reset($moduleList);
                 } else {
                     $parentModule = $this->typeList[$value];
                 }
                 if (!empty($value) && !empty($this->nameList[$fieldName]) && !empty($parentModule)) {
                     $parentMeta = $this->queryGenerator->getMeta($parentModule);
                     $value = textlength_check($this->nameList[$fieldName][$value]);
                     if ($parentMeta->isModuleEntity() && $parentModule != "Users") {
                         $value = "<a class='moduleColor_{$parentModule}' href='?module={$parentModule}&view=Detail&" . "record={$rawValue}' title='" . getTranslatedString($parentModule, $parentModule) . "'>{$value}</a>";
                     }
                 } else {
                     $value = '--';
                 }
             } elseif ($field->getFieldDataType() == 'owner') {
                 $value = textlength_check($this->ownerNameList[$fieldName][$value]);
             } elseif ($field->getUIType() == 25) {
                 //TODO clean request object reference.
                 $contactId = $_REQUEST['record'];
                 $emailId = $this->db->query_result($result, $i, "activityid");
                 $result1 = $this->db->pquery("SELECT access_count FROM vtiger_email_track WHERE " . "crmid=? AND mailid=?", array($contactId, $emailId));
                 $value = $this->db->query_result($result1, 0, "access_count");
                 if (!$value) {
                     $value = 0;
                 }
             } elseif ($field->getUIType() == 8) {
                 if (!empty($value)) {
                     $temp_val = html_entity_decode($value, ENT_QUOTES, $default_charset);
                     $json = new Zend_Json();
                     $value = vt_suppressHTMLTags(implode(',', $json->decode($temp_val)));
                 }
             } elseif ($field->getFieldDataType() == 'taxes') {
                 if (!empty($value)) {
                     $valueArray = $value != "" ? explode(',', $value) : [];
                     $tmp = '';
                     $tmpArray = [];
                     $taxs = Vtiger_Taxes_UIType::getTaxes();
                     foreach ($valueArray as $index => $tax) {
                         if (isset($taxs[$tax])) {
                             $tmpArray[] = $taxs[$tax]['value'] . '% - ' . $taxs[$tax]['name'];
                         }
                     }
                     $value = implode(', ', $tmpArray);
                     $value = Vtiger_Functions::textLength($value);
                 }
             } elseif ($field->getFieldDataType() == 'inventoryLimit') {
                 if (!empty($value)) {
                     $valueArray = $value != "" ? explode(',', $value) : [];
                     $tmp = '';
                     $tmpArray = [];
                     $limits = Vtiger_InventoryLimit_UIType::getLimits();
                     foreach ($valueArray as $index => $limit) {
                         if (isset($limits[$limit])) {
                             $tmpArray[] = $limits[$limit]['value'] . ' - ' . $limits[$limit]['name'];
                         }
                     }
                     $value = implode(', ', $tmpArray);
                     $value = Vtiger_Functions::textLength($value);
                 }
             } elseif ($field->getFieldDataType() == 'multiReferenceValue') {
                 $params = $field->getFieldParams();
                 $fieldModel = Vtiger_Field_Model::getInstanceFromFieldId($params['field']);
                 $valueTmp = trim($value, '|#|');
                 $valueTmp = $valueTmp != "" ? explode('|#|', $valueTmp) : [];
                 foreach ($valueTmp as $index => $tmp) {
                     $valueTmp[$index] = $fieldModel->getUITypeModel()->getDisplayValue($tmp);
                 }
                 $value = implode(', ', $valueTmp);
                 $value = Vtiger_Functions::textLength($value);
             } elseif (in_array($uitype, array(7, 9, 90))) {
                 $value = "<span align='right'>" . textlength_check($value) . "</div>";
             } else {
                 $value = Vtiger_Functions::textLength($value);
             }
             //				// vtlib customization: For listview javascript triggers
             //				$value = "$value <span type='vtlib_metainfo' vtrecordid='{$recordId}' vtfieldname=".
             //					"'{$fieldName}' vtmodule='$module' style='display:none;'></span>";
             //				// END
             $row[$fieldName] = $value;
         }
         $data[$recordId] = $row;
     }
     return $data;
 }
Example #25
0
    function GenerateReport($outputformat, $filtersql, $directOutput = false, $startLimit = false, $endLimit = false)
    {
        global $adb, $current_user, $php_max_execution_time;
        global $modules, $app_strings;
        global $mod_strings;
        require 'user_privileges/user_privileges_' . $current_user->id . '.php';
        $modules_selected = array();
        $modules_selected[] = $this->primarymodule;
        if (!empty($this->secondarymodule)) {
            $sec_modules = split(":", $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, false, $startLimit, $endLimit);
            $sSQL .= " LIMIT 0, " . (self::$HTMLVIEW_MAX_ROWS + 1);
            // Pull a record more than limit
            $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 = split(' ', $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 == $this->primarymodule . '__LBL_ACTION' && $fieldvalue != '-') {
                                $fieldvalue = "<a href='index.php?module={$this->primarymodule}&action=DetailView&record={$fieldvalue}' target='_blank'>" . getTranslatedString('LBL_VIEW_DETAILS', 'Reports') . "</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: Provide feedback on export option if required
                // NOTE: We should make sure to pull at-least 1 row more than max-limit for this to work.
                if ($noofrows > self::$HTMLVIEW_MAX_ROWS) {
                    // Performance Optimization: Output directly
                    if ($directOutput) {
                        echo '</tr></table><br><table width="100%" cellpading="0" cellspacing="0"><tr>';
                        echo sprintf('<td colspan="%s" align="right"><span class="genHeaderGray">%s</span></td>', $y, getTranslatedString('Only') . " " . self::$HTMLVIEW_MAX_ROWS . "+ " . getTranslatedString('records found') . ". " . getTranslatedString('Export to') . " <a href=\"javascript:;\" onclick=\"goToURL(CrearEnlace('ReportsAjax&file=CreateCSV',{$this->reportid}));\"><img style='vertical-align:text-top' src='themes/images/csv-file.png'></a> /" . " <a href=\"javascript:;\" onclick=\"goToURL(CrearEnlace('CreateXL',{$this->reportid}));\"><img style='vertical-align:text-top' src='themes/images/xls-file.jpg'></a>");
                    } else {
                        $valtemplate .= '</tr></table><br><table width="100%" cellpading="0" cellspacing="0"><tr>';
                        $valtemplate .= sprintf('<td colspan="%s" align="right"><span class="genHeaderGray">%s</span></td>', $y, getTranslatedString('Only') . " " . self::$HTMLVIEW_MAX_ROWS . " " . getTranslatedString('records found') . ". " . getTranslatedString('Export to') . " <a href=\"javascript:;\" onclick=\"goToURL(CrearEnlace('ReportsAjax&file=CreateCSV',{$this->reportid}));\"><img style='vertical-align:text-top' src='themes/images/csv-file.png'></a> /" . " <a href=\"javascript:;\" onclick=\"goToURL(CrearEnlace('CreateXL',{$this->reportid}));\"><img style='vertical-align:text-top' src='themes/images/xls-file.jpg'></a>");
                    }
                }
                // Performance Optimization
                if ($directOutput) {
                    $totalDisplayString = $noofrows;
                    if ($noofrows > self::$HTMLVIEW_MAX_ROWS) {
                        $totalDisplayString = self::$HTMLVIEW_MAX_ROWS . "+";
                    }
                    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='{$totalDisplayString}';</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, $outputformat, false, $startLimit, $endLimit);
            $result = $adb->pquery($sSQL, array());
            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 {
                            $fieldLabel = str_replace("__", " ", $fieldLabel);
                            $translatedLabel = getTranslatedString($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), $module);
                        }
                        $headerLabel = $translatedLabel;
                        if (!empty($this->secondarymodule)) {
                            if ($moduleLabel != '') {
                                $headerLabel = $moduleLabel . " " . $translatedLabel;
                            }
                        }
                        // Check for role based pick list
                        $temp_val = $fld->name;
                        $fieldvalue = getReportFieldValue($this, $picklistarray, $fld, $custom_field_values, $i);
                        if ($fld->name == $this->primarymodule . '__LBL_ACTION' && $fieldvalue != '-') {
                            $fieldvalue = "<a href='index.php?module={$this->primarymodule}&view=Detail&record={$fieldvalue}' target='_blank'>" . getTranslatedString('LBL_VIEW_DETAILS', 'Reports') . "</a>";
                        }
                        $arraylists[$headerLabel] = $fieldvalue;
                    }
                    $arr_val[] = $arraylists;
                    set_time_limit($php_max_execution_time);
                } while ($custom_field_values = $adb->fetch_array($result));
                $data['data'] = $arr_val;
                $data['count'] = $noofrows;
                return $data;
            }
        } 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);
                            }
                        }
                        // Since there are duplicate entries for this table
                        if ($fieldlist[1] == 'vtiger_inventoryproductrel') {
                            $module_name = $this->primarymodule;
                        }
                        $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");
            static $modulename_cache = array();
            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);
                        $module_name = NULL;
                        $cachekey = $fieldlist[1] . ":" . $fieldlist[2];
                        if (!isset($modulename_cache[$cachekey])) {
                            $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'));
                                $modulename_cache[$cachekey] = $module_name;
                            }
                        } else {
                            $module_name = $modulename_cache[$cachekey];
                        }
                        if ($module_name) {
                            $fieldlabel = trim(str_replace($escapedchars, " ", $fieldlist[3]));
                            $fieldlabel = str_replace("__", " ", $fieldlabel);
                            $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);
                            }
                            $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;
        } elseif ($outputformat == "PRINT") {
            $sSQL = $this->sGetSQLforReport($this->reportid, $filtersql, $outputformat);
            $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 - 1; $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 = split(' ', $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 - 1; $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;
        }
    }
Example #26
0
    /**
     * Function to save the custom view record
     */
    public function save()
    {
        $db = PearDatabase::getInstance();
        $currentUserModel = Users_Record_Model::getCurrentUserModel();
        $cvId = $this->getId();
        $moduleModel = $this->getModule();
        $moduleName = $moduleModel->get('name');
        $viewName = $this->get('viewname');
        $setDefault = $this->get('setdefault');
        $setMetrics = $this->get('setmetrics');
        $status = $this->get('status');
        if ($status == self::CV_STATUS_PENDING) {
            if ($currentUserModel->isAdminUser()) {
                $status = self::CV_STATUS_PUBLIC;
            }
        }
        if (!$cvId) {
            $cvId = $db->getUniqueID("vtiger_customview");
            $this->set('cvid', $cvId);
            $sql = 'INSERT INTO vtiger_customview(cvid, viewname, setdefault, setmetrics, entitytype, status, userid) VALUES (?,?,?,?,?,?,?)';
            $params = array($cvId, $viewName, $setDefault, $setMetrics, $moduleName, $status, $currentUserModel->getId());
            $db->pquery($sql, $params);
        } else {
            $sql = 'UPDATE vtiger_customview SET viewname=?, setdefault=?, setmetrics=?, status=? WHERE cvid=?';
            $params = array($viewName, $setDefault, $setMetrics, $status, $cvId);
            $db->pquery($sql, $params);
            $db->pquery('DELETE FROM vtiger_cvcolumnlist WHERE cvid = ?', array($cvId));
            $db->pquery('DELETE FROM vtiger_cvstdfilter WHERE cvid = ?', array($cvId));
            $db->pquery('DELETE FROM vtiger_cvadvfilter WHERE cvid = ?', array($cvId));
            $db->pquery('DELETE FROM vtiger_cvadvfilter_grouping WHERE cvid = ?', array($cvId));
        }
        if ($setDefault == 1) {
            $query = 'SELECT 1 FROM vtiger_user_module_preferences WHERE userid = ? AND tabid = ?';
            $queryParams = array($currentUserModel->getId(), $moduleModel->getId());
            $queryResult = $db->pquery($query, $queryParams);
            if ($db->num_rows($queryResult) > 0) {
                $updateSql = 'UPDATE vtiger_user_module_preferences SET default_cvid = ? WHERE userid = ? AND tabid = ?';
                $updateParams = array($cvId, $currentUserModel->getId(), $moduleModel->getId());
                $db->pquery($updateSql, $updateParams);
            } else {
                $insertSql = 'INSERT INTO vtiger_user_module_preferences(userid, tabid, default_cvid) VALUES (?,?,?)';
                $insertParams = array($currentUserModel->getId(), $moduleModel->getId(), $cvId);
                $db->pquery($insertSql, $insertParams);
            }
        } else {
            $deleteSql = 'DELETE FROM vtiger_user_module_preferences WHERE userid = ? AND tabid = ? AND default_cvid = ?';
            $deleteParams = array($currentUserModel->getId(), $moduleModel->getId(), $cvId);
            $db->pquery($deleteSql, $deleteParams);
        }
        $selectedColumnsList = $this->get('columnslist');
        if (!empty($selectedColumnsList)) {
            $noOfColumns = count($selectedColumnsList);
            for ($i = 0; $i < $noOfColumns; $i++) {
                $columnSql = 'INSERT INTO vtiger_cvcolumnlist (cvid, columnindex, columnname) VALUES (?,?,?)';
                $columnParams = array($cvId, $i, $selectedColumnsList[$i]);
                $db->pquery($columnSql, $columnParams);
            }
        } else {
            //no fields were sent so add default All filter columns
            $defaultModuleFilter = $db->pquery('SELECT cvid FROM vtiger_customview WHERE setdefault = 1 AND entitytype = ?', array($moduleName));
            $defaultViewId = $db->query_result($defaultModuleFilter, 0, 'cvid');
            //User Specific filterId
            if (empty($defaultViewId)) {
                $userDefaultModuleFilter = $db->pquery('SELECT default_cvid FROM vtiger_user_module_preferences WHERE
											userid = ? AND tabid = ?', array($currentUserModel->id, $moduleModel->getId()));
                $defaultViewId = $db->query_result($userDefaultModuleFilter, 0, 'default_cvid');
            }
            //First filterid of module
            if (empty($defaultViewId)) {
                $firstDefaultFilter = $db->pquery('SELECT cvid FROM vtiger_customview WHERE entitytype = ?', array($moduleName));
                $defaultViewId = $db->query_result($firstDefaultFilter, 0, 'cvid');
            }
            // Get the defaults filters columnlist
            $columnSql = "INSERT INTO vtiger_cvcolumnlist (cvid, columnindex, columnname)\n\t\t\t\t\t\t\tSELECT ?, columnindex, columnname FROM vtiger_cvcolumnlist WHERE cvid = ?";
            $db->pquery($columnSql, array($cvId, $defaultViewId));
        }
        $stdFilterList = $this->get('stdfilterlist');
        if (!empty($stdFilterList) && !empty($stdFilterList['columnname'])) {
            $stdFilterSql = 'INSERT INTO vtiger_cvstdfilter(cvid,columnname,stdfilter,startdate,enddate) VALUES (?,?,?,?,?)';
            $stdFilterParams = array($cvId, $stdFilterList['columnname'], $stdFilterList['stdfilter'], $db->formatDate($stdFilterList['startdate'], true), $db->formatDate($stdFilterList['enddate'], true));
            $db->pquery($stdFilterSql, $stdFilterParams);
        }
        $advFilterList = $this->get('advfilterlist');
        if (!empty($advFilterList)) {
            foreach ($advFilterList as $groupIndex => $groupInfo) {
                if (empty($groupInfo)) {
                    continue;
                }
                $groupColumns = $groupInfo['columns'];
                $groupCondition = $groupInfo['condition'];
                foreach ($groupColumns as $columnIndex => $columnCondition) {
                    if (empty($columnCondition)) {
                        continue;
                    }
                    $advFilterColumn = $columnCondition['columnname'];
                    $advFilterComparator = $columnCondition['comparator'];
                    $advFitlerValue = $columnCondition['value'];
                    $advFilterColumnCondition = $columnCondition['column_condition'];
                    $columnInfo = explode(":", $advFilterColumn);
                    $fieldName = $columnInfo[2];
                    $fieldModel = $moduleModel->getField($fieldName);
                    //Required if Events module fields are selected for the condition
                    if (!$fieldModel) {
                        $modulename = $moduleModel->get('name');
                        if ($modulename == 'Calendar') {
                            $eventModuleModel = Vtiger_Module_model::getInstance('Events');
                            $fieldModel = $eventModuleModel->getField($fieldName);
                        }
                    }
                    $fieldType = $fieldModel->getFieldDataType();
                    if ($fieldType == 'currency') {
                        if ($fieldModel->get('uitype') == '72') {
                            // Some of the currency fields like Unit Price, Totoal , Sub-total - doesn't need currency conversion during save
                            $advFitlerValue = CurrencyField::convertToDBFormat($advFitlerValue, null, true);
                        } else {
                            $advFitlerValue = CurrencyField::convertToDBFormat($advFitlerValue);
                        }
                    }
                    $temp_val = explode(",", $advFitlerValue);
                    if (($fieldType == 'date' || $fieldType == 'time' && $fieldName != 'time_start' && $fieldName != 'time_end' || $fieldType == 'datetime') && ($fieldType != '' && $advFitlerValue != '')) {
                        $val = array();
                        for ($x = 0; $x < count($temp_val); $x++) {
                            //if date and time given then we have to convert the date and
                            //leave the time as it is, if date only given then temp_time
                            //value will be empty
                            if (trim($temp_val[$x]) != '') {
                                $date = new DateTimeField(trim($temp_val[$x]));
                                if ($fieldType == 'date') {
                                    $val[$x] = DateTimeField::convertToDBFormat(trim($temp_val[$x]));
                                } elseif ($fieldType == 'datetime') {
                                    $val[$x] = $date->getDBInsertDateTimeValue();
                                } else {
                                    $val[$x] = $date->getDBInsertTimeValue();
                                }
                            }
                        }
                        $advFitlerValue = implode(",", $val);
                    }
                    $advCriteriaSql = 'INSERT INTO vtiger_cvadvfilter(cvid,columnindex,columnname,comparator,value,groupid,column_condition)
											values (?,?,?,?,?,?,?)';
                    $advCriteriaParams = array($cvId, $columnIndex, $advFilterColumn, $advFilterComparator, $advFitlerValue, $groupIndex, $advFilterColumnCondition);
                    $db->pquery($advCriteriaSql, $advCriteriaParams);
                    // Update the condition expression for the group to which the condition column belongs
                    $groupConditionExpression = '';
                    if (!empty($advFilterList[$groupIndex]["conditionexpression"])) {
                        $groupConditionExpression = $advFilterList[$groupIndex]["conditionexpression"];
                    }
                    $groupConditionExpression = $groupConditionExpression . ' ' . $columnIndex . ' ' . $advFilterColumnCondition;
                    $advFilterList[$groupIndex]["conditionexpression"] = $groupConditionExpression;
                }
                $groupConditionExpression = $advFilterList[$groupIndex]["conditionexpression"];
                if (empty($groupConditionExpression)) {
                    continue;
                }
                // Case when the group doesn't have any column criteria
                $advGroupSql = 'INSERT INTO vtiger_cvadvfilter_grouping(groupid,cvid,group_condition,condition_expression) VALUES (?,?,?,?)';
                $advGroupParams = array($groupIndex, $cvId, $groupCondition, $groupConditionExpression);
                $db->pquery($advGroupSql, $advGroupParams);
            }
        }
    }
Example #27
0
        $encode_val = vtlib_purify($_REQUEST['encode_val']);
        $decode_val = base64_decode($encode_val);
        $explode_decode_val = explode('&', trim($decode_val, '&'));
        $tabid = getTabid($currentModule);
        foreach ($explode_decode_val as $fieldvalue) {
            $value = explode("=", $fieldvalue);
            $field_name_val = $value[0];
            $field_value = urldecode($value[1]);
            $finfo = VTCacheUtils::lookupFieldInfo($tabid, $field_name_val);
            if ($finfo !== false) {
                if ($finfo['uitype'] == '56') {
                    $field_value = $field_value == 'on' ? '1' : '0';
                }
                if ($finfo['uitype'] == '71' or $finfo['uitype'] == '72') {
                    $currencyField = new CurrencyField($field_value);
                    $field_value = CurrencyField::convertToDBFormat($field_value, $current_user);
                }
                if ($finfo['uitype'] == '33' or $finfo['uitype'] == '3313') {
                    if (is_array($field_value)) {
                        $field_value = implode(' |##| ', $field_value);
                    }
                }
            }
            $focus->column_fields[$field_name_val] = $field_value;
        }
    }
    $errormessageclass = isset($_REQUEST['error_msgclass']) ? vtlib_purify($_REQUEST['error_msgclass']) : '';
    $errormessage = isset($_REQUEST['error_msg']) ? vtlib_purify($_REQUEST['error_msg']) : '';
    $smarty->assign('ERROR_MESSAGE_CLASS', $errormessageclass);
    $smarty->assign('ERROR_MESSAGE', $errormessage);
} elseif (empty($_REQUEST['record']) && $focus->mode != 'edit') {
 public function addUserSearchConditions($input)
 {
     global $log, $default_charset;
     if ($input['searchtype'] == 'advance') {
         $json = new Zend_Json();
         $advft_criteria = $_REQUEST['advft_criteria'];
         if (!empty($advft_criteria)) {
             $advft_criteria = $json->decode($advft_criteria);
         }
         $advft_criteria_groups = $_REQUEST['advft_criteria_groups'];
         if (!empty($advft_criteria_groups)) {
             $advft_criteria_groups = $json->decode($advft_criteria_groups);
         }
         if (empty($advft_criteria) || count($advft_criteria) <= 0) {
             return;
         }
         $advfilterlist = getAdvancedSearchCriteriaList($advft_criteria, $advft_criteria_groups, $this->getModule());
         if (empty($advfilterlist) || count($advfilterlist) <= 0) {
             return;
         }
         if ($this->conditionInstanceCount > 0) {
             $this->startGroup(self::$AND);
         } else {
             $this->startGroup('');
         }
         foreach ($advfilterlist as $groupindex => $groupcolumns) {
             $filtercolumns = $groupcolumns['columns'];
             if (count($filtercolumns) > 0) {
                 $this->startGroup('');
                 foreach ($filtercolumns as $index => $filter) {
                     $name = explode(':', $filter['columnname']);
                     if (empty($name[2]) && $name[1] == 'crmid' && $name[0] == 'vtiger_crmentity') {
                         $name = $this->getSQLColumn('id');
                     } else {
                         $name = $name[2];
                     }
                     $this->addCondition($name, $filter['value'], $filter['comparator']);
                     $columncondition = $filter['column_condition'];
                     if (!empty($columncondition)) {
                         $this->addConditionGlue($columncondition);
                     }
                 }
                 $this->endGroup();
                 $groupConditionGlue = $groupcolumns['condition'];
                 if (!empty($groupConditionGlue)) {
                     $this->addConditionGlue($groupConditionGlue);
                 }
             }
         }
         $this->endGroup();
     } elseif ($input['type'] == 'dbrd') {
         if ($this->conditionInstanceCount > 0) {
             $this->startGroup(self::$AND);
         } else {
             $this->startGroup('');
         }
         $allConditionsList = $this->getDashBoardConditionList();
         $conditionList = $allConditionsList['conditions'];
         $relatedConditionList = $allConditionsList['relatedConditions'];
         $noOfConditions = count($conditionList);
         $noOfRelatedConditions = count($relatedConditionList);
         foreach ($conditionList as $index => $conditionInfo) {
             $this->addCondition($conditionInfo['fieldname'], $conditionInfo['value'], $conditionInfo['operator']);
             if ($index < $noOfConditions - 1 || $noOfRelatedConditions > 0) {
                 $this->addConditionGlue(self::$AND);
             }
         }
         foreach ($relatedConditionList as $index => $conditionInfo) {
             $this->addRelatedModuleCondition($conditionInfo['relatedModule'], $conditionInfo['conditionModule'], $conditionInfo['finalValue'], $conditionInfo['SQLOperator']);
             if ($index < $noOfRelatedConditions - 1) {
                 $this->addConditionGlue(self::$AND);
             }
         }
         $this->endGroup();
     } else {
         if (isset($input['search_field']) && $input['search_field'] != "") {
             $fieldName = vtlib_purify($input['search_field']);
         } else {
             return;
         }
         if ($this->conditionInstanceCount > 0) {
             $this->startGroup(self::$AND);
         } else {
             $this->startGroup('');
         }
         $moduleFields = $this->getModuleFields();
         $field = $moduleFields[$fieldName];
         $type = $field->getFieldDataType();
         if (isset($input['search_text']) && $input['search_text'] != "") {
             // search other characters like "|, ?, ?" by jagi
             $value = $input['search_text'];
             $stringConvert = function_exists(iconv) ? @iconv("UTF-8", $default_charset, $value) : $value;
             if (!$this->isStringType($type)) {
                 $value = trim($stringConvert);
             }
             if ($type == 'picklist') {
                 global $mod_strings;
                 // Get all the keys for the for the Picklist value
                 $mod_keys = array_keys($mod_strings, $value);
                 if (sizeof($mod_keys) >= 1) {
                     // Iterate on the keys, to get the first key which doesn't start with LBL_      (assuming it is not used in PickList)
                     foreach ($mod_keys as $mod_idx => $mod_key) {
                         $stridx = strpos($mod_key, 'LBL_');
                         // Use strict type comparision, refer strpos for more details
                         if ($stridx !== 0) {
                             $value = $mod_key;
                             break;
                         }
                     }
                 }
             }
             if ($type == 'currency') {
                 // Some of the currency fields like Unit Price, Total, Sub-total etc of Inventory modules, do not need currency conversion
                 if ($field->getUIType() == '72') {
                     $value = CurrencyField::convertToDBFormat($value, null, true);
                 } else {
                     $currencyField = new CurrencyField($value);
                     $value = $currencyField->getDBInsertedValue();
                 }
             }
         }
         if (!empty($input['operator'])) {
             $operator = $input['operator'];
         } elseif (trim(strtolower($value)) == 'null') {
             $operator = 'e';
         } else {
             if (!$this->isNumericType($type) && !$this->isDateType($type)) {
                 $operator = 'c';
             } else {
                 $operator = 'h';
             }
         }
         $this->addCondition($fieldName, $value, $operator);
         $this->endGroup();
     }
 }
Example #29
0
 /**
  * Function to get the record model based on the request parameters
  * @param Vtiger_Request $request
  * @return Vtiger_Record_Model or Module specific Record Model instance
  */
 public function getRecordModelFromRequest(Vtiger_Request $request)
 {
     $moduleName = $request->getModule();
     $recordId = $request->get('record');
     if (!empty($recordId)) {
         $recordModel = Vtiger_Record_Model::getInstanceById($recordId, $moduleName);
         $recordModel->set('id', $recordId);
         $recordModel->set('mode', 'edit');
         $fieldModelList = $recordModel->getModule()->getFields();
         foreach ($fieldModelList as $fieldName => $fieldModel) {
             //For not converting craetedtime and modified time to user format
             $uiType = $fieldModel->get('uitype');
             if ($uiType == 70) {
                 $fieldValue = $recordModel->get($fieldName);
             } elseif (in_array($uiType, [71, 72])) {
                 // currency ui types
                 $fieldValue = $recordModel->get($fieldName);
                 $fieldValue = CurrencyField::convertToUserFormat($fieldValue, null, true);
             } else {
                 $fieldValue = $fieldModel->getUITypeModel()->getUserRequestValue($recordModel->get($fieldName), $recordId);
             }
             if ($fieldName === $request->get('field')) {
                 $fieldValue = $request->get('value');
             }
             $fieldDataType = $fieldModel->getFieldDataType();
             if ($fieldDataType == 'time') {
                 $fieldValue = Vtiger_Time_UIType::getTimeValueWithSeconds($fieldValue);
             }
             if ($fieldValue !== null) {
                 if (!is_array($fieldValue)) {
                     $fieldValue = trim($fieldValue);
                 }
                 $recordModel->set($fieldName, $fieldValue);
             }
             $recordModel->set($fieldName, $fieldValue);
         }
     } else {
         $moduleModel = Vtiger_Module_Model::getInstance($moduleName);
         $recordModel = Vtiger_Record_Model::getCleanInstance($moduleName);
         $recordModel->set('mode', '');
         $fieldModelList = $moduleModel->getFields();
         foreach ($fieldModelList as $fieldName => $fieldModel) {
             if ($request->has($fieldName)) {
                 $fieldValue = $request->get($fieldName, null);
             } else {
                 $fieldValue = $fieldModel->getDefaultFieldValue();
             }
             $fieldDataType = $fieldModel->getFieldDataType();
             if ($fieldDataType == 'time') {
                 $fieldValue = Vtiger_Time_UIType::getTimeValueWithSeconds($fieldValue);
             }
             if ($fieldValue !== null) {
                 if (!is_array($fieldValue)) {
                     $fieldValue = trim($fieldValue);
                 }
                 $recordModel->set($fieldName, $fieldValue);
             }
         }
     }
     return $recordModel;
 }
Example #30
0
 /** Function to save the user information into the database
  * @param $module -- module name:: Type varchar
  *
  */
 function saveentity($module)
 {
     global $current_user;
     //$adb added by raju for mass mailing
     $insertion_mode = $this->mode;
     if (empty($this->column_fields['time_zone'])) {
         $dbDefaultTimeZone = DateTimeField::getDBTimeZone();
         $this->column_fields['time_zone'] = $dbDefaultTimeZone;
         $this->time_zone = $dbDefaultTimeZone;
     }
     if (empty($this->column_fields['currency_id'])) {
         $this->column_fields['currency_id'] = CurrencyField::getDBCurrencyId();
     }
     if (empty($this->column_fields['date_format'])) {
         $this->column_fields['date_format'] = 'yyyy-mm-dd';
     }
     if (empty($this->column_fields['start_hour'])) {
         $this->column_fields['start_hour'] = '08:00';
     }
     if (empty($this->column_fields['dayoftheweek'])) {
         $this->column_fields['dayoftheweek'] = 'Monday';
     }
     if (empty($this->column_fields['callduration'])) {
         $this->column_fields['callduration'] = 5;
     }
     if (empty($this->column_fields['othereventduration'])) {
         $this->column_fields['othereventduration'] = 5;
     }
     if (empty($this->column_fields['hour_format'])) {
         $this->column_fields['hour_format'] = 24;
     }
     if (empty($this->column_fields['activity_view'])) {
         $this->column_fields['activity_view'] = 'This Month';
     }
     if (empty($this->column_fields['calendarsharedtype'])) {
         $this->column_fields['calendarsharedtype'] = 'public';
     }
     if (empty($this->column_fields['default_record_view'])) {
         $this->column_fields['default_record_view'] = 'Summary';
     }
     if (empty($this->column_fields['status'])) {
         $this->column_fields['status'] = 'Active';
     }
     if (empty($this->column_fields['currency_decimal_separator']) && $this->column_fields['currency_decimal_separator'] != ' ') {
         $this->column_fields['currency_decimal_separator'] = '.';
     }
     if (empty($this->column_fields['currency_grouping_separator']) && $this->column_fields['currency_grouping_separator'] != ' ') {
         $this->column_fields['currency_grouping_separator'] = ' ';
     }
     $this->db->println("TRANS saveentity starts {$module}");
     $this->db->startTransaction();
     foreach ($this->tab_name as $table_name) {
         if ($table_name == 'vtiger_attachments') {
             $this->insertIntoAttachment($this->id, $module);
         } else {
             $this->insertIntoEntityTable($table_name, $module);
         }
     }
     if (Settings_Roles_Record_Model::getInstanceById($this->column_fields['roleid']) == null) {
         $roleid = Settings_Roles_Record_Model::getInstanceByName($this->column_fields['roleid']);
         if ($roleid) {
             $this->column_fields['roleid'] = $roleid->getId();
         } else {
             $roles = Settings_Roles_Record_Model::getAll();
             $this->column_fields['roleid'] = key($roles);
         }
     }
     require_once 'modules/Users/CreateUserPrivilegeFile.php';
     createUserPrivilegesfile($this->id);
     unset($_SESSION['next_reminder_interval']);
     unset($_SESSION['next_reminder_time']);
     if ($insertion_mode != 'edit') {
         $this->createAccessKey();
     }
     $this->db->completeTransaction();
     $this->db->println("TRANS saveentity ends");
 }