Example #1
0
 function fetchCurrencyRates($dateCur, $cron = false)
 {
     $db = PearDatabase::getInstance();
     $notifyNewRates = false;
     $vtigerCurrencySql = 'SELECT `id`, `currency_code` FROM `vtiger_currency_info` WHERE `currency_status` = ? AND `deleted` = 0 AND `defaultid` != ?;';
     $vtigerCurrencyResult = $db->pquery($vtigerCurrencySql, ['Active', '-11']);
     $numToConvert = $db->num_rows($vtigerCurrencyResult);
     if ($numToConvert >= 1) {
         $selectBankId = $this->getActiveBankId();
         $activeBankName = 'Settings_CurrencyUpdate_models_' . $this->getActiveBankName() . '_BankModel';
         $currIds = [];
         $otherCurrencyCode = [];
         while ($row = $db->fetchByAssoc($vtigerCurrencyResult)) {
             $id = $row['id'];
             $code = $row['currency_code'];
             $currIds[] = $id;
             $otherCurrencyCode[$code] = $id;
         }
         $existSql = 'SELECT COUNT(*) as num FROM `yetiforce_currencyupdate` WHERE `exchange_date` = ? AND `currency_id` IN (' . generateQuestionMarks($currIds) . ') AND `bank_id` = ? LIMIT 1;';
         $params = [$dateCur];
         $params = array_merge($params, $currIds);
         $params[] = $selectBankId;
         $existResult = $db->pquery($existSql, $params);
         $currNum = $db->getSingleValue($existResult);
         // download only if its not in archives
         if ($currNum != $numToConvert && class_exists($activeBankName)) {
             $bank = new $activeBankName();
             $bank->getRates($otherCurrencyCode, $dateCur, false);
             $notifyNewRates = true;
         }
     }
     return $notifyNewRates;
 }
 public function save()
 {
     $db = PearDatabase::getInstance();
     $id = $this->getId();
     $params = array();
     // SalesPlatform.ru begin
     array_push($params, $this->get('server'), $this->get('server_port'), $this->get('server_username'), $this->get('server_password'), $this->get('server_type'), $this->isSmtpAuthEnabled(), $this->get('server_path'), $this->get('from_email_field'), $this->get('server_tls'), $this->get('from_name'), $this->get('use_sendmail'), $this->get('use_mail_account'));
     //array_push($params, $this->get('server'),$this->get('server_port'),$this->get('server_username'),$this->get('server_password'),$this->get('server_type'),
     //$this->isSmtpAuthEnabled(),$this->get('server_path'),$this->get('from_email_field'));
     // SalesPlatform.ru end
     if (empty($id)) {
         $id = $db->getUniqueID(self::tableName);
         //To keep id in the beginning
         array_unshift($params, $id);
         // SalesPlatform.ru begin
         $query = 'INSERT INTO ' . self::tableName . ' VALUES(' . generateQuestionMarks($params) . ')';
         //$query = 'INSERT INTO '.self::tableName.' VALUES(?,?,?,?,?,?,?,?,?)';
         // SalesPlatform.ru end
     } else {
         // SalesPlatform.ru begin
         $query = 'UPDATE ' . self::tableName . ' SET server = ?, server_port= ?, server_username = ?, server_password = ?,
             server_type = ?,  smtp_auth= ?, server_path = ?, from_email_field=?, server_tls=?, from_name=?, use_sendmail=?, use_mail_account=? WHERE id = ?';
         //$query = 'UPDATE '.self::tableName.' SET server = ?, server_port= ?, server_username = ?, server_password = ?,
         //    server_type = ?,  smtp_auth= ?, server_path = ?, from_email_field=? WHERE id = ?';
         // SalesPlatform.ru end
         $params[] = $id;
     }
     $db->pquery($query, $params);
     return $id;
 }
Example #3
0
/** Function to  returns the combo field values in array format
 * @param $combofieldNames -- combofieldNames:: Type string array
 * @returns $comboFieldArray -- comboFieldArray:: Type string array
 */
