static function sanitizeRetrieveEntityInfo($newRow, $meta) { $newRow = DataTransform::sanitizeDateFieldsForInsert($newRow, $meta); $newRow = DataTransform::sanitizeCurrencyFieldsForInsert($newRow, $meta); $newRow = DataTransform::sanitizeTextFieldsForInsert($newRow, $meta); return $newRow; }
function handleEvent($eventName, $entityData) { global $current_user; $db = PearDatabase::getInstance(); $moduleName = $entityData->getModuleName(); //Specific to VAS if ($moduleName == 'Users') { return; } //END $recordId = $entityData->getId(); $vtEntityDelta = new VTEntityDelta(); $newEntityData = $vtEntityDelta->getNewEntity($moduleName, $recordId); $recordValues = $newEntityData->getData(); $isAssignToModified = $this->isAssignToChanged($moduleName, $recordId, $current_user); if (!$isAssignToModified) { return; } $wsModuleName = $this->getWsModuleName($moduleName); if ($wsModuleName == "Calendar") { $wsModuleName = vtws_getCalendarEntityType($recordId); } $handler = vtws_getModuleHandlerFromName($wsModuleName, $current_user); $meta = $handler->getMeta(); $recordWsValues = DataTransform::sanitizeData($recordValues, $meta); $syncServer = new SyncServer(); $syncServer->markRecordAsDeleteForAllCleints($recordWsValues); }
function sanitizeData($newRow, $meta, $t = null) { $newRow = DataTransform::sanitizeReferences($newRow, $meta); $newRow = DataTransform::sanitizeOwnerFields($newRow, $meta, $t); $newRow = DataTransform::sanitizeFields($newRow, $meta); return $newRow; }
function getRelatedRecords($id, $module, $relatedModule, $queryParameters, $user) { global $adb, $currentModule, $log, $current_user; // TODO To be integrated with PearDatabase $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; // END // pickup meta data of related module $webserviceObject = VtigerWebserviceObject::fromName($adb, $relatedModule); $handlerPath = $webserviceObject->getHandlerPath(); $handlerClass = $webserviceObject->getHandlerClass(); if ($relatedModule == 'Products' and $module != 'Products') { $srvwebserviceObject = VtigerWebserviceObject::fromName($adb, 'Services'); $srvhandlerPath = $srvwebserviceObject->getHandlerPath(); $srvhandlerClass = $srvwebserviceObject->getHandlerClass(); require_once $srvhandlerPath; $srvhandler = new $srvhandlerClass($srvwebserviceObject, $user, $adb, $log); $srvmeta = $srvhandler->getMeta(); } require_once $handlerPath; $handler = new $handlerClass($webserviceObject, $user, $adb, $log); $meta = $handler->getMeta(); $query = __getRLQuery($id, $module, $relatedModule, $queryParameters, $user); $result = $adb->pquery($query, array()); $records = array(); // Return results while ($row = $adb->fetch_array($result)) { if (($module == 'HelpDesk' or $module == 'Faq') and $relatedModule == 'ModComments') { $records[] = $row; } else { if (isset($row['id']) and getSalesEntityType($row['id']) == 'Services') { $records[] = DataTransform::sanitizeData($row, $srvmeta); } else { $records[] = DataTransform::sanitizeData($row, $meta); } } } return array('records' => $records); }
function sanitizeForInsert($row, $meta) { global $adb; $associatedToUser = false; $parentTypeId = null; if (strtolower($meta->getEntityName()) == "emails") { if (isset($row['parent_id'])) { $components = vtws_getIdComponents($row['parent_id']); $userObj = VtigerWebserviceObject::fromName($adb, 'Users'); $parentTypeId = $components[0]; if ($components[0] == $userObj->getEntityId()) { $associatedToUser = true; } } } // added to handle the setting reminder time if (strtolower($meta->getEntityName()) == "events") { if (isset($row['reminder_time']) && $row['reminder_time'] != null && $row['reminder_time'] != 0) { $_REQUEST['set_reminder'] = "Yes"; $_REQUEST['mode'] = 'edit'; $reminder = $row['reminder_time']; $seconds = (int) $reminder % 60; $minutes = (int) ($reminder / 60) % 60; $hours = (int) ($reminder / (60 * 60)) % 24; $days = (int) ($reminder / (60 * 60 * 24)); //at vtiger there cant be 0 minutes reminder so we are setting to 1 if ($minutes == 0) { $minutes = 1; } $_REQUEST['remmin'] = $minutes; $_REQUEST['remhrs'] = $hours; $_REQUEST['remdays'] = $days; } else { $_REQUEST['set_reminder'] = "No"; } if (isset($row['contact_id']) and strpos($row['contact_id'], ';') !== false) { $ctowsids = array(); $listofctos = explode(';', $row['contact_id']); foreach ($listofctos as $cto) { if (strpos($cto, 'x') !== false) { $ctowsid = vtws_getIdComponents($cto); $ctowsids[] = $ctowsid[1]; } else { $ctowsids[] = $cto; } } $row['contact_id'] = implode(';', $ctowsids); } } elseif (strtolower($meta->getEntityName()) == "calendar") { if (empty($row['sendnotification']) || strtolower($row['sendnotificaiton']) == 'no' || $row['sendnotificaiton'] == '0' || $row['sendnotificaiton'] == 'false' || strtolower($row['sendnotificaiton']) == 'n') { unset($row['sendnotification']); } } $references = $meta->getReferenceFieldDetails(); foreach ($references as $field => $typeList) { if (strpos($row[$field], 'x') !== false) { $row[$field] = vtws_getIdComponents($row[$field]); $row[$field] = $row[$field][1]; } } $ownerFields = $meta->getOwnerFields(); foreach ($ownerFields as $index => $field) { if (isset($row[$field]) && $row[$field] != null) { $ownerDetails = vtws_getIdComponents($row[$field]); $row[$field] = $ownerDetails[1]; } } if (strtolower($meta->getEntityName()) == "emails") { if (isset($row['parent_id'])) { if ($associatedToUser === true) { $_REQUEST['module'] = 'Emails'; $row['parent_id'] = $row['parent_id'] . "@-1|"; $_REQUEST['parent_id'] = $row['parent_id']; } else { $referenceHandler = vtws_getModuleHandlerFromId($parentTypeId, $meta->getUser()); $referenceMeta = $referenceHandler->getMeta(); $fieldId = getEmailFieldId($referenceMeta, $row['parent_id']); $row['parent_id'] .= "@{$fieldId}|"; } } } if ($row["id"]) { unset($row["id"]); } if (isset($row[$meta->getObectIndexColumn()])) { unset($row[$meta->getObectIndexColumn()]); } $row = DataTransform::sanitizeDateFieldsForInsert($row, $meta); $row = DataTransform::sanitizeCurrencyFieldsForInsert($row, $meta); return $row; }
public function save() { if ($this->_deleted == true) { return; } if ($this->_data == false) { return; } if ($this->_isDummy) { return; } if (empty($this->_id)) { ${"GLOBALS"}["udgdmdj"] = "result"; ${"GLOBALS"}["bgfrqsi"] = "result"; ${${"GLOBALS"}["bgfrqsi"]} = $this->createRecord(); return ${${"GLOBALS"}["udgdmdj"]}; } if ($this->_changed == false) { return; } global $default_charset; $wislscn = "_cache"; $this->prepareTransfer(); try { $mnjcnqlgng = "metaHandler"; $elevuutnetl = "metaHandler"; require_once "data/CRMEntity.php"; ${$elevuutnetl} = self::getMetaHandler($this->getModuleName()); $_REQUEST = $this->_data; ${${"GLOBALS"}["bnxctgz"]} = CRMEntity::getInstance($this->getModuleName()); $vanizlvofalw = "focus"; $focus->id = $this->_id; $focus->mode = "edit"; ${"GLOBALS"}["ivcjrkopdtg"] = "moduleFields"; $focus->retrieve_entity_info($this->_id, $this->getModuleName()); $focus->clearSingletonSaveFields(); $focus->column_fields = \DataTransform::sanitizeDateFieldsForInsert($focus->column_fields, ${${"GLOBALS"}["xjcvkdbwo"]}); $nlkugopxcby = "value"; $focus->column_fields = \DataTransform::sanitizeCurrencyFieldsForInsert($focus->column_fields, ${$mnjcnqlgng}); ${${"GLOBALS"}["ivcjrkopdtg"]} = $metaHandler->getModuleFields(); foreach ($focus->column_fields as ${${"GLOBALS"}["hjgwjtwk"]} => ${$nlkugopxcby}) { if ($this->_data[${${"GLOBALS"}["hjgwjtwk"]}] != ${${"GLOBALS"}["uphxwmiizl"]} && !in_array(${${"GLOBALS"}["hjgwjtwk"]}, array("record_id", "record_module"))) { $dlmyihkhrx = "key"; ${"GLOBALS"}["qxesemuz"] = "newValue"; ${"GLOBALS"}["iaebjbr"] = "moduleFields"; $eklkegifwy = "fieldDataType"; $yuelkvntx = "fieldInstance"; ${"GLOBALS"}["qfydrxtn"] = "fieldDataType"; ${${"GLOBALS"}["qxesemuz"]} = $this->_data[${${"GLOBALS"}["hjgwjtwk"]}]; ${$yuelkvntx} = ${${"GLOBALS"}["iaebjbr"]}[${$dlmyihkhrx}]; if (empty(${${"GLOBALS"}["rrjhgcneilp"]})) { throw new \Exception("Field " . ${${"GLOBALS"}["hjgwjtwk"]} . " not found in module " . $this->getModuleName() . "."); } ${$eklkegifwy} = $fieldInstance->getFieldDataType(); if ("reference" == ${${"GLOBALS"}["xoonpevch"]} || "owner" == ${${"GLOBALS"}["qfydrxtn"]}) { ${"GLOBALS"}["smqnzlzkae"] = "key"; ${${"GLOBALS"}["rztsbw"]} = $this->getCrmId(${${"GLOBALS"}["rztsbw"]}); $lnakiyyxnloc = "newValue"; if ($focus->column_fields[${${"GLOBALS"}["smqnzlzkae"]}] == ${$lnakiyyxnloc}) { continue; } } $focus->column_fields[${${"GLOBALS"}["hjgwjtwk"]}] = ${${"GLOBALS"}["rztsbw"]}; } } foreach ($focus->column_fields as ${${"GLOBALS"}["okvmusckd"]} => ${${"GLOBALS"}["naoyqsa"]}) { ${"GLOBALS"}["xkqgctp"] = "fieldValue"; ${"GLOBALS"}["bxkclviriy"] = "default_charset"; if (is_array(${${"GLOBALS"}["naoyqsa"]})) { throw new \Exception("Wrong input VTEntity::" . __LINE__ . "=" . serialize(${${"GLOBALS"}["naoyqsa"]})); } $focus->column_fields[${${"GLOBALS"}["okvmusckd"]}] = html_entity_decode(${${"GLOBALS"}["xkqgctp"]}, ENT_QUOTES, ${${"GLOBALS"}["bxkclviriy"]}); } ${$vanizlvofalw} = $this->modifyValuesBeforeSave(${${"GLOBALS"}["bnxctgz"]}); $_REQUEST["file"] = ""; $_REQUEST["ajxaction"] = ""; ${${"GLOBALS"}["djwhrrnnsjk"]} = $_REQUEST["action"]; $_REQUEST["action"] = ""; $focus->isLineItemUpdate = false; $focus->save($this->getModuleName()); } catch (\Exception $exp) { if ($exp->getCode() == "DATABASE_QUERY_ERROR") { $nhkvwsu = "handleResult"; global $adb; ${$nhkvwsu} = $this->_handleDatabaseError($adb->database->_errorMsg); return; } if ($exp->getCode() == "MANDATORY_FIELDS_MISSING") { ${"GLOBALS"}["xkshfsxwf"] = "handleResult"; ${"GLOBALS"}["gmokooantx"] = "handleResult"; ${${"GLOBALS"}["gmokooantx"]} = $this->_handleMandatoryError(${${"GLOBALS"}["jvdhxqdu"]}); if (${${"GLOBALS"}["xkshfsxwf"]} !== false) { return; } } \Workflow2::error_handler($exp->getCode(), $exp->getMessage(), $exp->getFile(), $exp->getLine()); } $this->afterTransfer(); $this->_changed = false; $_FILES = ${${"GLOBALS"}["rednnyjghpl"]}; unset(VTEntity::${$wislscn}[VTEntity::$_user->id][$this->_id]); if (!$this instanceof VTInventoryEntity) { $this->_data = false; } }
public function query($q) { $mysql_query = $this->wsVTQL2SQL($q, $meta, $queryRelatedModules); $this->pearDB->startTransaction(); $result = $this->pearDB->pquery($mysql_query, array()); $error = $this->pearDB->hasFailedTransaction(); $this->pearDB->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $noofrows = $this->pearDB->num_rows($result); $output = array(); for ($i = 0; $i < $noofrows; $i++) { $row = $this->pearDB->fetchByAssoc($result, $i); if (!$meta->hasPermission(EntityMeta::$RETRIEVE, $row["crmid"])) { continue; } $newrow = DataTransform::sanitizeDataWithColumn($row, $meta); if (__FQNExtendedQueryIsFQNQuery($q)) { // related query $relflds = array_diff_key($row, $newrow); foreach ($queryRelatedModules as $relmod => $relmeta) { $lrm = strtolower($relmod); $newrflds = array(); foreach ($relflds as $fldname => $fldvalue) { $fldmod = substr($fldname, 0, strlen($relmod)); if (isset($row[$fldname]) and $fldmod == $lrm) { $newkey = substr($fldname, strlen($lrm)); $newrflds[$newkey] = $fldvalue; } } $relrow = DataTransform::sanitizeDataWithColumn($newrflds, $relmeta); $newrelrow = array(); foreach ($relrow as $key => $value) { $newrelrow[$lrm . $key] = $value; } $newrow = array_merge($newrow, $newrelrow); } } $output[] = $newrow; } return $output; }
public function query($q) { $parser = new Parser($this->user, $q); $error = $parser->parse(); if ($error) { return $parser->getError(); } $mysql_query = $parser->getSql(); $meta = $parser->getObjectMetaData(); $this->pearDB->startTransaction(); $result = $this->pearDB->pquery($mysql_query, array()); $error = $this->pearDB->hasFailedTransaction(); $this->pearDB->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation"); } $noofrows = $this->pearDB->num_rows($result); $output = array(); for ($i = 0; $i < $noofrows; $i++) { $row = $this->pearDB->fetchByAssoc($result, $i); if (!$meta->hasPermission(EntityMeta::$RETRIEVE, $row["crmid"])) { continue; } $output[] = DataTransform::sanitizeDataWithColumn($row, $meta); } return $output; }
public function update($element) { global $adb; $ids = vtws_getIdComponents($element["id"]); if (!empty($element['filename'])) { $element['filesize'] = $element['filename']['size']; $attachid = SaveAttachmentDB($element); $element['filetype'] = $element['filename']['type']; $element['filename'] = $filename = str_replace(' ', '_', $element['filename']['name']); } $relations = $element['relations']; unset($element['relations']); $element = DataTransform::sanitizeForInsert($element, $this->meta); $crmObject = new VtigerCRMObject($this->tabId, true); $crmObject->setObjectId($ids[1]); $error = $crmObject->update($element); if (!$error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation"); } $id = $crmObject->getObjectId(); $error = $crmObject->read($id); if (!$error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation"); } if (!empty($attachid)) { // Link file attached to document $adb->pquery("DELETE from vtiger_seattachmentsrel where crmid=?", array($id)); $adb->pquery("INSERT INTO vtiger_seattachmentsrel(crmid, attachmentsid) VALUES(?,?)", array($id, $attachid)); } // Establish relations //$adb->pquery("DELETE from vtiger_senotesrel where crmid=?",Array($id)); //foreach ($relations as $rel) { // $ids = vtws_getIdComponents($rel); // $relid = $ids[1]; // $adb->pquery("INSERT INTO vtiger_senotesrel(crmid, notesid) VALUES(?,?)",Array($relid, $id)); //} return DataTransform::filterAndSanitize($crmObject->getFields(), $this->meta); }
public function query($q) { $parser = new Parser($this->user, $q); if (stripos($q, 'related.') > 0) { // related query require_once 'include/Webservices/Utils.php'; require_once 'include/Webservices/GetRelatedRecords.php'; $queryParameters['columns'] = trim(substr($q, 6, stripos($q, ' from ') - 5)); $moduleRegex = "/[fF][rR][Oo][Mm]\\s+([^\\s;]+)/"; preg_match($moduleRegex, $q, $m); $relatedModule = trim($m[1]); $moduleRegex = "/[rR][eE][lL][aA][tT][eE][dD]\\.([^\\s;]+)\\s*=\\s*([^\\s;]+)/"; preg_match($moduleRegex, $q, $m); $moduleName = trim($m[1]); $id = trim($m[2], "(')"); $mysql_query = __getRLQuery($id, $moduleName, $relatedModule, $queryParameters, $this->user); // where, limit and order $afterwhere = substr($q, stripos($q, ' where ') + 6); // eliminate related conditions $relatedCond = "/\\(*[rR][eE][lL][aA][tT][eE][dD]\\.([^\\s;]+)\\s*=\\s*([^\\s;]+)\\)*\\s*([aA][nN][dD]|[oO][rR]\\s)*/"; preg_match($relatedCond, $afterwhere, $pieces); $glue = isset($pieces[3]) ? trim($pieces[3]) : 'and'; $afterwhere = trim(preg_replace($relatedCond, '', $afterwhere), ' ;'); $relatedCond = "/\\s+([aA][nN][dD]|[oO][rR])+\\s+([oO][rR][dD][eE][rR])+/"; $afterwhere = trim(preg_replace($relatedCond, ' order ', $afterwhere), ' ;'); $relatedCond = "/\\s+([aA][nN][dD]|[oO][rR])+\\s+([lL][iI][mM][iI][tT])+/"; $afterwhere = trim(preg_replace($relatedCond, ' limit ', $afterwhere), ' ;'); // if related is at the end of condition we need to strip last and|or if (strtolower(substr($afterwhere, -3)) == 'and') { $afterwhere = substr($afterwhere, 0, strlen($afterwhere) - 3); } if (strtolower(substr($afterwhere, -2)) == 'or') { $afterwhere = substr($afterwhere, 0, strlen($afterwhere) - 2); } // transform REST ids $relatedCond = "/=\\s*'*\\d+x(\\d+)'*/"; $afterwhere = preg_replace($relatedCond, ' = $1 ', $afterwhere); // kill unbalanced parenthesis $balanced = 0; $pila = array(); for ($ch = 0; $ch < strlen($afterwhere); $ch++) { if ($afterwhere[$ch] == '(') { $pila[$balanced] = array('pos' => $ch, 'dir' => '('); $balanced++; } elseif ($afterwhere[$ch] == ')') { if ($balanced > 0 and $pila[$balanced - 1]['dir'] == '(') { array_pop($pila); $balanced--; } else { $pila[$balanced] = array('pos' => $ch, 'dir' => ')'); $balanced++; } } } foreach ($pila as $paren) { $afterwhere[$paren['pos']] = ' '; } // transform artificial commentcontent for FAQ and Ticket comments if (strtolower($relatedModule) == 'modcomments' and (strtolower($moduleName) == 'helpdesk' or strtolower($moduleName) == 'faq')) { $afterwhere = str_ireplace('commentcontent', 'comments', $afterwhere); } // transform fieldnames to columnnames $handler = vtws_getModuleHandlerFromName($relatedModule, $this->user); $meta = $handler->getMeta(); $fldmap = $meta->getFieldColumnMapping(); $tblmap = $meta->getColumnTableMapping(); $tok = strtok($afterwhere, ' '); $chgawhere = ''; while ($tok !== false) { if (!empty($fldmap[$tok])) { $chgawhere .= (strpos($tok, '.') ? '' : $tblmap[$fldmap[$tok]] . '.') . $fldmap[$tok] . ' '; } else { $chgawhere .= $tok . ' '; } $tok = strtok(' '); } $afterwhere = $chgawhere; if (!empty($afterwhere)) { $start = strtolower(substr(trim($afterwhere), 0, 5)); if ($start != 'limit' and $start != 'order') { // there is a condition we add the glue $mysql_query .= " {$glue} "; } $mysql_query .= " {$afterwhere}"; } if (stripos($q, 'count(*)') > 0) { $mysql_query = str_ireplace(' as count ', '', mkCountQuery($mysql_query)); } } else { $error = $parser->parse(); if ($error) { return $parser->getError(); } $mysql_query = $parser->getSql(); $meta = $parser->getObjectMetaData(); } $this->pearDB->startTransaction(); $result = $this->pearDB->pquery($mysql_query, array()); $error = $this->pearDB->hasFailedTransaction(); $this->pearDB->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } $noofrows = $this->pearDB->num_rows($result); $output = array(); for ($i = 0; $i < $noofrows; $i++) { $row = $this->pearDB->fetchByAssoc($result, $i); if (!$meta->hasPermission(EntityMeta::$RETRIEVE, $row["crmid"])) { continue; } $output[] = DataTransform::sanitizeDataWithColumn($row, $meta); } return $output; }
public static function createInventoryDetails($related_focus, $module) { global $adb, $log, $current_user, $currentModule; $save_currentModule = $currentModule; $currentModule = 'InventoryDetails'; $related_to = $related_focus->id; $taxtype = getInventoryTaxType($module, $related_to); if ($taxtype == 'group') { $query = "SELECT id as related_to, vtiger_inventoryproductrel.productid, sequence_no, lineitem_id, quantity, listprice, comment as description,\n\t\t\tquantity * listprice AS extgross,\n\t\t\tCOALESCE( discount_percent, COALESCE( discount_amount *100 / ( quantity * listprice ) , 0 ) ) AS discount_percent,\n\t\t\tCOALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 ) ) AS discount_amount,\n\t\t\t(quantity * listprice) - COALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 )) AS extnet,\n\t\t\t((quantity * listprice) - COALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 ))) AS linetotal,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.cost_price else vtiger_service.cost_price end as cost_price,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.vendor_id else 0 end as vendor_id\n\t\t\tFROM vtiger_inventoryproductrel\n\t\t\tLEFT JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid\n\t\t\tLEFT JOIN vtiger_service ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid\n\t\t\tWHERE id = ?"; } elseif ($taxtype == 'individual') { $query = "SELECT id as related_to, vtiger_inventoryproductrel.productid, sequence_no, lineitem_id, quantity, listprice, comment as description,\n\t\t\tcoalesce( tax1 , 0 ) AS tax1, coalesce( tax2 , 0 ) AS tax2, coalesce( tax3 , 0 ) AS tax3,\n\t\t\t( COALESCE( tax1, 0 ) + COALESCE( tax2, 0 ) + COALESCE( tax3, 0 ) ) as tax_percent,\n\t\t\tquantity * listprice AS extgross,\n\t\t\tCOALESCE( discount_percent, COALESCE( discount_amount *100 / ( quantity * listprice ) , 0 ) ) AS discount_percent,\n\t\t\tCOALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 ) ) AS discount_amount,\n\t\t\t(quantity * listprice) - COALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 )) AS extnet,\n\t\t\t((quantity * listprice) - COALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 ))) * ( COALESCE( tax1, 0 ) + COALESCE( tax2, 0 ) + COALESCE( tax3, 0 ) ) /100 AS linetax,\n\t\t\t((quantity * listprice) - COALESCE( discount_amount, COALESCE( discount_percent * quantity * listprice /100, 0 ))) * ( 1 + ( COALESCE( tax1, 0 ) + COALESCE( tax2, 0 ) + COALESCE( tax3, 0 )) /100) AS linetotal,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.cost_price else vtiger_service.cost_price end as cost_price,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.vendor_id else 0 end as vendor_id\n\t\t\tFROM vtiger_inventoryproductrel\n\t\t\tLEFT JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid\n\t\t\tLEFT JOIN vtiger_service ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid\n\t\t\tWHERE id = ?"; } $res_inv_lines = $adb->pquery($query, array($related_to)); $accountid = '0'; $contactid = '0'; switch ($module) { case 'Quotes': $accountid = $related_focus->column_fields['account_id']; $contactid = $related_focus->column_fields['contact_id']; break; case 'SalesOrder': $accountid = $related_focus->column_fields['account_id']; $contactid = $related_focus->column_fields['contact_id']; break; case 'Invoice': $accountid = $related_focus->column_fields['account_id']; $contactid = $related_focus->column_fields['contact_id']; break; case 'PurchaseOrder': $contactid = $related_focus->column_fields['contact_id']; break; default: break; } // Delete all InventoryDetails where related with $related_to $res_to_del = $adb->pquery('SELECT inventorydetailsid FROM vtiger_inventorydetails INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_inventorydetails.inventorydetailsid WHERE deleted = 0 AND related_to = ? and lineitem_id not in (select lineitem_id from vtiger_inventoryproductrel where id=?)', array($related_to, $related_to)); while ($invdrow = $adb->getNextRow($res_to_del, false)) { $invdet_focus = new InventoryDetails(); $invdet_focus->id = $invdrow['inventorydetailsid']; $invdet_focus->trash('InventoryDetails', $invdet_focus->id); } $requestindex = 1; while (isset($_REQUEST['deleted' . $requestindex]) and $_REQUEST['deleted' . $requestindex] == 1) { $requestindex++; } // read $res_inv_lines result to create a new InventoryDetail for each register. // Remember to take the Vendor if the Product is related with this. while ($row = $adb->getNextRow($res_inv_lines, false)) { $invdet_focus = array(); $invdet_focus = new InventoryDetails(); $rec_exists = $adb->pquery('SELECT inventorydetailsid FROM vtiger_inventorydetails INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_inventorydetails.inventorydetailsid WHERE deleted = 0 AND lineitem_id = ?', array($row['lineitem_id'])); if ($adb->num_rows($rec_exists) > 0) { $invdet_focus->id = $adb->query_result($rec_exists, 0, 0); $invdet_focus->retrieve_entity_info($invdet_focus->id, 'InventoryDetails'); $invdet_focus->mode = 'edit'; } else { $invdet_focus->id = ''; $invdet_focus->mode = ''; } foreach ($invdet_focus->column_fields as $fieldname => $val) { if (isset($_REQUEST[$fieldname . $requestindex])) { $invdet_focus->column_fields[$fieldname] = vtlib_purify($_REQUEST[$fieldname . $requestindex]); } elseif (isset($row[$fieldname])) { $invdet_focus->column_fields[$fieldname] = $row[$fieldname]; } } $invdet_focus->column_fields['lineitem_id'] = $row['lineitem_id']; $_REQUEST['assigntype'] = 'U'; $invdet_focus->column_fields['assigned_user_id'] = $current_user->id; $invdet_focus->column_fields['account_id'] = $accountid; $invdet_focus->column_fields['contact_id'] = $contactid; if ($taxtype == 'group') { $invdet_focus->column_fields['tax_percent'] = 0; $invdet_focus->column_fields['linetax'] = 0; } $handler = vtws_getModuleHandlerFromName('InventoryDetails', $current_user); $meta = $handler->getMeta(); $invdet_focus->column_fields = DataTransform::sanitizeRetrieveEntityInfo($invdet_focus->column_fields, $meta); $invdet_focus->save("InventoryDetails"); $requestindex++; while (isset($_REQUEST['deleted' . $requestindex]) and $_REQUEST['deleted' . $requestindex] == 1) { $requestindex++; } } $currentModule = $save_currentModule; }
public function save() { if ($this->_deleted == true) { return; } if ($this->_data == false) { return; } if ($this->_isDummy) { return; } if (empty($this->_id)) { $result = $this->createRecord(); return $result; } if (VTEntity::$_user === false || VTEntity::$_user->is_admin != "on") { $useUser = Users::getActiveAdminUser(); } else { $useUser = VTEntity::$_user; } $oldFiles = $_FILES; require_once "include/Webservices/Update.php"; if ($this->_changed == false) { return; } // I must prevent $ajaxSave to come true in vtws_update. This will remove all date fields ! unset($_FILES); #$oldA = $_REQUEST['file']; #$oldB = $_REQUEST['action']; #$_REQUEST['file'] = "VTEntitiy"; #$_REQUEST['action'] = "WebServiceSave"; global $current_user, $default_charset; $oldCurrentUser = $current_user; $current_user = $useUser; $this->prepareTransfer(); try { require_once 'data/CRMEntity.php'; $metaHandler = self::getMetaHandler($this->getModuleName()); $focus = CRMEntity::getInstance($this->getModuleName()); $focus->id = $this->_id; $focus->mode = 'edit'; $focus->retrieve_entity_info($this->_id, $this->getModuleName()); $focus->clearSingletonSaveFields(); $focus->column_fields = \DataTransform::sanitizeDateFieldsForInsert($focus->column_fields, $metaHandler); $focus->column_fields = \DataTransform::sanitizeCurrencyFieldsForInsert($focus->column_fields, $metaHandler); $moduleFields = $metaHandler->getModuleFields(); foreach ($focus->column_fields as $key => $value) { if ($this->_data[$key] != $value && !in_array($key, array('record_id', 'record_module'))) { //var_dump($key, $this->_data[$key], $value); $newValue = $this->_data[$key]; $fieldInstance = $moduleFields[$key]; if (empty($fieldInstance)) { throw new \Exception('Field ' . $key . ' not found in module ' . $this->getModuleName() . '.'); } $fieldDataType = $fieldInstance->getFieldDataType(); if ('reference' == $fieldDataType || 'owner' == $fieldDataType) { $newValue = $this->getCrmId($newValue); if ($focus->column_fields[$key] == $newValue) { continue; } } //var_dump('set'); $focus->column_fields[$key] = $newValue; } } foreach ($focus->column_fields as $fieldName => $fieldValue) { $focus->column_fields[$fieldName] = html_entity_decode($fieldValue, ENT_QUOTES, $default_charset); } $_REQUEST['file'] = ''; $_REQUEST['ajxaction'] = ''; // Added as Mass Edit triggers workflow and date and currency fields are set to user format // When saving the information in database saveentity API should convert to database format // and save it. But it converts in database format only if that date & currency fields are // changed(massedit) other wise they wont be converted thereby changing the values in user // format, CRMEntity.php line 474 has the login to check wheather to convert to database format $actionName = $_REQUEST['action']; $_REQUEST['action'] = ''; // For workflows update field tasks is deleted all the lineitems. $focus->isLineItemUpdate = false; $focus->save($this->getModuleName()); //// Reverting back the action name as there can be some dependencies on this. //$_REQUEST['action'] = $actionName; //$result = vtws_update($this->_data, $useUser); $current_user = $oldCurrentUser; } catch (Exception $exp) { $current_user = $oldCurrentUser; if ($exp->getCode() == "DATABASE_QUERY_ERROR") { global $adb; $handleResult = $this->_handleDatabaseError($adb->database->_errorMsg); return; } if ($exp->getCode() == "MANDATORY_FIELDS_MISSING") { $handleResult = $this->_handleMandatoryError($exp); if ($handleResult !== false) { return; } } throw $exp; } $this->afterTransfer(); $this->_changed = false; $_FILES = $oldFiles; }
function dup_dependent_rec($record_id, $relatedModule, $new_record_id, $dependent_tables, $maped_relations) { global $adb, $current_user; $invmods = getInventoryModules(); foreach ($dependent_tables as $module => $tables) { if (in_array($module, $invmods)) { continue; } // we can't duplicate these if (empty($maped_relations) or isset($maped_relations[$module])) { require_once "modules/" . $module . "/" . $module . ".php"; $handler = vtws_getModuleHandlerFromName($module, $current_user); $meta = $handler->getMeta(); $related_field = $tables['columname']; $queryGenerator = new QueryGenerator($module, $current_user); $queryGenerator->setFields(array('id')); $queryGenerator->addReferenceModuleFieldCondition($relatedModule, $related_field, 'id', $record_id, 'e'); $query = $queryGenerator->getQuery(); $result = $adb->pquery($query, array()); while ($r = $adb->fetch_array($result)) { // Duplicate dependent records $entity = new $module(); $entity->mode = ''; $entity->retrieve_entity_info($r[0], $module); $entity->column_fields[$related_field] = $new_record_id; $entity->column_fields = DataTransform::sanitizeRetrieveEntityInfo($entity->column_fields, $meta); $entity->save($module); } } } }
function vtws_sync($mtime, $elementType, $user) { global $adb, $recordString, $modifiedTimeString; $ignoreModules = array(""); $typed = true; $dformat = "Y-m-d H:i:s"; $datetime = date($dformat, $mtime); $setypeArray = array(); $setypeData = array(); $setypeHandler = array(); $setypeNoAccessArray = array(); if (!isset($elementType) || $elementType == '' || $elementType == null) { $typed = false; } $adb->startTransaction(); $q = "select crmid,setype from vtiger_crmentity where modifiedtime >? and smownerid=? and deleted=0"; $params = array($datetime, $user->id); if ($typed) { $q = $q . " and setype=?"; array_push($params, $elementType); } $result = $adb->pquery($q, $params); do { if ($arre) { if (strpos($arre["setype"], " ") === FALSE) { if ($arre["setype"] == 'Calendar') { $seType = vtws_getCalendarEntityType($arre['crmid']); } else { $seType = $arre["setype"]; } if (array_search($seType, $ignoreModules) === FALSE) { $setypeArray[$arre["crmid"]] = $seType; if (!$setypeData[$seType]) { $webserviceObject = VtigerWebserviceObject::fromName($adb, $seType); $handlerPath = $webserviceObject->getHandlerPath(); $handlerClass = $webserviceObject->getHandlerClass(); require_once $handlerPath; $setypeHandler[$seType] = new $handlerClass($webserviceObject, $user, $adb, $log); $meta = $setypeHandler[$seType]->getMeta(); $setypeData[$seType] = new VtigerCRMObject(getTabId($meta->getEntityName()), true); } } } } $arre = $adb->fetchByAssoc($result); } while ($arre); $output = array(); $output["updated"] = array(); foreach ($setypeArray as $key => $val) { $handler = $setypeHandler[$val]; $meta = $handler->getMeta(); if (!$meta->hasAccess() || !$meta->hasWriteAccess() || !$meta->hasPermission(EntityMeta::$RETRIEVE, $key)) { if (!$setypeNoAccessArray[$val]) { $setypeNoAccessArray[] = $val; } continue; } try { $error = $setypeData[$val]->read($key); if (!$error) { //Ignore records whose fetch results in an error. continue; } $output["updated"][] = DataTransform::filterAndSanitize($setypeData[$val]->getFields(), $meta); } catch (WebServiceException $e) { //ignore records the user doesn't have access to. continue; } catch (Exception $e) { throw new WebServiceException(WebServiceErrorCode::$INTERNALERROR, "Unknown Error while processing request"); } } $setypeArray = array(); $setypeData = array(); $q = "select crmid,setype,modifiedtime from vtiger_crmentity where modifiedtime >? and smownerid=? and deleted=1"; $params = array($datetime, $user->id); if ($typed) { $q = $q . " and setype=?"; array_push($params, $elementType); } $result = $adb->pquery($q, $params); do { if ($arre) { if (strpos($arre["setype"], " ") === FALSE) { if ($arre["setype"] == 'Calendar') { $seType = vtws_getCalendarEntityType($arre['crmid']); } else { $seType = $arre["setype"]; } if (array_search($seType, $ignoreModules) === FALSE) { $setypeArray[$arre["crmid"]] = $seType; if (!$setypeData[$seType]) { $webserviceObject = VtigerWebserviceObject::fromName($adb, $seType); $handlerPath = $webserviceObject->getHandlerPath(); $handlerClass = $webserviceObject->getHandlerClass(); require_once $handlerPath; $setypeHandler[$seType] = new $handlerClass($webserviceObject, $user, $adb, $log); $meta = $setypeHandler[$seType]->getMeta(); $setypeData[$seType] = new VtigerCRMObject(getTabId($meta->getEntityName()), true); } } } } $arre = $adb->fetchByAssoc($result); } while ($arre); $output["deleted"] = array(); foreach ($setypeArray as $key => $val) { $handler = $setypeHandler[$val]; $meta = $handler->getMeta(); if (!$meta->hasAccess() || !$meta->hasWriteAccess()) { if (!$setypeNoAccessArray[$val]) { $setypeNoAccessArray[] = $val; } continue; } $output["deleted"][] = vtws_getId($meta->getEntityId(), $key); } $q = "select max(modifiedtime) as modifiedtime from vtiger_crmentity where modifiedtime >? and smownerid=?"; $params = array($datetime, $user->id); if ($typed) { $q = $q . " and setype=?"; array_push($params, $elementType); } else { if (sizeof($setypeNoAccessArray) > 0) { $q = $q . " and setype not in ('" . generateQuestionMarks($setypeNoAccessArray) . "')"; array_push($params, $setypeNoAccessArray); } } $result = $adb->pquery($q, $params); $arre = $adb->fetchByAssoc($result); $modifiedtime = $arre['modifiedtime']; if (!$modifiedtime) { $modifiedtime = $mtime; } else { $modifiedtime = vtws_getSeconds($modifiedtime); } if (is_string($modifiedtime)) { $modifiedtime = intval($modifiedtime); } $output['lastModifiedTime'] = $modifiedtime; $error = $adb->hasFailedTransaction(); $adb->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation"); } VTWS_PreserveGlobal::flush(); return $output; }
public function createEntityRecord($moduleName, $entityLabel) { $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user); $moduleMeta = $moduleHandler->getMeta(); $moduleFields = $moduleMeta->getModuleFields(); $mandatoryFields = $moduleMeta->getMandatoryFields(); $entityNameFieldsString = $moduleMeta->getNameFields(); $entityNameFields = explode(',', $entityNameFieldsString); $fieldData = array(); foreach ($entityNameFields as $entityNameField) { $entityNameField = trim($entityNameField); if (in_array($entityNameField, $mandatoryFields)) { $fieldData[$entityNameField] = $entityLabel; } } foreach ($mandatoryFields as $mandatoryField) { if (empty($fieldData[$mandatoryField])) { $fieldInstance = $moduleFields[$mandatoryField]; if ($fieldInstance->getFieldDataType() == 'owner') { $fieldData[$mandatoryField] = $this->user->id; } else { if (!in_array($mandatoryField, $entityNameFields) && $fieldInstance->getFieldDataType() != 'reference') { $fieldData[$mandatoryField] = '????'; } } } } $fieldData = DataTransform::sanitizeData($fieldData, $moduleMeta); $entityIdInfo = vtws_create($moduleName, $fieldData, $this->user); $adb = PearDatabase::getInstance(); $entityIdComponents = vtws_getIdComponents($entityIdInfo['id']); $recordId = $entityIdComponents[1]; $entityfields = getEntityFieldNames($moduleName); switch ($moduleName) { case 'HelpDesk': $entityfields['fieldname'] = array('ticket_title'); break; case 'Documents': $entityfields['fieldname'] = array('notes_title'); break; case 'Documents': $entityfields['fieldname'] = array('notes_title'); break; } $label = ''; if (is_array($entityfields['fieldname'])) { foreach ($entityfields['fieldname'] as $field) { $label .= $fieldData[$field] . " "; } } else { $label = $fieldData[$entityfields['fieldname']]; } $label = trim($label); $adb->pquery('UPDATE vtiger_crmentity SET label=? WHERE crmid=?', array($label, $recordId)); $recordModel = Vtiger_Record_Model::getCleanInstance($moduleName); $focus = $recordModel->getEntity(); $focus->id = $recordId; $focus->column_fields = $fieldData; $this->entityData[] = VTEntityData::fromCRMEntity($focus); $focus->updateMissingSeqNumber($moduleName); return $entityIdInfo; }
function vtws_sync($mtime, $elementType, $syncType, $user) { global $adb, $recordString, $modifiedTimeString; $numRecordsLimit = 100; $ignoreModules = array("Users"); $typed = true; $dformat = "Y-m-d H:i:s"; $datetime = date($dformat, $mtime); $setypeArray = array(); $setypeData = array(); $setypeHandler = array(); $setypeNoAccessArray = array(); $output = array(); $output["updated"] = array(); $output["deleted"] = array(); $applicationSync = false; if (is_object($syncType) && $syncType instanceof Users) { $user = $syncType; } else { if ($syncType == 'application') { $applicationSync = true; } else { if ($syncType == 'userandgroup') { $userAndGroupSync = true; } } } if ($applicationSync && !is_admin($user)) { throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Only admin users can perform application sync"); } $ownerIds = array($user->id); // To get groupids in which this user exist if ($userAndGroupSync) { $groupresult = $adb->pquery("select groupid from vtiger_users2group where userid=?", array($user->id)); $numOfRows = $adb->num_rows($groupresult); if ($numOfRows > 0) { for ($i = 0; $i < $numOfRows; $i++) { $ownerIds[count($ownerIds)] = $adb->query_result($groupresult, $i, "groupid"); } } } // End if (!isset($elementType) || $elementType == '' || $elementType == null) { $typed = false; } $adb->startTransaction(); $accessableModules = array(); $entityModules = array(); $modulesDetails = vtws_listtypes(null, $user); $moduleTypes = $modulesDetails['types']; $modulesInformation = $modulesDetails["information"]; foreach ($modulesInformation as $moduleName => $entityInformation) { if ($entityInformation["isEntity"]) { $entityModules[] = $moduleName; } } if (!$typed) { $accessableModules = $entityModules; } else { if (!in_array($elementType, $entityModules)) { throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation is denied"); } $accessableModules[] = $elementType; } $accessableModules = array_diff($accessableModules, $ignoreModules); if (count($accessableModules) <= 0) { $output['lastModifiedTime'] = $mtime; $output['more'] = false; return $output; } if ($typed) { $handler = vtws_getModuleHandlerFromName($elementType, $user); $moduleMeta = $handler->getMeta(); $entityDefaultBaseTables = $moduleMeta->getEntityDefaultTableList(); //since there will be only one base table for all entities $baseCRMTable = $entityDefaultBaseTables[0]; if ($elementType == "Calendar" || $elementType == "Events") { $baseCRMTable = getSyncQueryBaseTable($elementType); } } else { $baseCRMTable = " vtiger_crmentity "; } //modifiedtime - next token $q = "SELECT modifiedtime FROM {$baseCRMTable} WHERE modifiedtime>? and setype IN(" . generateQuestionMarks($accessableModules) . ") "; $params = array($datetime); foreach ($accessableModules as $entityModule) { if ($entityModule == "Events") { $entityModule = "Calendar"; } $params[] = $entityModule; } if (!$applicationSync) { $q .= ' and smownerid IN(' . generateQuestionMarks($ownerIds) . ')'; $params = array_merge($params, $ownerIds); } $q .= " order by modifiedtime limit {$numRecordsLimit}"; $result = $adb->pquery($q, $params); $modTime = array(); for ($i = 0; $i < $adb->num_rows($result); $i++) { $modTime[] = $adb->query_result($result, $i, 'modifiedtime'); } if (!empty($modTime)) { $maxModifiedTime = max($modTime); } if (!$maxModifiedTime) { $maxModifiedTime = $datetime; } foreach ($accessableModules as $elementType) { $handler = vtws_getModuleHandlerFromName($elementType, $user); $moduleMeta = $handler->getMeta(); $deletedQueryCondition = $moduleMeta->getEntityDeletedQuery(); preg_match_all("/(?:\\s+\\w+[ \t\n\r]+)?([^=]+)\\s*=([^\\s]+|'[^']+')/", $deletedQueryCondition, $deletedFieldDetails); $fieldNameDetails = $deletedFieldDetails[1]; $deleteFieldValues = $deletedFieldDetails[2]; $deleteColumnNames = array(); foreach ($fieldNameDetails as $tableName_fieldName) { $fieldComp = explode(".", $tableName_fieldName); $deleteColumnNames[$tableName_fieldName] = $fieldComp[1]; } $params = array($moduleMeta->getTabName(), $datetime, $maxModifiedTime); $queryGenerator = new QueryGenerator($elementType, $user); $fields = array(); $moduleFields = $moduleMeta->getModuleFields(); $moduleFieldNames = getSelectClauseFields($elementType, $moduleMeta, $user); $moduleFieldNames[] = 'id'; $queryGenerator->setFields($moduleFieldNames); $selectClause = "SELECT " . $queryGenerator->getSelectClauseColumnSQL(); // adding the fieldnames that are present in the delete condition to the select clause // since not all fields present in delete condition will be present in the fieldnames of the module foreach ($deleteColumnNames as $table_fieldName => $columnName) { if (!in_array($columnName, $moduleFieldNames)) { $selectClause .= ", " . $table_fieldName; } } if ($elementType == "Emails") { $fromClause = vtws_getEmailFromClause(); } else { $fromClause = $queryGenerator->getFromClause(); } $fromClause .= " INNER JOIN (select modifiedtime, crmid,deleted,setype FROM {$baseCRMTable} WHERE setype=? and modifiedtime >? and modifiedtime<=?"; if (!$applicationSync) { $fromClause .= 'and smownerid IN(' . generateQuestionMarks($ownerIds) . ')'; $params = array_merge($params, $ownerIds); } $fromClause .= ' ) vtiger_ws_sync ON (vtiger_crmentity.crmid = vtiger_ws_sync.crmid)'; $q = $selectClause . " " . $fromClause; $result = $adb->pquery($q, $params); $recordDetails = array(); $deleteRecordDetails = array(); while ($arre = $adb->fetchByAssoc($result)) { $key = $arre[$moduleMeta->getIdColumn()]; if (vtws_isRecordDeleted($arre, $deleteColumnNames, $deleteFieldValues)) { if (!$moduleMeta->hasAccess()) { continue; } $output["deleted"][] = vtws_getId($moduleMeta->getEntityId(), $key); } else { if (!$moduleMeta->hasAccess() || !$moduleMeta->hasPermission(EntityMeta::$RETRIEVE, $key)) { continue; } try { $output["updated"][] = DataTransform::sanitizeDataWithColumn($arre, $moduleMeta); } catch (WebServiceException $e) { //ignore records the user doesn't have access to. continue; } catch (Exception $e) { throw new WebServiceException(WebServiceErrorCode::$INTERNALERROR, "Unknown Error while processing request"); } } } } $q = "SELECT crmid FROM {$baseCRMTable} WHERE modifiedtime>? and setype IN(" . generateQuestionMarks($accessableModules) . ")"; $params = array($maxModifiedTime); foreach ($accessableModules as $entityModule) { if ($entityModule == "Events") { $entityModule = "Calendar"; } $params[] = $entityModule; } if (!$applicationSync) { $q .= 'and smownerid IN(' . generateQuestionMarks($ownerIds) . ')'; $params = array_merge($params, $ownerIds); } $result = $adb->pquery($q, $params); if ($adb->num_rows($result) > 0) { $output['more'] = true; } else { $output['more'] = false; } if (!$maxModifiedTime) { $modifiedtime = $mtime; } else { $modifiedtime = vtws_getSeconds($maxModifiedTime); } if (is_string($modifiedtime)) { $modifiedtime = intval($modifiedtime); } $output['lastModifiedTime'] = $modifiedtime; $error = $adb->hasFailedTransaction(); $adb->completeTransaction(); if ($error) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR)); } VTWS_PreserveGlobal::flush(); return $output; }
public function createEntityRecord($moduleName, $entityLabel) { $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user); $moduleMeta = $moduleHandler->getMeta(); $moduleFields = $moduleMeta->getModuleFields(); $mandatoryFields = $moduleMeta->getMandatoryFields(); $entityNameFieldsString = $moduleMeta->getNameFields(); $entityNameFields = explode(',', $entityNameFieldsString); $fieldData = array(); foreach ($entityNameFields as $entityNameField) { $entityNameField = trim($entityNameField); if (in_array($entityNameField, $mandatoryFields)) { $fieldData[$entityNameField] = $entityLabel; } } foreach ($mandatoryFields as $mandatoryField) { if (empty($fieldData[$mandatoryField])) { $fieldInstance = $moduleFields[$mandatoryField]; if ($fieldInstance->getFieldDataType() == 'owner') { $fieldData[$mandatoryField] = $this->user->id; } else { $defaultValue = $fieldInstance->getDefault(); if (!empty($defaultValue)) { $fieldData[$mandatoryField] = $defaultValue; } else { $fieldData[$mandatoryField] = '????'; } } } } $fieldData = DataTransform::sanitizeData($fieldData, $moduleMeta); $entityIdInfo = vtws_create($moduleName, $fieldData, $this->user); $focus = CRMEntity::getInstance($moduleName); $focus->updateMissingSeqNumber($moduleName); return $entityIdInfo; }
public function update($element) { $ids = vtws_getIdComponents($element["id"]); $element = DataTransform::sanitizeForInsert($element, $this->meta); $element = $this->restrictFields($element); $columnStr = 'set ' . implode('=?,', array_keys($element)) . ' =? '; $query = 'update ' . $this->entityTableName . ' ' . $columnStr . 'where ' . $this->meta->getObectIndexColumn() . '=?'; $params = array_values($element); array_push($params, $ids[1]); $result = null; $transactionSuccessful = vtws_runQueryAsTransaction($query, $params, $result); if (!$transactionSuccessful) { throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation"); } return $this->retrieve(vtws_getId($ids[0], $ids[1])); }
/** * 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; } }
function vtws_createEntity($recordid, $originMod, $targetMod) { global $adb, $current_user, $log; $return = 0; $newEntityInfo = CRMEntity::getInstance($targetMod); $mapfound = false; foreach ($originMod as $modName) { if ($recordid[$modName]) { $oldEntityInfo = CRMEntity::getInstance($modName); $oldEntityInfo->retrieve_entity_info(vtws_getIdComponents($recordid[$modName])[1], $modName); $map_name = $modName . '2' . $targetMod; $cbMapid = GlobalVariable::getVariable('BusinessMapping_' . $map_name, cbMap::getMapIdByName($map_name)); if ($cbMapid) { $mapfound = true; $cbMap = cbMap::getMapByID($cbMapid); $newEntityInfo->column_fields = $cbMap->Mapping($oldEntityInfo->column_fields, $newEntityInfo->column_fields); } } } if ($mapfound) { try { $webserviceObject = VtigerWebserviceObject::fromName($adb, $targetMod); $handlerPath = $webserviceObject->getHandlerPath(); $handlerClass = $webserviceObject->getHandlerClass(); require_once $handlerPath; $handler = new $handlerClass($webserviceObject, $current_user, $adb, $log); $meta = $handler->getMeta(); $values = DataTransform::sanitizeReferences($newEntityInfo->column_fields, $meta); $values = DataTransform::sanitizeOwnerFields($values, $meta); $return = vtws_create($targetMod, $values, $current_user); } catch (Exception $e) { throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $targetMod); } } return $return; }