示例#1
0
 /**
  * Getting value to display
  * @param type $value
  * @return type
  */
 public function getDisplayValue($value)
 {
     if ($value != 0) {
         return Vtiger_Functions::getCRMRecordLabel($value);
     }
     return '';
 }
示例#2
0
 function wf_combine_comments($crmid)
 {
     global $adb, $default_charset;
     $sql = "SELECT *\n           FROM\n               vtiger_modcomments\n           INNER JOIN vtiger_crmentity\n               ON (vtiger_crmentity.crmid = vtiger_modcomments.modcommentsid)\n           INNER JOIN vtiger_users\n               ON (vtiger_users.id = vtiger_crmentity.smownerid)\n           WHERE related_to = " . $crmid . " AND vtiger_crmentity.deleted = 0 ORDER BY createdtime DESC";
     $result = $adb->query($sql, true);
     $html = "";
     while ($row = $adb->fetchByAssoc($result)) {
         if (!empty($row['customer'])) {
         }
         $html .= "<div style='font-size:12px;'><strong>Kommentar von " . (!empty($row['customer']) ? Vtiger_Functions::getCRMRecordLabel($row['customer']) : $row["first_name"] . " " . $row["last_name"]) . " geschrieben " . date("d.m.Y H:i:s", strtotime($row["createdtime"])) . "</strong><br>";
         $html .= nl2br($row["commentcontent"]) . "</div><br><br>";
     }
     return $html;
 }
示例#3
0
 public static function getBreadcrumbs()
 {
     $breadcrumbs = false;
     $request = new Vtiger_Request($_REQUEST, $_REQUEST);
     $currentUser = Users_Record_Model::getCurrentUserModel();
     $userPrivModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
     $roleMenu = 'user_privileges/menu_' . filter_var($userPrivModel->get('roleid'), FILTER_SANITIZE_NUMBER_INT) . '.php';
     if (file_exists($roleMenu)) {
         require $roleMenu;
     } else {
         require 'user_privileges/menu_0.php';
     }
     if (count($menus) == 0) {
         require 'user_privileges/menu_0.php';
     }
     if ($request->get('parent') == 'Settings') {
         $moduleName = 'Settings:';
     }
     $breadcrumbsOn = $purl = false;
     $moduleName .= $module = $request->get('module');
     $view = $request->get('view');
     if ($request->get('parent') != '' && $request->get('parent') != 'Settings') {
         $parentMenu = self::getParentMenu($parentList, $request->get('parent'), $module);
         if (count($parentMenu) > 0) {
             $breadcrumbs = array_reverse($parentMenu);
         }
     } elseif ($request->get('parent') == 'Settings') {
         $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_SETTINGS', $moduleName)];
     }
     $breadcrumbs[] = ['name' => vtranslate($module, $moduleName)];
     if ($view == 'Edit' && $request->get('record') == '') {
         $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_CREATE', $moduleName)];
     } elseif ($view != '' && $view != 'index' && $view != 'Index') {
         $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_' . strtoupper($view), $moduleName)];
     } elseif ($view == '') {
         $breadcrumbs[] = ['name' => vtranslate('LBL_HOME', $moduleName)];
     }
     if ($request->get('record') != '') {
         $recordLabel = Vtiger_Functions::getCRMRecordLabel($request->get('record'));
         if ($recordLabel != '') {
             $breadcrumbs[] = ['name' => $recordLabel];
         }
     }
     return $breadcrumbs;
 }
示例#4
0
 function process($data)
 {
     $adb = PearDatabase::getInstance();
     $html = '';
     if ($data['record'] != '') {
         $vtEntityDelta = new VTEntityDelta();
         $delta = $vtEntityDelta->getEntityDelta($data['module'], $data['record']);
         if (count($delta) == 0) {
             return '';
         }
         $tabid = getTabid($data['module']);
         $html = '<ul>';
         foreach ($delta as $fieldName => $values) {
             if ($fieldName != 'modifiedtime' && in_array($fieldName, array('record_id', 'record_module')) == false && strstr($fieldName, 'label') === false) {
                 $result = $adb->pquery("SELECT uitype,fieldlabel FROM vtiger_field WHERE fieldname = ? AND tabid = ?", array($fieldName, $tabid), true);
                 $fieldlabel = $adb->query_result_raw($result, 0, 'fieldlabel');
                 $uitype = $adb->query_result_raw($result, 0, 'uitype');
                 $oldValue = $values['oldValue'];
                 if ($oldValue == '') {
                     $oldValue = 'LBL_NULL_VALUE';
                 }
                 $currentValue = $values['currentValue'];
                 if ($currentValue == '') {
                     $currentValue = 'LBL_NULL_VALUE';
                 }
                 if ($uitype == 10 && $oldValue != 'LBL_NULL_VALUE' && $currentValue != 'LBL_NULL_VALUE') {
                     $oldValue = Vtiger_Functions::getCRMRecordLabel($oldValue);
                     $currentValue = Vtiger_Functions::getCRMRecordLabel($currentValue);
                 } elseif (in_array($uitype, array('53', '52', '77')) && $oldValue != 'LBL_NULL_VALUE' && $currentValue != 'LBL_NULL_VALUE') {
                     $oldValue = Vtiger_Functions::getOwnerRecordLabel($oldValue);
                     $currentValue = Vtiger_Functions::getOwnerRecordLabel($currentValue);
                 } elseif ($uitype == 56 && $oldValue != 'LBL_NULL_VALUE' && $currentValue != 'LBL_NULL_VALUE') {
                     $oldValue = $oldValue == 1 ? vtranslate('LBL_YES', $data['module']) : vtranslate('LBL_NO', $data['module']);
                     $currentValue = $currentValue == 1 ? vtranslate('LBL_YES', $data['module']) : vtranslate('LBL_NO', $data['module']);
                 } else {
                     $oldValue = vtranslate($oldValue, $data['module']);
                     $currentValue = vtranslate($currentValue, $data['module']);
                 }
                 $html .= '<li>' . vtranslate('LBL_CHANGED', $data['module']) . ' <strong>' . vtranslate($fieldlabel, $data['module']) . '</strong> ' . vtranslate('LBL_FROM') . ' <i>' . $oldValue . '</i> ' . vtranslate('LBL_TO') . ' <i>' . $currentValue . '</i></li>';
             }
         }
         $html .= '</ul>';
         return $html;
     }
 }
示例#5
0
 public function process(Vtiger_Request $request)
 {
     $adb = PearDatabase::getInstance();
     $moduleName = $request->getModule();
     $id = $request->get('id');
     $sourceModule = $request->get('sourceModule');
     $sourceData = array();
     if (isRecordExists($id)) {
         $record = Vtiger_Record_Model::getInstanceById($id, $sourceModule);
         $entity = $record->getEntity();
         $sourceData = $entity->column_fields;
         if ($sourceModule == 'HelpDesk') {
             $sourceData['contact_label'] = Vtiger_Functions::getCRMRecordLabel($sourceData['contact_id']);
             if (Vtiger_Functions::getCRMRecordType($sourceData['parent_id']) != 'Accounts') {
                 unset($sourceData['parent_id']);
             } else {
                 $sourceData['account_label'] = Vtiger_Functions::getCRMRecordLabel($sourceData['parent_id']);
             }
         } else {
             if ($sourceModule == 'Project') {
                 $ifExist = $adb->query("select * from vtiger_account where accountid = " . $sourceData['linktoaccountscontacts'] . "", true, "Błąd podczas pobierania danych z vtiger_crmentityrel");
                 if ($adb->num_rows($ifExist) > 0) {
                     $sourceData['account_label'] = Vtiger_Functions::getCRMRecordLabel($sourceData['linktoaccountscontacts']);
                 } else {
                     $sourceData['contact_label'] = Vtiger_Functions::getCRMRecordLabel($sourceData['linktoaccountscontacts']);
                 }
             }
         }
     }
     if ($sourceData === false) {
         $result = array('success' => false, 'message' => vtranslate('LBL_FAILED_TO_IMPORT_INFO', $moduleName));
     } else {
         $result = array('success' => true, 'sourceData' => $sourceData);
     }
     $response = new Vtiger_Response();
     $response->setResult($result);
     $response->emit();
 }
 public function beforeGetTaskform($data)
 {
     $pplkpxdfnevl = "viewer";
     $iuekfubh = "data";
     ${${"GLOBALS"}["cgfmjwwpip"]} = \PearDatabase::getInstance();
     list(${${"GLOBALS"}["nhsboiruw"]}, ${$pplkpxdfnevl}) = ${$iuekfubh};
     ${"GLOBALS"}["kqvmnsqcq"] = "productCache";
     $viewer->assign("availTaxes", getAllTaxes("available"));
     $viewer->assign("availCurrency", getAllCurrencies());
     ${${"GLOBALS"}["kqvmnsqcq"]} = array();
     foreach (${${"GLOBALS"}["nhsboiruw"]}[$this->field] as ${${"GLOBALS"}["lbltvfz"]}) {
         if (!empty(${${"GLOBALS"}["lbltvfz"]}["productid"])) {
             ${"GLOBALS"}["bcfngarcjdy"] = "product";
             ${${"GLOBALS"}["djmvvsgdvdv"]} = \Vtiger_Record_Model::getInstanceById(${${"GLOBALS"}["lbltvfz"]}["productid"]);
             $kkoeiyxt = "productCache";
             ${$kkoeiyxt}[${${"GLOBALS"}["bcfngarcjdy"]}["productid"]] = array("data" => $dataObj->getData(), "tax" => $dataObj->getTaxes(), "label" => \Vtiger_Functions::getCRMRecordLabel(${${"GLOBALS"}["lbltvfz"]}["productid"]));
         }
     }
     $viewer->assign("productCache", ${${"GLOBALS"}["nmqsaly"]});
     $viewer->assign("selectedProducts", ${${"GLOBALS"}["nhsboiruw"]}[$this->field]);
     $viewer->assign("additionalProductFields", \Workflow\VTInventoryEntity::getAdditionalProductFields());
     $this->addInlineJS("");
     $viewer->assign("ProductChooser", $viewer->fetch("modules/Settings/Workflow2/helpers/ProductChooser.tpl"));
 }
 public function beforeGetTaskform($viewer)
 {
     global $adb, $current_language, $mod_strings;
     $viewer->assign("related_modules", VtUtils::getEntityModules(true));
     $search_module = $this->get("search_module");
     if (!empty($_POST["task"]["search_module"])) {
         $parts = explode("#~#", $_POST["task"]["search_module"]);
     } elseif (!empty($search_module)) {
         if ($search_module != -1) {
             $parts = explode("#~#", $search_module);
         }
     } else {
         return;
     }
     if (!empty($parts)) {
         $viewer->assign("related_tabid", $parts[1]);
         $search_module_name = VtUtils::getModuleName($parts[1]);
         #$workflowSettings = $this->getWorkflow()->getSettings();
         $workflows = $workflows = Workflow2::getWorkflowsForModule($search_module_name, 1);
         $viewer->assign("workflows", $workflows);
         $fields = VtUtils::getFieldsWithBlocksForModule($search_module_name);
         $viewer->assign("sort_fields", $fields);
         $moduleObj = \Vtiger_Module_Model::getInstance($search_module_name);
         $viewer->assign('productCache', array());
         if ($moduleObj instanceof \Inventory_Module_Model) {
             $viewer->assign('searchByProduct', true);
             $product = $this->get('products');
             if (!empty($product)) {
                 //$dataObj = \Vtiger_Record_Model::getInstanceById($product);
                 $productCache[$product] = array('label' => \Vtiger_Functions::getCRMRecordLabel($product));
                 $viewer->assign('productCache', $productCache);
             }
         }
         $views = array();
         $allviews = \CustomView_Record_Model::getAll($search_module_name);
         foreach ($allviews as $view) {
             $views[$view->get('cvid')] = $view->get('viewname');
         }
         $viewer->assign('customviews', $views);
     }
 }
示例#8
0
 static function computeCRMRecordLabels($module, $ids, $search = false)
 {
     $adb = PearDatabase::getInstance();
     if (!is_array($ids)) {
         $ids = [$ids];
     }
     if ($module == 'Events') {
         $module = 'Calendar';
     }
     if ($module) {
         $entityDisplay = [];
         if ($ids) {
             if ($module == 'Groups') {
                 $metainfo = ['tablename' => 'vtiger_groups', 'entityidfield' => 'groupid', 'fieldname' => 'groupname'];
             } else {
                 $metainfo = self::getEntityModuleInfo($module);
             }
             $table = $metainfo['tablename'];
             $idcolumn = $metainfo['entityidfield'];
             $columnsName = explode(',', $metainfo['fieldname']);
             $columnsSearch = explode(',', $metainfo['searchcolumn']);
             $columns = array_unique(array_merge($columnsName, $columnsSearch));
             $moduleInfo = self::getModuleFieldInfos($module);
             $moduleInfoExtend = [];
             if (count($moduleInfo) > 0) {
                 foreach ($moduleInfo as $field => $fieldInfo) {
                     $moduleInfoExtend[$fieldInfo['columnname']] = $fieldInfo;
                 }
             }
             $leftJoin = '';
             $leftJoinTables = [];
             $paramsCol = [];
             $focus = CRMEntity::getInstance($module);
             foreach (array_filter($columns) as $column) {
                 if (array_key_exists($column, $moduleInfoExtend)) {
                     $paramsCol[] = $column;
                     if ($moduleInfoExtend[$column]['tablename'] != $table && !in_array($moduleInfoExtend[$column]['tablename'], $leftJoinTables)) {
                         $otherTable = $moduleInfoExtend[$column]['tablename'];
                         $leftJoinTables[] = $otherTable;
                         $focusTables = $focus->tab_name_index;
                         $leftJoin .= ' LEFT JOIN ' . $otherTable . ' ON ' . $otherTable . '.' . $focusTables[$otherTable] . ' = ' . $table . '.' . $focusTables[$table];
                     }
                 }
             }
             $paramsCol[] = $idcolumn;
             $sql = sprintf('SELECT ' . implode(',', $paramsCol) . ' AS id FROM %s ' . $leftJoin . ' WHERE %s IN (%s)', $table, $idcolumn, generateQuestionMarks($ids));
             $result = $adb->pquery($sql, $ids);
             for ($i = 0; $i < $adb->num_rows($result); $i++) {
                 $row = $adb->raw_query_result_rowdata($result, $i);
                 $label_name = [];
                 $label_search = [];
                 foreach ($columnsName as $columnName) {
                     if ($moduleInfoExtend && in_array($moduleInfoExtend[$columnName]['uitype'], [10, 51, 75, 81])) {
                         $label_name[] = Vtiger_Functions::getCRMRecordLabel($row[$columnName]);
                     } else {
                         $label_name[] = $row[$columnName];
                     }
                 }
                 if ($search) {
                     foreach ($columnsSearch as $columnName) {
                         if ($moduleInfoExtend && in_array($moduleInfoExtend[$columnName]['uitype'], [10, 51, 75, 81])) {
                             $label_search[] = Vtiger_Functions::getCRMRecordLabel($row[$columnName]);
                         } else {
                             $label_search[] = $row[$columnName];
                         }
                     }
                     $entityDisplay[$row['id']] = ['name' => implode(' ', $label_name), 'search' => implode(' ', $label_search)];
                 } else {
                     $entityDisplay[$row['id']] = trim(implode(' ', $label_name));
                 }
             }
         }
         return $entityDisplay;
     }
 }
示例#9
0
function getParentName($parent_id)
{
    return Vtiger_Functions::getCRMRecordLabel($parent_id);
}
示例#10
0
 public function findRecordsById($ids)
 {
     $return = false;
     if (!empty($ids) && $ids != '0') {
         $recordModelMailScanner = Vtiger_Record_Model::getCleanInstance('OSSMailScanner');
         $config = $recordModelMailScanner->getConfig('email_list');
         if (strpos($ids, ',')) {
             $idsArray = explode(",", $ids);
         } else {
             $idsArray[0] = $ids;
         }
         foreach ($idsArray as $id) {
             $module = Vtiger_Functions::getCRMRecordType($id);
             $label = Vtiger_Functions::getCRMRecordLabel($id);
             $return .= '<a href="index.php?module=' . $module . '&view=Detail&record=' . $id . '" target="' . $config['target'] . '"> ' . $label . '</a>,';
         }
     }
     return trim($return, ',');
 }