function getComboArray($combofieldNames)
{
    global $log, $mod_strings;
    $log->debug("Entering getComboArray(" . $combofieldNames . ") method ...");
    global $adb, $current_user;
    $roleid = $current_user->roleid;
    $comboFieldArray = array();
    foreach ($combofieldNames as $tableName => $arrayName) {
        $fldArrName = $arrayName;
        $arrayName = array();
        $sql = "select {$tableName} from vtiger_{$tableName}";
        $params = array();
        if (!is_admin($current_user)) {
            $subrole = getRoleSubordinates($roleid);
            if (count($subrole) > 0) {
                $roleids = $subrole;
                array_push($roleids, $roleid);
            } else {
                $roleids = $roleid;
            }
            $sql = "select distinct {$tableName} from vtiger_{$tableName}  inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_{$tableName}.picklist_valueid where roleid in(" . generateQuestionMarks($roleids) . ") order by sortid";
            $params = array($roleids);
        }
        $result = $adb->pquery($sql, $params);
        while ($row = $adb->fetch_array($result)) {
            $val = $row[$tableName];
            $arrayName[$val] = getTranslatedString($val);
        }
        $comboFieldArray[$fldArrName] = $arrayName;
    }
    $log->debug("Exiting getComboArray method ...");
    return $comboFieldArray;
}
Example #4
0
 public static function getEntityModulesList()
 {
     $db = PearDatabase::getInstance();
     self::preModuleInitialize2();
     $presence = array(0, 2);
     $restrictedModules = array('Emails', 'Integration', 'Dashboard', 'ModComments', 'PBXManager', 'vtmessages', 'vttwitter');
     $module = array('Potentials', 'Project', 'HelpDesk');
     $query = 'SELECT name FROM vtiger_tab WHERE
                 presence IN (' . generateQuestionMarks($presence) . ')
                 AND isentitytype = ?
                 AND name NOT IN (' . generateQuestionMarks($restrictedModules) . ') AND name IN (' . generateQuestionMarks($module) . ')';
     $result = $db->pquery($query, array($presence, 1, $restrictedModules, $module));
     $numOfRows = $db->num_rows($result);
     $modulesList = array();
     for ($i = 0; $i < $numOfRows; $i++) {
         $moduleName = $db->query_result($result, $i, 'name');
         $modulesList[$moduleName] = $moduleName;
     }
     // If calendar is disabled we should not show events module too
     // in layout editor
     if (!array_key_exists('Calendar', $modulesList)) {
         unset($modulesList['Events']);
     }
     return $modulesList;
 }
 /**
  * Function to get list of record models in this relation
  * @param <Vtiger_Paging_Model> $pagingModel
  * @return <array> List of record models <Vtiger_Record_Model>
  */
 public function getEntries($pagingModel)
 {
     $relationModel = $this->getRelationModel();
     $parentRecordModel = $this->getParentRecordModel();
     $relatedModuleName = $relationModel->getRelationModuleModel()->getName();
     $relatedRecordModelsList = parent::getEntries($pagingModel);
     $emailEnabledModulesInfo = $relationModel->getEmailEnabledModulesInfoForDetailView();
     if (array_key_exists($relatedModuleName, $emailEnabledModulesInfo) && $relatedRecordModelsList) {
         $fieldName = $emailEnabledModulesInfo[$relatedModuleName]['fieldName'];
         $tableName = $emailEnabledModulesInfo[$relatedModuleName]['tableName'];
         $db = PearDatabase::getInstance();
         $relatedRecordIdsList = array_keys($relatedRecordModelsList);
         $query = "SELECT campaignrelstatus, {$fieldName} FROM {$tableName}\n\t\t\t\t\t\tINNER JOIN vtiger_campaignrelstatus ON vtiger_campaignrelstatus.campaignrelstatusid = {$tableName}.campaignrelstatusid\n\t\t\t\t\t\tWHERE {$fieldName} IN (" . generateQuestionMarks($relatedRecordIdsList) . ") AND campaignid = ?";
         array_push($relatedRecordIdsList, $parentRecordModel->getId());
         $result = $db->pquery($query, $relatedRecordIdsList);
         $numOfrows = $db->num_rows($result);
         for ($i = 0; $i < $numOfrows; $i++) {
             $recordId = $db->query_result($result, $i, $fieldName);
             $relatedRecordModel = $relatedRecordModelsList[$recordId];
             $relatedRecordModel->set('status', $db->query_result($result, $i, 'campaignrelstatus'));
             $relatedRecordModelsList[$recordId] = $relatedRecordModel;
         }
     }
     return $relatedRecordModelsList;
 }
Example #6
0
 public function deleteRecords(Vtiger_Request $request)
 {
     $searchValue = $request->get('search_value');
     $selectedIds = $request->get('selected_ids');
     $excludedIds = $request->get('excluded_ids');
     $db = PearDatabase::getInstance();
     $query = 'DELETE FROM vtiger_portal';
     $params = array();
     if (!empty($selectedIds) && $selectedIds != 'all' && count($selectedIds) > 0) {
         $query .= " WHERE portalid IN (" . generateQuestionMarks($selectedIds) . ")";
         $params = $selectedIds;
     } else {
         if ($selectedIds == 'all') {
             if (empty($searchValue) && count($excludedIds) > 0) {
                 $query .= " WHERE portalid NOT IN (" . generateQuestionMarks($excludedIds) . ")";
                 $params = $excludedIds;
             } else {
                 if (!empty($searchValue) && count($excludedIds) < 1) {
                     $query .= " WHERE portalname LIKE '%" . $searchValue . "%'";
                 } else {
                     if (!empty($searchValue) && count($excludedIds) > 0) {
                         $query .= " WHERE portalname LIKE '%" . $searchValue . "%' AND portalid NOT IN (" . generateQuestionMarks($excludedIds) . ")";
                         $params = $excludedIds;
                     }
                 }
             }
         }
     }
     $db->pquery($query, $params);
 }
Example #7
0
	public static function getSupportedModulesList() {
		$db = PearDatabase::getInstance();

		$presence = array(0, 2);
		$restrictedModules = array('SPSocialConnector', 'SMSNotifier', 'Emails', 'Integration', 'Dashboard', 'ModComments', 'vtmessages', 'vttwitter');

		$query = 'SELECT name FROM vtiger_tab WHERE
						presence IN ('. generateQuestionMarks($presence) .')
						AND isentitytype = ?
						AND name NOT IN ('. generateQuestionMarks($restrictedModules) .')';
		$result = $db->pquery($query, array($presence, 1, $restrictedModules));
		$numOfRows = $db->num_rows($result);

		$modulesList = array();
		for($i=0; $i<$numOfRows; $i++) {
			$moduleName = $db->query_result($result, $i, 'name');
			$modulesList[$moduleName] = vtranslate($moduleName, $moduleName);
		}
		// If calendar is disabled we should not show events module too
		// in layout editor
        if(!array_key_exists('Calendar', $modulesList)) {
            unset($modulesList['Events']);
        }
		return $modulesList;
	}
