Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • vtiger/vtigercrm
  • varma/vtigercrm
  • alanbell/vtigercrm
  • mariusz.krzaczkowski/vtigercrm
  • manu.k/vtigercrm
  • adrgranado/vtigercrm
  • uma.s/vtigercrm
  • sardoj/vtigercrm
  • preexo/vtigercrm
  • david.valminos/vtigercrm
  • luca.saba/vtigercrm
  • dubwise/vtigercrm
  • valmir.ttcasolucoes/vtigercrm
  • lord_alan/vtigercrm
  • adrien.futschik/vtigercrm
  • edonit.rexhepi/vtigercrm
  • robert.heinze/vtigercrm
  • nrdimatteo/vtigercrm
  • sebastianzahan/vtigercrm
  • Miky/vtigercrm
  • germanf/vtigercrm
  • bernhardkau1/vtigercrm
  • olegtsoy/vtigercrm
  • grandel/vtigercrm
  • mario.thummler/vtigercrm
  • sutharsan/vtigercrm
  • james.douglas/vtigercrm
  • vikas/vtigercrm
  • jeffmchristensen/vtigercrm
  • lukasz.g/vtigercrm
  • nicolas.gasnier/vtigercrm
  • hamish.theitcompany/vtigercrm
  • engrbm87/vtigercrm
  • Quoc/vtigercrm
  • peter.maria.engeli/vtigercrm
  • kiranraju.j/vtigercrm
  • manuel.lozano/vtigercrm
  • dhaupin/vtigercrm
  • Ragupathyranesh/vtigercrm
  • Stefanbauer/vtigercrm
  • ruben.estrada/vtigercrm
  • sg_mwi1/vtigercrm
  • khaluk/vtigercrm
  • franzfroemel/vtigercrm
  • milan9615/vtigercrm
  • carlos.martin/vtigercrm
  • cmaggi/vtigercrm
  • Soltoon.theLeader/vtigercrm
  • alex.kaplun/vtigercrm
  • navid.hosseini/vtigercrm
  • maie/vtigercrm
  • simonetravaglini/vtigercrm
  • bertrand.wattel/vtigercrm
  • balaji.m/vtigercrm
  • mclarke4/vtigercrm
  • lajeeshk/vtigercrm
  • liam/vtigercrm
  • novikov.sergey/vtigercrm
  • johnwayne.williamson/vtigercrm
  • florian.strahberger-schramm/vtigercrm
  • daniel.schaefer/vtigercrm
  • christopher.gunther/vtigercrm
  • adrien.faveraux/vtigercrm
  • carsten.brandt/vtigercrm
  • stephane.molano/vtigercrm
  • krastan.petrov/vtigercrm
  • alfredo.bravo/vtigercrm
  • flipflop.Joe/vtigercrm
  • mirko.stagni/vtigercrm
  • remigio.ruberto/vtigercrm
  • gautam.dhudashiya/vtigercrm
  • manish.devitechnosolutions1/vtigercrm
  • matinbeigi/vtigercrm
  • devs/vtigercrm
  • happy.dev/vtigercrm
  • m.gigon/vtigercrm
  • manuelmigone/vtigercrm
  • eduardo.gqf/vtigercrm
  • elsayedEl-araby/vtigercrm
  • mirza.mehran/vtigercrm
  • maurice.courtois/vtigercrm
  • zuhri.utama/vtigercrm
  • shilpa.k/vtigercrm
  • Ignazio/vtigercrm
  • code80team/vtigercrm
  • code80/vtigercrm
  • nilay.automatesmb/cache
  • greeshma.kk/vtigercrm
  • vijay.tilak/vtigercrm
  • Paolo.Palamini/vtigercrm
  • estevan/vtigercrm
  • mobilcmcdk/vtigercrm
  • massimiliano.vessi/vtigercrm
  • daniel.voelskow/vtigercrm
  • james1/vtigercrm
  • lokesh.s/vtigercrm
  • rdb/vtigercrm
  • neftaliyagua/vtigercrm
  • angelo.paglialonga/vtigercrm
  • webmarka/vtigercrm
  • javanile/vtigercrm
  • akshath/vtigercrm
  • Hemanth/vtigercrm
  • opencrmitalia/vtigercrm
  • direzione/vtigercrm
  • umadas306/vtigercrm
  • jd-wraptec/vtigercrm
  • felipe.camacho/vtigercrm
  • Martin.allen/vtigercrm
  • amit.r/vtigercrm
  • vicus/vtigercrm
  • dev.osmi/vtigercrm
  • laurent.guillout/vtigercrm
  • christian.blaeul/vtigercrm
  • ap.js100/vtigercrm
  • yoann.mourot/vtigercrm-temp
  • christian.cruz/vtigercrm
  • zyli/vtigercrm
  • kaushik.p/vtigercrm
  • Madhuk/vtigercrm
  • cinakzm/vtigercrm
  • raquel.martinez/vtigercrm
  • tosajibadhi/vtigercrm
  • melvin.i/vtigercrm-melvin
  • ashashingadia/vtigercrm
  • stefanwarnat/vtigercrm
  • saran.s/vtigercrm
  • eduardomozart/vtigercrm
  • Daniel.Lennartz1/vtigercrm
  • juergen.fassmann/vtigercrm
  • Michel.Ram/vtigercrm
  • vincenzo.bruno/vtigercrm
  • Hitesh.Solanki/vtigercrm