示例#11
0
 public function findCrmRecordsByMessage_id($params, $metod)
 {
     $adb = PearDatabase::getInstance();
     $id = false;
     if ($params['crmid']) {
         $id = $params['crmid'];
     } else {
         $result = $adb->pquery("SELECT ossmailviewid FROM vtiger_ossmailview WHERE id = ? AND mbox = ?", array($params['uid'], $params['folder']), true);
         if ($adb->num_rows($result) > 0) {
             $id = $adb->query_result_raw($result, 0, 'ossmailviewid');
         }
     }
     if ($id) {
         if ($metod != 'all') {
         }
         $result = $adb->pquery("SELECT * FROM vtiger_crmentityrel WHERE (vtiger_crmentityrel.crmid = ?) OR ( vtiger_crmentityrel.relcrmid = ? )", array($id, $id), true);
         for ($i = 0; $i < $adb->num_rows($result); $i++) {
             $module = $adb->query_result($result, $i, 'module');
             $relmodule = $adb->query_result($result, $i, 'relmodule');
             $crmid = $adb->query_result($result, $i, 'crmid');
             $relcrmid = $adb->query_result($result, $i, 'relcrmid');
             if ($module != 'OSSMailView') {
                 if (isRecordExists($crmid)) {
                     $return[$module]['record'] = array('crmid' => $crmid, 'module' => $module, 'label' => Vtiger_Functions::getCRMRecordLabel($crmid));
                     $return[$module]['rows'][] = array('crmid' => $crmid, 'module' => $module, 'label' => Vtiger_Functions::getCRMRecordLabel($crmid));
                 }
             } elseif ($relmodule != 'OSSMailView') {
                 if (isRecordExists($relcrmid)) {
                     $return[$relmodule]['record'] = array('crmid' => $relcrmid, 'module' => $relmodule, 'label' => Vtiger_Functions::getCRMRecordLabel($relcrmid));
                     $return[$relmodule]['rows'][] = array('crmid' => $relcrmid, 'module' => $relmodule, 'label' => Vtiger_Functions::getCRMRecordLabel($relcrmid));
                 }
             }
         }
     }
     return $return;
 }
示例#12
0
 /**
  * Function returns the Calendar Events for the module
  * @param <String> $mode - upcoming/overdue mode
  * @param <Vtiger_Paging_Model> $pagingModel - $pagingModel
  * @param <String> $user - all/userid
  * @param <String> $recordId - record id
  * @return <Array>
  */
 function getAssignedProjectsTasks($mode, $pagingModel, $user, $recordId = false)
 {
     $currentUser = Users_Record_Model::getCurrentUserModel();
     $db = PearDatabase::getInstance();
     if (!$user) {
         $user = $currentUser->getId();
     }
     $nowInUserFormat = Vtiger_Datetime_UIType::getDisplayDateTimeValue(date('Y-m-d H:i:s'));
     $nowInDBFormat = Vtiger_Datetime_UIType::getDBDateTimeValue($nowInUserFormat);
     list($currentDate, $currentTime) = explode(' ', $nowInDBFormat);
     $instance = CRMEntity::getInstance('ProjectTask');
     $UserAccessConditions = $instance->getUserAccessConditionsQuerySR('ProjectTask');
     $params = array();
     $query = "SELECT vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.setype, vtiger_projecttask.*\n\t\t\tFROM vtiger_projecttask\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_projecttask.projecttaskid\n\t\t\tWHERE vtiger_crmentity.deleted=0 AND vtiger_crmentity.smcreatorid = ?";
     $params[] = $currentUser->getId();
     $query .= $UserAccessConditions;
     if ($mode === 'upcoming') {
         $query .= " AND targetenddate >= ?";
     } elseif ($mode === 'overdue') {
         $query .= " AND targetenddate < ?";
     }
     $params[] = $currentDate;
     $accessibleUsers = $currentUser->getAccessibleUsers();
     $accessibleGroups = $currentUser->getAccessibleGroups();
     if ($user != 'all' && $user != '' && (array_key_exists($user, $accessibleUsers) || array_key_exists($user, $accessibleGroups))) {
         $query .= " AND vtiger_crmentity.smownerid = ?";
         $params[] = $user;
     }
     $query .= " ORDER BY targetenddate LIMIT ?, ?";
     $params[] = $pagingModel->getStartIndex();
     $params[] = $pagingModel->getPageLimit() + 1;
     $result = $db->pquery($query, $params);
     $numOfRows = $db->num_rows($result);
     $projecttasks = array();
     for ($i = 0; $i < $numOfRows; $i++) {
         $row = $db->query_result_rowdata($result, $i);
         $model = Vtiger_Record_Model::getCleanInstance('ProjectTask');
         $model->setData($row);
         $model->setId($row['crmid']);
         if ($row['projectid']) {
             if (isRecordExists($row['projectid'])) {
                 $record = Vtiger_Record_Model::getInstanceById($row['projectid'], 'Project');
                 if (isRecordExists($record->get('linktoaccountscontacts'))) {
                     $model->set('account', '<a href="index.php?module=' . Vtiger_Functions::getCRMRecordType($record->get('linktoaccountscontacts')) . '&view=Detail&record=' . $record->get('linktoaccountscontacts') . '">' . Vtiger_Functions::getCRMRecordLabel($record->get('linktoaccountscontacts')) . '</a>');
                 }
             }
         }
         $projecttasks[] = $model;
     }
     $pagingModel->calculatePageRange($projecttasks);
     if ($numOfRows > $pagingModel->getPageLimit()) {
         array_pop($projecttasks);
         $pagingModel->set('nextPageExists', true);
     } else {
         $pagingModel->set('nextPageExists', false);
     }
     return $projecttasks;
 }
示例#13
0
 public static function getMenu()
 {
     $db = PearDatabase::getInstance();
     $profileId = self::getCurrentUserProfile();
     $userModel = Users_Record_Model::getCurrentUserModel();
     $isAdmin = is_admin($userModel);
     if ($isAdmin) {
         $sql = "SELECT * FROM `vtiger_ossmenumanager` WHERE `parent_id` = ? AND `visible` = ? ORDER BY `sequence` ASC;";
         $params = array(0, 1);
     } else {
         $sql = "SELECT * FROM `vtiger_ossmenumanager` WHERE `parent_id` = ? AND `visible` = ? AND (";
         if (!empty($profileId)) {
             for ($i = 0; $i < count($profileId); $i++) {
                 $sql .= "`permission` RLIKE ' " . $profileId[$i] . " ' OR ";
             }
         }
         $sql .= " `permission` = '' OR `permission` = '0') ORDER BY `sequence` ASC;";
         $params = array(0, 1);
         //	echo '<pre>';print_r($num);echo '</pre>';
     }
     $result = $db->pquery($sql, $params, true);
     $num = $db->num_rows($result);
     $menuStructure = array();
     $breadcrumbs = array();
     $request = new Vtiger_Request($_REQUEST, $_REQUEST);
     if ($num > 0) {
         for ($i = 0; $i < $num; $i++) {
             $id = $db->query_result($result, $i, 'id');
             $locationicon = $db->query_result($result, $i, 'locationicon');
             $sizeicon = $db->query_result($result, $i, 'sizeicon');
             $name = $db->query_result($result, $i, 'label');
             $sizeicon_first = substr($sizeicon, 0, strpos($sizeicon, "x"));
             $sizeicon_second = substr($sizeicon, 3, 5);
             $langfied = $db->query_result($result, $i, 'langfield');
             if ($langfied) {
                 $res = explode('#', $langfied);
                 for ($k = 0; count($res) > $k; $k++) {
                     $prefix = substr($res[$k], 0, strpos($res[$k], "*"));
                     $value = substr($res[$k], 6);
                     if (Users_Record_Model::getCurrentUserModel()->get('language') == $prefix) {
                         //		echo '<pre>';print_r($_matches[1][$k]);echo '</pre>';exit;
                         $name = $value;
                     }
                 }
             }
             $menuStructure[$name] = array();
             if ($isAdmin) {
                 $subSql = "SELECT * FROM `vtiger_ossmenumanager` WHERE `parent_id` = ? AND `visible` = ? ORDER BY `sequence` ASC;";
                 $subParams = array($id, 1);
             } else {
                 $subSql = "SELECT * FROM `vtiger_ossmenumanager` WHERE `parent_id` = ? AND `visible` = ? AND (";
                 if (!empty($profileId)) {
                     for ($k = 0; $k < count($profileId); $k++) {
                         $subSql .= "`permission` RLIKE ' " . $profileId[$k] . " ' OR ";
                     }
                 }
                 $subSql .= " `permission` = '' OR `permission` = '0') ORDER BY `sequence` ASC;";
                 $subParams = array($id, 1);
             }
             $subResult = $db->pquery($subSql, $subParams, true);
             $subNum = $db->num_rows($subResult);
             if ($subNum > 0) {
                 for ($j = 0; $j < $subNum; $j++) {
                     $subName = $db->query_result($subResult, $j, 'label');
                     $subNameOrg = $subName;
                     $type = $db->query_result($subResult, $j, 'type');
                     $tabId = $db->query_result($subResult, $j, 'tabid');
                     $newWindow = $db->query_result($subResult, $j, 'new_window');
                     $locationiconname = $db->query_result($subResult, $j, 'locationicon');
                     $subsizeicon = $db->query_result($subResult, $j, 'sizeicon');
                     $subsizeicon_first = substr($subsizeicon, 0, strpos($subsizeicon, "x"));
                     $subsizeicon_second = substr($subsizeicon, 3, 5);
                     $langfiedpick = $db->query_result($subResult, $j, 'langfield');
                     if ($langfiedpick && intval($type) == 0) {
                         $res = explode('#', $langfiedpick);
                         for ($k = 0; count($res) > $k; $k++) {
                             $prefix = substr($res[$k], 0, strpos($res[$k], "*"));
                             $value = substr($res[$k], 6);
                             //	echo '<pre>';print_r($value);echo '</pre>';exit;
                             if (Users_Record_Model::getCurrentUserModel()->get('language') == $prefix) {
                                 $subName = $value;
                             }
                         }
                     } elseif ($langfiedpick) {
                         $res = explode('#', $langfiedpick);
                         for ($k = 0; count($res) > $k; $k++) {
                             $prefix = substr($res[$k], 0, strpos($res[$k], "*"));
                             $value = substr($res[$k], 6);
                             //	echo '<pre>';print_r($value);echo '</pre>';exit;
                             if (Users_Record_Model::getCurrentUserModel()->get('language') == $prefix) {
                                 $subName = $value;
                             }
                         }
                     }
                     if ($newWindow == 1) {
                         $newWindow = '*_blank*';
                     } else {
                         $newWindow = '';
                     }
                     switch (intval($type)) {
                         case 0:
                             $model = Vtiger_Module_Model::getInstance($subNameOrg);
                             if ($model) {
                                 $url = $model->getDefaultUrl();
                             } else {
                                 // usuń nieistniejącą pozycję
                                 $recordModel = Vtiger_Record_Model::getCleanInstance('OSSMenuManager');
                                 $recordModel->deleteMenu($subId);
                                 $url = false;
                             }
                             break;
                         case 1:
                         case 2:
                         case 3:
                         case 4:
                         default:
                             $url = $db->query_result_raw($subResult, $j, 'url');
                     }
                     if ($url !== false) {
                         $url = $newWindow . $url;
                         $menuStructure[$name][$j] = array('name' => $subName, 'mod' => $subNameOrg, 'link' => $url, 'sizeicon_first' => $subsizeicon_first, 'sizeicon_second' => $subsizeicon_second, 'locationiconname' => $locationiconname);
                     }
                     $moduleName = Vtiger_Functions::getModuleName($tabId);
                     $excludedViews = array("DashBoard", 'index', 'Index');
                     $purl = false;
                     if ($request->get('module') != '' && $request->get('module') == $moduleName && vglobal('breadcrumbs') && $request->get('parent') == '') {
                         $breadcrumbs[] = array('lable' => vtranslate($name, 'OSSMenuManager'));
                         $breadcrumbs[] = array('lable' => vtranslate($subName, $moduleName), 'url' => $url, 'class' => 'moduleColor_' . $moduleName);
                         if ($request->get('view') == 'Edit' && $request->get('record') == '') {
                             $breadcrumbs[] = array('lable' => vtranslate('LBL_VIEW_CREATE', $moduleName));
                         } elseif (!in_array($request->get('view'), $excludedViews)) {
                             $breadcrumbs[] = array('lable' => vtranslate('LBL_VIEW_' . strtoupper($request->get('view')), $moduleName));
                         }
                         if ($request->get('record') != '') {
                             $recordLabel = Vtiger_Functions::getCRMRecordLabel($request->get('record'));
                             if ($recordLabel != '') {
                                 $breadcrumbs[] = array('lable' => $recordLabel);
                             }
                         }
                     } elseif (vglobal('breadcrumbs') && $request->get('module') != '' && $request->get('parent') == '') {
                         $parts = parse_url($url);
                         parse_str($parts['query'], $purl);
                         if ($request->get('module') == $purl['module'] && $request->get('view') == $purl['view'] && $request->get('viewname') == $purl['viewname']) {
                             $breadcrumbs[] = array('lable' => vtranslate($name, 'OSSMenuManager'));
                             $breadcrumbs[] = array('lable' => vtranslate($request->get('module'), $request->get('module')), 'url' => 'index.php?module=' . $request->get('module') . '&view=List', 'class' => 'moduleColor_' . $request->get('module'));
                             if ($request->get('view') != 'List') {
                                 $breadcrumbs[] = array('lable' => vtranslate($subName, $moduleName), 'url' => $url);
                             }
                         }
                     }
                 }
             }
             $menuStructureGroupe[$name]['iconf'] = $sizeicon_first;
             $menuStructureGroupe[$name]['picon'] = $locationicon;
             $menuStructureGroupe[$name]['icons'] = $sizeicon_second;
         }
         if (vglobal('breadcrumbs') && count($breadcrumbs) == 0 && $request->get('module') != '' && $request->get('parent') == '') {
             $breadcrumbs[] = array('lable' => vtranslate($request->get('module'), $request->get('module')), 'url' => 'index.php?module=' . $request->get('module') . '&view=List', 'class' => 'moduleColor_' . $request->get('module'));
             if ($request->get('view') == 'Edit' && $request->get('record') == '') {
                 $breadcrumbs[] = array('lable' => vtranslate('LBL_VIEW_CREATE', $request->get('module')));
             } else {
                 $breadcrumbs[] = array('lable' => vtranslate('LBL_VIEW_' . strtoupper($request->get('view')), $request->get('module')));
             }
             if ($request->get('record') != '') {
                 $recordLabel = Vtiger_Functions::getCRMRecordLabel($request->get('record'));
                 if ($recordLabel != '') {
                     $breadcrumbs[] = array('lable' => $recordLabel);
                 }
             }
         }
         return array('structure' => $menuStructure, 'icons' => $menuStructureGroupe, 'breadcrumbs' => $breadcrumbs);
     } else {
         return array();
     }
 }
示例#14
0
 static function computeCRMRecordLabels($module, $ids, $search = false)
 {
     global $adb;
     if (!is_array($ids)) {
         $ids = array($ids);
     }
     if ($module == 'Events') {
         $module = 'Calendar';
     }
     if ($module) {
         $entityDisplay = array();
         if ($ids) {
             if ($module == 'Groups') {
                 $metainfo = array('tablename' => 'vtiger_groups', 'entityidfield' => 'groupid', 'fieldname' => 'groupname');
                 /*} else if ($module == 'DocumentFolders') { 
                 		$metainfo = array('tablename' => 'vtiger_attachmentsfolder','entityidfield' => 'folderid','fieldname' => 'foldername'); */
             } else {
                 $metainfo = self::getEntityModuleInfo($module);
             }
             $table = $metainfo['tablename'];
             $idcolumn = $metainfo['entityidfield'];
             $columns_name = explode(',', $metainfo['fieldname']);
             $columns_search = explode(',', $metainfo['searchcolumn']);
             $columns = array_unique(array_merge($columns_name, $columns_search));
             $sql = sprintf('SELECT ' . implode(',', array_filter($columns)) . ', %s AS id FROM %s WHERE %s IN (%s)', $idcolumn, $table, $idcolumn, generateQuestionMarks($ids));
             $result = $adb->pquery($sql, $ids);
             $ModuleInfo = self::getModuleFieldInfos($module);
             while ($row = $adb->fetch_array($result)) {
                 $label_name = array();
                 $label_search = array();
                 foreach ($columns_name as $columnName) {
                     $fieldObiect = $ModuleInfo[$columnName];
                     if (in_array($fieldObiect['uitype'], array(10, 51, 75, 81))) {
                         $label_name[] = Vtiger_Functions::getCRMRecordLabel($row[$columnName]);
                     } else {
                         $label_name[] = $row[$columnName];
                     }
                 }
                 if ($search) {
                     foreach ($columns_search as $columnName) {
                         $fieldObiect = $ModuleInfo[$columnName];
                         if (in_array($fieldObiect['uitype'], array(10, 51, 75, 81))) {
                             $label_search[] = Vtiger_Functions::getCRMRecordLabel($row[$columnName]);
                         } else {
                             $label_search[] = $row[$columnName];
                         }
                     }
                     $entityDisplay[$row['id']] = array('name' => implode(' ', $label_name), 'search' => implode(' ', $label_search));
                 } else {
                     $entityDisplay[$row['id']] = implode(' ', $label_name);
                 }
             }
         }
         return $entityDisplay;
     }
 }