Example #8
0
 function Reports($reportId = "")
 {
     $db = PearDatabase::getInstance();
     $currentUser = Users_Record_Model::getCurrentUserModel();
     $userId = $currentUser->getId();
     $this->initListOfModules();
     if ($reportId != "") {
         // Lookup information in cache first
         $cachedInfo = VTCacheUtils::lookupReport_Info($userId, $reportId);
         $subOrdinateUsers = VTCacheUtils::lookupReport_SubordinateUsers($reportId);
         if ($cachedInfo === false) {
             $ssql = "SELECT vtiger_reportmodules.*, vtiger_report.* FROM vtiger_report\n\t\t\t\t\t\t\tINNER JOIN vtiger_reportmodules ON vtiger_report.reportid = vtiger_reportmodules.reportmodulesid\n\t\t\t\t\t\t\tWHERE vtiger_report.reportid = ?";
             $params = array($reportId);
             require_once 'include/utils/GetUserGroups.php';
             require 'user_privileges/user_privileges_' . $userId . '.php';
             $userGroups = new GetUserGroups();
             $userGroups->getAllUserGroups($userId);
             $userGroupsList = $userGroups->user_groups;
             if (!empty($userGroupsList) && $currentUser->isAdminUser() == false) {
                 $userGroupsQuery = " (shareid IN (" . generateQuestionMarks($userGroupsList) . ") AND setype='groups') OR";
                 array_push($params, $userGroupsList);
             }
             $nonAdminQuery = " vtiger_report.reportid IN (SELECT reportid from vtiger_reportsharing\n\t\t\t\t\t\t\t\t\tWHERE {$userGroupsQuery} (shareid=? AND setype='users'))";
             if ($currentUser->isAdminUser() == false) {
                 $ssql .= " AND (({$nonAdminQuery})\n\t\t\t\t\t\t\t\tOR vtiger_report.sharingtype = 'Public'\n\t\t\t\t\t\t\t\tOR vtiger_report.owner = ? OR vtiger_report.owner IN\n\t\t\t\t\t\t\t\t\t(SELECT vtiger_user2role.userid FROM vtiger_user2role\n\t\t\t\t\t\t\t\t\tINNER JOIN vtiger_users ON vtiger_users.id = vtiger_user2role.userid\n\t\t\t\t\t\t\t\t\tINNER JOIN vtiger_role ON vtiger_role.roleid = vtiger_user2role.roleid\n\t\t\t\t\t\t\t\t\tWHERE vtiger_role.parentrole LIKE '{$current_user_parent_role_seq}::%')\n\t\t\t\t\t\t\t\t)";
                 array_push($params, $userId, $userId);
             }
             $result = $db->pquery($ssql, $params);
             if ($result && $db->num_rows($result)) {
                 $reportModulesRow = $db->fetch_array($result);
                 // Update information in cache now
                 VTCacheUtils::updateReport_Info($userId, $reportId, $reportModulesRow["primarymodule"], $reportModulesRow["secondarymodules"], $reportModulesRow["reporttype"], $reportModulesRow["reportname"], $reportModulesRow["description"], $reportModulesRow["folderid"], $reportModulesRow["owner"]);
             }
             $subOrdinateUsers = array();
             $subResult = $db->pquery("SELECT userid FROM vtiger_user2role\n\t\t\t\t\t\t\t\t\tINNER JOIN vtiger_users ON vtiger_users.id = vtiger_user2role.userid\n\t\t\t\t\t\t\t\t\tINNER JOIN vtiger_role ON vtiger_role.roleid = vtiger_user2role.roleid\n\t\t\t\t\t\t\t\t\tWHERE vtiger_role.parentrole LIKE '{$current_user_parent_role_seq}::%'", array());
             $numOfSubRows = $db->num_rows($subResult);
             for ($i = 0; $i < $numOfSubRows; $i++) {
                 $subOrdinateUsers[] = $db->query_result($subResult, $i, 'userid');
             }
             // Update subordinate user information for re-use
             VTCacheUtils::updateReport_SubordinateUsers($reportId, $subOrdinateUsers);
             // Re-look at cache to maintain code-consistency below
             $cachedInfo = VTCacheUtils::lookupReport_Info($userId, $reportId);
         }
         if ($cachedInfo) {
             $this->primodule = $cachedInfo["primarymodule"];
             $this->secmodule = $cachedInfo["secondarymodules"];
             $this->reporttype = $cachedInfo["reporttype"];
             $this->reportname = decode_html($cachedInfo["reportname"]);
             $this->reportdescription = decode_html($cachedInfo["description"]);
             $this->folderid = $cachedInfo["folderid"];
             if ($currentUser->isAdminUser() == true || in_array($cachedInfo["owner"], $subOrdinateUsers) || $cachedInfo["owner"] == $userId) {
                 $this->is_editable = true;
             } else {
                 $this->is_editable = false;
             }
         }
     }
     return $this;
 }
Example #9
0
 /**
  * To update call status from 'ringing' to 'no-response', if status not updated 
  * for more than 5 minutes
  * @param type $recordIds
  */
 public function updateCallStatus($recordIds) {
     $db = PearDatabase::getInstance();
     $query = "UPDATE ".self::moduletableName." SET callstatus='no-response' 
               WHERE pbxmanagerid IN (".generateQuestionMarks($recordIds).") 
               AND callstatus='ringing'";
     $db->pquery($query, $recordIds);
 }
Example #10
0
    /**
     * Function to get mapping supported field ids list
     * @return <Array> list of field ids
     */
    public function getMappingSupportedFieldIdsList()
    {
        if (!$this->supportedFieldIdsList) {
            $selectedTabidsList[] = getTabid($this->getName());
            $presense = array(0, 2);
            $restrictedFieldNames = array('campaignrelstatus');
            $restrictedUitypes = array(4, 10, 51, 52, 53, 57, 58, 69, 70);
            $selectedGeneratedTypes = array(1, 2);
            $db = PearDatabase::getInstance();
            $query = 'SELECT fieldid FROM vtiger_field
						WHERE presence IN (' . generateQuestionMarks($presense) . ')
						AND tabid IN (' . generateQuestionMarks($selectedTabidsList) . ')
						AND uitype NOT IN (' . generateQuestionMarks($restrictedUitypes) . ')
						AND fieldname NOT IN (' . generateQuestionMarks($restrictedFieldNames) . ')
						AND generatedtype IN (' . generateQuestionMarks($selectedGeneratedTypes) . ')';
            $params = array_merge($presense, $selectedTabidsList, $restrictedUitypes, $restrictedFieldNames, $selectedGeneratedTypes);
            $result = $db->pquery($query, $params);
            $numOfRows = $db->num_rows($result);
            $fieldIdsList = array();
            for ($i = 0; $i < $numOfRows; $i++) {
                $fieldIdsList[] = $db->query_result($result, $i, 'fieldid');
            }
            $this->supportedFieldIdsList = $fieldIdsList;
        }
        return $this->supportedFieldIdsList;
    }
