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 1411 additions and 371 deletions
<?php
/* +**********************************************************************************
* 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 Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
* ***********************************************************************************/
require_once 'include/Webservices/Retrieve.php';
require_once 'include/Webservices/Create.php';
require_once 'include/Webservices/Delete.php';
require_once 'include/Webservices/DescribeObject.php';
require_once 'vendor/autoload.php';
vimport('includes.runtime.Globals');
vimport('includes.runtime.BaseModel');
function vtws_convertPotential($entityvalues, $user) {
global $adb, $log;
if (empty($entityvalues['assignedTo'])) {
$entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id);
}
if (empty($entityvalues['transferRelatedRecordsTo'])) {
$entityvalues['transferRelatedRecordsTo'] = 'Project';
}
$potentialObject = VtigerWebserviceObject::fromName($adb, 'Potentials');
$handlerPath = $potentialObject->getHandlerPath();
$handlerClass = $potentialObject->getHandlerClass();
require_once $handlerPath;
$potentialHandler = new $handlerClass($potentialObject, $user, $adb, $log);
$potentialInfo = vtws_retrieve($entityvalues['potentialId'], $user);
$sql = 'SELECT converted FROM vtiger_potential WHERE converted=1 AND potentialid=?';
$potentialIdComponents = vtws_getIdComponents($entityvalues['potentialId']);
$result = $adb->pquery($sql, array($potentialIdComponents[1]));
if ($result === false) {
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_'.WebServiceErrorCode::$DATABASEQUERYERROR));
}
$rowCount = $adb->num_rows($result);
if ($rowCount > 0) {
throw new WebServiceException(WebServiceErrorCode::$POTENTIAL_ALREADY_CONVERTED, 'Potential is already converted');
}
$entityIds = array();
$availableModules = array('Project');
if (!(($entityvalues['entities']['Project']['create']))) {
return null;
}
foreach ($availableModules as $entityName) {
if ($entityvalues['entities'][$entityName]['create']) {
$entityvalue = $entityvalues['entities'][$entityName];
$entityObject = VtigerWebserviceObject::fromName($adb, $entityvalue['name']);
$handlerPath = $entityObject->getHandlerPath();
$handlerClass = $entityObject->getHandlerClass();
require_once $handlerPath;
$entityHandler = new $handlerClass($entityObject, $user, $adb, $log);
$entityObjectValues = array();
$entityObjectValues['assigned_user_id'] = $entityvalues['assignedTo'];
$entityObjectValues = vtws_populateConvertPotentialEntities($entityvalue, $entityObjectValues, $entityHandler, $potentialHandler, $potentialInfo);
try {
$entityObjectValues['isconvertedfrompotential'] = 1;
$entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user);
$entityIds[$entityName] = $entityRecord['id'];
} catch (DuplicateException $e) {
throw $e;
} catch (Exception $e) {
throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE, $e->getMessage().' : '.$entityvalue['name']);
}
}
}
try {
vtws_convertPotentialTransferHandler($potentialIdComponents, $entityIds, $entityvalues);
vtws_updateConvertPotentialStatus($entityIds, $entityvalues['potentialId'], $user);
} catch (Exception $e) {
foreach ($entityIds as $entity => $id) {
vtws_delete($id, $user);
}
return null;
}
return $entityIds;
}
/*
* populate the entity fields with the Potential info.
* if mandatory field is not provided populate with '????'
* returns the entity array.
*/
function vtws_populateConvertPotentialEntities($entityvalue, $entity, $entityHandler, $potentialHandler, $potentialinfo) {
global $adb, $log;
$entityName = $entityvalue['name'];
$sql = 'SELECT * FROM vtiger_convertpotentialmapping';
$result = $adb->pquery($sql, array());
if ($adb->num_rows($result)) {
$column = 'potentialfid';
if ($entityName == 'Project') {
$column = 'projectfid';
}
$potentialFields = $potentialHandler->getMeta()->getModuleFields();
$entityFields = $entityHandler->getMeta()->getModuleFields();
$row = $adb->fetch_array($result);
$count = 1;
do {
$entityField = vtws_getFieldfromFieldId($row[$column], $entityFields);
if ($entityField == null) {
//user doesn't have access so continue.TODO update even if user doesn't have access
continue;
}
$potentialField = vtws_getFieldfromFieldId($row['potentialfid'], $potentialFields);
if ($potentialField == null) {
//user doesn't have access so continue.TODO update even if user doesn't have access
continue;
}
$potentialFieldName = $potentialField->getFieldName();
$entityFieldName = $entityField->getFieldName();
$entity[$entityFieldName] = $potentialinfo[$potentialFieldName];
$count++;
} while ($row = $adb->fetch_array($result));
foreach ($entityFields as $fieldName => $fieldModel) {
if (!empty($entityFields[$fieldName]) && $fieldModel->getDefault() && $fieldName != 'isconvertedfrompotential') {
if (!isset($entityvalue[$fieldName]) && empty($entity[$fieldName])) {
$entityvalue[$fieldName] = $fieldModel->getDefault();
}
}
}
foreach ($entityvalue as $fieldname => $fieldvalue) {
if (!empty($fieldvalue)) {
$entity[$fieldname] = $fieldvalue;
}
}
$entity['potentialid'] = $potentialinfo['id'];
$entity = vtws_validateConvertEntityMandatoryValues($entity, $entityHandler, $entityName);
}
return $entity;
}
/**
* function to handle the transferring of related records for Potential
* @param <Array> $potentialIdComponents - Exploded Webservice Id
* @param <Array> $entityIds - Converted Project Id
* @param <Array> $entityvalues - Mapped Potential and Project values
* @return <Boolean>
*/
function vtws_convertPotentialTransferHandler($potentialIdComponents, $entityIds, $entityvalues) {
try {
$entityidComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]);
vtws_transferPotentialRelatedRecords($potentialIdComponents[1], $entityidComponents[1], $entityvalues['transferRelatedRecordsTo']);
} catch (Exception $e) {
return false;
}
return true;
}
function vtws_updateConvertPotentialStatus($entityIds, $potentialId, $user) {
global $adb, $log;
$potentialIdComponents = vtws_getIdComponents($potentialId);
if ($entityIds['Project'] != '' || $entityIds['Contacts'] != '') {
$sql = 'UPDATE vtiger_potential SET converted=1 where potentialid=?';
$result = $adb->pquery($sql, array($potentialIdComponents[1]));
if ($result === false) {
throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_MARK_POTENTIAL_CONVERTED, 'Failed mark potential converted');
}
//update the modifiedtime and modified by information for the record
$potentialModifiedTime = $adb->formatDate(date('Y-m-d H:i:s'), true);
$crmentityUpdateSql = 'UPDATE vtiger_crmentity SET modifiedtime=?, modifiedby=? WHERE crmid=?';
$adb->pquery($crmentityUpdateSql, array($potentialModifiedTime, $user->id, $potentialIdComponents[1]));
}
}
......@@ -10,14 +10,21 @@
function vtws_create($elementType, $element, $user) {
$types = vtws_listtypes(null, $user);
if (!in_array($elementType, $types['types'])) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation is denied");
}
$types = vtws_listtypes(null, $user);
if (!in_array($elementType, $types['types'])) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation is denied");
}
global $log, $adb, $app_strings;
global $log, $adb;
//setting $app_strings
if(empty($app_strings)) {
$currentLanguage = Vtiger_Language_Handler::getLanguage();
$moduleLanguageStrings = Vtiger_Language_Handler::getModuleStringsFromFile($currentLanguage);
$app_strings = $moduleLanguageStrings['languageStrings'];
}
// Cache the instance for re-use
// Cache the instance for re-use
if(!isset($vtws_create_cache[$elementType]['webserviceobject'])) {
$webserviceObject = VtigerWebserviceObject::fromName($adb,$elementType);
$vtws_create_cache[$elementType]['webserviceobject'] = $webserviceObject;
......@@ -26,60 +33,59 @@ function vtws_create($elementType, $element, $user) {
}
// END
$handlerPath = $webserviceObject->getHandlerPath();
$handlerClass = $webserviceObject->getHandlerClass();
$handlerPath = $webserviceObject->getHandlerPath();
$handlerClass = $webserviceObject->getHandlerClass();
require_once $handlerPath;
require_once $handlerPath;
$handler = new $handlerClass($webserviceObject, $user, $adb, $log);
$meta = $handler->getMeta();
if ($meta->hasCreateAccess() !== true) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to write is denied");
}
$handler = new $handlerClass($webserviceObject, $user, $adb, $log);
$meta = $handler->getMeta();
if ($meta->hasCreateAccess() !== true) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to write is denied");
}
$referenceFields = $meta->getReferenceFieldDetails();
foreach ($referenceFields as $fieldName => $details) {
if (isset($element[$fieldName]) && strlen($element[$fieldName]) > 0) {
$ids = vtws_getIdComponents($element[$fieldName]);
$elemTypeId = $ids[0];
$elemId = $ids[1];
$referenceObject = VtigerWebserviceObject::fromId($adb, $elemTypeId);
if (!in_array($referenceObject->getEntityName(), $details)) {
throw new WebServiceException(WebServiceErrorCode::$REFERENCEINVALID,
"Invalid reference specified for $fieldName");
}
$referenceFields = $meta->getReferenceFieldDetails();
foreach ($referenceFields as $fieldName => $details) {
if (isset($element[$fieldName]) && strlen($element[$fieldName]) > 0) {
$ids = vtws_getIdComponents($element[$fieldName]);
$elemTypeId = $ids[0];
$elemId = $ids[1];
$referenceObject = VtigerWebserviceObject::fromId($adb, $elemTypeId);
if (!in_array($referenceObject->getEntityName(), $details)) {
throw new WebServiceException(WebServiceErrorCode::$REFERENCEINVALID,
"Invalid reference specified for $fieldName");
}
if ($referenceObject->getEntityName() == 'Users') {
if(!$meta->hasAssignPrivilege($element[$fieldName])) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Cannot assign record to the given user");
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Cannot assign record to the given user");
}
}
if (!in_array($referenceObject->getEntityName(), $types['types']) && $referenceObject->getEntityName() != 'Users') {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED,
"Permission to access reference type is denied" . $referenceObject->getEntityName());
}
} else if ($element[$fieldName] !== NULL) {
unset($element[$fieldName]);
}
}
if (!in_array($referenceObject->getEntityName(), $types['types']) && $referenceObject->getEntityName() != 'Users') {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED,
"Permission to access reference type is denied" . $referenceObject->getEntityName());
}
} else if (array_key_exists($fieldName, $element) && $element[$fieldName] !== NULL) {
unset($element[$fieldName]);
}
}
if ($meta->hasMandatoryFields($element)) {
if ($meta->hasMandatoryFields($element)) {
$ownerFields = $meta->getOwnerFields();
if (is_array($ownerFields) && sizeof($ownerFields) > 0) {
foreach ($ownerFields as $ownerField) {
if (isset($element[$ownerField]) && $element[$ownerField] !== null &&
!$meta->hasAssignPrivilege($element[$ownerField])) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Cannot assign record to the given user");
}
}
}
$entity = $handler->create($elementType, $element);
VTWS_PreserveGlobal::flush();
return $entity;
} else {
$ownerFields = $meta->getOwnerFields();
if (is_array($ownerFields) && php7_sizeof($ownerFields) > 0) {
foreach ($ownerFields as $ownerField) {
if (isset($element[$ownerField]) && $element[$ownerField] !== null &&
!$meta->hasAssignPrivilege($element[$ownerField])) {
throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Cannot assign record to the given user");
}
}
}
$entity = $handler->create($elementType, $element);
VTWS_PreserveGlobal::flush();
return $entity;
} else {
return null;
}
return null;
}
}
?>
\ No newline at end of file
?>
......@@ -41,32 +41,45 @@ function vtws_changePassword($id, $oldPassword, $newPassword, $confirmPassword,
WebServiceErrorCode::$INVALIDOLDPASSWORD));
}
}
if(strcmp($newPassword, $confirmPassword) === 0) {
$db = PearDatabase::getInstance();
$db->dieOnError = true;
$db->startTransaction();
$success = $newUser->change_password($oldPassword, $newPassword, false);
$error = $db->hasFailedTransaction();
$db->completeTransaction();
if($error) {
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$DATABASEQUERYERROR));
}
if(!$success) {
throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$CHANGEPASSWORDFAILURE));
}
} else {
throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$CHANGEPASSWORDFAILURE));
}
if(isPasswordStrong($newPassword)) {
if(strcmp($newPassword, $confirmPassword) === 0) {
$db = PearDatabase::getInstance();
$db->dieOnError = true;
$db->startTransaction();
$success = $newUser->change_password($oldPassword, $newPassword, false);
$error = $db->hasFailedTransaction();
$db->completeTransaction();
if($error) {
throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$DATABASEQUERYERROR));
}
if(!$success) {
throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$CHANGEPASSWORDFAILURE));
}
} else {
throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$CHANGEPASSWORDFAILURE));
}
} else {
throw new WebServiceException(WebServiceErrorCode::$CHANGEPASSWORDFAILURE,
vtws_getWebserviceTranslatedString('LBL_'.
WebServiceErrorCode::$PASSWORDNOTSTRONG));
}
VTWS_PreserveGlobal::flush();
return array('message' => 'Changed password successfully');
}
}
?>
function isPasswordStrong($new_password){
$runtime_configs = Vtiger_Runtime_Configs::getInstance();
$password_regex = $runtime_configs->getValidationRegex('password_regex');
if (preg_match('/'.$password_regex.'/i', $new_password) == 1) {
return true;
}
return false;
}
?>
\ No newline at end of file
......@@ -17,6 +17,7 @@ require_once 'include/Webservices/VtigerActorOperation.php';
class VtigerCompanyDetails extends VtigerActorOperation {
public function create($elementType, $element) {
$db = PearDatabase::getInstance();
$params = array();
$sql = 'select * from vtiger_organizationdetails';
$result = $db->pquery($sql,$params);
$rowCount = $db->num_rows($result);
......@@ -52,5 +53,12 @@ class VtigerCompanyDetails extends VtigerActorOperation {
return parent::revise($element);
}
public function retrieve($id) {
$element = parent::retrieve($id);
if (empty($element['logo'])) {
$element['logo'] = vtws_getCompanyEncodedImage($element['logoname']);
}
return $element;
}
}
?>
\ No newline at end of file
......@@ -7,14 +7,15 @@
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
class DataTransform{
public static $recordString = "record_id";
public static $recordModuleString = 'record_module';
function sanitizeDataWithColumn($row,$meta){
public static $recordSource = 'WEBSERVICE';
static function sanitizeDataWithColumn($row,$meta){
$newRow = array();
if(isset($row['count(*)'])){
return DataTransform::sanitizeDataWithCountColumn($row,$meta);
......@@ -28,31 +29,35 @@
$newRow = DataTransform::sanitizeData($newRow,$meta,true);
return $newRow;
}
function sanitizeDataWithCountColumn($row,$meta){
static function sanitizeDataWithCountColumn($row,$meta){
$newRow = array();
foreach($row as $col=>$val){
$newRow['count'] = $val;
}
return $newRow;
}
function filterAndSanitize($row,$meta){
static function filterAndSanitize($row,$meta){
$recordLabel = isset($row['label']) ? $row['label'] :"";
$row = DataTransform::filterAllColumns($row,$meta);
$row = DataTransform::sanitizeData($row,$meta);
if(!empty($recordLabel)){
$row['label'] = $recordLabel;
}
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;
......@@ -61,12 +66,12 @@
$components = vtws_getIdComponents($row['parent_id']);
$userObj = VtigerWebserviceObject::fromName($adb,'Users');
$parentTypeId = $components[0];
if($components[0] == $userObj->getEntityId()){
if($components[0] == $userObj->getEntityId()){
$associatedToUser = true;
}
}
}
// added to handle the setting reminder time
// 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";
......@@ -98,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];
}
......@@ -125,7 +130,7 @@
}
}
}
if($row["id"]){
if(isset($row["id"]) && $row["id"]){
unset($row["id"]);
}
if(isset($row[$meta->getObectIndexColumn()])){
......@@ -134,50 +139,56 @@
$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'])) {
$row['source'] = self::$recordSource;
}
return $row;
}
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];
}
return $newRow;
}
function sanitizeFields($row,$meta){
static function sanitizeFields($row,$meta){
$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
$recordString = DataTransform::$recordString;
$recordModuleString = DataTransform::$recordModuleString;
if(isset($row[$recordModuleString])){
unset($row[$recordModuleString]);
}
if(isset($row['id'])){
if(strpos($row['id'],'x')===false){
$row['id'] = vtws_getId($meta->getEntityId(),$row['id']);
}
}
if(isset($row[$recordString])){
$row['id'] = vtws_getId($meta->getEntityId(),$row[$recordString]);
unset($row[$recordString]);
}
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.
......@@ -186,31 +197,34 @@
}else if(isset($row[$meta->getObectIndexColumn()]) && strcmp($meta->getObectIndexColumn(),"id")!==0){
unset($row[$meta->getObectIndexColumn()]);
}
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);
$handlerPath = $webserviceObject->getHandlerPath();
$handlerClass = $webserviceObject->getHandlerClass();
require_once $handlerPath;
$handler = new $handlerClass($webserviceObject,$meta->getUser(),$adb,$log);
$entityMeta = $handler->getMeta();
if($entityMeta->exists($row[$field])){
......@@ -231,21 +245,54 @@
}
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){
if(isset($row[$field]) && $row[$field]!=null){
if(isset($row[$field]) && $row[$field]!=null && $row[$field] != 0){
$ownerType = vtws_getOwnerType($row[$field]);
$webserviceObject = VtigerWebserviceObject::fromName($adb,$ownerType);
$row[$field] = vtws_getId($webserviceObject->getEntityId(),$row[$field]);
if ($ownerType) {
$webserviceObject = VtigerWebserviceObject::fromName($adb,$ownerType);
$row[$field] = vtws_getId($webserviceObject->getEntityId(),$row[$field]);
}
}
}
return $row;
}
/**
* 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;
}
}
function sanitizeDateFieldsForInsert($row,$meta){
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){
......@@ -259,15 +306,39 @@
return $row;
}
function sanitizeCurrencyFieldsForInsert($row,$meta){
static function sanitizeCurrencyFieldsForInsert($row,$meta){
global $current_user;
$moduleFields = $meta->getModuleFields();
foreach($moduleFields as $fieldName=>$fieldObj){
if($fieldObj->getFieldDataType()=="currency" && !empty($row[$fieldName])) {
if($fieldObj->getUIType() == '71') {
$row[$fieldName] = CurrencyField::convertToUserFormat($row[$fieldName],$current_user);
} else if($fieldObj->getUIType() == '72') {
if (!empty($row[$fieldName])) {
if($fieldObj->getFieldDataType()=="currency") {
if($fieldObj->getUIType() == '71') {
$row[$fieldName."_raw"] = $row[$fieldName];
$row[$fieldName] = CurrencyField::convertToUserFormat($row[$fieldName],$current_user);
} else if($fieldObj->getUIType() == '72') {
$currencyConversionRate = isset($row['conversion_rate']) ? $row['conversion_rate'] : 0;
if (!empty($currencyConversionRate)) {
$rawBaseCurrencyValue = CurrencyField::convertToDollar($row[$fieldName], $currencyConversionRate);
$row[$fieldName."_raw"] = $rawBaseCurrencyValue;
$row[$fieldName."_raw_converted"] = CurrencyField::convertToUserFormat($rawBaseCurrencyValue, $current_user);
}
$row[$fieldName] = CurrencyField::convertToUserFormat($row[$fieldName],$current_user,true);
}
} else if($fieldObj->getUIType() == 7 && in_array($fieldObj->getFieldType(), array('N', 'NN'))) {
$row[$fieldName] = CurrencyField::convertToUserFormat($row[$fieldName],$current_user,true);
} else if($fieldObj->getUIType() == 1 && in_array($fieldObj->getFieldType(), array('N', 'NN')) && in_array($fieldObj->getFieldName(), array('qty_per_unit', 'qtyinstock'))) {
$row[$fieldName] = CurrencyField::convertToUserFormat($row[$fieldName],$current_user,true);
}
}
}
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);
}
}
}
......
......@@ -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,10 +8,11 @@
* All Rights Reserved.
*************************************************************************************/
#[\AllowDynamicProperties]
abstract class EntityMeta{
public static $RETRIEVE = "DetailView";
public static $CREATE = "Save";
public static $CREATE = "CreateView";
public static $UPDATE = "EditView";
public static $DELETE = "Delete";
......@@ -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(){
......@@ -47,7 +55,7 @@ abstract class EntityMeta{
$this->emailFields = array();
$moduleFields = $this->getModuleFields();
foreach ($moduleFields as $fieldName=>$webserviceField) {
if(strcasecmp($webserviceField->getFieldType(),'e') === 0){
if((strcasecmp($webserviceField->getFieldType(),'e') === 0) || $webserviceField->getUIType() === '13'){
array_push($this->emailFields, $fieldName);
}
}
......@@ -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;
}
?>
......@@ -10,6 +10,7 @@
require_once 'include/Webservices/Utils.php';
require_once 'include/Webservices/ModuleTypes.php';
require_once 'include/utils/CommonUtils.php';
require_once('include/utils/GetUserGroups.php');
require_once 'include/Webservices/DescribeObject.php';
function vtws_sync($mtime,$elementType,$syncType,$user){
......@@ -45,14 +46,10 @@ require_once 'include/Webservices/DescribeObject.php';
$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");
}
$userGroups = new GetUserGroups();
$userGroups->getAllUserGroups($user->id);
$ownerIds = array_merge($ownerIds, $userGroups->user_groups);
}
}
// End
......@@ -85,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;
......@@ -171,6 +168,11 @@ require_once 'include/Webservices/DescribeObject.php';
$params = array_merge($params,$ownerIds);
}
$fromClause.= ' ) vtiger_ws_sync ON (vtiger_crmentity.crmid = vtiger_ws_sync.crmid)';
if ($elementType == 'Events') {
// If we have more than one contact attached to Vtiger Event then we are getting duplicates
$moduleFocus = CRMEntity::getInstance('Activity');
$fromClause .= " GROUP BY $moduleFocus->table_name.$moduleFocus->table_index";
}
$q = $selectClause." ".$fromClause;
$result = $adb->pquery($q, $params);
$recordDetails = array();
......
......@@ -29,14 +29,14 @@ function vtws_history($element, $user) {
$record = $element['record'];
$mode = empty($element['mode'])? 'Private' : $element['mode']; // Private or All
$page = empty($element['page'])? 0 : intval($element['page']); // Page to start
$idComponents = vtws_getIdComponents($record); // We have it - as the input is validated.
$acrossAllModule = false;
if ($moduleName == 'Home') $acrossAllModule = true;
// Pre-condition check
if (empty($moduleName)) {
$moduleName = Mobile_WS_Utils::detectModulenameFromRecordId($record);
$idComponents = vtws_getIdComponents($record); // We have it - as the input is validated.
}
if (!$acrossAllModule && !ModTracker::isTrackingEnabledForModule($moduleName)) {
......@@ -55,16 +55,29 @@ function vtws_history($element, $user) {
AND vtiger_crmentity.deleted = 0';
if ($mode == 'Private') {
$sql .= ' WHERE vtiger_modtracker_basic.whodid = ?';
$params[] = $user->getId();
$sql .= ' WHERE vtiger_modtracker_basic.whodid = ?';
$params[] = $user->id;
if ($acrossAllModule) {
// TODO collate only active (or enabled) modules for tracking.
} else if ($moduleName) {
$sql .= ' AND vtiger_modtracker_basic.module = ?';
$params[] = $moduleName;
}
if ($idComponents[1]) {
$sql .= ' AND vtiger_modtracker_basic.crmid = ?';
$params[] = $idComponents[1];
}
} else if ($mode == 'All') {
if ($acrossAllModule) {
// TODO collate only active (or enabled) modules for tracking.
} else if($moduleName) {
$sql .= ' WHERE vtiger_modtracker_basic.module = ?';
$params[] = $moduleName;
} else {
$sql .= ' WHERE vtiger_modtracker_basic.crmid = ?';
}
if ($idComponents[1]) {
$sql .= ' AND vtiger_modtracker_basic.crmid = ?';
$params[] = $idComponents[1];
}
}
......@@ -72,14 +85,21 @@ function vtws_history($element, $user) {
// Get most recently tracked changes with limit
$start = $page*$MAXLIMIT; if ($start > 0) $start = $start + 1; // Adjust the start range
$sql .= sprintf(' ORDER BY vtiger_modtracker_basic.id DESC LIMIT %s,%s', $start, $MAXLIMIT);
$result = $adb->pquery($sql, $params);
$recordValuesMap = array();
$orderedIds = array();
$updatesOrderedIds = array();
$relationOrderedIds = array();
while ($row = $adb->fetch_array($result)) {
$orderedIds[] = $row['id'];
if ($row['status'] === ModTracker::$LINK || $row['status'] === ModTracker::$UNLINK) {
$relationOrderedIds[] = $row['id'];
} else {
$updatesOrderedIds[] = $row['id'];
}
$whodid = vtws_history_entityIdHelper('Users', $row['whodid']);
$crmid = vtws_history_entityIdHelper($acrossAllModule? '' : $moduleName, $row['crmid']);
......@@ -106,12 +126,12 @@ function vtws_history($element, $user) {
$historyItems = array();
// Minor optimizatin to avoid 2nd query run when there is nothing to expect.
if (!empty($orderedIds)) {
if (!empty($updatesOrderedIds)) {
$sql = 'SELECT vtiger_modtracker_detail.* FROM vtiger_modtracker_detail';
$sql .= ' WHERE vtiger_modtracker_detail.id IN (' . generateQuestionMarks($orderedIds) . ')';
$sql .= ' WHERE vtiger_modtracker_detail.id IN (' . generateQuestionMarks($updatesOrderedIds) . ')';
// LIMIT here is not required as $ids extracted is with limit at record level earlier.
$params = $orderedIds;
$params = $updatesOrderedIds;
$result = $adb->pquery($sql, $params);
while ($row = $adb->fetch_array($result)) {
......@@ -124,8 +144,33 @@ function vtws_history($element, $user) {
);
$recordValuesMap[$row['id']] = $item;
}
}
if (!empty($relationOrderedIds)) {
// get related record ids
$sql = 'SELECT vtiger_modtracker_relations.* , vtiger_crmentity.label FROM vtiger_modtracker_relations
INNER JOIN vtiger_crmentity ON vtiger_modtracker_relations.targetid = vtiger_crmentity.crmid
WHERE vtiger_modtracker_relations.id IN ('.generateQuestionMarks($relationOrderedIds).') ORDER BY vtiger_modtracker_relations.changedon DESC';
// Group the values per basic-transaction
// LIMIT here is not required as $ids extracted is with limit at record level earlier.
$params = $relationOrderedIds;
$result = $adb->pquery($sql, $params);
while ($row = $adb->fetch_array($result)) {
$item = $recordValuesMap[$row['id']];
// NOTE: For reference field values transform them to webservice id.
$item['values']['record'] = array(
'id' => $row['targetid'],
'module' => $row['targetmodule'],
'label' => decode_html($row['label'])
);
$recordValuesMap[$row['id']] = $item;
}
}
// Group the values per basic-transaction
if (!empty($orderedIds)) {
foreach ($orderedIds as $id) {
$historyItems[] = $recordValuesMap[$id];
}
......@@ -155,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
?>
<?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/VtigerModuleOperation.php';
require_once 'include/Webservices/Utils.php';
......@@ -15,26 +15,57 @@ 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)) {
$element = parent::create($elementType, $element);
$handler = vtws_getModuleHandlerFromName('LineItem', $this->user);
$eventManager = new VTEventsManager(vglobal('adb'));
$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);
$focus->updateMissingSeqNumber($elementType);
vglobal('VTIGER_BULK_SAVE_MODE', $currentBulkSaveMode);
$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);
} else {
throw new WebServiceException(WebServiceErrorCode::$MANDFIELDSMISSING, "Mandatory Fields Missing..");
}
......@@ -47,16 +78,43 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$lineItemList = $element['LineItems'];
$handler = vtws_getModuleHandlerFromName('LineItem', $this->user);
if (!empty($lineItemList)) {
$eventManager = new VTEventsManager(vglobal('adb'));
$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);
$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);
$original_update_product_array = vglobal('updateInventoryProductRel_update_product_array');
$updateInventoryProductRel_update_product_array = array();
$this->triggerAfterSaveEvents($updatedElement, $eventManager);
vglobal('updateInventoryProductRel_update_product_array',$original_update_product_array);
vglobal('updateInventoryProductRel_deduct_stock', $currentValue);
} else {
$updatedElement = $this->revise($element);
}
......@@ -74,7 +132,20 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$lineItemList = $element['LineItems'];
unset($element['LineItems']);
$eventManager = new VTEventsManager(vglobal('adb'));
$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);
$updatedElement = parent::revise($element);
vglobal('VTIGER_BULK_SAVE_MODE', $currentBulkSaveMode);
$handler->setLineItems('LineItem', $lineItemList, $updatedElement);
$parent = $handler->getParentById($element['id']);
$handler->updateParent($lineItemList, $parent);
......@@ -84,16 +155,33 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$parent['hdnGrandTotal'] = $updatedParent['hdnGrandTotal'];
$parent['pre_tax_total'] = $updatedParent['pre_tax_total'];
$parent['LineItems'] = $handler->getAllLineItemForParent($parentId);
$updatedElement = array_merge($updatedElement,$parent);
$currentValue = vglobal('updateInventoryProductRel_deduct_stock');
vglobal('updateInventoryProductRel_deduct_stock', false);
$original_update_product_array = vglobal('updateInventoryProductRel_update_product_array');
$updateInventoryProductRel_update_product_array = array();
$this->triggerAfterSaveEvents($updatedElement, $eventManager);
vglobal('updateInventoryProductRel_update_product_array',$original_update_product_array);
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
// 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);
......@@ -101,6 +189,9 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
public function retrieve($id) {
$element = parent::retrieve($id);
$chargesElement = $this->getChargesElement($element['id']);
$element = array_merge($element, $chargesElement);
$skipLineItemFields = getLineItemFields();
foreach ($skipLineItemFields as $key => $field) {
if (array_key_exists($field, $element)) {
......@@ -111,10 +202,22 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$idComponents = vtws_getIdComponents($id);
$lineItems = $handler->getAllLineItemForParent($idComponents[1]);
$element['LineItems'] = $lineItems;
$element['productid'] = $lineItems[0]['productid'];
$recordCompoundTaxesElement = $this->getCompoundTaxesElement($element, $lineItems);
$element = array_merge($element, $recordCompoundTaxesElement);
$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];
......@@ -123,13 +226,14 @@ class VtigerInventoryOperation extends VtigerModuleOperation {
$result = parent::delete($id);
return $result;
}
/**
* function to display discounts,taxes and adjustments
* @param type $element
* @return type
*/
protected function sanitizeInventoryForInsert($element) {
$meta = $this->getMeta();
if (!empty($element['hdnTaxType'])) {
$_REQUEST['taxtype'] = $element['hdnTaxType'];
}
......@@ -137,69 +241,304 @@ 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 {
$_REQUEST['discount_type_final'] = '';
$_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 {
} else {
$_REQUEST['adjustmentType'] = '';
$_REQUEST['adjustment'] = '';
}
if (!empty($element['hdnGrandTotal'])) {
$_REQUEST['total'] = $element['hdnGrandTotal'];
}
if (isset($element['region_id'])) {
$_REQUEST['region_id'] = $element['region_id'];
}
if (empty($element['conversion_rate']) && !$_REQUEST['conversion_rate']) {
$element['conversion_rate'] = 1;
$_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;
}
public function sanitizeShippingTaxes($element){
$_REQUEST['shipping_handling_charge'] = $element['hdnS_H_Amount'];
$taxDetails = getAllTaxes('all', 'sh');
foreach ($taxDetails as $taxInfo) {
//removing previous taxes
unset($_REQUEST[$taxInfo['taxname'] . '_sh_percent']);
if ($taxInfo['deleted'] == '0' || $taxInfo['deleted'] === 0) {
if(isset($element['hdnS_H_Percent']) && $element['hdnS_H_Percent'] != 0){
$_REQUEST[$taxInfo['taxname'] . '_sh_percent'] = $element['hdnS_H_Percent'];
$subTotal = (float)$element['hdnSubTotal'];
$overallDiscountAmount = $element['hdnDiscountAmount'];
if ($element['hdnDiscountPercent']) {
$overallDiscountAmount = ($subTotal * (float)$element['hdnDiscountPercent']) / 100;
}
$itemsTotalAfterOverAllDiscount = $subTotal - $overallDiscountAmount;
$shippingTaxes = array();
$allShippingTaxes = getAllTaxes('available', 'sh');
foreach ($allShippingTaxes as $shTaxInfo) {
$shippingTaxes[$shTaxInfo['taxid']] = $shTaxInfo;
}
$totalSHAmount = 0;
$totalSHTaxesAmount = 0;
$allCharges = getAllCharges();
foreach ($allCharges as $chargeId => $chargeInfo) {
$chargeName = html_entity_decode(strtolower(str_replace(' ', '_', $chargeInfo['name'])));
if (array_key_exists($chargeName, $element)) {
$chargeValue = $element[$chargeName];
$pos = strpos($chargeValue, '%');
$chargeValue = str_replace('%', '', $chargeValue);
if ($pos !== FALSE) {
$_REQUEST['charges'][$chargeId]['percent'] = $chargeValue;
$chargeValue = ((float)$itemsTotalAfterOverAllDiscount * (float)$chargeValue) / 100;
}
$totalSHAmount = $totalSHAmount + $chargeValue;
$totalSHTaxesAmount = $totalSHTaxesAmount + $chargeValue;
$_REQUEST['charges'][$chargeId]['value'] = $chargeValue;
}
foreach ($chargeInfo['taxes'] as $taxId) {
$taxKey = $chargeName."_shtax$taxId";
if (array_key_exists($taxKey, $element) && $shippingTaxes[$taxId]) {
$_REQUEST['charges'][$chargeId]['taxes'][$taxId] = $element[$taxKey];
}
}
}
if ($totalSHAmount) {
$_REQUEST['shipping_handling_charge'] = $element['hdnS_H_Amount'] = $totalSHAmount;
$_REQUEST['s_h_percent'] = $totalSHTaxesAmount;
} else {
$_REQUEST['shipping_handling_charge'] = $_REQUEST['charges'][1]['value'] = $element['hdnS_H_Amount'];
foreach ($shippingTaxes as $shTaxId => $shTaxInfo) {
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_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 {
if(isset($element[$taxInfo['taxname'] . '_sh_percent'])){
$_REQUEST[$taxInfo['taxname'] . '_sh_percent'] = $element[$taxInfo['taxname'] . '_sh_percent'];
$shTaxValue = 0;
if(isset($element[$shTaxInfo['taxname'] . '_sh_percent'])) {
$shTaxValue = $element[$shTaxInfo['taxname'] . '_sh_percent'];
}
//if there is Shipping Amount and shipping taxes is provided with 0
elseif($element['hdnS_H_Amount'] > 0 && $element['hdnS_H_Percent'] === 0){
$_REQUEST[$taxInfo['taxname'] . '_sh_percent'] = 0;
}else{
$_REQUEST[$taxInfo['taxname'] . '_sh_percent'] = $taxInfo['percentage'];
$_REQUEST['charges'][1]['taxes'][$shTaxId] = $shTaxValue;
}
}
}
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;
}
}
$shippingTaxes = array();
$allShippingTaxes = getAllTaxes('available', 'sh');
foreach ($allShippingTaxes as $shTaxInfo) {
$shippingTaxes[$shTaxInfo['taxid']] = $shTaxInfo;
}
$allCharges = getAllCharges();
foreach ($allCharges as $chargeId => $chargeInfo) {
$chargeField = array();
$chargeField['name'] = html_entity_decode(strtolower(str_replace(' ', '_', $chargeInfo['name'])));
$chargeField['label'] = $chargeInfo['name'];
$chargeField['type'] = array('name' => 'double');
$chargeField['mandatory'] = false;
$chargeField['nullable'] = true;
$chargeField['editable'] = true;
$chargeField['default'] = ($chargeInfo['format'] === 'Percent') ? $chargeInfo['value'].'%' : $chargeInfo['value'];
$describe['fields'][] = $chargeField;
foreach ($chargeInfo['taxes'] as $shTaxId) {
$shTaxField = array();
$shTaxField['name'] = $chargeField['name'].'_'.$shippingTaxes[$shTaxId]['taxname'];
$shTaxField['label'] = $chargeInfo['name'].' '.$shippingTaxes[$shTaxId]['taxlabel'];
$shTaxField['default'] = $shippingTaxes[$shTaxId]['percentage'];
$shTaxField['type'] = array('name' => 'double');
$shTaxField['nullable'] = true;
$shTaxField['editable'] = true;
$shTaxField['mandatory']= false;
$describe['fields'][] = $shTaxField;
}
}
return $describe;
}
/**
* Function to trigger the events which are before save
* @param <type> $element
* @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);
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);
}
}
}
/**
* Function to trigger the events which are after save
* @param <type> $element
* @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);
}
}
}
/**
* Function to construct focus object
* @param <type> $element
* @param <type> $action
* @return <type>
*/
public function constructFocusObject($element) {
$focus = CRMEntity::getInstance($this->getMeta()->getTabName());
$fields = $focus->column_fields;
foreach($fields as $fieldName => $fieldValue) {
$fieldValue = $element[$fieldName];
if(is_array($fieldValue)) {
$focus->column_fields[$fieldName] = $fieldValue;
} else if($fieldValue !== null) {
$focus->column_fields[$fieldName] = decode_html($fieldValue);
}
}
$ids = vtws_getIdComponents($element['id']);
$focus->id = $ids[1];
return $focus;
}
public function getChargesElement($elementId) {
$chargesElement = array();
if ($elementId) {
$ids = vtws_getIdComponents($elementId);
$id = $ids[1];
$result = $this->pearDB->pquery('SELECT * FROM vtiger_inventorychargesrel WHERE recordid = ?', array($id));
$rowData = $this->pearDB->fetch_array($result);
if (isset($rowData['charges']) && $rowData['charges']) {
$allCharges = getAllCharges();
$shippingTaxes = array();
$allShippingTaxes = getAllTaxes('all', 'sh');
foreach ($allShippingTaxes as $shTaxInfo) {
$shippingTaxes[$shTaxInfo['taxid']] = $shTaxInfo;
}
$charges = Zend_Json::decode(html_entity_decode($rowData['charges']));
foreach ($charges as $chargeId => $chargeInfo) {
$chargeName = html_entity_decode(strtolower(str_replace(' ', '_', $allCharges[$chargeId]['name'])));
$chargeValue = $chargeInfo['value'];
if (array_key_exists('percent', $chargeInfo)) {
$chargeValue = $chargeInfo['percent'].'%';
}
$chargesElement[$chargeName] = $chargeValue;
if ($chargeInfo['taxes']) {
foreach ($chargeInfo['taxes'] as $taxId => $taxPercent) {
if ($shippingTaxes[$taxId]) {
$chargesElement[$chargeName.'_shtax'.$taxId] = $taxPercent;
}
}
}
}
}
}
return $element;
return $chargesElement;
}
public function getCompoundTaxesElement($element, $lineItems) {
$idComponents = vtws_getIdComponents($element['id']);
$recordId = $idComponents[1];
$compoundTaxesElement = array();
$recordTaxesCompoundInfo = array();
$compoundInfo = getCompoundTaxesInfoForInventoryRecord($recordId, getSalesEntityType($recordId));
if (is_array($compoundInfo)) {
foreach ($compoundInfo as $taxId => $comInfo) {
foreach ($comInfo as $cTaxId) {
$recordTaxesCompoundInfo["tax$taxId"][] = "tax$cTaxId";
}
}
}
if ($recordTaxesCompoundInfo) {
if ($element['hdnTaxType'] === 'group') {
$compoundTaxesElement['compoundTaxInfo'] = $recordTaxesCompoundInfo;
} else {
foreach ($lineItems as $key => $lineItem) {
$lineItems[$key]['compoundTaxInfo'] = $recordTaxesCompoundInfo;
}
}
}
$compoundTaxesElement['LineItems'] = $lineItems;
return $compoundTaxesElement;
}
/* NOTE: Special case to pull the default setting of TermsAndCondition */
public function describe($elementType) {
$describe = parent::describe($elementType);
$tandc = getTermsAndConditions();
foreach ($describe['fields'] as $key => $list){
if($list["name"] == 'terms_conditions'){
$describe['fields'][$key]['default'] = $tandc;
}
}
return $describe;
}
}
?>
\ No newline at end of file
......@@ -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,14 +24,15 @@ 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 static $parentCache = array();
private $inActiveTaxList = null;
private static $parentCache = array();
public function __construct($webserviceObject,$user,$adb,$log) {
$this->user = $user;
......@@ -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,43 +77,39 @@ class VtigerLineItemOperation extends VtigerActorOperation {
* @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);
}
$result = null;
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){
......@@ -160,8 +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) {
......@@ -174,27 +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'];
}
......@@ -205,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 (!empty($element[$fieldName])) {
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]
);
......@@ -219,33 +221,43 @@ class VtigerLineItemOperation extends VtigerActorOperation {
}
}
}
if ($found) {
$this->taxList = $this->providedTaxList;
}
} elseif ($found == false) {
array_merge($this->taxList, $productTaxList);
}
} else {
$meta = $this->getMeta();
$moduleFields = $meta->getModuleFields();
$availableTaxes = getAllTaxes('available');
$found = false;
$found = false;
foreach ($moduleFields as $fieldName => $field) {
if (preg_match('/tax\d+/', $fieldName) != 0) {
$found = true;
if (!empty($element[$fieldName])) {
$found = true;
if (isset($element[$fieldName])) {
$this->taxList[$fieldName] = array(
'label' => $field->getFieldLabelKey(),
'percentage' => $element[$fieldName]
);
}
}
}
if(!$found) {
foreach($availableTaxes as $taxInfo){
$this->taxList[$taxInfo['taxname']] = array(
'label' => $field->getFieldLabelKey(),
'percentage' => $taxInfo['percentage']
);
}
}
}
}
if(!$found) {
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;
}
......@@ -266,13 +278,21 @@ class VtigerLineItemOperation extends VtigerActorOperation {
}
public function setLineItems($elementType, $lineItemList, $parent){
$currentValue = vglobal('updateInventoryProductRel_deduct_stock');
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']);
$this->newId = $id[1];
$this->create($elementType, $lineItem);
}
$element['parent_id'] = $parent['id'];
vglobal('updateInventoryProductRel_deduct_stock', true);
$this->updateInventoryStock($element,$parent);
vglobal('updateInventoryProductRel_deduct_stock', $currentValue);
}
public function create($elementType, $element) {
......@@ -280,23 +300,57 @@ 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);
$updatedLineItemList = $createdLineItem;
$updatedLineItemList['parent_id'] = $element['parent_id'];
$this->setCache($parentId, $updatedLineItemList);
$this->updateInventoryStock($element,$parent);
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);
$element['id'] = $id;
$parent = $this->getParentById($element['parent_id']);
return $this->resetTaxInfo($element, $parent);
}
......@@ -313,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']);
......@@ -329,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);
......@@ -345,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);
......@@ -403,6 +456,18 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$lineItemList = $this->getAllLineItemForParent($parentId);
$parent['hdnSubTotal'] = 0;
$taxAmount = 0;
$compoundOn = $allTaxes = array();
$allItemTaxes = getAllTaxes('available');
foreach ($allItemTaxes as $taxInfo) {
$taxCompoundOnInfo = array();
if ($taxInfo['compoundon']) {
$taxCompoundOnInfo = Zend_Json::decode(html_entity_decode($taxInfo['compoundon']));
}
$compoundOn[$taxInfo['taxid']] = $taxCompoundOnInfo;
$allTaxes[$taxInfo['taxname']] = $taxInfo;
}
foreach ($lineItemList as $lineItem) {
$discount = 0;
$lineItemTotal = $lineItem['listprice'] * $lineItem['quantity'];
......@@ -417,10 +482,23 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$lineItemTotal = $lineItemTotal - $discount;
$parent['hdnSubTotal'] = ($parent['hdnSubTotal'] ) + $lineItemTotal;
if(strcasecmp($parent['hdnTaxType'], $this->Individual) ===0){
foreach ($this->taxList as $taxInfo) {
$lineItemTaxAmount = ($taxInfo['percentage'])/100*$lineItemTotal;
$parent['hdnSubTotal'] += $lineItemTaxAmount;
$taxAmountsList = array();
foreach ($this->taxList as $taxName => $taxInfo) {
$taxAmountsList[$allTaxes[$taxName]['taxid']] = array('percentage' => $taxInfo['percentage'], 'amount' => ($lineItemTotal * $taxInfo['percentage']) / 100);
}
foreach ($taxAmountsList as $taxId => $taxInfo) {
if ($compoundOn[$taxId]) {
$amount = $lineItemTotal;
foreach ($compoundOn[$taxId] as $comTaxId) {
$amount += $taxAmountsList[$comTaxId]['amount'];
}
$taxAmountsList[$taxId]['amount'] = ($amount * $taxInfo['percentage']) / 100;
}
$parent['hdnSubTotal'] += $taxInfo['amount'];
}
$individualPreTaxTotal += $lineItemTotal;
}
}
......@@ -428,22 +506,76 @@ class VtigerLineItemOperation extends VtigerActorOperation {
$discount = ($parent['hdnDiscountAmount']);
} elseif(!empty($parent['hdnDiscountPercent'])){
$discount = ($parent['hdnDiscountPercent']/100 * $parent['hdnSubTotal']);
} else {
$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);
foreach ($this->taxList as $taxInfo) {
$taxAmount += ($taxInfo['percentage'])/100*$taxTotal;
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);
}
foreach ($taxAmountsList as $taxId => $taxInfo) {
if ($compoundOn[$taxId]) {
$amount = $taxTotal;
foreach ($compoundOn[$taxId] as $comTaxId) {
$amount += $taxAmountsList[$comTaxId]['amount'];
}
$taxInfo['amount'] = $taxAmountsList[$taxId]['amount'] = ($amount * $taxInfo['percentage']) / 100;
}
$taxAmount += $taxInfo['amount'];
}
}
$shippingTax = getAllTaxes('all', 'sh','edit',$parentId);
$shippingTaxInfo = array();
foreach ($shippingTax as $taxInfo) {
$taxAmount += ($taxInfo['percentage'])/100*$parent['hdnS_H_Amount'];
$shippingTaxInfo[$taxInfo['taxname']] = $taxInfo['percentage'];
}
//Calculating charge values
$result = $this->pearDB->pquery('SELECT * FROM vtiger_inventorychargesrel WHERE recordid = ?', array($parentId));
$rowData = $this->pearDB->fetch_array($result);
if ($rowData['charges']) {
$allShippingTaxes = array();
$shippingTaxes = getAllTaxes('all', 'sh', 'edit', $parentId);
foreach ($shippingTaxes as $shippingTaxInfo) {
$compoundOnInfo = array();
if ($shippingTaxInfo['compoundon']) {
$compoundOnInfo = Zend_Json::decode(html_entity_decode($shippingTaxInfo['compoundon']));
}
$shippingTaxInfo['compoundon'] = $compoundOnInfo;
$allShippingTaxes[$shippingTaxInfo['taxid']] = $shippingTaxInfo;
}
$charges = Zend_Json::decode(html_entity_decode($rowData['charges']));
foreach ($charges as $chargeId => $chargeInfo) {
$chargeTaxes = $chargeInfo['taxes'];
if ($chargeTaxes) {
foreach ($chargeTaxes as $shTaxId => $shTaxPercentage) {
$amount = $calculatedOn = $chargeInfo['value'];
if ($allShippingTaxes[$shTaxId]['method'] === 'Compound') {
foreach ($allShippingTaxes[$shTaxId]['compoundon'] as $comShTaxId) {
$calculatedOn += ($amount * $chargeTaxes[$comShTaxId]) / 100;
}
}
$shTaxAmount = ($calculatedOn * $shTaxPercentage) / 100;
$taxAmount += $shTaxAmount;
}
}
}
}
$parent['hdnGrandTotal'] = $total + $taxAmount + $parent['txtAdjustment'];
$parentTypeHandler = vtws_getModuleHandlerFromId($parent['id'], $this->user);
......@@ -455,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);
self::$parentCache[$parent['id']] = $parent;
$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');
}
}
......@@ -469,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();
......@@ -490,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();
......@@ -504,7 +633,9 @@ class VtigerLineItemOperation extends VtigerActorOperation {
private function updateInventoryStock($element, $parent){
global $updateInventoryProductRel_update_product_array;
$updateInventoryProductRel_update_product_array = array();
if(empty($updateInventoryProductRel_update_product_array)){
$updateInventoryProductRel_update_product_array = array();
}
$entityCache = new VTEntityCache($this->user);
$entityData = $entityCache->forId($element['parent_id']);
updateInventoryProductRel($entityData);
......@@ -525,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;
}
......@@ -557,7 +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']);
return $describe;
}
}
?>
\ No newline at end of file
?>
......@@ -37,11 +37,19 @@ class VtigerTaxOperation extends VtigerActorOperation {
$this->moduleFields = null;
}
public function create($elementType, $element) {
$element = $this->restrictFields($element);
public function create($elementType, $taxElement) {
$element = $this->restrictFields($taxElement);
$taxFormula = $taxElement[$taxElement['taxname'].'_formula'];
if (!$taxFormula) {
$taxFormula = $taxElement['formula'];
}
$element['formula'] = $taxFormula;
$taxName = $this->getNewTaxName();
$element['taxname'] = $taxName;
$element['deleted'] = 0;
$element = $this->sanitizeElementForInsert($element);
$createdElement = parent::create($elementType, $element);
$sql = "alter table vtiger_inventoryproductrel add column $taxName decimal(7,3)";
$result = $this->pearDB->pquery($sql,array());
......@@ -55,7 +63,9 @@ class VtigerTaxOperation extends VtigerActorOperation {
}
public function update($element) {
$element['taxname'] = $this->getCurrentTaxName();
$element['taxname'] = $this->getTaxName($element);
$element = $this->sanitizeElementForInsert($element);
return parent::update($element);
}
......@@ -91,6 +101,26 @@ class VtigerTaxOperation extends VtigerActorOperation {
return $currentTaxName;
}
/**
* Function get tax name
* @param <Array> $element
* @return <String> taxName
*/
private function getTaxName($element) {
if ($element['taxlabel']) {
$sql = 'SELECT taxname FROM vtiger_inventorytaxinfo WHERE taxlabel = ?';
$params = array($element['taxlabel']);
$result = $this->pearDB->pquery($sql, $params);
$it = new SqlResultIterator($this->pearDB, $result);
$taxName = NULL;
foreach ($it as $row) {
$taxName = $row->taxname;
}
return $taxName;
}
return $this->getCurrentTaxName();
}
private function getNewTaxName() {
$currentTaxName = $this->getCurrentTaxName();
......@@ -107,5 +137,105 @@ class VtigerTaxOperation extends VtigerActorOperation {
return 'tax1';
}
public function retrieve($id) {
$element = parent::retrieve($id);
//Constructing regions as element fields
$regions = Zend_Json::decode(html_entity_decode($element['regions']));
if ($regions) {
$allRegions = getAllRegions();
foreach ($allRegions as $regionId => $regionInfo) {
$regionInfo['name'] = strtolower(str_replace(' ', '_', $regionInfo['name']));
$allRegions[$regionId] = $regionInfo;
}
foreach ($regions as $regionInfo) {
foreach ($regionInfo['list'] as $regionId) {
$element[$allRegions[$regionId]['name']] = $regionInfo['value'];
}
}
}
unset($element['regions']);
//Constructing compound info as element field
$compoundOn = Zend_Json::decode(html_entity_decode($element['compoundon']));
if ($compoundOn) {
$allTaxes = array();
$allItemTaxes = getAllTaxes();
foreach ($allItemTaxes as $taxInfo) {
$allTaxes[$taxInfo['taxid']] = $taxInfo;
}
$compoundInfo = '';
foreach ($compoundOn as $taxId) {
$compoundInfo = "$compoundInfo+".$allTaxes[$taxId]['taxname'];
}
$element[$element['taxname'].'_formula'] = ltrim($compoundInfo, '+');
}
unset($element['compoundon']);
return $element;
}
/**
* Function to sanitize element for insert
* @param <Array> $element
* @return <Array>
*/
private function sanitizeElementForInsert($element) {
$compoundOn = $regions = array();
$type = 'Fixed';
$method = 'Simple';
$taxFormula = $element[$element['taxname'].'_formula'];
if (!$taxFormula) {
$taxFormula = $element['formula'];
}
if ($taxFormula) {
$taxFormulaElements = explode('+', $taxFormula);
$sql = 'SELECT taxid, method FROM vtiger_inventorytaxinfo WHERE taxname IN ('.generateQuestionMarks($taxFormulaElements).')';
$params = $taxFormulaElements;
$result = $this->pearDB->pquery($sql, $params);
$it = new SqlResultIterator($this->pearDB, $result);
foreach ($it as $row) {
if ($row->method === 'Simple') {
$compoundOn[] = $row->taxid;
}
}
}
if ($compoundOn) {
$method = 'Compound';
}
$regionsList = array();
$allRegions = getAllRegions();
foreach ($allRegions as $regionId => $regionInfo) {
$regionName = strtolower(str_replace(' ', '_', $regionInfo['name']));
if (array_key_exists($regionName, $element)) {
$regionValue = $element[$regionName];
$regionsList[$regionValue][] = $regionId;
}
}
foreach ($regionsList as $regionValue => $regions) {
$regions[] = array('list' => $regions, 'value' => $regionValue);
}
if ($regions) {
$type = 'Variable';
}
if ($element['method'] === 'Deducted' && !$compoundOn && !$regions) {
$method = 'Deducted';
}
$element['type'] = $type;
$element['method'] = $method;
$element['regions'] = Zend_Json::encode($regions);
$element['compoundon'] = Zend_Json::encode($compoundOn);
return $element;
}
}
?>
\ No newline at end of file
......@@ -31,13 +31,15 @@
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){
global $adb;
$sql = "select * from vtiger_ws_userauthtoken where userid=? and expiretime >= ?";
$sql = "select token from vtiger_ws_userauthtoken where userid=? and expiretime >= ?";
$result = $adb->pquery($sql,array($userId,time()));
if($result != null && isset($result)){
if($adb->num_rows($result)>0){
......@@ -50,7 +52,7 @@
function vtws_getUserAccessKey($userId){
global $adb;
$sql = "select * from vtiger_users where id=?";
$sql = "select accesskey from vtiger_users where id=?";
$result = $adb->pquery($sql,array($userId));
if($result != null && isset($result)){
if($adb->num_rows($result)>0){
......
......@@ -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]);
}
}
}
......