示例#15
0
 function findCrmDetail($params, $metod)
 {
     $OSSMailViewModel = Vtiger_Record_Model::getCleanInstance('OSSMailView');
     $Array = $OSSMailViewModel->findCrmRecordsByMessage_id($params, $metod);
     if (count($Array['Potentials'])) {
         $crmid = $Array['Potentials']['record']['crmid'];
         $module = $Array['Potentials']['record']['module'];
         $PotentialsRecord_Model = Vtiger_Record_Model::getInstanceById($crmid, $module);
         $related_to = $PotentialsRecord_Model->get('related_to');
         $contact_id = $PotentialsRecord_Model->get('contact_id');
         if ($related_to != 0 && $related_to != '') {
             $Array['Potentials']['Accounts'] = array('crmid' => $related_to, 'label' => Vtiger_Functions::getCRMRecordLabel($related_to));
         }
         if ($contact_id != 0 && $contact_id != '') {
             $Array['Potentials']['Contacts'] = array('crmid' => $contact_id, 'label' => Vtiger_Functions::getCRMRecordLabel($contact_id));
         }
     }
     if (count($Array['Project'])) {
         $crmid = $Array['Project']['record']['crmid'];
         $module = $Array['Project']['record']['module'];
         $ProjectRecord_Model = Vtiger_Record_Model::getInstanceById($crmid, $module);
         $acc_cont = $ProjectRecord_Model->get('linktoaccountscontacts');
         if ($acc_cont != 0 && $acc_cont != '') {
             $Array['Project']['RelRecord'] = array('crmid' => $acc_cont, 'label' => Vtiger_Functions::getCRMRecordLabel($acc_cont), 'module' => Vtiger_Functions::getCRMRecordType($acc_cont));
         }
     }
     if (count($Array['HelpDesk'])) {
         $crmid = $Array['HelpDesk']['record']['crmid'];
         $module = $Array['HelpDesk']['record']['module'];
         $HelpDeskRecord_Model = Vtiger_Record_Model::getInstanceById($crmid, $module);
         $parent_id = $HelpDeskRecord_Model->get('parent_id');
         $contact_id = $HelpDeskRecord_Model->get('contact_id');
         if ($parent_id != 0 && $parent_id != '') {
             $Array['HelpDesk']['Accounts'] = array('crmid' => $parent_id, 'label' => Vtiger_Functions::getCRMRecordLabel($parent_id));
         }
         if ($contact_id != 0 && $contact_id != '') {
             $Array['HelpDesk']['Contacts'] = array('crmid' => $contact_id, 'label' => Vtiger_Functions::getCRMRecordLabel($contact_id));
         }
     }
     return $Array;
 }
示例#16
0
 public function process($ModuleName, $ID, $record_form, $config)
 {
     $db = PearDatabase::getInstance();
     $ModuleNameID = Vtiger_Functions::getModuleId($ModuleName);
     $sql_ext = '';
     $save_record1 = true;
     $save_record2 = true;
     $save_record = true;
     $type = 'info';
     $info = false;
     if ($ID != 0 && $ID != '' && !array_key_exists($config['what1'], $record_form)) {
         $Record_Model = Vtiger_Record_Model::getInstanceById($ID, $ModuleName);
         $value1 = $Record_Model->get($config['what1']);
     } else {
         if (array_key_exists($config['what1'], $record_form)) {
             $value1 = $record_form[$config['what1']];
         }
     }
     if ($ID != 0 && $ID != '' && !array_key_exists($config['what2'], $record_form)) {
         $Record_Model = Vtiger_Record_Model::getInstanceById($ID, $ModuleName);
         $value2 = $Record_Model->get($config['what2']);
     } else {
         if (array_key_exists($config['what2'], $record_form)) {
             $value2 = $record_form[$config['what2']];
         }
     }
     if (!is_array($config['where1'])) {
         $wheres1[] = $config['where1'];
     } else {
         $wheres1 = $config['where1'];
     }
     if (!is_array($config['where2'])) {
         $wheres2[] = $config['where2'];
     } else {
         $wheres2 = $config['where2'];
     }
     if ($value1 != '') {
         foreach ($wheres1 as $where) {
             $where = explode('=', $where);
             $DestModuleName = Vtiger_Functions::getModuleName($where[2]);
             $ModuleInstance = CRMEntity::getInstance($DestModuleName);
             $tab_name_index = $ModuleInstance->tab_name_index;
             $index = $tab_name_index[$where[0]];
             $sql_param = array($value1);
             $sql_ext = '';
             if ($ModuleNameID == $where[2] && $ID != 0 && $ID != '') {
                 $sql_param[] = $ID;
                 $sql_ext = 'AND ' . $index . ' <> ?';
             }
             $result = $db->pquery("SELECT {$index} FROM {$where[0]} WHERE {$where[1]} = ? {$sql_ext};", $sql_param, true);
             for ($i = 0; $i < $db->num_rows($result); $i++) {
                 $save_record1 = false;
                 $id = $db->query_result_raw($result, $i, $index);
                 $result = $db->pquery("SELECT smownerid FROM vtiger_crmentity WHERE crmid = ?", array($id), true);
                 $fieldlabel .= '<a target="_blank" href="index.php?module=' . $DestModuleName . '&view=Detail&record=' . $id . '">&bull; ' . Vtiger_Functions::getCRMRecordLabel($id) . '</a> (' . Vtiger_Functions::getOwnerRecordLabel($db->query_result($result, 0, 'smownerid')) . '),';
             }
         }
     }
     if ($value2 != '') {
         foreach ($wheres2 as $where) {
             $where = explode('=', $where);
             $DestModuleName = Vtiger_Functions::getModuleName($where[2]);
             $ModuleInstance = CRMEntity::getInstance($DestModuleName);
             $tab_name_index = $ModuleInstance->tab_name_index;
             $index = $tab_name_index[$where[0]];
             $sql_param = array($value1);
             $sql_ext = '';
             if ($ModuleNameID == $where[2] && $ID != 0 && $ID != '') {
                 $sql_param[] = $ID;
                 $sql_ext = 'AND ' . $index . ' <> ?';
             }
             $result = $db->pquery("SELECT {$index} FROM {$where[0]} WHERE {$where[1]} = ? {$sql_ext};", $sql_param, true);
             for ($i = 0; $i < $db->num_rows($result); $i++) {
                 $save_record2 = false;
                 $id = $db->query_result_raw($result, $i, $index);
                 $result = $db->pquery("SELECT smownerid FROM vtiger_crmentity WHERE crmid = ?", array($id), true);
                 $fieldlabel .= '<a target="_blank" href="index.php?module=' . $DestModuleName . '&view=Detail&record=' . $id . '">&bull; ' . Vtiger_Functions::getCRMRecordLabel($id) . '</a> (' . Vtiger_Functions::getOwnerRecordLabel($db->query_result($result, 0, 'smownerid')) . '),';
             }
         }
     }
     if ($config['locksave'] == 0 && $ID == '') {
         $info = $config['info0'];
     } elseif (!$save_record1 && !$save_record2) {
         $type = 'error';
         $save_record = false;
         $info = $config['info2'];
     } elseif (!$save_record1 || !$save_record2) {
         $type = 'error';
         $save_record = false;
         $info = $config['info1'];
     }
     if (!$save_record || $info) {
         return array('save_record' => $save_record, 'type' => 0, 'info' => array('title' => vtranslate($info, 'DataAccess') . ' <br/ >' . trim($fieldlabel, ','), 'type' => $type, 'hide' => false));
     } else {
         return array('save_record' => true);
     }
 }
示例#17
0
 public function updateCard($moduleName, $record, $card)
 {
     $this->log->debug(__CLASS__ . '::' . __METHOD__ . ' | Start CRM ID:' . $record['crmid']);
     $vcard = Sabre\VObject\Reader::read($card['carddata']);
     $vcard->PRODID = self::PRODID;
     unset($vcard->TEL);
     unset($vcard->EMAIL);
     unset($vcard->REV);
     if ($moduleName == 'Contacts') {
         $name = $record['firstname'] . ' ' . $record['lastname'];
         $vcard->N = [$record['lastname'], $record['firstname']];
         $org = Vtiger_Functions::getCRMRecordLabel($record['parentid']);
         if ($org != '') {
             $vcard->ORG = $org;
         }
     }
     if ($moduleName == 'OSSEmployees') {
         $name = $record['name'] . ' ' . $record['last_name'];
         $vcard->N = [$record['last_name'], $record['name']];
         $vcard->ORG = Vtiger_CompanyDetails_Model::getInstanceById()->get('organizationname');
     }
     $vcard->FN = $name;
     foreach ($this->telFields[$moduleName] as $key => $val) {
         if ($record[$key] != '') {
             $vcard->add('TEL', $record[$key], ['type' => explode(',', $val)]);
         }
     }
     foreach ($this->mailFields[$moduleName] as $key => $val) {
         if ($record[$key] != '') {
             $vcard->add('EMAIL', $record[$key], ['type' => explode(',', $val)]);
         }
     }
     $cardData = Sabre\DAV\StringUtil::ensureUTF8($vcard->serialize());
     $etag = md5($cardData);
     $modifiedtime = strtotime($record['modifiedtime']);
     $stmt = $this->pdo->prepare('UPDATE dav_cards SET carddata = ?, lastmodified = ?, size = ?, etag = ?, crmid = ? WHERE id = ?;');
     $stmt->execute([$cardData, $modifiedtime, strlen($cardData), $etag, $record['crmid'], $card['id']]);
     $this->addChange($card['uri'], 2);
     $this->log->debug(__CLASS__ . '::' . __METHOD__ . ' | End');
 }