Example #11
0
 public function showEmailsList($srecord, $smodule, $config, $type, $filter = 'All')
 {
     $return = [];
     $adb = PearDatabase::getInstance();
     $widgets = $this->modules_email_actions_widgets;
     $queryParams = [];
     if ($widgets[$smodule]) {
         $ids = [];
         $relatedID = [];
         if ($filter == 'All' || $filter == 'Contacts') {
             $result = $adb->pquery('SELECT vtiger_contactdetails.contactid FROM vtiger_contactdetails ' . 'INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid ' . 'WHERE vtiger_contactdetails.parentid = ? AND vtiger_crmentity.deleted = ?', [$srecord, 0]);
             while ($row = $adb->fetch_array($result)) {
                 $relatedID[] = $row['contactid'];
             }
         }
         if ($filter != 'Contacts') {
             $relatedID[] = $srecord;
         }
         $query = 'SELECT ossmailviewid FROM vtiger_ossmailview_relation WHERE crmid IN(' . implode(',', $relatedID) . ') AND `deleted` = ? ORDER BY `date` DESC';
         if ($config['widget_limit'] != '') {
             $query .= ' LIMIT ' . $config['widget_limit'];
         }
         $result = $adb->pquery($query, [0]);
         while ($row = $adb->fetch_array($result)) {
             $ids[] = $row['ossmailviewid'];
         }
         if (count($ids) == 0) {
             return [];
         }
         $queryParams[] = $ids;
         if ($type != 'All') {
             $ifwhere = ' AND type = ?';
             $queryParams[] = $type;
         }
         $query = 'SELECT vtiger_ossmailview.* FROM vtiger_ossmailview INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ossmailview.ossmailviewid';
         $query .= ' WHERE ossmailviewid IN (' . generateQuestionMarks($ids) . ')' . $ifwhere;
         $currentUser = Users_Record_Model::getCurrentUserModel();
         $moduleName = 'OSSMailView';
         $instance = CRMEntity::getInstance($moduleName);
         $securityParameter = $instance->getUserAccessConditionsQuerySR($moduleName, $currentUser);
         if ($securityParameter != '') {
             $query .= $securityParameter;
         }
         $query .= ' ORDER BY ossmailviewid DESC';
         if ($config['widget_limit'] != '') {
             $query .= ' LIMIT ' . $config['widget_limit'];
         }
         $result = $adb->pquery($query, $queryParams, true);
         while ($row = $adb->fetch_array($result)) {
             $from = $this->findRecordsById($row['from_id']);
             $from = $from && $from != '' ? $from : $row['from_email'];
             $to = $this->findRecordsById($row['to_id']);
             $to = $to && $to != '' ? $to : $row['to_email'];
             $content = Vtiger_Functions::removeHtmlTags(['link', 'style', 'a', 'img', 'script', 'base'], decode_html($row['content']));
             $return[] = ['id' => $row['ossmailviewid'], 'date' => $row['date'], 'firstLetter' => strtoupper(Vtiger_Functions::textLength(trim(strip_tags($from)), 1, false)), 'subject' => '<a href="index.php?module=OSSMailView&view=preview&record=' . $row['ossmailviewid'] . '" target="' . $config['target'] . '"> ' . $row['subject'] . '</a>', 'attachments' => $row['attachments_exist'], 'from' => $from, 'to' => $to, 'url' => 'index.php?module=OSSMailView&view=preview&record=' . $row['ossmailviewid'], 'type' => $row['type'], 'teaser' => Vtiger_Functions::textLength(trim(preg_replace('/[ \\t]+/', ' ', strip_tags($content))), 100), 'body' => $content];
         }
     }
     return $return;
 }
Example #12
0
	/**
	 * Function to delete records
	 * @param <Array> $recordIdsList
	 * @return <Boolean> true/false
	 */
	public static function deleteRecords($recordIdsList = array()) {
		if ($recordIdsList) {
			$db = PearDatabase::getInstance();
			$query = 'DELETE FROM vtiger_sysvars WHERE id IN (' . generateQuestionMarks($recordIdsList). ')';
			$db->pquery($query, $recordIdsList);
			return true;
		}
		return false;
	}
Example #13
0
 public function process(Vtiger_Request $request)
 {
     PDFMaker_Debugger_Model::GetInstance()->Init();
     $PDFMaker = new PDFMaker_PDFMaker_Model();
     if ($PDFMaker->CheckPermissions("DELETE") == false) {
         $PDFMaker->DieDuePermission();
     }
     $adb = PearDatabase::getInstance();
     $id_array = array();
     if ($request->has('templateid') && !$request->isEmpty('templateid')) {
         $templateid = $request->get('templateid');
         $checkSql = "select module from vtiger_pdfmaker where templateid=?";
         $checkRes = $adb->pquery($checkSql, array($templateid));
         $checkRow = $adb->fetchByAssoc($checkRes);
         //if we are trying to delete template that is not allowed for current user then die because user should not be able to see the template
         //$PDFMaker->CheckTemplatePermissions($checkRow["module"], $templateid);
         $Template_Permissions_Data = $PDFMaker->returnTemplatePermissionsData($checkRow["module"], $templateid);
         if ($Template_Permissions_Data["delete"] === false) {
             $this->DieDuePermission();
         }
         $sql = "delete from vtiger_pdfmaker where templateid=?";
         $adb->pquery($sql, array($templateid));
         $sql = "delete from vtiger_pdfmaker_settings where templateid=?";
         $adb->pquery($sql, array($templateid));
     } else {
         $idlist = $request->get('idlist');
         $id_array = explode(';', $idlist);
         $checkSql = "select templateid, module from vtiger_pdfmaker where templateid IN (" . generateQuestionMarks($id_array) . ")";
         $checkRes = $adb->pquery($checkSql, $id_array);
         $checkArr = array();
         while ($checkRow = $adb->fetchByAssoc($checkRes)) {
             $checkArr[$checkRow["templateid"]] = $checkRow["module"];
         }
         for ($i = 0; $i < count($id_array) - 1; $i++) {
             //if we are trying to delete template that is not allowed for current user then die because user should not be able to see the template
             //$PDFMaker->CheckTemplatePermissions($checkArr[$id_array[$i]], $id_array[$i]);
             $Template_Permissions_Data = $PDFMaker->returnTemplatePermissionsData($checkArr[$id_array[$i]], $id_array[$i]);
             if ($Template_Permissions_Data["delete"] === false) {
                 $this->DieDuePermission();
             }
             $sql = "delete from vtiger_pdfmaker where templateid=?";
             $adb->pquery($sql, array($id_array[$i]));
             $sql = "delete from vtiger_pdfmaker_settings where templateid=?";
             $adb->pquery($sql, array($id_array[$i]));
         }
     }
     $ajaxDelete = $request->get('ajaxDelete');
     $listViewUrl = "index.php?module=PDFMaker&view=List";
     if ($ajaxDelete) {
         $response = new Vtiger_Response();
         $response->setResult($listViewUrl);
         return $response;
     } else {
         header("Location: {$listViewUrl}");
     }
 }