133 results
Show changes
Showing
with 500 additions and 205 deletions
......@@ -14,7 +14,7 @@
public static $recordModuleString = 'record_module';
public static $recordSource = 'WEBSERVICE';
function sanitizeDataWithColumn($row,$meta){
static function sanitizeDataWithColumn($row,$meta){
$newRow = array();
if(isset($row['count(*)'])){
......@@ -30,7 +30,7 @@
return $newRow;
}
function sanitizeDataWithCountColumn($row,$meta){
static function sanitizeDataWithCountColumn($row,$meta){
$newRow = array();
foreach($row as $col=>$val){
$newRow['count'] = $val;
......@@ -38,8 +38,8 @@
return $newRow;
}
function filterAndSanitize($row,$meta){
$recordLabel = $row['label'];
static function filterAndSanitize($row,$meta){
$recordLabel = isset($row['label']) ? $row['label'] :"";
$row = DataTransform::filterAllColumns($row,$meta);
$row = DataTransform::sanitizeData($row,$meta);
if(!empty($recordLabel)){
......@@ -48,15 +48,16 @@
return $row;
}
function sanitizeData($newRow,$meta,$t=null){
static function sanitizeData($newRow,$meta,$t=null){
$newRow = DataTransform::sanitizeReferences($newRow,$meta);
$newRow = DataTransform::sanitizeOwnerFields($newRow,$meta,$t);
$newRow = DataTransform::sanitizeFileFieldsForIds($newRow, $meta);
$newRow = DataTransform::sanitizeFields($newRow,$meta);
return $newRow;
}
function sanitizeForInsert($row,$meta){
static function sanitizeForInsert($row,$meta){
global $adb;
$associatedToUser = false;
$parentTypeId = null;
......@@ -102,7 +103,7 @@
}
$references = $meta->getReferenceFieldDetails();
foreach($references as $field=>$typeList){
if(strpos($row[$field],'x')!==false){
if(isset($row[$field]) && strpos($row[$field],'x')!==false){
$row[$field] = vtws_getIdComponents($row[$field]);
$row[$field] = $row[$field][1];
}
......@@ -129,7 +130,7 @@
}
}
}
if($row["id"]){
if(isset($row["id"]) && $row["id"]){
unset($row["id"]);
}
if(isset($row[$meta->getObectIndexColumn()])){
......@@ -138,6 +139,7 @@
$row = DataTransform::sanitizeDateFieldsForInsert($row,$meta);
$row = DataTransform::sanitizeCurrencyFieldsForInsert($row,$meta);
$row = DataTransform::sanitizeStringFields($row,$meta);
// New field added to store Source of Created Record
if (!isset($row['source'])) {
......@@ -148,14 +150,14 @@
}
function filterAllColumns($row,$meta){
static function filterAllColumns($row,$meta){
$recordString = DataTransform::$recordString;
$allFields = $meta->getFieldColumnMapping();
$newRow = array();
foreach($allFields as $field=>$col){
$newRow[$field] = $row[$field];
$newRow[$field] = isset($row[$field]) ? $row[$field] : null;
}
if(isset($row[$recordString])){
$newRow[$recordString] = $row[$recordString];
......@@ -164,7 +166,7 @@
}
function sanitizeFields($row,$meta){
static function sanitizeFields($row,$meta){
$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
$recordString = DataTransform::$recordString;
......@@ -186,7 +188,7 @@
}
if(!isset($row['id'])){
if($row[$meta->getObectIndexColumn()] ){
if(isset($row[$meta->getObectIndexColumn()] )){
$row['id'] = vtws_getId($meta->getEntityId(),$row[$meta->getObectIndexColumn()]);
}else{
//TODO Handle this.
......@@ -197,21 +199,24 @@
}
foreach ($row as $field => $value) {
$row[$field] = html_entity_decode($value, ENT_QUOTES, $default_charset);
$row[$field] = $value ? html_entity_decode($value, ENT_QUOTES, $default_charset) : $value;
}
return $row;
}
function sanitizeReferences($row,$meta){
static function sanitizeReferences($row,$meta){
global $adb,$log;
$references = $meta->getReferenceFieldDetails();
foreach($references as $field=>$typeList){
if($meta->getEntityName() == 'Users' && $field == 'roleid'){
continue;
}
if(strtolower($meta->getEntityName()) == "emails"){
if(isset($row['parent_id'])){
if (isset($row['parent_id']) && $row['parent_id'] !== null && strpos($row['parent_id'], '@') !== false) {
list($row['parent_id'], $fieldId) = explode('@', $row['parent_id']);
}
}
if($row[$field]){
if(isset($row[$field]) && $row[$field]){
$found = false;
foreach ($typeList as $entity) {
$webserviceObject = VtigerWebserviceObject::fromName($adb,$entity);
......@@ -241,7 +246,7 @@
return $row;
}
function sanitizeOwnerFields($row,$meta,$t=null){
static function sanitizeOwnerFields($row,$meta,$t=null){
global $adb;
$ownerFields = $meta->getOwnerFields();
foreach($ownerFields as $index=>$field){
......@@ -255,8 +260,39 @@
}
return $row;
}
function sanitizeDateFieldsForInsert($row,$meta){
/**
* Function to attach the image/file ids in retrieve/query operations
* @param type $row
* @param type $meta
* @return <array>
*/
static function sanitizeFileFieldsForIds($row, $meta) {
$moduleFields = $meta->getModuleFields();
$supportedUITypes = array(61, 69, 28); //file and image uitypes
$attachmentIds = array();
foreach ($moduleFields as $fieldName => $fieldObj) {
if (in_array($fieldObj->getUIType(), $supportedUITypes)) {
//while doing retrieve operation we have record_id and on query operation we have id.
$id = isset($row['record_id']) ? $row['record_id'] : (isset($row['id']) ? $row['id'] : null);
$ids = Vtiger_Functions::getAttachmentIds($id, $meta->getEntityId());
if($ids) {
foreach($ids as $id){
array_push($attachmentIds, $id);
}
}
break;
}
}
if (!empty($attachmentIds)){
$row['imageattachmentids'] = implode(',', $attachmentIds);
}
return $row;
}
static function sanitizeDateFieldsForInsert($row,$meta){
global $current_user;
$moduleFields = $meta->getModuleFields();
foreach($moduleFields as $fieldName=>$fieldObj){
......@@ -270,7 +306,7 @@
return $row;
}
function sanitizeCurrencyFieldsForInsert($row,$meta){
static function sanitizeCurrencyFieldsForInsert($row,$meta){
global $current_user;
$moduleFields = $meta->getModuleFields();
foreach($moduleFields as $fieldName=>$fieldObj){
......@@ -280,7 +316,7 @@
$row[$fieldName."_raw"] = $row[$fieldName];
$row[$fieldName] = CurrencyField::convertToUserFormat($row[$fieldName],$current_user);
} else if($fieldObj->getUIType() == '72') {
$currencyConversionRate = $row['conversion_rate'];
$currencyConversionRate = isset($row['conversion_rate']) ? $row['conversion_rate'] : 0;
if (!empty($currencyConversionRate)) {
$rawBaseCurrencyValue = CurrencyField::convertToDollar($row[$fieldName], $currencyConversionRate);
$row[$fieldName."_raw"] = $rawBaseCurrencyValue;
......@@ -297,5 +333,16 @@
}
return $row;
}
static function sanitizeStringFields($row,$meta){
if(in_array($meta->getEntityName(),array('Groups', 'Currency', 'Tax', 'ProductTaxes'))){
foreach ($row as $field => $value) {
if(is_string($value)){
$row[$field] = vtlib_purify($value);
}
}
}
return $row;
}
}
?>
......@@ -10,7 +10,15 @@
function vtws_describe($elementType,$user){
global $log,$adb;
global $log,$adb,$app_strings;
//setting $app_strings
if (!$app_strings) {
$currentLanguage = Vtiger_Language_Handler::getLanguage();
$moduleLanguageStrings = Vtiger_Language_Handler::getModuleStringsFromFile($currentLanguage);
$app_strings = $moduleLanguageStrings['languageStrings'];
}
$webserviceObject = VtigerWebserviceObject::fromName($adb,$elementType);
$handlerPath = $webserviceObject->getHandlerPath();
$handlerClass = $webserviceObject->getHandlerClass();
......
......@@ -8,6 +8,7 @@
* All Rights Reserved.
*************************************************************************************/
#[\AllowDynamicProperties]
abstract class EntityMeta{
public static $RETRIEVE = "DetailView";
......@@ -34,12 +35,19 @@ abstract class EntityMeta{
protected $ownerFields;
protected $moduleFields = null;
protected function EntityMeta($webserviceObject,$user){
$this->webserviceObject = $webserviceObject;
protected function __construct($webserviceObject,$user)
{
$this->webserviceObject = $webserviceObject;
$this->objectName = $this->webserviceObject->getEntityName();
$this->objectId = $this->webserviceObject->getEntityId();
$this->user = $user;
}
protected function EntityMeta($webserviceObject,$user){
// PHP4-style constructor.
// This will NOT be invoked, unless a sub-class that extends `foo` calls it.
// In that case, call the new-style constructor to keep compatibility.
self::__construct($webserviceObject,$user);
}
public function getEmailFields(){
......@@ -269,4 +277,4 @@ abstract class EntityMeta{
abstract public function getName($webserviceId);
abstract public function isModuleEntity();
}
?>
\ No newline at end of file
?>
......@@ -10,17 +10,19 @@
function vtws_extendSession(){
global $adb,$API_VERSION,$application_unique_key;
if(isset($_SESSION["authenticated_user_id"]) && $_SESSION["app_unique_key"] == $application_unique_key){
$userId = $_SESSION["authenticated_user_id"];
$sessionManager = new SessionManager();
$sessionManager->set("authenticatedUserId", $userId);
$crmObject = VtigerWebserviceObject::fromName($adb,"Users");
$userId = vtws_getId($crmObject->getEntityId(),$userId);
$vtigerVersion = vtws_getVtigerVersion();
$resp = array("sessionName"=>$sessionManager->getSessionId(),"userId"=>$userId,"version"=>$API_VERSION,"vtigerVersion"=>$vtigerVersion);
return $resp;
}else{
throw new WebServiceException(WebServiceErrorCode::$AUTHFAILURE,"Authencation Failed");
}
if($_SESSION['authenticatedUserId'] || (isset($_SESSION["authenticated_user_id"]) && $_SESSION["app_unique_key"] == $application_unique_key)){
$userId = ($_SESSION["authenticated_user_id"]) ? $_SESSION["authenticated_user_id"] : $_SESSION['authenticatedUserId'];
//unsetting as session manager will set it, if set then it is not extended by HTTP_Session::setExpire
unset($_SESSION['__HTTP_Session_Expire_TS']);
$sessionManager = new SessionManager();
$sessionManager->set("authenticatedUserId", $userId);
$crmObject = VtigerWebserviceObject::fromName($adb,"Users");
$userId = vtws_getId($crmObject->getEntityId(),$userId);
$vtigerVersion = vtws_getVtigerVersion();
$resp = array("sessionName"=>$sessionManager->getSessionId(),"userId"=>$userId,"version"=>$API_VERSION,"vtigerVersion"=>$vtigerVersion);
return $resp;
}else{
throw new WebServiceException(WebServiceErrorCode::$AUTHFAILURE,"Authencation Failed");
}
}
?>
\ No newline at end of file
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
function vtws_file_retrieve($file_id, $user) {
global $log, $adb;
$idComponents = vtws_getIdComponents($file_id);
$attachmentId = $idComponents[1];
$id = vtws_getAttachmentRecordId($attachmentId);
if(!$id || !$attachmentId) {
throw new WebServiceException(WebServiceErrorCode::$RECORDNOTFOUND, "Record you are trying to access is not found");
} else {
$id = vtws_getId($idComponents[0], $id);
}
$webserviceObject = VtigerWebserviceObject::fromId($adb, $id);
$handlerPath = $webserviceObject->getHandlerPath();
$handlerClass = $webserviceObject->getHandlerClass();
require_once $handlerPath;
$handler = new $handlerClass($webserviceObject, $user, $adb, $log);
// If setype of the record is not equal to webservice entity
$meta = $handler->getMeta();
$elementType = $meta->getObjectEntityName($id);
if ($elementType !== $webserviceObject->getEntityName()) {
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Id specified is incorrect");
}
// If User don't have access to the module (OR) View is not allowed
$types = vtws_listtypes(null, $user);
$viewPermission = Users_Privileges_Model::isPermitted($elementType, 'DetailView', $recordId);
if (!$viewPermission || !in_array($elementType, $types['types'])) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation is denied");
}
$response = $handler->file_retrieve($id, $elementType, $attachmentId);
VTWS_PreserveGlobal::flush();
return $response;
}
?>
......@@ -82,7 +82,7 @@ require_once 'include/Webservices/DescribeObject.php';
$accessableModules = array_diff($accessableModules,$ignoreModules);
if(count($accessableModules)<=0)
if(php7_count($accessableModules)<=0)
{
$output['lastModifiedTime'] = $mtime;
$output['more'] = false;
......
......@@ -95,7 +95,7 @@ function vtws_history($element, $user) {
while ($row = $adb->fetch_array($result)) {
$orderedIds[] = $row['id'];
if ($row['status'] === ModTracker::$LINK) {
if ($row['status'] === ModTracker::$LINK || $row['status'] === ModTracker::$UNLINK) {
$relationOrderedIds[] = $row['id'];
} else {
$updatesOrderedIds[] = $row['id'];
......@@ -200,4 +200,4 @@ function vtws_history_entityIdHelper($moduleName, $id) {
$wsEntityIdCache[$moduleName][$id] = vtws_getWebserviceEntityId($moduleName, $id);
}
return $wsEntityIdCache[$moduleName][$id];
}
\ No newline at end of file
}
......@@ -51,7 +51,7 @@ class VtigerInventoryMeta extends VtigerCRMObjectMeta {
$field['displaytype'] = 1;
$field['uitype'] = 1;
$fieldDataType = 'V';
$typeOfData = $fieldType.'~O';
$typeOfData = $fieldDataType.'~O';
$field['typeofdata'] = $typeOfData;
$field['tabid'] = null;
......@@ -61,4 +61,4 @@ class VtigerInventoryMeta extends VtigerCRMObjectMeta {
}
}
?>
\ No newline at end of file
?>
......@@ -15,20 +15,29 @@ require_once 'include/Webservices/Utils.php';
* Description of VtigerInventoryOperation
*/
class VtigerInventoryOperation extends VtigerModuleOperation {
public static $CREATE_OPERATI0N;
public function create($elementType, $element) {
self::$CREATE_OPERATI0N = true;
if (!$element['hdnTaxType']) {
$element['hdnTaxType'] = Inventory_TaxRecord_Model::getSelectedDefaultTaxMode();
}
$element = $this->sanitizeInventoryForInsert($element);
$element = $this->sanitizeShippingTaxes($element);
$lineItems = $element['LineItems'];
if (!empty($lineItems)) {
$eventManager = new VTEventsManager(vglobal('adb'));
$this->triggerBeforeSaveEvents($element, $eventManager);
$sanitizedData = DataTransform::sanitizeForInsert($element,$this->meta);
$this->triggerBeforeSaveEvents($sanitizedData, $eventManager);
$currentBulkSaveMode = vglobal('VTIGER_BULK_SAVE_MODE');
if ($currentBulkSaveMode === NULL) {
$currentBulkSaveMode = false;
}
vglobal('VTIGER_BULK_SAVE_MODE', true);
global $currentModule;
$currentModule = $elementType;
$element = parent::create($elementType, $element);
$focus = CRMEntity::getInstance($elementType);
......@@ -38,20 +47,21 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$handler = vtws_getModuleHandlerFromName('LineItem', $this->user);
$handler->setLineItems('LineItem', $lineItems, $element);
$parent = $handler->getParentById($element['id']);
$parent = $handler->getParentById($element['id']);
$handler->updateParent($lineItems, $parent);
$updatedParent = $handler->getParentById($element['id']);
//since subtotal and grand total is updated in the update parent api
$parent['hdnSubTotal'] = $updatedParent['hdnSubTotal'];
$parent['hdnGrandTotal'] = $updatedParent['hdnGrandTotal'];
$parent['pre_tax_total'] = $updatedParent['pre_tax_total'];
$components = vtws_getIdComponents($element['id']);
$parentId = $components[1];
$parent['LineItems'] = $handler->getAllLineItemForParent($parentId);
$updatedParent = $handler->getParentById($element['id']);
//since subtotal and grand total is updated in the update parent api
$parent['hdnSubTotal'] = $updatedParent['hdnSubTotal'];
$parent['hdnGrandTotal'] = $updatedParent['hdnGrandTotal'];
$parent['pre_tax_total'] = $updatedParent['pre_tax_total'];
$components = vtws_getIdComponents($element['id']);
$parentId = $components[1];
$parent['LineItems'] = $handler->getAllLineItemForParent($parentId);
$currentValue = vglobal('updateInventoryProductRel_deduct_stock');
vglobal('updateInventoryProductRel_deduct_stock', false);
$parent['new'] = true;
$this->triggerAfterSaveEvents($parent, $eventManager);
vglobal('updateInventoryProductRel_deduct_stock', $currentValue);
......@@ -69,13 +79,18 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$handler = vtws_getModuleHandlerFromName('LineItem', $this->user);
if (!empty($lineItemList)) {
$eventManager = new VTEventsManager(vglobal('adb'));
$this->triggerBeforeSaveEvents($element, $eventManager);
$sanitizedData = DataTransform::sanitizeForInsert($element,$this->meta);
$sanitizedData['id'] = $element['id'];
$this->triggerBeforeSaveEvents($sanitizedData, $eventManager);
unset($sanitizedData['id']);
$currentBulkSaveMode = vglobal('VTIGER_BULK_SAVE_MODE');
if ($currentBulkSaveMode === NULL) {
$currentBulkSaveMode = false;
}
vglobal('VTIGER_BULK_SAVE_MODE', true);
global $currentModule;
$currentModule = getTabname($this->tabId);
$updatedElement = parent::update($element);
vglobal('VTIGER_BULK_SAVE_MODE', $currentBulkSaveMode);
......@@ -83,12 +98,12 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$handler->setLineItems('LineItem', $lineItemList, $updatedElement);
$parent = $handler->getParentById($element['id']);
$handler->updateParent($lineItemList, $parent);
$updatedParent = $handler->getParentById($element['id']);
//since subtotal and grand total is updated in the update parent api
$parent['hdnSubTotal'] = $updatedParent['hdnSubTotal'];
$parent['hdnGrandTotal'] = $updatedParent['hdnGrandTotal'];
$parent['pre_tax_total'] = $updatedParent['pre_tax_total'];
$updatedElement = array_merge($updatedElement,$parent);
$updatedParent = $handler->getParentById($element['id']);
//since subtotal and grand total is updated in the update parent api
$parent['hdnSubTotal'] = $updatedParent['hdnSubTotal'];
$parent['hdnGrandTotal'] = $updatedParent['hdnGrandTotal'];
$parent['pre_tax_total'] = $updatedParent['pre_tax_total'];
$updatedElement = array_merge($updatedElement,$parent);
$currentValue = vglobal('updateInventoryProductRel_deduct_stock');
vglobal('updateInventoryProductRel_deduct_stock', false);
......@@ -118,8 +133,10 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
unset($element['LineItems']);
$eventManager = new VTEventsManager(vglobal('adb'));
$this->triggerBeforeSaveEvents($element, $eventManager);
$sanitizedData = DataTransform::sanitizeForInsert($element,$this->meta);
$sanitizedData['id'] = $element['id'];
$this->triggerBeforeSaveEvents($sanitizedData, $eventManager);
unset($sanitizedData['id']);
$currentBulkSaveMode = vglobal('VTIGER_BULK_SAVE_MODE');
if ($currentBulkSaveMode === NULL) {
$currentBulkSaveMode = false;
......@@ -151,14 +168,20 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
vglobal('updateInventoryProductRel_deduct_stock', $currentValue);
} else {
$prevAction = $_REQUEST['action'];
$prevAjaxAction = $_REQUEST['ajxaction'];
// This is added as we are passing data in user format, so in the crmentity insertIntoEntity API
// should convert to database format, we have added a check based on the action name there. But
// while saving Invoice and Purchase Order we are also depending on the same action file names to
// not to update stock if its an ajax save. In this case also we do not want line items to change.
$_REQUEST['action'] = 'FROM_WS';
//To avoid deletion of lineitems we use the ajaxaction DETAILVIEW as if we were updating signle fields from the detail view:
$_REQUEST['ajxaction'] = 'DETAILVIEW';
$parent = parent::revise($element);
$_REQUEST['action'] = $prevAction;
$_REQUEST['ajxaction'] = $prevAjaxAction;
$parent['LineItems'] = $handler->getAllLineItemForParent($parentId);
}
return array_merge($element,$parent);
......@@ -181,10 +204,20 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$element['LineItems'] = $lineItems;
$recordCompoundTaxesElement = $this->getCompoundTaxesElement($element, $lineItems);
$element = array_merge($element, $recordCompoundTaxesElement);
$element['productid'] = $lineItems[0]['productid'];
$element['productid'] = isset($lineItems[0]['productid']) ? $lineItems[0]['productid'] : "";
$element['LineItems_FinalDetails'] = $this->getLineItemFinalDetails($idComponents[1]);
return $element;
}
public function getLineItemFinalDetails($record) {
$finalDetails = array();
$recordModel = Inventory_Record_Model::getInstanceById($record);
if($recordModel) {
$finalDetails = $recordModel->getProducts();
}
return $finalDetails;
}
public function delete($id) {
$components = vtws_getIdComponents($id);
$parentId = $components[1];
......@@ -200,6 +233,7 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
* @return type
*/
protected function sanitizeInventoryForInsert($element) {
if (!empty($element['hdnTaxType'])) {
$_REQUEST['taxtype'] = $element['hdnTaxType'];
}
......@@ -207,10 +241,10 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$_REQUEST['subtotal'] = $element['hdnSubTotal'];
}
if ($element['hdnDiscountAmount']) {
if ((float) $element['hdnDiscountAmount'] && $element['hdnDiscountAmount'] !== '') {
$_REQUEST['discount_type_final'] = 'amount';
$_REQUEST['discount_amount_final'] = $element['hdnDiscountAmount'];
} elseif ($element['hdnDiscountPercent']) {
} elseif ((float) $element['hdnDiscountPercent'] && $element['hdnDiscountPercent'] !== '') {
$_REQUEST['discount_type_final'] = 'percentage';
$_REQUEST['discount_percentage_final'] = $element['hdnDiscountPercent'];
} else {
......@@ -218,8 +252,8 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$_REQUEST['discount_percentage_final'] = '';
}
if ($element['txtAdjustment']) {
$_REQUEST['adjustmentType'] = ((int) $element['txtAdjustment'] < 0) ? '-' : '+';
if ((float) $element['txtAdjustment']) {
$_REQUEST['adjustmentType'] = ((float) $element['txtAdjustment'] < 0) ? '-' : '+';
$_REQUEST['adjustment'] = abs($element['txtAdjustment']);
} else {
$_REQUEST['adjustmentType'] = '';
......@@ -237,6 +271,23 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$_REQUEST['conversion_rate'] = 1;
}
$lineItems = $element['LineItems'];
$totalNoOfProducts = php7_count($lineItems);
$_REQUEST['totalProductCount'] = $totalNoOfProducts;
$_REQUEST['REQUEST_FROM_WS'] = true;
$i = 1;
if (!is_array($lineItems)) {
$lineItems = array();
}
foreach ($lineItems as $lineItem) {
$productIdComponents = vtws_getIdComponents($lineItem['productid']);
$productId = $productIdComponents[1];
$_REQUEST['hdnProductId'.$i] = $productId;
$_REQUEST['qty'.$i] = $lineItem['quantity'];
$i++;
}
return $element;
}
......@@ -291,7 +342,9 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
unset($_REQUEST['charges'][1]['taxes'][$shTaxId]);
if(isset($element['hdnS_H_Percent']) && $element['hdnS_H_Percent'] != 0 && $element['hdnS_H_Amount'] != 0) {
$_REQUEST['charges'][1]['taxes'][$shTaxId] = $element['hdnS_H_Percent'];
$_REQUEST['s_h_percent'] = ($element['hdnS_H_Amount'] * $element['hdnS_H_Percent'])/100;
$_REQUEST['s_h_percent'] = ($element['hdnS_H_Percent']/$element['hdnS_H_Amount'])*100;
$_REQUEST['charges'][$firstActiveCharge]['taxes'][$shTaxId] = $_REQUEST['s_h_percent'];
$element['hdnS_H_Percent'] = $_REQUEST['s_h_percent'];
break;
} else {
$shTaxValue = 0;
......@@ -305,16 +358,16 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
return $element;
}
/* NOTE: Special case to pull the default setting of TermsAndCondition */
public function describe($elementType) {
$describe = parent::describe($elementType);
$tandc = getTermsAndConditions($elementType);
foreach ($describe['fields'] as $key => $list){
if($list["name"] == 'terms_conditions'){
$describe['fields'][$key]['default'] = $tandc;
}
}
/* NOTE: Special case to pull the default setting of TermsAndCondition */
public function describe($elementType) {
$describe = parent::describe($elementType);
$tandc = getTermsAndConditions($elementType);
foreach ($describe['fields'] as $key => $list){
if($list["name"] == 'terms_conditions'){
$describe['fields'][$key]['default'] = $tandc;
}
}
$shippingTaxes = array();
$allShippingTaxes = getAllTaxes('available', 'sh');
......@@ -350,8 +403,8 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
}
return $describe;
}
return $describe;
}
/**
* Function to trigger the events which are before save
......@@ -359,15 +412,17 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
* @param <type> $eventManager
*/
public function triggerBeforeSaveEvents($element, $eventManager) {
global $VTIGER_BULK_SAVE_MODE;
if ($eventManager) {
$eventManager->initTriggerCache();
$focusObj = $this->constructFocusObject($element);
$entityData = VTEntityData::fromCRMEntity($focusObj);
$eventManager->triggerEvent("vtiger.entity.beforesave.modifiable", $entityData);
$eventManager->triggerEvent("vtiger.entity.beforesave", $entityData);
$eventManager->triggerEvent("vtiger.entity.beforesave.final", $entityData);
if (!$VTIGER_BULK_SAVE_MODE) {
$eventManager->triggerEvent("vtiger.entity.beforesave.modifiable", $entityData);
$eventManager->triggerEvent("vtiger.entity.beforesave", $entityData);
$eventManager->triggerEvent("vtiger.entity.beforesave.final", $entityData);
}
}
}
......@@ -377,13 +432,18 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
* @param <type> $eventManager
*/
public function triggerAfterSaveEvents($element, $eventManager) {
global $VTIGER_BULK_SAVE_MODE;
if ($eventManager) {
$focusObj = $this->constructFocusObject($element);
if (isset($element['new']) && $element['new'] == true) {
$focusObj->newDelta = true;
}
$entityData = VTEntityData::fromCRMEntity($focusObj);
if (!$VTIGER_BULK_SAVE_MODE) {
$eventManager->triggerEvent("vtiger.entity.aftersave", $entityData);
$eventManager->triggerEvent("vtiger.entity.aftersave.final", $entityData);
$eventManager->triggerEvent("vtiger.entity.aftersave", $entityData);
$eventManager->triggerEvent("vtiger.entity.aftersave.final", $entityData);
}
}
}
......@@ -420,7 +480,7 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$result = $this->pearDB->pquery('SELECT * FROM vtiger_inventorychargesrel WHERE recordid = ?', array($id));
$rowData = $this->pearDB->fetch_array($result);
if ($rowData['charges']) {
if (isset($rowData['charges']) && $rowData['charges']) {
$allCharges = getAllCharges();
$shippingTaxes = array();
$allShippingTaxes = getAllTaxes('all', 'sh');
......
......@@ -92,7 +92,7 @@ class VtigerLineItemMeta extends VtigerCRMActorMeta {
if(in_array($fieldName,$mandatoryFieldList)){
$typeOfData = $fieldType.'~M';
}else if(($dbField->not_null == 1 && $fieldName != 'incrementondel'
&& $dbField->primary_key != 1) || $dbField->unique_key == 1){
&& $dbField->primary_key != 1) || (property_exists($dbField, 'unique_key') && $dbField->unique_key == 1)) {
$typeOfData = $fieldType.'~M';
}else{
$typeOfData = $fieldType.'~O';
......@@ -105,4 +105,4 @@ class VtigerLineItemMeta extends VtigerCRMActorMeta {
}
}
?>
\ No newline at end of file
?>
<?php
/*+*******************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
/* +**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.1
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*
*********************************************************************************/
* ***********************************************************************************/
require_once "include/Webservices/VtigerActorOperation.php";
require_once "include/Webservices/LineItem/VtigerInventoryOperation.php";
......@@ -25,13 +24,14 @@ require_once 'include/utils/InventoryUtils.php';
/**
* Description of VtigerLineItemOperation
*/
class VtigerLineItemOperation extends VtigerActorOperation {
class VtigerLineItemOperation extends VtigerActorOperation {
private static $lineItemCache = array();
private $taxType = null;
private $Individual = 'Individual';
private $Group = 'Group';
private $newId = null;
private $taxList = null;
private $inActiveTaxList = null;
private static $parentCache = array();
public function __construct($webserviceObject,$user,$adb,$log) {
......@@ -41,12 +41,12 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$this->pearDB = $adb;
$this->entityTableName = $this->getActorTables();
if($this->entityTableName === null){
throw new WebServiceException(WebServiceErrorCode::$UNKOWNENTITY,
"Entity is not associated with any tables");
throw new WebServiceException(WebServiceErrorCode::$UNKOWNENTITY, 'Entity is not associated with any tables');
}
$this->meta = new VtigerLineItemMeta($this->entityTableName,$webserviceObject,$adb,$user);
$this->moduleFields = null;
$this->taxList = array();
$this->inActiveTaxList = array();
}
protected function getNextId($elementType, $element) {
......@@ -77,34 +77,39 @@ class VtigerLineItemOperation extends VtigerActorOperation {
* @throws WebServiceException - Database error
*/
public function getAllLineItemForParent($parentId){
if (is_array($parentId)) {
$result = null;
if (!is_array($parentId)) {
$parentId = array($parentId);
}
$query = "SELECT vtiger_crmentity.label AS productname,vtiger_crmentity.setype as entitytype, {$this->entityTableName}.* FROM {$this->entityTableName}
LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_inventoryproductrel.productid
WHERE id IN (". generateQuestionMarks($parentId) .")";
$result = null;
$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;
$id = vtws_getId($this->meta->getEntityId(), $element['lineitem_id']);
$element = DataTransform::filterAndSanitize($element,$this->meta);
$element['id'] = $id;
$lineItemList[] = $element;
}
if (!is_array($parentId)) {
$parentId = array($parentId);
}
$query = "SELECT vtiger_crmentity.label AS productname,vtiger_crmentity.setype AS entitytype,vtiger_crmentity.deleted AS deleted, {$this->entityTableName}.*
FROM {$this->entityTableName}
LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_inventoryproductrel.productid
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) {
$rowElement = $element = $this->pearDB->query_result_rowdata($result,$i);
$element['parent_id'] = $parentId;
$productName = $element['productname'];
$entityType = $element['entitytype'];
$id = vtws_getId($this->meta->getEntityId(), $element['lineitem_id']);
$element = DataTransform::filterAndSanitize($element,$this->meta);
$element['product_name'] = $productName;
$element['entity_type'] = $entityType;
$element['id'] = $id;
$element['deleted'] = $rowElement['deleted'];
$lineItemList[] = $element;
}
return $lineItemList;
}
return $lineItemList;
}
public function _create($elementType, $element){
......@@ -151,7 +156,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
list($typeId,$recordId) = vtws_getIdComponents($element['productid']);
$productTaxInfo = $this->getProductTaxList($recordId);
}
if(count($productTaxInfo) == 0 && strcasecmp($parent['hdnTaxType'], $this->Individual) !==0) {
if(php7_count($productTaxInfo) == 0 && strcasecmp($parent['hdnTaxType'], $this->Individual) !==0) {
$meta = $this->getMeta();
$moduleFields = $meta->getModuleFields();
foreach ($moduleFields as $fieldName=>$field) {
......@@ -164,28 +169,33 @@ class VtigerLineItemOperation extends VtigerActorOperation {
}
private function updateTaxes($createdElement){
if(count($this->taxList) > 0 ) {
if (php7_count($this->taxList) > 0 || (is_array($this->inActiveTaxList) && php7_count($this->inActiveTaxList) > 0)) {
$taxList = $this->taxList;
if (is_array($this->inActiveTaxList) && php7_count($this->inActiveTaxList) > 0) {
$taxList = array_merge($taxList, $this->inActiveTaxList);
}
$id = vtws_getIdComponents($createdElement['id']);
$id = $id[1];
$sql = 'UPDATE vtiger_inventoryproductrel set ';
$sql .= implode('=?,',array_keys($this->taxList));
$sql .= implode('=?,',array_keys($taxList));
$sql .= '=? WHERE lineitem_id = ?';
$params = array();
foreach ($this->taxList as $taxInfo) {
foreach ($taxList as $taxInfo) {
$params[] = $taxInfo['percentage'];
}
$params[] = $id;
$result = null;
$transactionSuccessful = vtws_runQueryAsTransaction($sql,$params,$result);
if(!$transactionSuccessful){
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
"Database error while performing required operation");
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, 'Database error while performing required operation');
}
}
}
private function initTax($element, $parent) {
$this->taxList = array();
$this->inActiveTaxList = array();
$allTaxes = getAllTaxes();
if (!empty($element['parent_id'])) {
$this->taxType = $parent['hdnTaxType'];
}
......@@ -196,13 +206,14 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$meta = $this->getMeta();
$moduleFields = $meta->getModuleFields();
$productTaxList = $this->getProductTaxList($productId);
if (count($productTaxList) > 0) {
if (php7_count($productTaxList) > 0) {
$this->providedTaxList = array();
foreach ($moduleFields as $fieldName => $field) {
if (preg_match('/tax\d+/', $fieldName) != 0) {
if (isset($element[$fieldName])) {
$found = true;
if (is_array($productTaxList[$fieldName])) {
$this->taxList[$fieldName] = array(
$this->providedTaxList[$fieldName] = array(
'label' => $field->getFieldLabelKey(),
'percentage' => $element[$fieldName]
);
......@@ -210,6 +221,10 @@ class VtigerLineItemOperation extends VtigerActorOperation {
}
}
}
if ($found) {
$this->taxList = $this->providedTaxList;
}
} elseif ($found == false) {
array_merge($this->taxList, $productTaxList);
}
......@@ -229,15 +244,21 @@ class VtigerLineItemOperation extends VtigerActorOperation {
}
}
if(!$found) {
$availableTaxes = getAllTaxes('available');
foreach($availableTaxes as $taxInfo){
$this->taxList[$taxInfo['taxname']] = array(
'label' => $field->getFieldLabelKey(),
'percentage' => $taxInfo['percentage']
);
foreach ($allTaxes as $taxInfo) {
if ($taxInfo['deleted'] == '0') {
$this->taxList[$taxInfo['taxname']] = array(
'label' => $field->getFieldLabelKey(),
'percentage' => $taxInfo['percentage']
);
}
}
}
}
foreach ($allTaxes as $taxInfo) {
if ($taxInfo['deleted'] == '1' && !array_key_exists($taxInfo['taxname'], $this->taxList)) {
$this->inActiveTaxList[$taxInfo['taxname']] = array('percentage' => NULL);
}
}
$this->taxList;
}
......@@ -261,7 +282,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
vglobal('updateInventoryProductRel_deduct_stock', false);
$sequenceNo = 1;
foreach ($lineItemList as $lineItem) {
$lineItem['parent_id'] = $parent['id'];
$lineItem['parent_id'] = $parent['id'];
$lineItem['sequence_no'] = $sequenceNo++;
$this->initTax($lineItem, $parent);
$id = vtws_getIdComponents($lineItem['parent_id']);
......@@ -279,11 +300,12 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$parentId = $parentId[1];
$parent = $this->getParentById($element['parent_id']);
if(empty($element['listprice'])){
if (!isset($element['listprice']) && $element['listprice'] == '') {
$productId = vtws_getIdComponents($element['productid']);
$productId = $productId[1];
$element['listprice'] = $this->getProductPrice($productId);
}
$element = $this->calculateNetprice($element);
$id = vtws_getIdComponents($element['parent_id']);
$this->newId = $id[1];
$createdLineItem = $this->_create($elementType, $element);
......@@ -292,6 +314,39 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$this->setCache($parentId, $updatedLineItemList);
return $createdLineItem;
}
public function calculateNetprice($element) {
global $current_user;
$productId = $element['parent_id'];
$parent = $this->getParentById($productId);
$listPrice = $element['listprice'];
$quantity = $element['quantity'];
$discount_amount = $element['discount_amount'];
$discount_percent = $element['discount_percent'];
$productTotal = $listPrice * $quantity;
$total_after_discount = $productTotal;
if (!empty($discount_amount)) {
$total_after_discount -= $discount_amount;
}
if (!empty($discount_percent)) {
$percentage_discount = ($productTotal * $discount_percent) / 100;
$total_after_discount -= $percentage_discount;
}
$this->initTax($element, $parent);
if (strcasecmp($parent['hdnTaxType'], $this->Individual) === 0) {
$tax_net = 0;
foreach ($this->taxList as $taxname => $taxArray) {
$taxValue = $taxArray['percentage'];
$tax_net += ($taxValue * $total_after_discount) / 100;
}
}
$net_price = number_format(($total_after_discount + $tax_net), getCurrencyDecimalPlaces($current_user), '.', '');
$element['netprice'] = $net_price;
return $element;
}
public function retrieve($id) {
$element = parent::retrieve($id);
......@@ -312,7 +367,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$parent = $this->getParentById($element['parent_id']);
$location = $this->getLocationById($lineItemList, $element['id']);
if($location === false){
throw new WebserviceException('UNKOWN_CHILD','given line item is not child of parent');
throw new WebserviceException('UNKOWN_CHILD','given line item is not child of parent');
}
if(empty($element['listprice'])){
$productId = vtws_getIdComponents($element['productid']);
......@@ -328,7 +383,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$this->newId = $id[1];
$updatedLineItemList[] = $this->_create($elementType, $lineItem);
if($element == $lineItem){
$createdElement = $updatedLineItemList[count($updatedLineItemList) - 1];
$createdElement = $updatedLineItemList[php7_count($updatedLineItemList) - 1];
}
}
$this->setCache($parentId, $updatedLineItemList);
......@@ -344,8 +399,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$result = null;
$transactionSuccessful = vtws_runQueryAsTransaction($sql,$params,$result);
if(!$transactionSuccessful){
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
"Database error while performing required operation");
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, 'Database error while performing required operation');
}
$price = 0;
$it = new SqlResultIterator($db, $result);
......@@ -430,8 +484,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
if(strcasecmp($parent['hdnTaxType'], $this->Individual) ===0){
$taxAmountsList = array();
foreach ($this->taxList as $taxName => $taxInfo) {
$taxAmountsList[$allTaxes[$taxName]['taxid']] = array( 'percentage' => $taxInfo['percentage'],
'amount' => ($lineItemTotal * $taxInfo['percentage']) / 100);
$taxAmountsList[$allTaxes[$taxName]['taxid']] = array('percentage' => $taxInfo['percentage'], 'amount' => ($lineItemTotal * $taxInfo['percentage']) / 100);
}
foreach ($taxAmountsList as $taxId => $taxInfo) {
......@@ -445,6 +498,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$parent['hdnSubTotal'] += $taxInfo['amount'];
}
$individualPreTaxTotal += $lineItemTotal;
}
}
......@@ -456,9 +510,20 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$discount = 0;
}
$parent['pre_tax_total'] = $total = $parent['hdnSubTotal'] - $discount + $parent['hdnS_H_Amount'];
if ($parent['hdnTaxType'] === 'individual') {
$parent['pre_tax_total'] = $individualPreTaxTotal - $discount + $parent['hdnS_H_Amount'];
}
$taxTotal = $parent['hdnSubTotal'] - $discount;
if(strcasecmp($parent['hdnTaxType'], $this->Individual) !==0){
$this->initTax($createdElement, $parent);
if (strcasecmp($parent['hdnTaxType'], $this->Individual) !== 0) {
$newTaxList = array();
foreach ($createdElement as $element) {
$this->initTax($element, $parent);
$newTaxList[] = $this->taxList;
}
if ($newTaxList) {
$this->taxList = $newTaxList[0];
}
$taxAmountsList = array();
foreach ($this->taxList as $taxName => $taxInfo) {
$taxAmountsList[$allTaxes[$taxName]['taxid']] = array('percentage' => $taxInfo['percentage'], 'amount' => ($taxTotal * $taxInfo['percentage']) / 100);
......@@ -470,7 +535,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
foreach ($compoundOn[$taxId] as $comTaxId) {
$amount += $taxAmountsList[$comTaxId]['amount'];
}
$taxAmountsList[$taxId]['amount'] = ($amount * $taxInfo['percentage']) / 100;
$taxInfo['amount'] = $taxAmountsList[$taxId]['amount'] = ($amount * $taxInfo['percentage']) / 100;
}
$taxAmount += $taxInfo['amount'];
......@@ -501,7 +566,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$amount = $calculatedOn = $chargeInfo['value'];
if ($allShippingTaxes[$shTaxId]['method'] === 'Compound') {
foreach ($allShippingTaxes[$shTaxId]['compoundon'] as $comShTaxId) {
$calculatedOn += ($amount * $charges[$comShTaxId]) / 100;
$calculatedOn += ($amount * $chargeTaxes[$comShTaxId]) / 100;
}
}
......@@ -522,10 +587,9 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$parentInstance->tab_name_index[$parentInstance->table_name].'=?';
$params = array($parent['hdnSubTotal'],$parent['hdnGrandTotal'],$parent['pre_tax_total'],$parentId);
$transactionSuccessful = vtws_runQueryAsTransaction($sql,$params,$result);
$this->resetCacheForParent($parent['id']);
$this->setParent($parent['id'], $parent);
if(!$transactionSuccessful){
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
"Database error while performing required operation");
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, 'Database error while performing required operation');
}
}
......@@ -536,8 +600,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$result = null;
$transactionSuccessful = vtws_runQueryAsTransaction($sql,$params,$result);
if(!$transactionSuccessful){
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
"Database error while performing required operation");
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, 'Database error while performing required operation');
}
$it = new SqlResultIterator($db, $result);
$this->taxList = array();
......@@ -557,8 +620,7 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$result = null;
$transactionSuccessful = vtws_runQueryAsTransaction($sql,$params,$result);
if(!$transactionSuccessful){
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
"Database error while performing required operation");
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, 'Database error while performing required operation');
}
$it = new SqlResultIterator($db, $result);
$this->taxList = array();
......@@ -594,14 +656,20 @@ class VtigerLineItemOperation extends VtigerActorOperation {
}
public function getParentById($parentId){
if(empty(self::$parentCache[$parentId])){
return vtws_retrieve($parentId, $this->user);
} else {
return self::$parentCache[$parentId];
if (empty(self::$parentCache[$parentId])) {
self::$parentCache[$parentId] = Vtiger_Functions::jsonEncode(vtws_retrieve($parentId, $this->user));
}
return json_decode(self::$parentCache[$parentId], true);
}
public function setParent($parentId, $parent) {
if (is_array($parent) || is_object($parent)) {
$parent = Vtiger_Functions::jsonEncode($parent);
}
self::$parentCache[$parentId] = $parent;
}
function setCache($parentId, $updatedList) {
function setCache($parentId, $updatedList) {
self::$lineItemCache[$parentId] = $updatedList;
}
......@@ -626,9 +694,9 @@ class VtigerLineItemOperation extends VtigerActorOperation {
unset($describe['fields'][$key]);
}
}
// unset will retain array index in the result, we should remove
$describe['fields'] = array_values($describe['fields']);
// unset will retain array index in the result, we should remove
$describe['fields'] = array_values($describe['fields']);
return $describe;
}
}
?>
\ No newline at end of file
?>
......@@ -31,7 +31,9 @@
if($user->status != 'Inactive'){
return $user;
}
throw new WebServiceException(WebServiceErrorCode::$AUTHREQUIRED,'Given user is inactive');
// Finer exception message could be handy to enumeration attacks - so normalize it.
//throw new WebServiceException(WebServiceErrorCode::$AUTHREQUIRED,'Given user is inactive');
throw new WebServiceException(WebServiceErrorCode::$INVALIDUSERPWD,"Invalid username or password");
}
function vtws_getActiveToken($userId){
......@@ -60,4 +62,4 @@
return null;
}
?>
\ No newline at end of file
?>
......@@ -15,7 +15,7 @@
static $types = array();
if(!empty($fieldTypeList)) {
$fieldTypeList = array_map(strtolower, $fieldTypeList);
$fieldTypeList = array_map('strtolower', $fieldTypeList);
sort($fieldTypeList);
$fieldTypeString = implode(',', $fieldTypeList);
} else {
......@@ -135,4 +135,4 @@
return $types[$user->id][$fieldTypeString];
}
?>
\ No newline at end of file
?>
......@@ -9,7 +9,7 @@
*************************************************************************************/
function setBuiltIn($json){
$json->useBuiltinEncoderDecoder = true;
Zend_Json::$useBuiltinEncoderDecoder = true;
}
class OperationManager{
......@@ -35,9 +35,8 @@
private $preLogin;
private $operationId;
private $operationParams;
function OperationManager($adb,$operationName,$format, $sessionManager){
function __construct($adb,$operationName,$format, $sessionManager)
{
$this->format = strtolower($format);
$this->sessionManager = $sessionManager;
$this->formatObjects = array();
......@@ -58,6 +57,13 @@
$this->inParamProcess["encoded"] = &$this->formatObjects[$this->format]["decode"];
$this->fillOperationDetails($operationName);
}
function OperationManager($adb,$operationName,$format, $sessionManager){
// PHP4-style constructor.
// This will NOT be invoked, unless a sub-class that extends `foo` calls it.
// In that case, call the new-style constructor to keep compatibility.
self::__construct($adb,$operationName,$format, $sessionManager);
}
function isPreLoginOperation(){
return $this->preLogin == 1;
......@@ -126,10 +132,10 @@
}
function handleType($type,$value){
$result;
$value = stripslashes($value);
$result = null;
$value = $value ? stripslashes($value) : "";
$type = strtolower($type);
if($this->inParamProcess[$type]){
if(isset($this->inParamProcess[$type]) && $this->inParamProcess[$type]){
$result = call_user_func($this->inParamProcess[$type],$value);
}else{
$result = $value;
......@@ -142,9 +148,18 @@
try{
$operation = strtolower($this->operationName);
if(!$this->preLogin){
$params[] = $user;
$params["user"] = $user;
return call_user_func_array($this->handlerMethod,$params);
}else{
/* PHP 8.x fix to match target handler arguments (named parameter) */
if ($this->handlerMethod == "vtws_login") {
if (isset($params["accessKey"])) {
$params["pwd"] = $params["accessKey"];
unset($params["accessKey"]);
}
}
$userDetails = call_user_func_array($this->handlerMethod,$params);
if(is_array($userDetails)){
return $userDetails;
......@@ -154,10 +169,27 @@
$webserviceObject = VtigerWebserviceObject::fromName($adb,"Users");
$userId = vtws_getId($webserviceObject->getEntityId(),$userDetails->id);
$vtigerVersion = vtws_getVtigerVersion();
$resp = array("sessionName"=>$this->sessionManager->getSessionId(),"userId"=>$userId,"version"=>$API_VERSION,"vtigerVersion"=>$vtigerVersion);
return $resp;
$userInfo = array(
'username' => $userDetails->user_name,
'first_name' => $userDetails->first_name,
'last_name' => $userDetails->last_name,
'email' => $userDetails->email1,
'time_zone' => $userDetails->time_zone,
'hour_format' => $userDetails->hour_format,
'date_format' => $userDetails->date_format,
'is_admin' => $userDetails->is_admin,
'call_duration' => $userDetails->callduration,
'other_event_duration' => $userDetails->othereventduration,
'sessionName'=>$this->sessionManager->getSessionId(),
'userId'=>$userId,
'version'=>$API_VERSION,
'vtigerVersion'=>$vtigerVersion
);
return $userInfo;
}
}
} catch (DuplicateException $e) {
throw $e;
}catch(WebServiceException $e){
throw $e;
}catch(Exception $e){
......@@ -178,4 +210,4 @@
}
?>
\ No newline at end of file
?>
......@@ -14,42 +14,43 @@ class VTWS_PreserveGlobal{
static function preserveGlobal($name,$value){
//$name store the name of the global.
global $$name;
global ${$name};
//To not push null value . Ideally we should not push null value for any name
//But current user null is dangerous so we are checking for only current user
if(!empty($$name) || $name != 'current_user') {
if(!is_array(VTWS_PreserveGlobal::$globalData[$name])){
if(!empty(${$name}) || $name != 'current_user') {
if(!isset(VTWS_PreserveGlobal::$globalData[$name]) ||
!is_array(VTWS_PreserveGlobal::$globalData[$name])){
VTWS_PreserveGlobal::$globalData[$name] = array();
}
VTWS_PreserveGlobal::$globalData[$name][] = $$name;
VTWS_PreserveGlobal::$globalData[$name][] = ${$name};
}
$$name = $value;
return $$name;
${$name} = $value;
return ${$name};
}
static function restore($name){
//$name store the name of the global.
global $$name;
global ${$name};
if(is_array(VTWS_PreserveGlobal::$globalData[$name]) && count(VTWS_PreserveGlobal::$globalData[$name]) > 0){
$$name = array_pop(VTWS_PreserveGlobal::$globalData[$name]);
if(is_array(VTWS_PreserveGlobal::$globalData[$name]) && php7_count(VTWS_PreserveGlobal::$globalData[$name]) > 0){
${$name} = array_pop(VTWS_PreserveGlobal::$globalData[$name]);
}
$$name;
${$name};
}
static function getGlobal($name){
global $$name;
return VTWS_PreserveGlobal::preserveGlobal($name,$$name);
global ${$name};
return VTWS_PreserveGlobal::preserveGlobal($name,${$name});
}
static function flush(){
foreach (VTWS_PreserveGlobal::$globalData as $name => $detail) {
//$name store the name of the global.
global $$name;
if(is_array(VTWS_PreserveGlobal::$globalData[$name]) && count(VTWS_PreserveGlobal::$globalData[$name]) > 0) {
$$name = array_pop(VTWS_PreserveGlobal::$globalData[$name]);
global ${$name};
if(is_array(VTWS_PreserveGlobal::$globalData[$name]) && php7_count(VTWS_PreserveGlobal::$globalData[$name]) > 0) {
${$name} = array_pop(VTWS_PreserveGlobal::$globalData[$name]);
}
}
}
......
......@@ -10,7 +10,7 @@
require_once("include/Webservices/QueryParser.php");
function vtws_query($q,$user){
function vtws_query($query,$user){
static $vtws_query_cache = array();
......@@ -19,10 +19,10 @@
// Cache the instance for re-use
$moduleRegex = "/[fF][rR][Oo][Mm]\s+([^\s;]+)/";
$moduleName = '';
if(preg_match($moduleRegex, $q, $m)) $moduleName = trim($m[1]);
if(preg_match($moduleRegex, $query, $m)) $moduleName = trim($m[1]);
if(!isset($vtws_create_cache[$moduleName]['webserviceobject'])) {
$webserviceObject = VtigerWebserviceObject::fromQuery($adb,$q);
$webserviceObject = VtigerWebserviceObject::fromQuery($adb,$query);
$vtws_query_cache[$moduleName]['webserviceobject'] = $webserviceObject;
} else {
$webserviceObject = $vtws_query_cache[$moduleName]['webserviceobject'];
......@@ -61,9 +61,9 @@
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED,"Permission to read is denied");
}
$result = $handler->query($q);
$result = $handler->query($query);
VTWS_PreserveGlobal::flush();
return $result;
}
?>
\ No newline at end of file
?>
......@@ -19,11 +19,19 @@
private $hasError ;
private $error ;
private $user;
function Parser($user, $q){
function __construct($user, $q)
{
$this->query = $q;
$this->out = array();
$this->hasError = false;
$this->user = $user;
$this->user = $user;
}
function Parser($user, $q){
// PHP4-style constructor.
// This will NOT be invoked, unless a sub-class that extends `foo` calls it.
// In that case, call the new-style constructor to keep compatibility.
self::__construct($user, $q);
}
function parse(){
......
......@@ -24,7 +24,7 @@ function vtws_relatedtypes($elementType, $user) {
$sql = "SELECT vtiger_relatedlists.label, vtiger_tab.name, vtiger_tab.isentitytype FROM vtiger_relatedlists
INNER JOIN vtiger_tab ON vtiger_tab.tabid=vtiger_relatedlists.related_tabid
WHERE vtiger_relatedlists.tabid=? AND vtiger_tab.presence = 0";
WHERE vtiger_relatedlists.tabid=? AND vtiger_tab.presence = 0 AND vtiger_relatedlists.presence = 0";
$params = array($tabid);
$rs = $adb->pquery($sql, $params);
......
......@@ -78,7 +78,7 @@
$meta->isUpdateMandatoryFields($element);
$ownerFields = $meta->getOwnerFields();
if(is_array($ownerFields) && sizeof($ownerFields) >0){
if(is_array($ownerFields) && php7_sizeof($ownerFields) >0){
foreach($ownerFields as $ownerField){
if(isset($element[$ownerField]) && $element[$ownerField]!==null &&
!$meta->hasAssignPrivilege($element[$ownerField])){
......
......@@ -26,8 +26,8 @@
private $sessionVar = "__SessionExists";
private $error ;
function SessionManager(){
function __construct()
{
global $maxWebServiceSessionLifeSpan, $maxWebServiceSessionIdleTime;
$now = time();
......@@ -42,6 +42,13 @@
//otherwise it subtracts the time from previous time
HTTP_Session2::setIdle($this->idleLife, true);
}
function SessionManager(){
// PHP4-style constructor.
// This will NOT be invoked, unless a sub-class that extends `foo` calls it.
// In that case, call the new-style constructor to keep compatibility.
self::__construct();
}
function isValid(){
......