示例#18
0
 /**
  * Retrieve record information of the module
  * @param <Integer> $record - crmid of record
  * @param <String> $module - module name
  */
 function retrieve_entity_info($record, $module)
 {
     $adb = PearDatabase::getInstance();
     $log = vglobal('log');
     $app_strings = vglobal('app_strings');
     if (!isset($record)) {
         throw new NoPermittedToRecordException('LBL_RECORD_NOT_FOUND');
     }
     // INNER JOIN is desirable if all dependent table has entries for the record.
     // LEFT JOIN is desired if the dependent tables does not have entry.
     $join_type = 'LEFT JOIN';
     // Tables which has multiple rows for the same record
     // will be skipped in record retrieve - need to be taken care separately.
     $multirow_tables = NULL;
     if (isset($this->multirow_tables)) {
         $multirow_tables = $this->multirow_tables;
     } else {
         $multirow_tables = array('vtiger_campaignrelstatus', 'vtiger_attachments', 'vtiger_email_track');
     }
     // Lookup module field cache
     if ($module == 'Calendar' || $module == 'Events') {
         getColumnFields('Calendar');
         if (VTCacheUtils::lookupFieldInfo_Module('Events')) {
             $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events');
         } else {
             $cachedEventsFields = array();
         }
         $cachedCalendarFields = VTCacheUtils::lookupFieldInfo_Module('Calendar');
         $cachedModuleFields = array_merge($cachedEventsFields, $cachedCalendarFields);
         $module = 'Calendar';
     } else {
         $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
     }
     if ($cachedModuleFields === false) {
         // Pull fields and cache for further use
         $tabid = getTabid($module);
         $sql0 = "SELECT fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata,presence FROM vtiger_field WHERE tabid=?";
         // NOTE: Need to skip in-active fields which we will be done later.
         $result0 = $adb->pquery($sql0, array($tabid));
         if ($adb->num_rows($result0)) {
             while ($resultrow = $adb->fetch_array($result0)) {
                 // Update cache
                 VTCacheUtils::updateFieldInfo($tabid, $resultrow['fieldname'], $resultrow['fieldid'], $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']);
             }
             // Get only active field information
             $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
         }
     }
     if ($cachedModuleFields) {
         $column_clause = '';
         $from_clause = '';
         $where_clause = '';
         $limit_clause = ' LIMIT 1';
         // to eliminate multi-records due to table joins.
         $params = array();
         $required_tables = $this->tab_name_index;
         // copies-on-write
         foreach ($cachedModuleFields as $fieldinfo) {
             if (in_array($fieldinfo['tablename'], $multirow_tables)) {
                 continue;
             }
             // Alias prefixed with tablename+fieldname to avoid duplicate column name across tables
             // fieldname are always assumed to be unique for a module
             $column_clause .= $fieldinfo['tablename'] . '.' . $fieldinfo['columnname'] . ' AS ' . $this->createColumnAliasForField($fieldinfo) . ',';
         }
         $column_clause .= 'vtiger_crmentity.deleted';
         if (isset($required_tables['vtiger_crmentity'])) {
             $from_clause = ' vtiger_crmentity';
             unset($required_tables['vtiger_crmentity']);
             foreach ($required_tables as $tablename => $tableindex) {
                 if (in_array($tablename, $multirow_tables)) {
                     // Avoid multirow table joins.
                     continue;
                 }
                 $from_clause .= sprintf(' %s %s ON %s.%s=%s.%s', $join_type, $tablename, $tablename, $tableindex, 'vtiger_crmentity', 'crmid');
             }
         }
         $where_clause .= ' vtiger_crmentity.crmid = ? ';
         $params[] = $record;
         if ($module != '') {
             $where_clause .= ' AND vtiger_crmentity.setype = ?';
             $params[] = $module;
         }
         $sql = sprintf('SELECT %s FROM %s WHERE %s %s', $column_clause, $from_clause, $where_clause, $limit_clause);
         $result = $adb->pquery($sql, $params);
         if (!$result || $adb->num_rows($result) < 1) {
             throw new NoPermittedToRecordException('LBL_RECORD_NOT_FOUND');
         } else {
             $resultrow = $adb->query_result_rowdata($result);
             if (!empty($resultrow['deleted'])) {
                 throw new NoPermittedToRecordException('LBL_RECORD_DELETE');
             }
             foreach ($cachedModuleFields as $fieldinfo) {
                 $fieldvalue = '';
                 $fieldkey = $this->createColumnAliasForField($fieldinfo);
                 //Note : value is retrieved with a tablename+fieldname as we are using alias while building query
                 if (isset($resultrow[$fieldkey])) {
                     $fieldvalue = $resultrow[$fieldkey];
                 }
                 if (in_array($fieldinfo['uitype'], array('10', '51', '73'))) {
                     $this->column_fields[$fieldinfo['fieldname'] . '_label'] = Vtiger_Functions::getCRMRecordLabel($fieldvalue);
                 }
                 $this->column_fields[$fieldinfo['fieldname']] = $fieldvalue;
             }
         }
     }
     $this->column_fields['record_id'] = $record;
     $this->column_fields['record_module'] = $module;
 }
示例#19
0
function get_details($id, $module, $customerid, $sessionid)
{
    $adb = PearDatabase::getInstance();
    $log = vglobal('log');
    require_once 'include/utils/utils.php';
    require_once 'include/utils/UserInfoUtil.php';
    $log->debug("Entering customer portal function get_details ..");
    $user = new Users();
    $userid = getPortalUserid();
    $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
    $isPermitted = check_permission($customerid, $module, $id);
    if ($isPermitted == false) {
        return array("#NOT AUTHORIZED#");
    }
    if (!validateSession($customerid, $sessionid)) {
        return null;
    }
    $params = array($id);
    if ($module == 'Quotes') {
        $query = "SELECT\n\t\t\tvtiger_quotes.*,vtiger_crmentity.*,vtiger_quotesaddress.*,\n\t\t\tvtiger_quotescf.* FROM vtiger_quotes\n\t\t\tINNER JOIN vtiger_crmentity " . "ON vtiger_crmentity.crmid = vtiger_quotes.quoteid\n\t\t\tINNER JOIN vtiger_quotesaddress\n\t\t\t\tON vtiger_quotes.quoteid = vtiger_quotesaddress.quoteaddressid\n\t\t\tLEFT JOIN vtiger_quotescf\n\t\t\t\tON vtiger_quotes.quoteid = vtiger_quotescf.quoteid\n\t\t\tWHERE vtiger_quotes.quoteid=(" . generateQuestionMarks($id) . ") AND vtiger_crmentity.deleted = 0";
    } else {
        if ($module == 'SalesOrder') {
            $query = "SELECT vtiger_salesorder.*,vtiger_crmentity.*,vtiger_salesorderaddress.*,\n\t\t\tvtiger_salesordercf.* \n\t\t\tFROM vtiger_salesorder\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_salesorder.salesorderid\n\t\t\tINNER JOIN vtiger_salesorderaddress ON vtiger_salesorder.salesorderid = vtiger_salesorderaddress.salesorderaddressid\n\t\t\tLEFT JOIN vtiger_salesordercf ON vtiger_salesorder.salesorderid = vtiger_salesordercf.salesorderid\n\t\t\tWHERE vtiger_salesorder.salesorderid=(" . generateQuestionMarks($id) . ") AND vtiger_crmentity.deleted = 0";
        } else {
            if ($module == 'Documents') {
                $result = $adb->pquery('SELECT fieldparams FROM vtiger_field WHERE columnname = ? AND tablename = ?', ['folderid', 'vtiger_notes']);
                $tree = $adb->query_result($result, 0, 'fieldparams');
                $params[] = $tree;
                $query = "SELECT\n\t\t\tvtiger_notes.*,vtiger_crmentity.*, vtiger_trees_templates_data.label as foldername,vtiger_notescf.*\n\t\t\tFROM vtiger_notes\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_notes.notesid\n\t\t\tLEFT JOIN vtiger_trees_templates_data ON vtiger_trees_templates_data.tree = vtiger_notes.folderid\n\t\t\tLEFT JOIN vtiger_notescf ON vtiger_notescf.notesid = vtiger_notes.notesid\n\t\t\tWHERE vtiger_notes.notesid=(" . generateQuestionMarks($id) . ") AND vtiger_trees_templates_data.templateid = ? AND vtiger_crmentity.deleted=0";
            } else {
                if ($module == 'HelpDesk') {
                    $query = "SELECT\n\t\t\tvtiger_troubletickets.*,vtiger_crmentity.smownerid,vtiger_crmentity.createdtime,vtiger_crmentity.modifiedtime,vtiger_crmentity.attention,\n\t\t\tvtiger_ticketcf.*,vtiger_crmentity.description  FROM vtiger_troubletickets\n\t\t\tINNER JOIN vtiger_crmentity on vtiger_crmentity.crmid = vtiger_troubletickets.ticketid\n\t\t\tINNER JOIN vtiger_ticketcf\n\t\t\t\tON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid\n\t\t\tWHERE (vtiger_troubletickets.ticketid=(" . generateQuestionMarks($id) . ") AND vtiger_crmentity.deleted = 0)";
                } else {
                    if ($module == 'Services') {
                        $result = $adb->pquery('SELECT fieldparams FROM vtiger_field WHERE columnname = ? AND tablename = ?', ['pscategory', 'vtiger_service']);
                        $tree = $adb->query_result($result, 0, 'fieldparams');
                        $query = "SELECT vtiger_service.*,vtiger_crmentity.*,vtiger_servicecf.*, vtiger_trees_templates_data.label as pscategory\n\t\t\tFROM vtiger_service\n\t\t\tINNER JOIN vtiger_crmentity\n\t\t\t\tON vtiger_crmentity.crmid = vtiger_service.serviceid AND vtiger_crmentity.deleted = 0\n\t\t\tLEFT JOIN vtiger_servicecf ON vtiger_service.serviceid = vtiger_servicecf.serviceid\n\t\t\tLEFT JOIN vtiger_trees_templates_data ON vtiger_trees_templates_data.tree = vtiger_service.pscategory\n\t\t\tWHERE vtiger_service.serviceid= (" . generateQuestionMarks($id) . ")";
                    } else {
                        if ($module == 'Contacts') {
                            $query = "SELECT vtiger_contactdetails.*,vtiger_contactaddress.*,vtiger_contactsubdetails.*,vtiger_contactscf.*" . " ,vtiger_crmentity.*,vtiger_customerdetails.*\n\t\t \tFROM vtiger_contactdetails\n\t\t\tINNER JOIN vtiger_crmentity\n\t\t\t\tON vtiger_crmentity.crmid = vtiger_contactdetails.contactid\n\t\t\tINNER JOIN vtiger_contactaddress\n\t\t\t\tON vtiger_contactaddress.contactaddressid = vtiger_contactdetails.contactid\n\t\t\tINNER JOIN vtiger_contactsubdetails\n\t\t\t\tON vtiger_contactsubdetails.contactsubscriptionid = vtiger_contactdetails.contactid\n\t\t\tINNER JOIN vtiger_contactscf\n\t\t\t\tON vtiger_contactscf.contactid = vtiger_contactdetails.contactid\n\t\t\tLEFT JOIN vtiger_customerdetails\n\t\t\t\tON vtiger_customerdetails.customerid = vtiger_contactdetails.contactid\n\t\t\tWHERE vtiger_contactdetails.contactid = (" . generateQuestionMarks($id) . ") AND vtiger_crmentity.deleted = 0";
                        } else {
                            if ($module == 'Accounts') {
                                $query = "SELECT vtiger_account.*,vtiger_accountaddress.*,vtiger_accountscf.*,\n\t\t\tvtiger_crmentity.* FROM vtiger_account\n\t\t\tINNER JOIN vtiger_crmentity\n\t\t\t\tON vtiger_crmentity.crmid = vtiger_account.accountid\n\t\t\tINNER JOIN vtiger_accountaddress\n\t\t\t\tON vtiger_account.accountid = vtiger_accountaddress.accountaddressid\n\t\t\tINNER JOIN vtiger_accountscf\n\t\t\t\tON vtiger_account.accountid = vtiger_accountscf.accountid" . " WHERE vtiger_account.accountid = (" . generateQuestionMarks($id) . ") AND vtiger_crmentity.deleted = 0";
                            } else {
                                if ($module == 'Products') {
                                    $query = "SELECT vtiger_products.*,vtiger_productcf.*,vtiger_crmentity.* " . "FROM vtiger_products " . "INNER JOIN vtiger_crmentity " . "ON vtiger_crmentity.crmid = vtiger_products.productid " . "LEFT JOIN vtiger_productcf " . "ON vtiger_productcf.productid = vtiger_products.productid " . "LEFT JOIN vtiger_vendor\n\t\t\tON vtiger_vendor.vendorid = vtiger_products.vendor_id " . "WHERE vtiger_products.productid = (" . generateQuestionMarks($id) . ") AND vtiger_crmentity.deleted = 0";
                                } else {
                                    if ($module == 'Assets') {
                                        $query = "SELECT vtiger_assets.*, vtiger_assetscf.*, vtiger_crmentity.*\n\t\tFROM vtiger_assets\n\t\tINNER JOIN vtiger_crmentity\n\t\tON vtiger_assets.assetsid = vtiger_crmentity.crmid\n\t\tINNER JOIN vtiger_assetscf\n\t\tON vtiger_assetscf.assetsid = vtiger_assets.assetsid\n\t\tWHERE vtiger_crmentity.deleted = 0 AND vtiger_assets.assetsid = (" . generateQuestionMarks($id) . ")";
                                    } else {
                                        if ($module == 'Project') {
                                            $query = "SELECT vtiger_project.*, vtiger_projectcf.*, vtiger_crmentity.*\n\t\t\t\t\tFROM vtiger_project\n\t\t\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_project.projectid\n\t\t\t\t\tLEFT JOIN vtiger_projectcf ON vtiger_projectcf.projectid = vtiger_project.projectid\n\t\t\t\t\tWHERE vtiger_project.projectid = ? AND vtiger_crmentity.deleted = 0";
                                        } else {
                                            if ($module == 'ProjectMilestone') {
                                                $query = "SELECT vtiger_projectmilestone . * , vtiger_projectmilestonecf . * , vtiger_crmentity . * \n\t\t\t\t\tFROM vtiger_projectmilestone\n\t\t\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_projectmilestone.projectmilestoneid\n\t\t\t\t\tLEFT JOIN vtiger_projectmilestonecf ON vtiger_projectmilestonecf.projectmilestoneid = vtiger_projectmilestone.projectmilestoneid\n\t\t\t\t\tWHERE vtiger_projectmilestone.projectmilestoneid = ? AND vtiger_crmentity.deleted =0";
                                            } else {
                                                if ($module == 'ProjectTask') {
                                                    $query = "SELECT vtiger_projecttask.*, vtiger_projecttaskcf.*, vtiger_crmentity.*\n\t\t\t\t\tFROM vtiger_projecttask\n\t\t\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_projecttask.projecttaskid\n\t\t\t\t\tLEFT JOIN vtiger_projecttaskcf ON vtiger_projecttaskcf.projecttaskid = vtiger_projecttask.projecttaskid\n\t\t\t\t\tWHERE vtiger_projecttask.projecttaskid = ? AND vtiger_crmentity.deleted = 0";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    $res = $adb->pquery($query, $params);
    $fieldquery = "SELECT fieldname,columnname,fieldlabel,blocklabel,uitype FROM vtiger_field\n\t\tINNER JOIN  vtiger_blocks on vtiger_blocks.blockid=vtiger_field.block WHERE vtiger_field.tabid = ? AND displaytype in (1,2,4,10)\n\t\tORDER BY vtiger_field.block,vtiger_field.sequence";
    $fieldres = $adb->pquery($fieldquery, array(getTabid($module)));
    $nooffields = $adb->num_rows($fieldres);
    // Dummy instance to make sure column fields are initialized for futher processing
    $focus = CRMEntity::getInstance($module);
    for ($i = 0; $i < $nooffields; $i++) {
        $columnname = $adb->query_result($fieldres, $i, 'columnname');
        $fieldname = $adb->query_result($fieldres, $i, 'fieldname');
        $fieldid = $adb->query_result($fieldres, $i, 'fieldid');
        $blockid = $adb->query_result($fieldres, $i, 'block');
        $uitype = $adb->query_result($fieldres, $i, 'uitype');
        $blocklabel = $adb->query_result($fieldres, $i, 'blocklabel');
        $blockname = Vtiger_Language_Handler::getTranslatedString($blocklabel, $module, vglobal('default_language'));
        if ($blocklabel == 'LBL_COMMENTS' || $blocklabel == 'LBL_IMAGE_INFORMATION') {
            // the comments block of tickets is hardcoded in customer portal,get_ticket_comments is used for it
            continue;
        }
        if ($uitype == 83) {
            //for taxclass in products and services
            continue;
        }
        $fieldper = getFieldVisibilityPermission($module, $current_user->id, $fieldname);
        if ($fieldper == '1') {
            continue;
        }
        $fieldlabel = Vtiger_Language_Handler::getTranslatedString($adb->query_result($fieldres, $i, 'fieldlabel'), $module, vglobal('default_language'));
        $fieldvalue = $adb->query_result($res, 0, $columnname);
        $output[0][$module][$i]['fieldlabel'] = $fieldlabel;
        $output[0][$module][$i]['blockname'] = $blockname;
        if ($columnname == 'title' || $columnname == 'description' || $columnname == 'attention' || $columnname == 'solution') {
            $fieldvalue = decode_html($fieldvalue);
        }
        if ($uitype == 10 && $fieldvalue == 0) {
            $fieldvalue = '';
        }
        if ($uitype == 71 || $uitype == 72) {
            $fieldvalue = number_format($fieldvalue, 5, '.', '');
        }
        if ($uitype == 56) {
            if ($fieldvalue == 1) {
                $fieldvalue = Vtiger_Language_Handler::getTranslatedString('LBL_YES', $module, vglobal('default_language'));
            } else {
                $fieldvalue = Vtiger_Language_Handler::getTranslatedString('LBL_NO', $module, vglobal('default_language'));
            }
        }
        if ($columnname == 'parent_id' || $columnname == 'contactid' || $columnname == 'accountid' || $columnname == 'potentialid' || $fieldname == 'account_id' || $fieldname == 'contact_id' || $columnname == 'linktoaccountscontacts') {
            $crmid = $fieldvalue;
            $modulename = getSalesEntityType($crmid);
            if ($crmid != '' && $modulename != '') {
                $fieldvalues = getEntityName($modulename, array($crmid));
                if ($modulename == 'Contacts') {
                    $fieldvalue = '<a href="index.php?module=Contacts&action=index&id=' . $crmid . '">' . $fieldvalues[$crmid] . '</a>';
                } elseif ($modulename == 'Accounts') {
                    $fieldvalue = '<a href="index.php?module=Accounts&action=index&id=' . $crmid . '">' . $fieldvalues[$crmid] . '</a>';
                } else {
                    $fieldvalue = $fieldvalues[$crmid];
                }
            } else {
                $fieldvalue = '';
            }
        }
        if ($module == 'Quotes') {
            if ($fieldname == 'subject' && $fieldvalue != '') {
                $fieldid = $adb->query_result($res, 0, 'quoteid');
                $fieldvalue = '<a href="index.php?downloadfile=true&module=Quotes&action=index&id=' . $fieldid . '">' . $fieldvalue . '</a>';
            }
            if ($fieldname == 'total') {
                $sym = getCurrencySymbol($res, 0, 'currency_id');
                $fieldvalue = $sym . $fieldvalue;
            }
        }
        if ($module == 'Services') {
            if ($fieldname == 'pscategory' && $fieldvalue != '') {
                $fieldvalue = Vtiger_Language_Handler::getTranslatedString($fieldvalue, $module, vglobal('default_language'));
            }
        }
        if ($module == 'Documents') {
            $fieldid = $adb->query_result($res, 0, 'notesid');
            $filename = $fieldvalue;
            $folderid = $adb->query_result($res, 0, 'folderid');
            $filestatus = $adb->query_result($res, 0, 'filestatus');
            $filetype = $adb->query_result($res, 0, 'filelocationtype');
            if ($fieldname == 'filename') {
                if ($filestatus == 1) {
                    if ($filetype == 'I') {
                        $fieldvalue = '<a href="index.php?downloadfile=true&folderid=' . $folderid . '&filename=' . $filename . '&module=Documents&action=index&id=' . $fieldid . '" >' . $fieldvalue . '</a>';
                    } elseif ($filetype == 'E') {
                        $fieldvalue = '<a target="_blank" href="' . $filename . '" onclick = "updateCount(' . $fieldid . ');">' . $filename . '</a>';
                    }
                }
            }
            if ($fieldname == 'folderid') {
                $fieldvalue = Vtiger_Language_Handler::getTranslatedString($adb->query_result($res, 0, 'foldername'), $module, vglobal('default_language'));
            }
            if ($fieldname == 'filesize') {
                if ($filetype == 'I') {
                    $fieldvalue = $fieldvalue . ' B';
                } elseif ($filetype == 'E') {
                    $fieldvalue = '--';
                }
            }
            if ($fieldname == 'filelocationtype') {
                if ($fieldvalue == 'I') {
                    $fieldvalue = Vtiger_Language_Handler::getTranslatedString('LBL_INTERNAL', $module, vglobal('default_language'));
                } elseif ($fieldvalue == 'E') {
                    $fieldvalue = Vtiger_Language_Handler::getTranslatedString('LBL_EXTERNAL', $module, vglobal('default_language'));
                } else {
                    $fieldvalue = '---';
                }
            }
        }
        if ($columnname == 'product_id') {
            $fieldvalues = getEntityName('Products', array($fieldvalue));
            $fieldvalue = '<a href="index.php?module=Products&action=index&productid=' . $fieldvalue . '">' . $fieldvalues[$fieldvalue] . '</a>';
        }
        if ($module == 'Products') {
            if ($fieldname == 'vendor_id') {
                $fieldvalue = get_vendor_name($fieldvalue);
            }
        }
        if ($module == 'Assets') {
            if ($fieldname == 'account') {
                $accountid = $adb->query_result($res, 0, 'account');
                $accountres = $adb->pquery("select vtiger_account.accountname from vtiger_account where accountid=?", array($accountid));
                $accountname = $adb->query_result($accountres, 0, 'accountname');
                $fieldvalue = $accountname;
            }
            if ($fieldname == 'product') {
                $productid = $adb->query_result($res, 0, 'product');
                $productres = $adb->pquery("select vtiger_products.productname from vtiger_products where productid=?", array($productid));
                $productname = $adb->query_result($productres, 0, 'productname');
                $fieldvalue = $productname;
            }
            if ($fieldname == 'invoiceid') {
                $invoiceid = $adb->query_result($res, 0, 'invoiceid');
                $invoiceres = $adb->pquery("select vtiger_invoice.subject from vtiger_invoice where invoiceid=?", array($invoiceid));
                $invoicename = $adb->query_result($invoiceres, 0, 'subject');
                $fieldvalue = $invoicename;
            }
        }
        if (in_array($uitype, array('15', '16', '120'))) {
            $output[0][$module][$i]['orgfieldvalue'] = $fieldvalue;
            $fieldvalue = Vtiger_Language_Handler::getTranslatedString($fieldvalue, $module, vglobal('default_language'));
        }
        if (in_array($uitype, array('10'))) {
            $fieldvalue = Vtiger_Functions::getCRMRecordLabel($fieldvalue);
        }
        if (in_array($uitype, array('53', '52', '77'))) {
            $fieldvalue = Vtiger_Functions::getOwnerRecordLabel($fieldvalue);
        }
        if ($fieldname == 'unit_price') {
            $sym = getCurrencySymbol($res, 0, 'currency_id');
            $fieldvalue = round($fieldvalue, 2);
            $fieldvalue = $sym . $fieldvalue;
        }
        $output[0][$module][$i]['fieldvalue'] = $fieldvalue;
    }
    if ($module == 'HelpDesk') {
        $ticketid = $adb->query_result($res, 0, 'ticketid');
        $sc_info = getRelatedServiceContracts($ticketid);
        if (!empty($sc_info)) {
            $modulename = 'ServiceContracts';
            $blocklable = Vtiger_Language_Handler::getTranslatedString('LBL_SERVICE_CONTRACT_INFORMATION', $modulename, vglobal('default_language'));
            $j = $i;
            for ($k = 0; $k < count($sc_info); $k++) {
                foreach ($sc_info[$k] as $label => $value) {
                    $output[0][$module][$j]['fieldlabel'] = Vtiger_Language_Handler::getTranslatedString($label, $modulename, vglobal('default_language'));
                    $output[0][$module][$j]['fieldvalue'] = $value;
                    $output[0][$module][$j]['blockname'] = $blocklable;
                    $j++;
                }
            }
        }
    }
    $log->debug("Existing customer portal function get_details ..");
    return $output;
}
示例#20
0
 /**
  * Function to get Employees hierarchy of the given Employees
  * @param  integer   $id      - employeeid
  * returns Employees hierarchy in array format
  */
 function getEmployeeHierarchy($id)
 {
     global $log, $adb, $current_user;
     $log->debug("Entering getEmployeeHierarchy(" . $id . ") method ...");
     require 'user_privileges/user_privileges_' . $current_user->id . '.php';
     $listview_header = array();
     $listview_entries = array();
     foreach ($this->list_fields_name as $fieldname => $colname) {
         if (getFieldVisibilityPermission('OSSEmployees', $current_user->id, $colname) == '0') {
             $listview_header[] = getTranslatedString($fieldname);
         }
     }
     $rows_list = array();
     $encountered_accounts = array($id);
     $rows_list = $this->__getParentEmployees($id, $rows_list, $encountered_accounts);
     $rows_list = $this->__getChildEmployees($id, $rows_list, $rows_list[$id]['depth']);
     foreach ($rows_list as $employees_id => $account_info) {
         $account_info_data = array();
         $hasRecordViewAccess = is_admin($current_user) || isPermitted('OSSEmployees', 'DetailView', $employees_id) == 'yes';
         foreach ($this->list_fields_name as $fieldname => $colname) {
             if (!$hasRecordViewAccess && $colname != 'name') {
                 $account_info_data[] = '';
             } else {
                 if (getFieldVisibilityPermission('OSSEmployees', $current_user->id, $colname) == '0') {
                     $data = $account_info[$colname];
                     if ($colname == 'ossemployees_no') {
                         if ($employees_id != $id) {
                             if ($hasRecordViewAccess) {
                                 $data = '<a href="index.php?module=OSSEmployees&view=Detail&record=' . $employees_id . '">' . $data . '</a>';
                             } else {
                                 $data = '<i>' . $data . '</i>';
                             }
                         } else {
                             $data = '<b>' . $data . '</b>';
                         }
                         $account_depth = str_repeat(" .. ", $account_info['depth'] * 2);
                         $data = $account_depth . $data;
                         //} else if ($colname == 'last_name') {
                         //$data = '<a href="http://'. $data .'" target="_blank">'.$data.'</a>';
                     } else {
                         if ($colname == 'parentid' || $colname == 'projectid' || $colname == 'ticketid' || $colname == 'relategid') {
                             $data = '<a href="index.php?module=' . Vtiger_Functions::getCRMRecordType($data) . '&action=DetailView&record=' . $data . '">' . Vtiger_Functions::getCRMRecordLabel($data) . '</a>';
                         }
                     }
                     $account_info_data[] = $data;
                 }
             }
         }
         $listview_entries[$employees_id] = $account_info_data;
     }
     $hierarchy = array('header' => $listview_header, 'entries' => $listview_entries);
     $log->debug("Exiting getEmployeeHierarchy method ...");
     return $hierarchy;
 }
示例#21
0
/** This function returns the detailed list of vtiger_products associated to a given entity or a record.
 * Param $module - module name
 * Param $focus - module object
 * Param $seid - sales entity id
 * Return type is an object array
 */
function getAssociatedProducts($module, $focus, $seid = '')
{
    $log = vglobal('log');
    $log->debug("Entering getAssociatedProducts(" . $module . "," . get_class($focus) . "," . $seid . "='') method ...");
    $adb = PearDatabase::getInstance();
    $output = '';
    global $theme;
    $no_of_decimal_places = getCurrencyDecimalPlaces();
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    $product_Detail = array();
    // DG 15 Aug 2006
    // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "SELECT\n\t\t\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname,\n \t\t            case when vtiger_products.productid != '' then vtiger_products.product_no else vtiger_service.service_no end as productcode,\n\t\t\t\t\tcase when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price,\n \t\t            case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock,\n \t\t            case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype,\n \t\t                        vtiger_inventoryproductrel.listprice,\n \t\t                        vtiger_inventoryproductrel.description AS product_description,\n \t\t                        vtiger_inventoryproductrel.*,vtiger_crmentity.deleted,\n \t\t                        vtiger_products.usageunit,\n \t\t                        vtiger_service.service_usageunit\n \t                            FROM vtiger_inventoryproductrel\n\t\t\t\t\t\t\t\tLEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_inventoryproductrel.productid\n \t\t                        LEFT JOIN vtiger_products\n \t\t                                ON vtiger_products.productid=vtiger_inventoryproductrel.productid\n \t\t                        LEFT JOIN vtiger_service\n \t\t                                ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid\n \t\t                        WHERE id=?\n \t\t                        ORDER BY sequence_no";
        $params = array($focus->id);
    } elseif ($module == 'Potentials') {
        $query = "SELECT\n \t\t                        vtiger_products.productname,\n \t\t                        vtiger_products.productcode,\n \t\t                        vtiger_products.unit_price,\n \t\t                        vtiger_products.usageunit,\n \t\t                        vtiger_products.qtyinstock,\n \t\t                        vtiger_seproductsrel.*,vtiger_crmentity.deleted,\n \t\t                        vtiger_crmentity.description AS product_description\n \t\t                        FROM vtiger_products\n \t\t                        INNER JOIN vtiger_crmentity\n \t\t                                ON vtiger_crmentity.crmid=vtiger_products.productid\n \t\t                        INNER JOIN vtiger_seproductsrel\n \t\t                                ON vtiger_seproductsrel.productid=vtiger_products.productid\n \t\t                        WHERE vtiger_seproductsrel.crmid=?";
        $params = array($seid);
    } elseif ($module == 'Products') {
        $query = "SELECT\n \t\t                        vtiger_products.productid,\n \t\t                        vtiger_products.productcode,\n \t\t                        vtiger_products.productname,\n \t\t                        vtiger_products.unit_price,\n \t\t                        vtiger_products.usageunit,\n \t\t                        vtiger_products.qtyinstock,vtiger_crmentity.deleted,\n \t\t                        vtiger_crmentity.description AS product_description,\n \t\t                        'Products' AS entitytype\n \t\t                        FROM vtiger_products\n \t\t                        INNER JOIN vtiger_crmentity\n \t\t                                ON vtiger_crmentity.crmid=vtiger_products.productid\n \t\t                        WHERE vtiger_crmentity.deleted=0\n \t\t                                AND productid=?";
        $params = array($seid);
    } elseif ($module == 'Services') {
        $query = "SELECT\n \t\t                        vtiger_service.serviceid AS productid,\n \t\t                        'NA' AS productcode,\n \t\t                        vtiger_service.servicename AS productname,\n \t\t                        vtiger_service.unit_price AS unit_price,\n \t\t                        vtiger_service.service_usageunit AS usageunit,\n \t\t                        'NA' AS qtyinstock,vtiger_crmentity.deleted,\n \t\t                        vtiger_crmentity.description AS product_description,\n \t\t                       \t'Services' AS entitytype\n \t\t\t\t\t\t\t\tFROM vtiger_service\n \t\t                        INNER JOIN vtiger_crmentity\n \t\t                                ON vtiger_crmentity.crmid=vtiger_service.serviceid\n \t\t                        WHERE vtiger_crmentity.deleted=0\n \t\t                                AND serviceid=?";
        $params = array($seid);
    }
    $result = $adb->pquery($query, $params);
    $num_rows = $adb->num_rows($result);
    $finalTaxTotal = '0';
    for ($i = 1; $i <= $num_rows; $i++) {
        $deleted = $adb->query_result($result, $i - 1, 'deleted');
        $hdnProductId = $adb->query_result($result, $i - 1, 'productid');
        $hdnProductcode = $adb->query_result($result, $i - 1, 'productcode');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        $productdescription = $adb->query_result($result, $i - 1, 'product_description');
        $comment = $adb->query_result($result, $i - 1, 'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        if (($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') && $entitytype == 'Services') {
            $usageunit = vtranslate($adb->query_result($result, $i - 1, 'service_usageunit'), $entitytype);
        } else {
            $usageunit = vtranslate($adb->query_result($result, $i - 1, 'usageunit'), $entitytype);
        }
        $calculationsid = $adb->query_result($result, $i - 1, 'calculationsid');
        $purchase = $adb->query_result($result, $i - 1, 'purchase');
        $margin = $adb->query_result($result, $i - 1, 'margin');
        $marginp = $adb->query_result($result, $i - 1, 'marginp');
        $tax = $adb->query_result($result, $i - 1, 'tax');
        if ($deleted || !isset($deleted)) {
            $product_Detail[$i]['productDeleted' . $i] = true;
        } elseif (!$deleted) {
            $product_Detail[$i]['productDeleted' . $i] = false;
        }
        if (!empty($entitytype)) {
            $product_Detail[$i]['entityType' . $i] = $entitytype;
        }
        if (!empty($calculationsid)) {
            $product_Detail[$i]['calculationId' . $i] = $calculationsid;
            $product_Detail[$i]['calculation' . $i] = Vtiger_Functions::getCRMRecordLabel($calculationsid);
        }
        if ($listprice == '') {
            $listprice = $unitprice;
        }
        if ($qty == '') {
            $qty = 1;
        }
        //calculate productTotal
        $productTotal = $qty * $listprice;
        //Delete link in First column
        if ($i != 1) {
            $product_Detail[$i]['delRow' . $i] = "Del";
        }
        if (empty($focus->mode) && $seid != '') {
            $sub_prod_query = $adb->pquery("SELECT crmid as prod_id from vtiger_seproductsrel WHERE productid=? AND setype='Products'", array($seid));
        } else {
            $sub_prod_query = $adb->pquery("SELECT productid as prod_id from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        }
        $subprodid_str = '';
        $subprodname_str = '';
        $subProductArray = array();
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'prod_id');
                $sprod_name = $subProductArray[] = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodid_str .= $str_sep . $sprod_id;
                if (isset($sprod_name)) {
                    $subprodname_str .= $str_sep . " - " . $sprod_name;
                }
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $product_Detail[$i]['subProductArray' . $i] = $subProductArray;
        $product_Detail[$i]['hdnProductId' . $i] = $hdnProductId;
        $product_Detail[$i]['productName' . $i] = from_html($productname);
        /* Added to fix the issue Product Pop-up name display */
        if ($_REQUEST['action'] == 'CreateSOPDF' || $_REQUEST['action'] == 'CreatePDF' || $_REQUEST['action'] == 'SendPDFMail') {
            $product_Detail[$i]['productName' . $i] = htmlspecialchars($product_Detail[$i]['productName' . $i]);
        }
        $product_Detail[$i]['hdnProductcode' . $i] = $hdnProductcode;
        $product_Detail[$i]['productDescription' . $i] = from_html($productdescription);
        if ($module == 'Potentials' || $module == 'Products' || $module == 'Services') {
            $product_Detail[$i]['comment' . $i] = $productdescription;
        } else {
            $product_Detail[$i]['comment' . $i] = $comment;
        }
        if ($module != 'PurchaseOrder' && $focus->object_name != 'Order') {
            $product_Detail[$i]['qtyInStock' . $i] = decimalFormat($qtyinstock);
        }
        $listprice = number_format($listprice, $no_of_decimal_places, '.', '');
        $product_Detail[$i]['qty' . $i] = decimalFormat($qty);
        $product_Detail[$i]['listPrice' . $i] = $listprice;
        $product_Detail[$i]['unitPrice' . $i] = number_format($unitprice, $no_of_decimal_places, '.', '');
        $product_Detail[$i]['usageUnit' . $i] = $usageunit;
        $product_Detail[$i]['productTotal' . $i] = $productTotal;
        $product_Detail[$i]['subproduct_ids' . $i] = $subprodid_str;
        $product_Detail[$i]['subprod_names' . $i] = $subprodname_str;
        $product_Detail[$i]['purchase' . $i] = number_format($purchase, $no_of_decimal_places, '.', '');
        $product_Detail[$i]['margin' . $i] = number_format($margin, $no_of_decimal_places, '.', '');
        $product_Detail[$i]['marginp' . $i] = number_format($marginp, $no_of_decimal_places, '.', '');
        $product_Detail[$i]['tax' . $i] = $tax;
        $discount_percent = decimalFormat($adb->query_result($result, $i - 1, 'discount_percent'));
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $discount_amount = decimalFormat(number_format($discount_amount, $no_of_decimal_places, '.', ''));
        $discountTotal = '0';
        //Based on the discount percent or amount we will show the discount details
        //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(for Each Product)
        $product_Detail[$i]['discount_percent' . $i] = 0;
        $product_Detail[$i]['discount_amount' . $i] = 0;
        if (!empty($discount_percent)) {
            $product_Detail[$i]['discount_type' . $i] = "percentage";
            $product_Detail[$i]['discount_percent' . $i] = $discount_percent;
            $product_Detail[$i]['checked_discount_percent' . $i] = ' checked';
            $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:visible"';
            $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:hidden"';
            $discountTotal = $productTotal * $discount_percent / 100;
        } elseif (!empty($discount_amount)) {
            $product_Detail[$i]['discount_type' . $i] = "amount";
            $product_Detail[$i]['discount_amount' . $i] = $discount_amount;
            $product_Detail[$i]['checked_discount_amount' . $i] = ' checked';
            $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:visible"';
            $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:hidden"';
            $discountTotal = $discount_amount;
        } else {
            $product_Detail[$i]['checked_discount_zero' . $i] = ' checked';
        }
        $totalAfterDiscount = $productTotal - $discountTotal;
        $totalAfterDiscount = number_format($totalAfterDiscount, $no_of_decimal_places, '.', '');
        $discountTotal = number_format($discountTotal, $no_of_decimal_places, '.', '');
        $product_Detail[$i]['discountTotal' . $i] = $discountTotal;
        $product_Detail[$i]['totalAfterDiscount' . $i] = $totalAfterDiscount;
        $amount = '0';
        $tax_details = getTaxDetailsForProduct($hdnProductId, 'all');
        //First we should get all available taxes and then retrieve the corresponding tax values
        $allTaxes = getAllTaxes('available', '', 'edit', $focus->id);
        $taxtype = getInventoryTaxType($module, $focus->id);
        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 = '0';
            //condition to avoid this function call when create new PO/SO/Quotes/Invoice from Product module
            if ($focus->id != '') {
                if ($taxtype == 'individual') {
                    //if individual then show the entered tax percentage
                    $tax_value = getInventoryProductTaxValue($focus->id, $hdnProductId, $tax_name);
                } else {
                    //if group tax then we have to show the default value when change to individual tax
                    $tax_value = $tax_details[$tax_count]['percentage'];
                }
            } else {
                //if the above function not called then assign the default associated value of the product
                $tax_value = $tax_details[$tax_count]['percentage'];
            }
            $product_Detail[$i]['taxes'][$tax_count]['taxname'] = $tax_name;
            $product_Detail[$i]['taxes'][$tax_count]['taxlabel'] = $tax_label;
            $product_Detail[$i]['taxes'][$tax_count]['percentage'] = $tax_value;
            $amount = $totalAfterDiscount * $tax_value / 100;
            $amount = number_format($amount, $no_of_decimal_places, '.', '');
            $product_Detail[$i]['taxes'][$tax_count]['amount'] = $amount;
            if ($tax == $tax_name) {
                $product_Detail[$i]['taxTotal' . $i] = $amount;
            }
        }
        if ($taxtype == 'group') {
            foreach ($allTaxes as $key => $value) {
                if ($tax == $value['taxname']) {
                    $amount = $totalAfterDiscount * $value['percentage'] / 100;
                    $amount = number_format($amount, $no_of_decimal_places, '.', '');
                    $product_Detail[$i]['taxes'][$tax]['amount'] = $amount;
                    $finalTaxTotal += $amount;
                    $product_Detail[$i]['taxTotal' . $i] = $amount;
                }
            }
        }
        //Calculate netprice
        $netPrice = $totalAfterDiscount + number_format($product_Detail[$i]['taxTotal' . $i], $no_of_decimal_places, '.', '');
        //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module
        $product_Detail[$i]['netPrice' . $i] = $netPrice;
    }
    //set the taxtype
    $product_Detail[1]['final_details']['taxtype'] = $taxtype;
    //Get the Final Discount, S&H charge, Tax for S&H values
    //To set the Final Discount details
    $finalDiscount = '0';
    $product_Detail[1]['final_details']['discount_type_final'] = 'zero';
    $subTotal = $focus->column_fields['hdnSubTotal'] != '' ? $focus->column_fields['hdnSubTotal'] : '0';
    $subTotal = number_format($subTotal, $no_of_decimal_places, '.', '');
    $product_Detail[1]['final_details']['hdnSubTotal'] = $subTotal;
    $discountPercent = $focus->column_fields['hdnDiscountPercent'] != '' ? $focus->column_fields['hdnDiscountPercent'] : '0';
    $discountAmount = $focus->column_fields['hdnDiscountAmount'] != '' ? $focus->column_fields['hdnDiscountAmount'] : '0';
    if ($discountPercent != '0') {
        $discountAmount = $product_Detail[1]['final_details']['hdnSubTotal'] * $discountPercent / 100;
    }
    //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(For Final Discount)
    $discount_amount_final = '0';
    $discount_amount_final = number_format($discount_amount_final, $no_of_decimal_places, '.', '');
    $product_Detail[1]['final_details']['discount_percentage_final'] = 0;
    $product_Detail[1]['final_details']['discount_amount_final'] = $discount_amount_final;
    //fix for opensource issue not saving invoice data properly
    if (!empty($focus->column_fields['hdnDiscountPercent'])) {
        $finalDiscount = $subTotal * $discountPercent / 100;
        $product_Detail[1]['final_details']['discount_type_final'] = 'percentage';
        $product_Detail[1]['final_details']['discount_percentage_final'] = $discountPercent;
        $product_Detail[1]['final_details']['checked_discount_percentage_final'] = ' checked';
        $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:visible"';
        $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:hidden"';
    } elseif (!empty($focus->column_fields['hdnDiscountAmount'])) {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $product_Detail[1]['final_details']['discount_type_final'] = 'amount';
        $product_Detail[1]['final_details']['discount_amount_final'] = $discountAmount;
        $product_Detail[1]['final_details']['checked_discount_amount_final'] = ' checked';
        $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:visible"';
        $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:hidden"';
    }
    $finalDiscount = number_format($finalDiscount, $no_of_decimal_places, '.', '');
    $product_Detail[1]['final_details']['discountTotal_final'] = $finalDiscount;
    //To set the Final Tax values
    //we will get all taxes. if individual then show the product related taxes only else show all taxes
    //suppose user want to change individual to group or vice versa in edit time the we have to show all taxes. so that here we will store all the taxes and based on need we will show the corresponding taxes
    for ($tax_count = 0; $tax_count < count($allTaxes); $tax_count++) {
        $tax_name = $allTaxes[$tax_count]['taxname'];
        $tax_label = $allTaxes[$tax_count]['taxlabel'];
        //if taxtype is individual and want to change to group during edit time then we have to show the all available taxes and their default values
        //Also taxtype is group and want to change to individual during edit time then we have to provide the asspciated taxes and their default tax values for individual products
        if ($taxtype == 'group') {
            $tax_percent = $adb->query_result($result, 0, $tax_name);
        } else {
            $tax_percent = $allTaxes[$tax_count]['percentage'];
        }
        //$adb->query_result($result,0,$tax_name);
        if ($tax_percent == '' || $tax_percent == 'NULL') {
            $tax_percent = '0';
        }
        $taxamount = ($subTotal - $finalDiscount) * $tax_percent / 100;
        $taxamount = number_format($taxamount, $no_of_decimal_places, '.', '');
        $product_Detail[1]['final_details']['taxes'][$tax_count]['taxname'] = $tax_name;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['taxlabel'] = $tax_label;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['percentage'] = $tax_percent;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['amount'] = $taxamount;
    }
    $product_Detail[1]['final_details']['tax_totalamount'] = $finalTaxTotal;
    $product_Detail[1]['final_details']['tax'] = $tax;
    //To set the grand total
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0';
    $grandTotal = number_format($grandTotal, $no_of_decimal_places, '.', '');
    $product_Detail[1]['final_details']['grandTotal'] = $grandTotal;
    $log->debug("Exiting getAssociatedProducts method ...");
    return $product_Detail;
}
    public function process($moduleName, $iD, $record_form, $config)
    {
        $db = PearDatabase::getInstance();
        $moduleNameID = Vtiger_Functions::getModuleId($moduleName);
        $fieldlabel = $sql_ext = '';
        $save_record1 = true;
        $save_record2 = true;
        $save_record = true;
        $type = 0;
        $typeInfo = 'info';
        $info = false;
        if ($iD != 0 && $iD != '' && !array_key_exists($config['what1'], $record_form)) {
            $Record_Model = Vtiger_Record_Model::getInstanceById($iD, $moduleName);
            $value1 = $Record_Model->get($config['what1']);
        } else {
            if (array_key_exists($config['what1'], $record_form)) {
                $value1 = $record_form[$config['what1']];
            }
        }
        if ($iD != 0 && $iD != '' && !array_key_exists($config['what2'], $record_form)) {
            $Record_Model = Vtiger_Record_Model::getInstanceById($iD, $moduleName);
            $value2 = $Record_Model->get($config['what2']);
        } else {
            if (array_key_exists($config['what2'], $record_form)) {
                $value2 = $record_form[$config['what2']];
            }
        }
        if (!is_array($config['where1'])) {
            $wheres1[] = $config['where1'];
        } else {
            $wheres1 = $config['where1'];
        }
        if (!is_array($config['where2'])) {
            $wheres2[] = $config['where2'];
        } else {
            $wheres2 = $config['where2'];
        }
        if ($value1 != '') {
            foreach ($wheres1 as $where) {
                $where = explode('=', $where);
                $DestModuleName = Vtiger_Functions::getModuleName($where[2]);
                $ModuleInstance = CRMEntity::getInstance($DestModuleName);
                $tab_name_index = $ModuleInstance->tab_name_index;
                $index = $tab_name_index[$where[0]];
                $sql_param = array($value1);
                $sql_ext = '';
                $spacialCondition = '';
                $sqlSpecial = '';
                if ($moduleNameID == $where[2] && $iD != 0 && $iD != '') {
                    $sql_param[] = $iD;
                    $sql_ext = 'AND ' . $index . ' <> ?';
                }
                if ($DestModuleName == 'Leads') {
                    $spacialCondition = ' AND `converted` = 0';
                    if ('vtiger_crmentity' == $where[0]) {
                        $sqlSpecial = 'INNER JOIN vtiger_leaddetails ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid ';
                    }
                }
                $result = $db->pquery("SELECT {$index} FROM {$where[0]} {$sqlSpecial} WHERE {$where[1]} = ? {$sql_ext} {$spacialCondition};", $sql_param, true);
                $num = $db->num_rows($result);
                for ($i = 0; $i < $num; $i++) {
                    $id = $db->query_result_raw($result, $i, $index);
                    $metadata = Vtiger_Functions::getCRMRecordMetadata($id);
                    if ($metadata['setype'] == $DestModuleName) {
                        $save_record1 = false;
                        $deletedLabel = $metadata['deleted'] ? ' - ' . vtranslate('LBL_RECORD_DELETED', 'DataAccess') : '';
                        $fieldlabel .= '<li><a target="_blank" href="index.php?module=' . $DestModuleName . '&view=Detail&record=' . $id . '"><strong>' . Vtiger_Functions::getCRMRecordLabel($id) . '</strong></a> (' . Vtiger_Functions::getOwnerRecordLabel($metadata['smownerid']) . ')' . $deletedLabel . ',</li>';
                    }
                }
            }
        }
        if ($value2 != '') {
            foreach ($wheres2 as $where) {
                $where = explode('=', $where);
                $DestModuleName = Vtiger_Functions::getModuleName($where[2]);
                $ModuleInstance = CRMEntity::getInstance($DestModuleName);
                $tab_name_index = $ModuleInstance->tab_name_index;
                $index = $tab_name_index[$where[0]];
                $sql_param = array($value2);
                $sql_ext = '';
                $spacialCondition = '';
                $sqlSpecial = '';
                if ($moduleNameID == $where[2] && $iD != 0 && $iD != '') {
                    $sql_param[] = $iD;
                    $sql_ext = 'AND ' . $index . ' <> ?';
                }
                if ($DestModuleName == 'Leads') {
                    $spacialCondition = ' AND `converted` = 0';
                    if ('vtiger_crmentity' == $where[0]) {
                        $sqlSpecial = 'INNER JOIN vtiger_leaddetails ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid ';
                    }
                }
                $result = $db->pquery("SELECT {$index} FROM {$where[0]} WHERE {$where[1]} = ? {$sql_ext};", $sql_param, true);
                $num = $db->num_rows($result);
                for ($i = 0; $i < $num; $i++) {
                    $id = $db->query_result_raw($result, $i, $index);
                    $metadata = Vtiger_Functions::getCRMRecordMetadata($id);
                    if ($metadata['setype'] == $DestModuleName) {
                        $save_record2 = false;
                        $deletedLabel = $metadata['deleted'] ? ' - ' . vtranslate('LBL_RECORD_DELETED', 'DataAccess') : '';
                        $fieldlabel .= '<li><a target="_blank" href="index.php?module=' . $DestModuleName . '&view=Detail&record=' . $id . '"><strong>' . Vtiger_Functions::getCRMRecordLabel($id) . '</strong></a> (' . Vtiger_Functions::getOwnerRecordLabel($metadata['smownerid']) . ')' . $deletedLabel . ',</li>';
                    }
                }
            }
        }
        if ($config['locksave'] == 0) {
            $info = $config['info0'];
            $type = 2;
            $save_record = !$save_record1 || !$save_record2 ? false : true;
        } elseif (!$save_record1 && !$save_record2) {
            $typeInfo = 'error';
            $save_record = false;
            $info = $config['info2'];
        } elseif (!$save_record1 || !$save_record2) {
            $typeInfo = 'error';
            $save_record = false;
            $info = $config['info1'];
        }
        if ($config['locksave'] == 3 && !$save_record) {
            $type = $config['locksave'];
            $permission = Users_Privileges_Model::isPermitted($moduleName, 'DuplicateRecord');
            $text = '<div class="marginLeft10">' . vtranslate('LBL_DUPLICATED_FOUND', 'DataAccess') . ': <br/ >' . trim($fieldlabel, ',') . '</div>';
            if ($permission) {
                $title = '<strong>' . vtranslate('LBL_DUPLICTAE_CREATION_CONFIRMATION', 'DataAccess') . '</strong>';
                if (!empty($iD)) {
                    $text .= '<form class="form-horizontal"><div class="checkbox">
							<label>
								<input type="checkbox" name="cache"> ' . vtranslate('LBL_DONT_ASK_AGAIN', 'DataAccess') . '
							</label>
						</div></form>';
                }
                if ($record_form['view'] == 'quick_edit') {
                    $text = '<div class="alert alert-warning" role="alert">' . vtranslate('LBL_DUPLICTAE_QUICK_EDIT_CONFIRMATION', 'DataAccess') . '</div>' . $text;
                }
            }
            $info = ['text' => $text, 'title' => $title, 'type' => $permission ? 1 : 0];
        }
        if (!$save_record || $info) {
            return array('save_record' => $save_record, 'type' => $type, 'info' => $info ? $info : ['text' => vtranslate($info, 'DataAccess') . ' <br/ >' . trim($fieldlabel, ','), 'ntype' => $typeInfo, 'hide' => false]);
        } else {
            return array('save_record' => true);
        }
    }
示例#23
0
 function replaceRelVar($fieldId, $tpl, $recordId, $module, $start, $positionLength, $allLength)
 {
     $db = PearDatabase::getInstance();
     vimport("~~modules/{$module}/{$module}.php");
     $IDs = explode('||', $fieldId);
     $getFieldInfoSql = "SELECT * FROM vtiger_field WHERE fieldid = '" . $IDs[0] . "'";
     $getFieldInfoResult = $db->query($getFieldInfoSql, true);
     $fieldTab = $db->query_result_raw($getFieldInfoResult, 0, 'tablename');
     $fieldname = $db->query_result_raw($getFieldInfoResult, 0, 'fieldname');
     $fieldColumnName = $db->query_result_raw($getFieldInfoResult, 0, 'columnname');
     $tabid = $db->query_result_raw($getFieldInfoResult, 0, 'tabid');
     $uitype = $db->query_result_raw($getFieldInfoResult, 0, 'uitype');
     $moduleNameResult = $db->pquery("SELECT name FROM vtiger_tab WHERE tabid = ?", array($tabid), true);
     $fieldModule = $db->query_result_raw($moduleNameResult, 0, 'name');
     $moduleInstance = Vtiger_Record_Model::getInstanceById($recordId, $module);
     $getFieldInfoSql2 = "SELECT * FROM vtiger_field WHERE fieldid = ?";
     $getFieldInfoResult2 = $db->pquery($getFieldInfoSql2, array($IDs[1]), true);
     $rel_id = $moduleInstance->get($db->query_result_raw($getFieldInfoResult2, 0, 'fieldname'));
     $modObj = CRMEntity::getInstance($fieldModule);
     $primaryKey = $modObj->tab_name_index[$fieldTab];
     $getValueSql = "SELECT {$fieldColumnName} FROM {$fieldTab} WHERE {$primaryKey} = ?;";
     $getValueResult = $db->pquery($getValueSql, array($rel_id), true);
     $finalValue = $db->query_result_raw($getValueResult, 0, $fieldColumnName);
     if ($uitype == 10 || $uitype == 51 || $uitype == 73 || $uitype == 66 || $uitype == 57) {
         $finalValue = Vtiger_Functions::getCRMRecordLabel($finalValue);
     } elseif ($uitype == 15 || $uitype == 16) {
         $finalValue = vtranslate($finalValue, $module);
     } elseif ($uitype == 53 || $uitype == 52) {
         $finalValue = Vtiger_Functions::getOwnerRecordLabel($finalValue);
     }
     $tpl = substr_replace($tpl, $finalValue, $start, $allLength + $positionLength);
     return $tpl;
 }
示例#24
0
 function getHierarchy($id)
 {
     $adb = PearDatabase::getInstance();
     $log = vglobal('log');
     $current_user = vglobal('current_user');
     $log->debug("Entering getHierarchy(" . $id . ") method ...");
     require 'user_privileges/user_privileges_' . $current_user->id . '.php';
     $listview_header = array();
     $listview_entries = array();
     foreach ($this->list_fields as $fieldname => $colname) {
         if (getFieldVisibilityPermission('Calculations', $current_user->id, $colname['calculations']) == '0') {
             $listview_header[] = getTranslatedString($fieldname);
         }
     }
     $rows_list = array();
     $encountered_accounts = array($id);
     $rows_list = $this->__getParentRecord($id, $rows_list, $encountered_accounts);
     $rows_list = $this->__getChildRecord($id, $rows_list, $rows_list[$id]['depth']);
     foreach ($rows_list as $calculations_id => $account_info) {
         $account_info_data = array();
         $hasRecordViewAccess = is_admin($current_user) || isPermitted('Calculations', 'DetailView', $calculations_id) == 'yes';
         foreach ($this->list_fields as $fieldname => $colname) {
             $colname = $colname['calculations'];
             if (!$hasRecordViewAccess && $colname != 'name') {
                 $account_info_data[] = '';
             } else {
                 if (getFieldVisibilityPermission('Calculations', $current_user->id, $colname) == '0') {
                     $data = $account_info[$colname];
                     if ($colname == 'name') {
                         if ($calculations_id != $id) {
                             if ($hasRecordViewAccess) {
                                 $data = '<a href="index.php?module=Calculations&view=Detail&record=' . $calculations_id . '">' . $data . '</a>';
                             } else {
                                 $data = '<i>' . $data . '</i>';
                             }
                         } else {
                             $data = '<b>' . $data . '</b>';
                         }
                         $account_depth = str_repeat(" .. ", $account_info['depth']);
                         $data = $account_depth . $data;
                     } else {
                         if ($colname == 'relatedid') {
                             $data = '';
                             if ($data != 0) {
                                 $data = '<a href="index.php?module=Calculations&view=Detail&record=' . $data . '">' . Vtiger_Functions::getCRMRecordLabel($data) . '</a>';
                             }
                         } else {
                             if ($colname == 'website') {
                                 $data = '<a href="http://' . $data . '" target="_blank">' . $data . '</a>';
                             }
                         }
                     }
                     $account_info_data[] = $data;
                 }
             }
         }
         $listview_entries[$calculations_id] = $account_info_data;
     }
     $hierarchy = array('header' => $listview_header, 'entries' => $listview_entries);
     $log->debug("Exiting getHierarchy method ...");
     return $hierarchy;
 }
示例#25
0
 public static function getBreadcrumbs($pageTitle = false)
 {
     $breadcrumbs = false;
     $request = new Vtiger_Request($_REQUEST, $_REQUEST);
     $userPrivModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
     $roleMenu = 'user_privileges/menu_' . filter_var($userPrivModel->get('roleid'), FILTER_SANITIZE_NUMBER_INT) . '.php';
     if (file_exists($roleMenu)) {
         require $roleMenu;
     } else {
         require 'user_privileges/menu_0.php';
     }
     if (count($menus) == 0) {
         require 'user_privileges/menu_0.php';
     }
     $moduleName = $request->getModule();
     $view = $request->get('view');
     $parent = $request->get('parent');
     if ($parent !== 'Settings') {
         if (empty($parent)) {
             foreach ($parentList as &$parentItem) {
                 if ($moduleName == $parentItem['name']) {
                     $parent = $parentItem['parent'];
                     break;
                 }
             }
         }
         $parentMenu = self::getParentMenu($parentList, $parent, $moduleName);
         if (count($parentMenu) > 0) {
             $breadcrumbs = array_reverse($parentMenu);
         }
         $breadcrumbs[] = ['name' => vtranslate($moduleName, $moduleName), 'url' => 'index.php?module=' . $moduleName . '&view=List'];
         if ($pageTitle) {
             $breadcrumbs[] = ['name' => vtranslate($pageTitle, $moduleName)];
         } elseif ($view == 'Edit' && $request->get('record') == '') {
             $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_CREATE', $moduleName)];
         } elseif ($view != '' && $view != 'index' && $view != 'Index') {
             $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_' . strtoupper($view), $moduleName)];
         } elseif ($view == '') {
             $breadcrumbs[] = ['name' => vtranslate('LBL_HOME', $moduleName)];
         }
         if ($request->get('record') != '') {
             $recordLabel = Vtiger_Functions::getCRMRecordLabel($request->get('record'));
             if ($recordLabel != '') {
                 $breadcrumbs[] = ['name' => $recordLabel];
             }
         }
     } elseif ($parent === 'Settings') {
         $qualifiedModuleName = $request->getModule(false);
         $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_SETTINGS', $qualifiedModuleName), 'url' => 'index.php?module=Vtiger&parent=Settings&view=Index'];
         if ($moduleName !== 'Vtiger' || $view !== 'Index') {
             $fieldId = $request->get('fieldid');
             $menu = Settings_Vtiger_MenuItem_Model::getAll();
             foreach ($menu as &$menuModel) {
                 if (empty($fieldId)) {
                     if ($menuModel->getModule() == $moduleName) {
                         $parent = $menuModel->getMenu();
                         $breadcrumbs[] = ['name' => vtranslate($parent->get('label'), $qualifiedModuleName)];
                         $breadcrumbs[] = ['name' => vtranslate($menuModel->get('name'), $qualifiedModuleName), 'url' => $menuModel->getUrl()];
                         break;
                     }
                 } else {
                     if ($fieldId == $menuModel->getId()) {
                         $parent = $menuModel->getMenu();
                         $breadcrumbs[] = ['name' => vtranslate($parent->get('label'), $qualifiedModuleName)];
                         $breadcrumbs[] = ['name' => vtranslate($menuModel->get('name'), $qualifiedModuleName), 'url' => $menuModel->getUrl()];
                         break;
                     }
                 }
             }
             if ($pageTitle) {
                 $breadcrumbs[] = ['name' => vtranslate($pageTitle, $moduleName)];
             } elseif ($view == 'Edit' && $request->get('record') == '' && $request->get('parent_roleid') == '') {
                 $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_CREATE', $qualifiedModuleName)];
             } elseif ($view != '' && $view != 'List') {
                 $breadcrumbs[] = ['name' => vtranslate('LBL_VIEW_' . strtoupper($view), $qualifiedModuleName)];
             }
             if ($request->get('record') != '') {
                 $recordLabel = Vtiger_Functions::getUserRecordLabel($request->get('record'));
                 if ($recordLabel != '') {
                     $breadcrumbs[] = ['name' => $recordLabel];
                 }
             }
         }
     }
     return $breadcrumbs;
 }
示例#26
0
 public function process($ModuleName, $ID, $record_form, $config)
 {
     $db = PearDatabase::getInstance();
     $ModuleNameID = Vtiger_Functions::getModuleId($ModuleName);
     $fieldlabel = $sql_ext = '';
     $save_record1 = true;
     $save_record2 = true;
     $save_record = true;
     $type = 0;
     $typeInfo = 'info';
     $info = false;
     if ($ID != 0 && $ID != '' && !array_key_exists($config['what1'], $record_form)) {
         $Record_Model = Vtiger_Record_Model::getInstanceById($ID, $ModuleName);
         $value1 = $Record_Model->get($config['what1']);
     } else {
         if (array_key_exists($config['what1'], $record_form)) {
             $value1 = $record_form[$config['what1']];
         }
     }
     if ($ID != 0 && $ID != '' && !array_key_exists($config['what2'], $record_form)) {
         $Record_Model = Vtiger_Record_Model::getInstanceById($ID, $ModuleName);
         $value2 = $Record_Model->get($config['what2']);
     } else {
         if (array_key_exists($config['what2'], $record_form)) {
             $value2 = $record_form[$config['what2']];
         }
     }
     if (!is_array($config['where1'])) {
         $wheres1[] = $config['where1'];
     } else {
         $wheres1 = $config['where1'];
     }
     if (!is_array($config['where2'])) {
         $wheres2[] = $config['where2'];
     } else {
         $wheres2 = $config['where2'];
     }
     if ($value1 != '') {
         foreach ($wheres1 as $where) {
             $where = explode('=', $where);
             $DestModuleName = Vtiger_Functions::getModuleName($where[2]);
             $ModuleInstance = CRMEntity::getInstance($DestModuleName);
             $tab_name_index = $ModuleInstance->tab_name_index;
             $index = $tab_name_index[$where[0]];
             $sql_param = array($value1);
             $sql_ext = '';
             $spacialCondition = '';
             $sqlSpecial = '';
             if ($ModuleNameID == $where[2] && $ID != 0 && $ID != '') {
                 $sql_param[] = $ID;
                 $sql_ext = 'AND ' . $index . ' <> ?';
             }
             if ($DestModuleName == 'Leads') {
                 $spacialCondition = ' AND `converted` = 0';
                 if ('vtiger_crmentity' == $where[0]) {
                     $sqlSpecial = 'INNER JOIN vtiger_leaddetails ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid ';
                 }
             }
             $result = $db->pquery("SELECT {$index} FROM {$where[0]} {$sqlSpecial} WHERE {$where[1]} = ? {$sql_ext} {$spacialCondition};", $sql_param, true);
             $num = $db->num_rows($result);
             for ($i = 0; $i < $num; $i++) {
                 $id = $db->query_result_raw($result, $i, $index);
                 $metadata = Vtiger_Functions::getCRMRecordMetadata($id);
                 if ($metadata['setype'] == $DestModuleName) {
                     $save_record1 = false;
                     $deletedLabel = $metadata['deleted'] ? ' - ' . vtranslate('LBL_RECORD_DELETED', 'DataAccess') : '';
                     $fieldlabel .= '<a target="_blank" href="index.php?module=' . $DestModuleName . '&view=Detail&record=' . $id . '">&bull; ' . Vtiger_Functions::getCRMRecordLabel($id) . '</a> (' . Vtiger_Functions::getOwnerRecordLabel($metadata['smownerid']) . ')' . $deletedLabel . ',<br/>';
                 }
             }
         }
     }
     if ($value2 != '') {
         foreach ($wheres2 as $where) {
             $where = explode('=', $where);
             $DestModuleName = Vtiger_Functions::getModuleName($where[2]);
             $ModuleInstance = CRMEntity::getInstance($DestModuleName);
             $tab_name_index = $ModuleInstance->tab_name_index;
             $index = $tab_name_index[$where[0]];
             $sql_param = array($value2);
             $sql_ext = '';
             $spacialCondition = '';
             $sqlSpecial = '';
             if ($ModuleNameID == $where[2] && $ID != 0 && $ID != '') {
                 $sql_param[] = $ID;
                 $sql_ext = 'AND ' . $index . ' <> ?';
             }
             if ($DestModuleName == 'Leads') {
                 $spacialCondition = ' AND `converted` = 0';
                 if ('vtiger_crmentity' == $where[0]) {
                     $sqlSpecial = 'INNER JOIN vtiger_leaddetails ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid ';
                 }
             }
             $result = $db->pquery("SELECT {$index} FROM {$where[0]} WHERE {$where[1]} = ? {$sql_ext};", $sql_param, true);
             $num = $db->num_rows($result);
             for ($i = 0; $i < $num; $i++) {
                 $id = $db->query_result_raw($result, $i, $index);
                 $metadata = Vtiger_Functions::getCRMRecordMetadata($id);
                 if ($metadata['setype'] == $DestModuleName) {
                     $save_record2 = false;
                     $deletedLabel = $metadata['deleted'] ? ' - ' . vtranslate('LBL_RECORD_DELETED', 'DataAccess') : '';
                     $fieldlabel .= '<a target="_blank" href="index.php?module=' . $DestModuleName . '&view=Detail&record=' . $id . '">&bull; ' . Vtiger_Functions::getCRMRecordLabel($id) . '</a> (' . Vtiger_Functions::getOwnerRecordLabel($metadata['smownerid']) . ')' . $deletedLabel . ',<br/>';
                 }
             }
         }
     }
     if ($config['locksave'] == 0) {
         $info = $config['info0'];
         $type = 2;
         $save_record = !$save_record1 || !$save_record2 ? false : true;
     } elseif (!$save_record1 && !$save_record2) {
         $typeInfo = 'error';
         $save_record = false;
         $info = $config['info2'];
     } elseif (!$save_record1 || !$save_record2) {
         $typeInfo = 'error';
         $save_record = false;
         $info = $config['info1'];
     }
     if (!$save_record || $info) {
         return array('save_record' => $save_record, 'type' => $type, 'info' => ['text' => vtranslate($info, 'DataAccess') . ' <br/ >' . trim($fieldlabel, ','), 'ntype' => $typeInfo, 'hide' => false]);
     } else {
         return array('save_record' => true);
     }
 }
示例#27
0
 function replaceRelatedModuleFields($content, $module, $recordid, $fields, &$site_URL)
 {
     $db = PearDatabase::getInstance();
     require_once 'include/utils/utils.php';
     $userLang = Users_Record_Model::getCurrentUserModel()->get('language');
     include "languages/" . $userLang . "/OSSPdf.php";
     require_once 'include/utils/CommonUtils.php';
     require_once 'include/fields/CurrencyField.php';
     #################################################################################
     $uitypelist2 = array('10', '58', '51', '57', '68', '59', '75', '80', '76', '73', '81', '78');
     $uitype2module2 = array('58' => 'Campaigns', '51' => 'Accounts', '57' => 'Contacts', '68' => 'Accounts;Contacts', '59' => 'Products', '75' => 'Vendors', '80' => 'SalesOrder', '76' => 'Potentials', '73' => 'Accounts', '81' => 'Vendors', '78' => 'Quotes');
     #################################################################################
     $uitypelist = array('10', '58', '51', '57', '68', '59', '75', '80', '76', '73', '81', '52', '53', '78');
     $uitype2module = array('58' => 'Campaigns', '51' => 'Accounts', '57' => 'Contacts', '68' => 'Accounts;Contacts', '59' => 'Products', '75' => 'Vendors', '80' => 'SalesOrder', '76' => 'Potentials', '73' => 'Accounts', '81' => 'Vendors', '52' => 'Users', '53' => 'Users', '78' => 'Quotes');
     #################################################################################
     $ui_datefields = array('70', '5', '23');
     #################################################################################
     $ui_currfields = array('71', '72', '7');
     #################################################################################
     if ($module == 'Activity') {
         $wynik = $db->query("select tabid,name from vtiger_tab where name='Calendar'", true);
     } else {
         $wynik = $db->query("select tabid,name from vtiger_tab where name='{$module}'", true);
     }
     $moduleid = $db->query_result($wynik, 0, "tabid");
     $list = array();
     $pobierz = $db->query("select fieldid,uitype, fieldname from vtiger_field where tabid = '{$moduleid}'", true);
     for ($i = 0; $i < $db->num_rows($pobierz); $i++) {
         $uitype = $db->query_result($pobierz, $i, "uitype");
         $fieldid = $db->query_result($pobierz, $i, "fieldid");
         if (in_array($uitype, $uitypelist)) {
             if ($uitype == '10') {
                 $wynik = $db->query("select relmodule from vtiger_fieldmodulerel where fieldid = '{$fieldid}'", true);
                 for ($k = 0; $k < $db->num_rows($wynik); $k++) {
                     $list[$db->query_result($wynik, $k, "relmodule")] = $fields[$db->query_result($pobierz, $i, "fieldname")];
                 }
             } else {
                 $zmienna = $uitype2module[$uitype];
                 $zmienna = explode(';', $zmienna);
                 foreach ($zmienna as $value) {
                     $list[$value] = $fields[$db->query_result($pobierz, $i, "fieldname")];
                 }
             }
         }
     }
     if (count($list) > 0) {
         foreach ($list as $name => $record) {
             $modulename = $name;
             require_once "modules/{$modulename}/{$modulename}.php";
             if ($modulename == 'Users') {
                 $obiekt = new $modulename();
                 $pobierz_usera = $db->query("select * from vtiger_users where id = '{$record}'", true);
                 if ($db->num_rows($pobierz_usera) > 0) {
                     $obiekt->retrieve_entity_info($record, $modulename);
                 }
             } else {
                 $obiekt = new $modulename();
                 $assigned_module = getSalesEntityType($record);
                 if ($record != 0 && $assigned_module == $modulename) {
                     $obiekt->retrieve_entity_info($record, $modulename);
                 }
             }
             $pobierz = $db->query("select tabid from vtiger_tab where name = '{$modulename}'", true);
             $moduleid = $db->query_result($pobierz, 0, "tabid");
             $pobierz_bloki = $db->query("select blockid, blocklabel from vtiger_blocks where tabid = '{$moduleid}'", true);
             $relatedfield_list = array();
             for ($k = 0; $k < $db->num_rows($pobierz_bloki); $k++) {
                 $blockid = $db->query_result($pobierz_bloki, $k, "blockid");
                 $label = $db->query_result($pobierz_bloki, $k, "blocklabel");
                 $pobierz_pola = $db->query("select fieldname,fieldlabel,uitype from vtiger_field where block='{$blockid}' and tabid = '{$moduleid}'", true);
                 for ($i = 0; $i < $db->num_rows($pobierz_pola); $i++) {
                     $field_uitype = $db->query_result($pobierz_pola, $i, "uitype");
                     $label = $db->query_result($pobierz_pola, $i, "fieldlabel");
                     $key = $db->query_result($pobierz_pola, $i, "fieldname");
                     $value = $obiekt->column_fields[$key];
                     ################################################
                     /// Dla pól z datą
                     if (in_array($field_uitype, $ui_datefields)) {
                         $value = getValidDisplayDate($value);
                     }
                     ################################################
                     /// Dla pól z walutami
                     if (in_array($field_uitype, $ui_currfields)) {
                         $currfield = new CurrencyField($value);
                         $value = $currfield->getDisplayValue();
                     }
                     //// Dla pola z językiem użytkownika
                     if ($field_uitype == 27) {
                         if ($value == 'I') {
                             $value = getTranslatedString('Internal', $modulename);
                         } elseif ($value == 'E') {
                             $value = getTranslatedString('External', $modulename);
                         }
                     }
                     if ($field_uitype == 32) {
                         $name = '%' . $value . '%';
                         $new_value = $db->query("select name from vtiger_language where prefix like '{$name}'", true);
                         $value = getTranslatedString($db->query_result($new_value, 0, "name"));
                     }
                     /// dla pól z przypisanym użytkownikie,
                     if ($field_uitype == 53 || $field_uitype == 52) {
                         $value = getUserName($value);
                     }
                     /// dla pól z folderem
                     /*if( $field_uitype == 26 ) {
                           $new_value = $db->query( "select foldername from vtiger_attachmentsfolder where folderid = '$value'", true );
                           $value = $db->query_result( $new_value, 0, "foldername" );
                       }*/
                     /// Dla pól z roląużytkownika w organizacji
                     if ($field_uitype == 98) {
                         $new_value = $db->query("select rolename from vtiger_role where roleid = '{$value}'", true);
                         $value = $db->query_result($new_value, 0, "rolename");
                     }
                     /// Dla pól typu checkbox
                     if ($field_uitype == 56) {
                         if ($value == 1) {
                             $value = getTranslatedString('yes', "OSSPdf");
                         } elseif ($value == 0) {
                             $value = getTranslatedString('no', "OSSPdf");
                         }
                     }
                     /// Dla pola ze zdjęciem użytkownika
                     if ($field_uitype == 105) {
                         include_once "modules/OSSPdf/small_config.php";
                         if ($value != "") {
                             $sql = "SELECT CONCAT(vtiger_attachments.path,vtiger_attachments.attachmentsid,'_',vtiger_users.imagename) AS sciezka FROM vtiger_attachments\n                                INNER JOIN vtiger_salesmanattachmentsrel ON ( vtiger_salesmanattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid )\n                                INNER JOIN vtiger_users ON ( vtiger_users.id = vtiger_salesmanattachmentsrel.smid )\n                                  WHERE vtiger_salesmanattachmentsrel.smid = '{$record}'";
                             $pobierz_zdjecie = $db->query($sql, true);
                             if ($db->num_rows($pobierz_zdjecie) > 0) {
                                 $value = '<img src="' . $site_URL . '/' . $db->query_result($pobierz_zdjecie, 0, "sciezka") . '" width="' . $UserImage_width . 'px" height="' . $UserImage_height . 'px"></img>';
                             }
                         }
                     }
                     /// Dla pól typu lista wyboru
                     if ($field_uitype == 15 || $field_uitype == 16 || $field_uitype == 55 && $key == 'salutationtype') {
                         $value = getTranslatedString($value, $modulename);
                     }
                     if ($field_uitype == 83) {
                         $pobierz_tax = $db->query("select * from vtiger_producttaxrel where productid = '{$record}'", true);
                         for ($a = 0; $a < $db->num_rows($pobierz_tax); $a++) {
                             $taxid = $db->query_result($pobierz_tax, $a, "taxid");
                             $taxvalue = $db->query_result($pobierz_tax, $a, "taxpercentage");
                             if ($taxid == 1) {
                                 $value .= getTranslatedString('LBL_VAT') . getTranslatedString('COVERED_PERCENTAGE') . ': ' . $taxvalue . '%';
                             } elseif ($taxid == 2) {
                                 $value .= getTranslatedString('LBL_SALES') . getTranslatedString('COVERED_PERCENTAGE') . ': ' . $taxvalue . '%';
                             } elseif ($taxid == 3) {
                                 $value .= getTranslatedString('LBL_SERVICE') . getTranslatedString('COVERED_PERCENTAGE') . ': ' . $taxvalue . '%';
                             }
                             $value .= '<br/>';
                         }
                     }
                     ########################
                     if (in_array($field_uitype2, $uitypelist2)) {
                         if ($field_uitype == 10) {
                             $pobierz_wartosc = $db->query("select relmodule from vtiger_fieldmodulerel where fieldid = '{$fieldid}'", true);
                             for ($i = 0; $i < $db->num_rows($pobierz_wartosc); $i++) {
                                 $module .= $db->query_result($pobierz_wartosc, $i, "relmodule") . ';';
                             }
                         } else {
                             $module = $uitype2module[$field_uitype];
                         }
                         $module = trim($module, ';');
                         $ids = explode(';', $module);
                         foreach ($ids as $singleid) {
                             $newvalue = $db->query("select tablename, entityidfield,fieldname from vtiger_entityname where modulename = '{$singleid}'", true);
                             $tablename = $db->query_result($newvalue, 0, "tablename");
                             $fieldname = $db->query_result($newvalue, 0, "fieldname");
                             $tableid = $db->query_result($newvalue, 0, "entityidfield");
                             $newvalue2 = $db->query("select {$fieldname} from {$tablename} where {$tableid} = '{$value}'", true);
                             $value = $db->query_result($newvalue2, 0, $fieldname);
                         }
                     }
                     ########################
                     if ($field_uitype == 10 && is_numeric($value)) {
                         if ($value != 0) {
                             $value = Vtiger_Functions::getCRMRecordLabel($value);
                         } elseif ($value == 0) {
                             $value = '';
                         }
                     }
                     $string = "#" . $modulename . "_" . $key . "#";
                     $string2 = "#" . $modulename . "_label_" . $key . "#";
                     //."# TLUMACZENIE: ". getTranslatedString( $label, $modulename );
                     $pozycja = (int) strpos($content, $string2);
                     $content = str_replace($string2, getTranslatedString($label, $modulename), $content);
                     if ($record != 0 && ($assigned_module == $modulename || $modulename == 'Users')) {
                         $content = str_replace($string, $value, $content);
                     } else {
                         $content = str_replace($string, '', $content);
                     }
                 }
             }
         }
     }
     return $content;
 }
示例#28
0
    public function process($moduleName, $iD, $recordForm, $config)
    {
        $db = PearDatabase::getInstance();
        $params = [];
        $hierarchyAll = [];
        $save = true;
        $where = '';
        $hierarchyCheck = false;
        if ($iD != 0 && $iD != '' && !array_key_exists('vat_id', $recordForm)) {
            $recordModel = Vtiger_Record_Model::getInstanceById($iD, $moduleName);
            $vatId = $recordModel->get('vat_id');
        } else {
            if (array_key_exists('vat_id', $recordForm)) {
                $vatId = $recordForm['vat_id'];
            }
        }
        if ($iD != 0 && $iD != '' && !array_key_exists('accountname', $recordForm)) {
            $recordModel = Vtiger_Record_Model::getInstanceById($iD, $moduleName);
            $accountName = $recordModel->get('accountname');
        } else {
            if (array_key_exists('accountname', $recordForm)) {
                $accountName = $recordForm['accountname'];
            }
        }
        if ($vatId) {
            $moduleModel = Vtiger_Module_Model::getInstance($moduleName);
            $hierarchyField = Vtiger_Field_Model::getInstance('account_id', $moduleModel);
            if ($hierarchyField->isActiveField()) {
                if (array_key_exists('account_id', $recordForm)) {
                    $hierarchyValue = $recordForm['account_id'];
                } elseif ($iD != 0 && $iD != '' && !array_key_exists('account_id', $recordForm)) {
                    $recordModel = Vtiger_Record_Model::getInstanceById($iD, $moduleName);
                    $hierarchyValue = $recordModel->get('account_id');
                }
                if ($hierarchyValue) {
                    $hierarchyAll = $this->getHierarchy($hierarchyValue, $moduleName, $iD);
                } elseif ($iD) {
                    $hierarchyAll = $this->getHierarchy($iD, $moduleName, $iD);
                }
            }
            $params[] = $vatId;
            $where .= ' vat_id = ?';
        } else {
            $params[] = $accountName;
            $where .= ' accountname = ?';
        }
        if ($iD != 0 && $iD != '') {
            $params[] = $iD;
            $where .= ' AND accountid <> ?';
        }
        if ($hierarchyAll && $vatId) {
            $hierarchyParams = array_merge($params, array_keys($hierarchyAll));
            $hierarchyQuery = 'SELECT accountid,accountname FROM vtiger_account WHERE ' . $where . ' AND accountid IN (' . $db->generateQuestionMarks($hierarchyAll) . ')';
            $result = $db->pquery($hierarchyQuery, $hierarchyParams);
            if ($db->getRowCount($result)) {
                $hierarchyCheck = true;
            }
            while ($row = $db->getRow($result)) {
                if ($row['accountname'] == $accountName) {
                    $metaData = Vtiger_Functions::getCRMRecordMetadata($row['accountid']);
                    $save = false;
                    $fieldlabel .= '<a target="_blank" href="index.php?module=Accounts&view=Detail&record=' . $row['accountid'] . '">&bull; ' . Vtiger_Functions::getCRMRecordLabel($row['accountid']) . '</a> (' . Vtiger_Functions::getOwnerRecordLabel($metaData['smownerid']) . '),<br/>';
                }
            }
        }
        if (!$hierarchyCheck) {
            $sql = "SELECT accountid FROM vtiger_account WHERE {$where};";
            $result = $db->pquery($sql, $params);
            while ($id = $db->getSingleValue($result)) {
                $metaData = Vtiger_Functions::getCRMRecordMetadata($id);
                $save = false;
                $deletedLabel = $metaData['deleted'] ? ' - ' . vtranslate('LBL_RECORD_DELETED', 'DataAccess') : '';
                $fieldlabel .= '<a target="_blank" href="index.php?module=Accounts&view=Detail&record=' . $id . '">&bull; ' . Vtiger_Functions::getCRMRecordLabel($id) . '</a> (' . Vtiger_Functions::getOwnerRecordLabel($metaData['smownerid']) . ')' . $deletedLabel . ',<br/>';
            }
        }
        if (!$save) {
            $permission = Users_Privileges_Model::isPermitted($moduleName, 'DuplicateRecord');
            $text = '<div class="marginLeft10">' . vtranslate('LBL_DUPLICATED_FOUND', 'DataAccess') . ': <br/ >' . trim($fieldlabel, ',') . '</div>';
            if ($permission) {
                $title = '<strong>' . vtranslate('LBL_DUPLICTAE_CREATION_CONFIRMATION', 'DataAccess') . '</strong>';
                if (!empty($iD)) {
                    $text .= '<form class="form-horizontal"><div class="checkbox">
							<label>
								<input type="checkbox" name="cache"> ' . vtranslate('LBL_DONT_ASK_AGAIN', 'DataAccess') . '
							</label>
						</div></form>';
                }
                if ($recordForm['view'] == 'quick_edit') {
                    $text = '<div class="alert alert-warning" role="alert">' . vtranslate('LBL_DUPLICTAE_QUICK_EDIT_CONFIRMATION', 'DataAccess') . '</div>' . $text;
                }
            }
            return array('save_record' => $save, 'type' => 3, 'info' => ['text' => $text, 'title' => $title, 'type' => $permission ? 1 : 0]);
        } else {
            return array('save_record' => true);
        }
    }
示例#29
0
 static function computeCRMRecordLabels($module, $ids, $search = false)
 {
     $adb = PearDatabase::getInstance();
     if (!is_array($ids)) {
         $ids = array($ids);
     }
     if ($module == 'Events') {
         $module = 'Calendar';
     }
     if ($module) {
         $entityDisplay = array();
         if ($ids) {
             if ($module == 'Groups') {
                 $metainfo = array('tablename' => 'vtiger_groups', 'entityidfield' => 'groupid', 'fieldname' => 'groupname');
                 /* } else if ($module == 'DocumentFolders') { 
                 	  $metainfo = array('tablename' => 'vtiger_attachmentsfolder','entityidfield' => 'folderid','fieldname' => 'foldername'); */
             } else {
                 $metainfo = self::getEntityModuleInfo($module);
             }
             $table = $metainfo['tablename'];
             $idcolumn = $metainfo['entityidfield'];
             $columns_name = explode(',', $metainfo['fieldname']);
             $columns_search = explode(',', $metainfo['searchcolumn']);
             $columns = array_unique(array_merge($columns_name, $columns_search));
             $sql = sprintf('SELECT ' . implode(',', array_filter($columns)) . ', %s AS id FROM %s WHERE %s IN (%s)', $idcolumn, $table, $idcolumn, generateQuestionMarks($ids));
             $result = $adb->pquery($sql, $ids);
             $moduleInfo = self::getModuleFieldInfos($module);
             $moduleInfoExtend = [];
             if (count($moduleInfo) > 0) {
                 foreach ($moduleInfo as $field => $fieldInfo) {
                     $moduleInfoExtend[$fieldInfo['columnname']] = $fieldInfo;
                 }
             }
             for ($i = 0; $i < $adb->num_rows($result); $i++) {
                 $row = $adb->raw_query_result_rowdata($result, $i);
                 $label_name = array();
                 $label_search = array();
                 foreach ($columns_name as $columnName) {
                     if ($moduleInfoExtend && in_array($moduleInfoExtend[$columnName]['uitype'], array(10, 51, 75, 81))) {
                         $label_name[] = Vtiger_Functions::getCRMRecordLabel($row[$columnName]);
                     } else {
                         $label_name[] = $row[$columnName];
                     }
                 }
                 if ($search) {
                     foreach ($columns_search as $columnName) {
                         if ($moduleInfoExtend && in_array($moduleInfoExtend[$columnName]['uitype'], array(10, 51, 75, 81))) {
                             $label_search[] = Vtiger_Functions::getCRMRecordLabel($row[$columnName]);
                         } else {
                             $label_search[] = $row[$columnName];
                         }
                     }
                     $entityDisplay[$row['id']] = array('name' => implode(' ', $label_name), 'search' => implode(' ', $label_search));
                 } else {
                     $entityDisplay[$row['id']] = implode(' ', $label_name);
                 }
             }
         }
         return $entityDisplay;
     }
 }
示例#30
0
 public function process($feed, $request, $start, $end, &$result, $userid = false, $color = null, $textColor = 'white')
 {
     $dbStartDateOject = DateTimeField::convertToDBTimeZone($start);
     $dbStartDateTime = $dbStartDateOject->format('Y-m-d H:i:s');
     $dbStartDateTimeComponents = explode(' ', $dbStartDateTime);
     $dbStartDate = $dbStartDateTimeComponents[0];
     $dbEndDateObject = DateTimeField::convertToDBTimeZone($end);
     $dbEndDateTime = $dbEndDateObject->format('Y-m-d H:i:s');
     $currentUser = Users_Record_Model::getCurrentUserModel();
     $db = PearDatabase::getInstance();
     $moduleModel = Vtiger_Module_Model::getInstance('Events');
     if ($userid) {
         $focus = new Users();
         $focus->id = $userid;
         $focus->retrieve_entity_info($userid, 'Users');
         $user = Users_Record_Model::getInstanceFromUserObject($focus);
         $userName = $user->getName();
     }
     $params = array();
     if (empty($userid)) {
         $eventUserId = $currentUser->getId();
     } else {
         $eventUserId = $userid;
     }
     $params = array_merge(array($eventUserId), $feed->getGroupsIdsForUsers($eventUserId));
     $query = 'SELECT vtiger_activity.subject, vtiger_activity.eventstatus, vtiger_activity.visibility, vtiger_activity.date_start, vtiger_activity.time_start, vtiger_activity.due_date, vtiger_activity.time_end, vtiger_activity.activityid, vtiger_activity.activitytype, vtiger_seactivityrel.crmid as parent_id FROM vtiger_activity LEFT JOIN vtiger_seactivityrel ON vtiger_seactivityrel.activityid = vtiger_activity.activityid WHERE';
     $query .= " vtiger_activity.activitytype NOT IN ('Emails','Task') AND ";
     $hideCompleted = $currentUser->get('hidecompletedevents');
     if ($hideCompleted) {
         $query .= "vtiger_activity.eventstatus != 'HELD' AND ";
     }
     $query .= " ((concat(date_start, '', time_start)  >= '{$dbStartDateTime}' AND concat(due_date, '', time_end) < '{$dbEndDateTime}') ) AND vtiger_activity.smownerid IN (" . generateQuestionMarks($params) . ") AND vtiger_activity.deleted=0";
     $queryResult = $db->pquery($query, $params);
     while ($record = $db->fetchByAssoc($queryResult)) {
         $item = array();
         $crmid = $record['activityid'];
         $visibility = $record['visibility'];
         $activitytype = $record['activitytype'];
         $status = $record['eventstatus'];
         $item['id'] = $crmid;
         $item['visibility'] = $visibility;
         $item['activitytype'] = $activitytype;
         $item['status'] = $status;
         //dodanie powiazan albo z kontaktow albo z powiazanych
         $title_add = $record['parent_id'] ? Vtiger_Functions::getCRMRecordLabel($record['parent_id']) : implode(', ', getActivityRelatedContacts($crmid));
         if (!$currentUser->isAdminUser() && $visibility == 'Private' && $userid && $userid != $currentUser->getId()) {
             $item['title'] = decode_html($userName);
             $item['url'] = '';
         } else {
             $item['title'] = decode_html($record['subject']);
             $item['url'] = sprintf('index.php?module=Calendar&view=Detail&record=%s', $crmid);
         }
         if ($title_add != '') {
             $item['title'] .= ' [' . decode_html($title_add) . ']';
         }
         $dateTimeFieldInstance = new DateTimeField($record['date_start'] . ' ' . $record['time_start']);
         $userDateTimeString = $dateTimeFieldInstance->getDisplayDateTimeValue($currentUser);
         $dateTimeComponents = explode(' ', $userDateTimeString);
         $dateComponent = $dateTimeComponents[0];
         //Conveting the date format in to Y-m-d . since full calendar expects in the same format
         $dataBaseDateFormatedString = DateTimeField::__convertToDBFormat($dateComponent, $currentUser->get('date_format'));
         $item['start'] = $dataBaseDateFormatedString . ' ' . $dateTimeComponents[1];
         $dateTimeFieldInstance = new DateTimeField($record['due_date'] . ' ' . $record['time_end']);
         $userDateTimeString = $dateTimeFieldInstance->getDisplayDateTimeValue($currentUser);
         $dateTimeComponents = explode(' ', $userDateTimeString);
         $dateComponent = $dateTimeComponents[0];
         //Conveting the date format in to Y-m-d . since full calendar expects in the same format
         $dataBaseDateFormatedString = DateTimeField::__convertToDBFormat($dateComponent, $currentUser->get('date_format'));
         $item['end'] = $dataBaseDateFormatedString . ' ' . $dateTimeComponents[1];
         $item['className'] = $cssClass;
         $item['allDay'] = false;
         $item['color'] = $color;
         $item['textColor'] = $textColor;
         $item['module'] = $moduleModel->getName();
         $result[] = $item;
     }
     return $widget;
 }