Example #14
0
function vtGetModules($adb)
{
    $modules_not_supported = array('Documents', 'Calendar', 'Emails', 'Faq', 'Events', 'PBXManager', 'Users');
    $sql = "select distinct vtiger_field.tabid, name\n\t\t\tfrom vtiger_field \n\t\t\tinner join vtiger_tab \n\t\t\t\ton vtiger_field.tabid=vtiger_tab.tabid \n\t\t\twhere vtiger_tab.name not in(" . generateQuestionMarks($modules_not_supported) . ") and vtiger_tab.isentitytype=1 and vtiger_tab.presence = 0 ";
    $it = new SqlResultIterator($adb, $adb->pquery($sql, array($modules_not_supported)));
    $modules = array();
    foreach ($it as $row) {
        $modules[] = $row->name;
    }
    return $modules;
}
Example #15
0
 /** to get all the parent vtiger_groups of the specified group
  * @params $groupId --> Group Id :: Type Integer
  * @returns updates the parent group in the varibale $parent_groups of the class
  */
 function getAllUserGroups($userid)
 {
     $adb = PearDatabase::getInstance();
     $log = vglobal('log');
     $log->debug("Entering getAllUserGroups(" . $userid . ") method...");
     //Retreiving from the user2grouptable
     $query = "select * from vtiger_users2group where userid=?";
     $result = $adb->pquery($query, array($userid));
     $num_rows = $adb->num_rows($result);
     for ($i = 0; $i < $num_rows; $i++) {
         $now_group_id = $adb->query_result($result, $i, 'groupid');
         if (!in_array($now_group_id, $this->user_groups)) {
             $this->user_groups[] = $now_group_id;
         }
     }
     //Setting the User Role
     $userRole = fetchUserRole($userid);
     //Retreiving from the vtiger_user2role
     $query = "select * from vtiger_group2role where roleid=?";
     $result = $adb->pquery($query, array($userRole));
     $num_rows = $adb->num_rows($result);
     for ($i = 0; $i < $num_rows; $i++) {
         $now_group_id = $adb->query_result($result, $i, 'groupid');
         if (!in_array($now_group_id, $this->user_groups)) {
             $this->user_groups[] = $now_group_id;
         }
     }
     //Retreiving from the user2rs
     $parentRoles = getParentRole($userRole);
     $parentRolelist = array();
     foreach ($parentRoles as $par_rol_id) {
         array_push($parentRolelist, $par_rol_id);
     }
     array_push($parentRolelist, $userRole);
     $query = "select * from vtiger_group2rs where roleandsubid in (" . generateQuestionMarks($parentRolelist) . ")";
     $result = $adb->pquery($query, array($parentRolelist));
     $num_rows = $adb->num_rows($result);
     for ($i = 0; $i < $num_rows; $i++) {
         $now_group_id = $adb->query_result($result, $i, 'groupid');
         if (!in_array($now_group_id, $this->user_groups)) {
             $this->user_groups[] = $now_group_id;
         }
     }
     foreach ($this->user_groups as $grp_id) {
         $focus = new GetParentGroups();
         $focus->getAllParentGroups($grp_id);
         foreach ($focus->parent_groups as $par_grp_id) {
             if (!in_array($par_grp_id, $this->user_groups)) {
                 $this->user_groups[] = $par_grp_id;
             }
         }
     }
     $log->debug("Exiting getAllUserGroups method...");
 }
Example #16
0
 public function save()
 {
     $db = PearDatabase::getInstance();
     $map = $this->getAllValues();
     $map['content'] = "" . $db->getEmptyBlob() . "";
     $columnNames = array_keys($map);
     $columnValues = array_values($map);
     if (count($map) > 0) {
         $db->pquery('INSERT INTO ' . self::$tableName . ' (' . implode(',', $columnNames) . ') VALUES (' . generateQuestionMarks($columnValues) . ')', array($columnValues));
         $db->updateBlob(self::$tableName, "content", "name='" . $db->sql_escape_string($this->getValue('name')) . "' AND module='" . $db->sql_escape_string($this->getValue('module')) . "'", $this->getStringifiedContent());
     }
 }
Example #17
0
 public function __create($elementType, $element)
 {
     require_once 'include/utils/utils.php';
     $db = PearDatabase::getInstance();
     $this->id = $this->getNextId($elementType, $element);
     $element[$this->meta->getObectIndexColumn()] = $this->id;
     //Insert into group vtiger_table
     $query = "insert into {$this->entityTableName}(" . implode(',', array_keys($element)) . ") values(" . generateQuestionMarks(array_keys($element)) . ")";
     $result = null;
     $transactionSuccessful = vtws_runQueryAsTransaction($query, array_values($element), $result);
     return $transactionSuccessful;
 }
Example #18
0
 function save()
 {
     $adb = PearDatabase::getInstance();
     if (count($this->fieldData) == 0) {
         return;
     }
     if (!Vtiger_Utils::CheckTable($this->tableName)) {
         Vtiger_Utils::CreateTable($this->tableName, "(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n\t\t\t\t\tuserid INT NOT NULL,\n\t\t\t\t\tentitytype VARCHAR(200) NOT NULL,\n\t\t\t\t\tcrmid INT NOT NULL)", true);
     }
     $fieldNames = array_keys($this->fieldData);
     $fieldValues = array_values($this->fieldData);
     $adb->pquery('INSERT INTO ' . $this->tableName . '(' . implode(',', $fieldNames) . ') VALUES (' . generateQuestionMarks($fieldValues) . ')', array($fieldValues));
 }
Example #19
0
	public function getModulesList()
	{
		$adb = PearDatabase::getInstance();
		$restrictedModules = array('Emails', 'Integration', 'Dashboard', 'ModComments', 'SMSNotifier');
		$sql = 'SELECT * FROM vtiger_tab WHERE isentitytype = ? AND name NOT IN (' . generateQuestionMarks($restrictedModules) . ')';
		$params = array(1, $restrictedModules);
		$result = $adb->pquery($sql, $params);
		$modules = array();
		while ($row = $adb->fetch_array($result)) {
			$modules[$row['tabid']] = $row;
		}
		return $modules;
	}
function Contacts_createPortalLoginDetails($entityData)
{
    vimport('modules.Settings.CustomerPortal.helpers.CustomerPortalPassword');
    $encodePass = vglobal('encode_customer_portal_passwords');
    $adb = PearDatabase::getInstance();
    $wsId = $entityData->getId();
    $parts = explode('x', $wsId);
    $entityId = $parts[1];
    $email = $entityData->get('email');
    if (($entityData->get('portal') == 'on' || $entityData->get('portal') == '1') && $entityData->get('contactstatus') != 'Inactive') {
        $sql = "SELECT id, user_name, user_password, isactive FROM vtiger_portalinfo WHERE id=?";
        $result = $adb->pquery($sql, array($entityId));
        $insert = false;
        if ($adb->num_rows($result) == 0) {
            $insert = true;
        } else {
            $dbusername = $adb->query_result($result, 0, 'user_name');
            $isactive = $adb->query_result($result, 0, 'isactive');
            if ($email == $dbusername && $isactive == 1 && !$entityData->isNew()) {
                $update = false;
            } else {
                if ($entityData->get('portal') == 'on' || $entityData->get('portal') == '1') {
                    $sql = "UPDATE vtiger_portalinfo SET user_name=?, isactive=1 WHERE id=?";
                    $adb->pquery($sql, array($email, $entityId));
                    $password = $adb->query_result($result, 0, 'user_password');
                    $update = true;
                } else {
                    $sql = "UPDATE vtiger_portalinfo SET user_name=?, isactive=? WHERE id=?";
                    $adb->pquery($sql, array($email, 0, $entityId));
                    $update = false;
                }
            }
        }
        if ($insert == true) {
            $password = makeRandomPassword();
            $truePassword = $password;
            if ($encodePass) {
                $password = CustomerPortalPassword::encryptPassword($password, $email);
                $params = array($entityId, $email, $password, 'C', 1, CustomerPortalPassword::getCryptType(), $truePassword);
                $sql = "INSERT INTO vtiger_portalinfo(`id`, `user_name`, `user_password`, `type`, `isactive`, `crypt_type`, `password_sent`) VALUES(" . generateQuestionMarks($params) . ")";
            } else {
                $params = array($entityId, $email, $password, 'C', 1, $truePassword);
                $sql = "INSERT INTO vtiger_portalinfo(`id`, `user_name`, `user_password`, `type`, `isactive`, `password_sent`) VALUES(" . generateQuestionMarks($params) . ")";
            }
            $adb->pquery($sql, $params);
        }
    } else {
        $sql = "UPDATE vtiger_portalinfo SET user_name=?,isactive=0 WHERE id=?";
        $adb->pquery($sql, array($email, $entityId));
    }
}
Example #21
0
 /**
  * Function which will get count of modules
  * @param <Boolean> $onlyActive - if true get count of only active modules else all the modules
  * @return <integer> number of modules
  */
 public static function getModulesCount($onlyActive = false)
 {
     $db = PearDatabase::getInstance();
     $query = 'SELECT * FROM vtiger_tab';
     $params = array();
     if ($onlyActive) {
         $presence = array(0);
         $nonVisibleModules = self::getNonVisibleModulesList();
         $query .= ' WHERE presence IN (' . generateQuestionMarks($presence) . ')';
         $query .= ' AND name NOT IN (' . generateQuestionMarks($nonVisibleModules) . ')';
         array_push($params, $presence, $nonVisibleModules);
     }
     $result = $db->pquery($query, $params);
     return $db->num_rows($result);
 }
Example #22
0
 public static function getAll($configurable = true)
 {
     $db = PearDatabase::getInstance();
     $sql = 'SELECT * FROM vtiger_org_share_action_mapping';
     $params = array();
     if ($configurable) {
         $sql .= ' WHERE share_action_name NOT IN (' . generateQuestionMarks(self::$nonConfigurableActions) . ')';
         array_push($params, self::$nonConfigurableActions);
     }
     $result = $db->pquery($sql, $params);
     $noOfRows = $db->num_rows($result);
     $actionModels = array();
     for ($i = 0; $i < $noOfRows; ++$i) {
         $actionModels[] = self::getInstanceFromQResult($result, $i);
     }
     return $actionModels;
 }
Example #23
0
 public function showEmailsList($srecord, $smodule, $Config, $type)
 {
     $return = [];
     $adb = PearDatabase::getInstance();
     $widgets = $this->modules_email_actions_widgets;
     $queryParams = [];
     if ($widgets[$smodule]) {
         $ids = [];
         $result = $adb->pquery('SELECT ossmailviewid FROM vtiger_ossmailview_relation WHERE crmid = ? AND `deleted` = ? ORDER BY `date` DESC LIMIT ' . $Config['widget_limit'], [$srecord, 0]);
         while ($row = $adb->fetch_array($result)) {
             $ids[] = $row['ossmailviewid'];
         }
         if (count($ids) == 0) {
             return [];
         }
         $queryParams[] = $ids;
         if ($type != 'all') {
             $ifwhere = ' AND type = ?';
             $queryParams[] = $type;
         }
         $query = 'SELECT vtiger_ossmailview.* FROM vtiger_ossmailview INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ossmailview.ossmailviewid';
         $query .= ' WHERE ossmailviewid IN (' . generateQuestionMarks($ids) . ')' . $ifwhere;
         $currentUser = Users_Record_Model::getCurrentUserModel();
         $moduleName = 'OSSMailView';
         $instance = CRMEntity::getInstance($moduleName);
         $securityParameter = $instance->getUserAccessConditionsQuerySR($moduleName, $currentUser);
         if ($securityParameter != '') {
             $query .= $securityParameter;
         }
         $query .= ' ORDER BY ossmailviewid DESC LIMIT ' . $Config['widget_limit'];
         $result = $adb->pquery($query, $queryParams, true);
         while ($row = $adb->fetch_array($result)) {
             $from = $this->findRecordsById($row['from_id']);
             $to = $this->findRecordsById($row['to_id']);
             $return[$row['ossmailviewid']]['id'] = $row['ossmailviewid'];
             $return[$row['ossmailviewid']]['date'] = $row['date'];
             $return[$row['ossmailviewid']]['subject'] = '<a href="index.php?module=OSSMailView&view=preview&record=' . $row['ossmailviewid'] . '" target="' . $Config['target'] . '"> ' . $this->limit_text($row['subject']) . '</a>';
             $return[$row['ossmailviewid']]['attachments'] = $row['attachments_exist'];
             $return[$row['ossmailviewid']]['from'] = $from == '' && $from ? $from : $this->limit_text($row['from_email']);
             $return[$row['ossmailviewid']]['to'] = $to == '' && $to ? $to : $this->limit_text($row['to_email']);
             $return[$row['ossmailviewid']]['type'] = $row['type'];
             $return[$row['ossmailviewid']]['body'] = Vtiger_Functions::removeHtmlTags(array('link', 'style', 'a', 'img', 'script', 'head', 'base'), decode_html($row['content']));
         }
     }
     return $return;
 }
Example #24
0
    /**
     * Static function to get the list of all the Settings Menus
     * @return <Array> - List of Settings_Vtiger_Menu_Model instances
     */
    public static function getAll()
    {
        $db = PearDatabase::getInstance();
        $restrictBlock = array('LBL_MODULE_MANAGER');
        $sql = 'SELECT * FROM ' . self::$menusTable . ' WHERE label NOT IN (' . generateQuestionMarks($restrictBlock) . ')
				ORDER BY sequence';
        $params = array($restrictBlock);
        $result = $db->pquery($sql, $params);
        $noOfMenus = $db->num_rows($result);
        $menuModels = array();
        for ($i = 0; $i < $noOfMenus; ++$i) {
            $blockId = $db->query_result($result, $i, self::$menuId);
            $rowData = $db->query_result_rowdata($result, $i);
            $menuModels[$blockId] = Settings_Vtiger_Menu_Model::getInstanceFromArray($rowData);
        }
        return $menuModels;
    }
Example #25
0
/**
 * Function to get customfield entries
 * @param string $module - Module name
 * return array  $cflist - customfield entries
 */
function getCFListEntries($module)
{
    global $adb, $app_strings, $theme, $smarty, $log;
    $tabid = getTabid($module);
    if ($module == 'Calendar') {
        $tabid = array(9, 16);
    }
    $theme_path = "themes/" . $theme . "/";
    $image_path = "themes/images/";
    $dbQuery = "select fieldid,columnname,fieldlabel,uitype,displaytype,block,vtiger_convertleadmapping.cfmid,tabid from vtiger_field left join vtiger_convertleadmapping on  vtiger_convertleadmapping.leadfid = vtiger_field.fieldid where tabid in (" . generateQuestionMarks($tabid) . ") and vtiger_field.presence in (0,2) and generatedtype = 2 order by sequence";
    $result = $adb->pquery($dbQuery, array($tabid));
    $row = $adb->fetch_array($result);
    $count = 1;
    $cflist = array();
    if ($row != '') {
        do {
            $cf_element = array();
            $cf_element['no'] = $count;
            $cf_element['label'] = getTranslatedString($row["fieldlabel"], $module);
            $fld_type_name = getCustomFieldTypeName($row["uitype"]);
            $cf_element['type'] = $fld_type_name;
            $cf_tab_id = $row["tabid"];
            if ($module == 'Leads') {
                $mapping_details = getListLeadMapping($row["cfmid"]);
                $cf_element[] = $mapping_details['accountlabel'];
                $cf_element[] = $mapping_details['contactlabel'];
                $cf_element[] = $mapping_details['potentiallabel'];
            }
            if ($module == 'Calendar') {
                if ($cf_tab_id == '9') {
                    $cf_element['activitytype'] = getTranslatedString('Task', $module);
                } else {
                    $cf_element['activitytype'] = getTranslatedString('Event', $module);
                }
            }
            if ($module == 'Calendar') {
                $cf_element['tool'] = '&nbsp;<img style="cursor:pointer;" onClick="deleteCustomField(' . $row["fieldid"] . ',\'' . $module . '\', \'' . $row["columnname"] . '\', \'' . $row["uitype"] . '\')" src="' . vtiger_imageurl('delete.gif', $theme) . '" border="0"  alt="' . $app_strings['LBL_DELETE_BUTTON_LABEL'] . '" title="' . $app_strings['LBL_DELETE_BUTTON_LABEL'] . '"/></a>';
            }
            $cflist[] = $cf_element;
            $count++;
        } while ($row = $adb->fetch_array($result));
    }
    return $cflist;
}
Example #26
0
 public function showEmailsList($srecord, $smodule, $Config, $type)
 {
     $return = array();
     $adb = PearDatabase::getInstance();
     $widgets = $this->modules_email_actions_widgets;
     $queryParams = array();
     if ($widgets[$smodule]) {
         $ids = array();
         $result = $adb->pquery("SELECT * FROM vtiger_crmentityrel WHERE (vtiger_crmentityrel.crmid = ?) OR ( vtiger_crmentityrel.relcrmid = ? ) ", array($srecord, $srecord), true);
         foreach ($result->GetArray() as $row) {
             if ($row['module'] == 'OSSMailView') {
                 $ids[] = $row['crmid'];
             } elseif ($row['relmodule'] == 'OSSMailView') {
                 $ids[] = $row['relcrmid'];
             }
         }
         if (count($ids) == 0) {
             return array();
         }
         $queryParams[] = $ids;
         if ($type != 'all') {
             $ifwhere = "AND type = ?";
             $queryParams[] = $type;
         }
         $query = "SELECT * FROM vtiger_ossmailview INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ossmailview.ossmailviewid";
         global $current_user;
         $query .= ' ' . getNonAdminAccessControlQuery('OSSMailView', $current_user);
         $query .= " WHERE ossmailviewid IN (" . generateQuestionMarks($ids) . ") {$ifwhere} ORDER BY ossmailviewid DESC LIMIT " . $Config['widget_limit'];
         $result = $adb->pquery($query, $queryParams, true);
         foreach ($result->GetArray() as $row) {
             $from = $this->findRecordsById($row['from_id']);
             $to = $this->findRecordsById($row['to_id']);
             $return[$row['ossmailviewid']]['date'] = $row['createdtime'];
             $return[$row['ossmailviewid']]['subject'] = '<a href="index.php?module=OSSMailView&view=preview&record=' . $row['ossmailviewid'] . '" target="' . $Config['target'] . '"> ' . $this->limit_text($row['subject']) . '</a>';
             $return[$row['ossmailviewid']]['attachments'] = $row['attachments_exist'];
             $return[$row['ossmailviewid']]['from'] = $from == '' && $from ? $from : $this->limit_text($row['from_email']);
             $return[$row['ossmailviewid']]['to'] = $to == '' && $to ? $to : $this->limit_text($row['to_email']);
             $return[$row['ossmailviewid']]['type'] = $row['type'];
             $return[$row['ossmailviewid']]['body'] = $row['content'];
         }
     }
     return $return;
 }
 public function create($elementType, $element)
 {
     $element = DataTransform::sanitizeForInsert($element, $this->meta);
     if (strcasecmp($elementType, 'Groups') === 0) {
         $id = $this->pearDB->getUniqueId("vtiger_users");
     } else {
         $id = $this->pearDB->getUniqueId($this->entityTableName);
     }
     $element = $this->restrictFields($element);
     $element[$this->meta->getObectIndexColumn()] = $id;
     //Insert into group vtiger_table
     $query = "insert into {$this->entityTableName}(" . implode(',', array_keys($element)) . ") values(" . generateQuestionMarks(array_keys($element)) . ")";
     $result = null;
     $transactionSuccessful = vtws_runQueryAsTransaction($query, array_values($element), $result);
     if (!$transactionSuccessful) {
         throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation create");
     }
     return $this->retrieve(vtws_getId($this->meta->getEntityId(), $id));
 }
Example #28
0
 public function updateFieldSequenceNumber($blockFieldSequence)
 {
     $log = vglobal('log');
     $log->debug("Entering Settings_QuickCreateEditor_Module_Model::updateFieldSequenceNumber(" . $blockFieldSequence . ") method ...");
     $fieldIdList = array();
     $db = PearDatabase::getInstance();
     $query = 'UPDATE vtiger_field SET ';
     $query .= ' quickcreatesequence= CASE ';
     foreach ($blockFieldSequence as $newFieldSequence) {
         $fieldId = $newFieldSequence['fieldid'];
         $sequence = $newFieldSequence['sequence'];
         $block = $newFieldSequence['block'];
         $fieldIdList[] = $fieldId;
         $query .= ' WHEN fieldid=' . $fieldId . ' THEN ' . $sequence;
     }
     $query .= ' END ';
     $query .= ' WHERE fieldid IN (' . generateQuestionMarks($fieldIdList) . ')';
     $db->pquery($query, array($fieldIdList));
     $log->debug("Exiting Settings_QuickCreateEditor_Module_Model::updateFieldSequenceNumber(" . $blockFieldSequence . ") method ...");
 }
Example #29
0
    public function getModTrackerModules($active = false)
    {
        $adb = PearDatabase::getInstance();
        $restrictedModules = array('Emails', 'Integration', 'Dashboard', 'ModComments', 'PBXManager', 'vtmessages', 'vttwitter');
        $params = array(0, 2, 1);
        $params = array_merge($params, $restrictedModules);
        $sql = 'SELECT vtiger_tab.name,vtiger_tab.tabid, vtiger_modtracker_tabs.visible 
				FROM vtiger_tab LEFT JOIN vtiger_modtracker_tabs ON vtiger_tab.tabid = vtiger_modtracker_tabs.tabid
				WHERE vtiger_tab.presence IN (?,?) AND vtiger_tab.isentitytype = ? AND vtiger_tab.name NOT IN (' . generateQuestionMarks($restrictedModules) . ')';
        if ($active) {
            $sql = ' AND vtiger_modtracker_tabs.visible = ?';
            $params[] = 1;
        }
        $result = $adb->pquery($sql, $params);
        $modules = array();
        for ($i = 0; $i < $adb->num_rows($result); $i++) {
            $row = $adb->query_result_rowdata($result, $i);
            $modules[] = array('id' => $row['tabid'], 'module' => $row['name'], 'active' => $row['visible'] == 1 ? true : false);
        }
        return $modules;
    }
 /**
  * Function gives all the line items related to inventory records
  * @param $parentId - record id or array of the inventory record id's
  * @return <Array> - list of line items
  * @throws WebServiceException - Database error
  */
 public function getAllLineItemForParent($parentId)
 {
     if (is_array($parentId)) {
         $result = null;
         $query = "SELECT * FROM {$this->entityTableName} WHERE id IN (" . generateQuestionMarks($parentId) . ")";
         $transactionSuccessful = vtws_runQueryAsTransaction($query, array($parentId), $result);
         if (!$transactionSuccessful) {
             throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
         }
         $lineItemList = array();
         if ($result) {
             $rowCount = $this->pearDB->num_rows($result);
             for ($i = 0; $i < $rowCount; ++$i) {
                 $element = $this->pearDB->query_result_rowdata($result, $i);
                 $element['parent_id'] = $parentId;
                 $lineItemList[$element['id']][] = DataTransform::filterAndSanitize($element, $this->meta);
             }
         }
         return $lineItemList;
     } else {
         $result = null;
         $query = "select * from {$this->entityTableName} where id=?";
         $transactionSuccessful = vtws_runQueryAsTransaction($query, array($parentId), $result);
         if (!$transactionSuccessful) {
             throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
         }
         $lineItemList = array();
         if ($result) {
             $rowCount = $this->pearDB->num_rows($result);
             for ($i = 0; $i < $rowCount; ++$i) {
                 $element = $this->pearDB->query_result_rowdata($result, $i);
                 $element['parent_id'] = $parentId;
                 $lineItemList[] = DataTransform::filterAndSanitize($element, $this->meta);
             }
         }
         return $lineItemList;
     }
 }