public function put($recordDetails, $user)
 {
     $this->user = $user;
     $recordDetails = $this->syncToNativeFormat($recordDetails);
     $createdRecords = $recordDetails['created'];
     $updatedRecords = $recordDetails['updated'];
     $deletedRecords = $recordDetails['deleted'];
     if (count($createdRecords) > 0) {
         $createdRecords = $this->translateReferenceFieldNamesToIds($createdRecords, $user);
         $createdRecords = $this->fillNonExistingMandatoryPicklistValues($createdRecords);
     }
     foreach ($createdRecords as $index => $record) {
         $createdRecords[$index] = vtws_create($record['module'], $record, $this->user);
     }
     if (count($updatedRecords) > 0) {
         $updatedRecords = $this->translateReferenceFieldNamesToIds($updatedRecords, $user);
     }
     $crmIds = array();
     foreach ($updatedRecords as $index => $record) {
         $webserviceRecordId = $record["id"];
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         $crmIds[] = $recordIdComp[1];
     }
     $assignedRecordIds = wsapp_checkIfRecordsAssignToUser($crmIds, $this->user->id);
     foreach ($updatedRecords as $index => $record) {
         $webserviceRecordId = $record["id"];
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         if (in_array($recordIdComp[1], $assignedRecordIds)) {
             $updatedRecords[$index] = vtws_revise($record, $this->user);
         } else {
             $this->assignToChangedRecords[$index] = $record;
         }
     }
     $hasDeleteAccess = null;
     $deletedCrmIds = array();
     foreach ($deletedRecords as $index => $record) {
         $webserviceRecordId = $record;
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         $deletedCrmIds[] = $recordIdComp[1];
     }
     $assignedDeletedRecordIds = wsapp_checkIfRecordsAssignToUser($deletedCrmIds, $this->user->id);
     foreach ($deletedRecords as $index => $record) {
         $idComp = vtws_getIdComponents($record);
         if (empty($hasDeleteAccess)) {
             $handler = vtws_getModuleHandlerFromId($idComp[0], $this->user);
             $meta = $handler->getMeta();
             $hasDeleteAccess = $meta->hasDeleteAccess();
         }
         if ($hasDeleteAccess) {
             if (in_array($idComp[1], $assignedDeletedRecordIds)) {
                 vtws_delete($record, $this->user);
             }
         }
     }
     $recordDetails['created'] = $createdRecords;
     $recordDetails['updated'] = $updatedRecords;
     $recordDetails['deleted'] = $deletedRecords;
     return $this->nativeToSyncFormat($recordDetails);
 }
Пример #2
0
 function process(Mobile_API_Request $request)
 {
     global $current_user;
     // Required for vtws_update API
     $current_user = $this->getActiveUser();
     $module = $request->get('module');
     //update if recordid exist
     $recordid = $request->get('record');
     $valueArray = Mobile_API_Request::getvaluemap($request);
     $values = '';
     if (!empty($valueArray) && is_string($valueArray)) {
         $values = Zend_Json::decode($valueArray);
     } else {
         $values = $valueArray;
         // Either empty or already decoded.
     }
     //catch error
     $response = new Mobile_API_Response();
     if (empty($values)) {
         $response->setError(1501, "Values cannot be empty!");
         return $response;
     }
     try {
         // Retrieve or Initialize
         if (!empty($recordid)) {
             $this->recordValues = parent::processRetrieve($request);
         } else {
             $this->recordValues = array();
         }
         // Set the modified values
         foreach ($values as $name => $value) {
             $this->recordValues[$name] = $value;
         }
         // Update or Create
         if (isset($this->recordValues['id'])) {
             $this->recordValues = vtws_update($this->recordValues, $current_user);
         } else {
             // Set right target module name for Calendar/Event record
             if ($module == 'Calendar') {
                 if (!empty($this->recordValues['eventstatus']) && $this->recordValues['activitytype'] != 'Task') {
                     $module = 'Events';
                 }
             }
             $this->recordValues = vtws_create($module, $this->recordValues, $current_user);
         }
         // Update the record id
         $request->set('record', $this->recordValues['id']);
         $request->set('id', $this->recordValues['id']);
         // Gather response with full details
         $response = parent::process($request);
     } catch (Exception $e) {
         $response->setError($e->getCode(), $e->getMessage());
     }
     return $response;
 }
Пример #3
0
 function captureNow($request)
 {
     $returnURL = false;
     try {
         foreach ($request as $key => $value) {
             $request[utf8_decode($key)] = $value;
         }
         if (!vtlib_isModuleActive('Webforms')) {
             throw new Exception('webforms is not active');
         }
         $webform = Webforms_Model::retrieveWithPublicId(vtlib_purify($request['publicid']));
         if (empty($webform)) {
             throw new Exception("Webform not found.");
         }
         $returnURL = $webform->getReturnUrl();
         // Retrieve user information
         $user = CRMEntity::getInstance('Users');
         $user->id = $user->getActiveAdminId();
         $user->retrieve_entity_info($user->id, 'Users');
         // Prepare the parametets
         $parameters = array();
         $webformFields = $webform->getFields();
         foreach ($webformFields as $webformField) {
             if ($webformField->getDefaultValue() != null) {
                 $parameters[$webformField->getFieldName()] = decode_html($webformField->getDefaultValue());
             } else {
                 $webformNeutralizedField = html_entity_decode($webformField->getNeutralizedField());
                 if (is_array(vtlib_purify($request[$webformNeutralizedField]))) {
                     $fieldData = implode(" |##| ", vtlib_purify($request[$webformNeutralizedField]));
                 } else {
                     $fieldData = vtlib_purify($request[$webformNeutralizedField]);
                     $fieldData = decode_html($fieldData);
                 }
                 $parameters[$webformField->getFieldName()] = stripslashes($fieldData);
             }
             if ($webformField->getRequired()) {
                 if (empty($parameters[$webformField->getFieldName()])) {
                     throw new Exception("Required fields not filled");
                 }
             }
         }
         $parameters['assigned_user_id'] = vtws_getWebserviceEntityId('Users', $webform->getOwnerId());
         // Create the record
         $record = vtws_create($webform->getTargetModule(), $parameters, $user);
         $this->sendResponse($returnURL, 'ok');
         return;
     } catch (Exception $e) {
         $this->sendResponse($returnURL, false, $e->getMessage());
         return;
     }
 }
Пример #4
0
 function getContent(Mobile_API_Request $request)
 {
     $comment = $request->get('comment');
     $parentid = $request->get('parentid');
     if (isset($comment) && !empty($comment)) {
         $parentmodule = Mobile_WS_Utils::detectModulenameFromRecordId($parentid);
         if ($parentmodule != 'HelpDesk') {
             include_once 'include/Webservices/Create.php';
             $current_user = $this->getActiveUser();
             $userid = Mobile_WS_Utils::getEntityModuleWSId('Users') . "x" . $current_user->id;
             $arr_comment = array('commentcontent' => $comment, 'related_to' => $parentid, 'creator' => $userid, 'assigned_user_id' => $userid);
             $ele = vtws_create('ModComments', $arr_comment, $current_user);
         } else {
             $parentrecordid = vtws_getIdComponents($parentid);
             $parentrecordid = $parentrecordid[1];
             //there is currently no vtws service available for ticket comments
             $current_user = $this->getActiveUser();
             $current_user_id = $current_user->id;
             $userrecordid = vtws_getIdComponents($current_user_id);
             $userrecordid = $userrecordid[1];
             $arr_comment = array('commentcontent' => $comment, 'related_to' => $parentrecordid, 'creator' => $current_user_id);
             //$ele = vtws_create('ModComments', $arr_comment, $current_user);
             $saverecord = Mobile_WS_Utils::createTicketComment($arr_comment);
             if ($saverecord == true) {
                 $userid = Mobile_WS_Utils::getEntityModuleWSId('Users') . "x" . $current_user_id;
                 $ele['commentcontent'] = $arr_comment['commentcontent'];
                 $ele['creator'] = $userid;
                 $ele['assigned_user_id'] = $userid;
                 $ele['related_to'] = $parentid;
                 $ele['id'] = '';
                 $ele['createdtime'] = DateTimeField::convertToUserFormat(date('Y-m-d H:i:s'));
             }
         }
     }
     $response = new Mobile_API_Response();
     $ele['assigned_user_id'] = vtws_getName($ele['creator'], $current_user);
     $response->setResult(array('comment' => $ele));
     return $response;
 }
Пример #5
0
function vtws_convertlead($entityvalues, $user)
{
    $adb = PearDatabase::getInstance();
    $log = vglobal('log');
    $log->debug('Start ' . __CLASS__ . ':' . __FUNCTION__);
    if (empty($entityvalues['assignedTo'])) {
        $entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if (empty($entityvalues['transferRelatedRecordsTo'])) {
        $entityvalues['transferRelatedRecordsTo'] = 'Accounts';
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadInfo = vtws_retrieve($entityvalues['leadId'], $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($entityvalues['leadId']);
    $result = $adb->pquery($sql, array($leadIdComponents[1]));
    if ($result === false) {
        $log->error('Error converting a lead: ' . vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount > 0) {
        $log->error('Error converting a lead: Lead is already converted');
        throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    require_once "include/events/include.inc";
    $em = new VTEventsManager($adb);
    // Initialize Event trigger cache
    $em->initTriggerCache();
    $entityData = VTEntityData::fromEntityId($adb, $leadIdComponents[1]);
    $em->triggerEvent('entity.convertlead.before', [$entityvalues, $user, $leadInfo]);
    $entityIds = [];
    $availableModules = ['Accounts', 'Contacts', 'Potentials'];
    if (!($entityvalues['entities']['Accounts']['create'] || $entityvalues['entities']['Contacts']['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_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo);
            //update potential related to property
            if ($entityvalue['name'] == 'Potentials') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['related_to'] = $entityIds['Accounts'];
                }
                if (!empty($entityIds['Contacts'])) {
                    $entityObjectValues['contact_id'] = $entityIds['Contacts'];
                }
            }
            //update the contacts relation
            if ($entityvalue['name'] == 'Contacts') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['parent_id'] = $entityIds['Accounts'];
                }
            }
            try {
                $create = true;
                if ($entityvalue['name'] == 'Accounts' && $entityvalue['convert_to_id'] && is_int($entityvalue['convert_to_id'])) {
                    $entityIds[$entityName] = vtws_getWebserviceEntityId('Accounts', $entityvalue['convert_to_id']);
                    $create = false;
                }
                if ($create) {
                    $entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user);
                    $entityIds[$entityName] = $entityRecord['id'];
                }
            } catch (Exception $e) {
                $log->error('Error converting a lead: ' . $e->getMessage());
                throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $entityvalue['name']);
            }
        }
    }
    try {
        $accountIdComponents = vtws_getIdComponents($entityIds['Accounts']);
        $accountId = $accountIdComponents[1];
        $contactIdComponents = vtws_getIdComponents($entityIds['Contacts']);
        $contactId = $contactIdComponents[1];
        if (!empty($accountId) && !empty($contactId) && !empty($entityIds['Potentials'])) {
            $potentialIdComponents = vtws_getIdComponents($entityIds['Potentials']);
            $potentialId = $potentialIdComponents[1];
            $sql = "insert into vtiger_contpotentialrel values(?,?)";
            $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
            if ($result === false) {
                throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
            }
        }
        $transfered = vtws_convertLeadTransferHandler($leadIdComponents, $entityIds, $entityvalues);
        $relatedIdComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]);
        vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $relatedIdComponents[1]);
        vtws_updateConvertLeadStatus($entityIds, $entityvalues['leadId'], $user);
        if ($em) {
            $em->triggerEvent('entity.convertlead.after', [$entityvalues, $user, $leadInfo, $entityIds]);
        }
    } catch (Exception $e) {
        $log->error('Error converting a lead: ' . $e->getMessage());
        foreach ($entityIds as $entity => $id) {
            vtws_delete($id, $user);
        }
        return null;
    }
    $log->debug('End ' . __CLASS__ . ':' . __FUNCTION__);
    return $entityIds;
}
Пример #6
0
 public function createRecord(Vtiger_Request $request)
 {
     $user = Users_Record_Model::getCurrentUserModel();
     $moduleName = $request->get('modulename');
     $name = explode("@", $request->get('email'));
     $element['lastname'] = $name[0];
     $element['email'] = $request->get('email');
     $element['phone'] = $request->get('number');
     $element['assigned_user_id'] = vtws_getWebserviceEntityId('Users', $user->id);
     $moduleInstance = Vtiger_Module_Model::getInstance($moduleName);
     $mandatoryFieldModels = $moduleInstance->getMandatoryFieldModels();
     foreach ($mandatoryFieldModels as $mandatoryField) {
         $fieldName = $mandatoryField->get('name');
         $fieldType = $mandatoryField->getFieldDataType();
         $defaultValue = decode_html($mandatoryField->get('defaultvalue'));
         if (!empty($element[$fieldName])) {
             continue;
         } else {
             $fieldValue = $defaultValue;
             if (empty($fieldValue)) {
                 $fieldValue = Vtiger_Util_Helper::getDefaultMandatoryValue($fieldType);
             }
             $element[$fieldName] = $fieldValue;
         }
     }
     $entity = vtws_create($moduleName, $element, $user);
     $this->updateCustomerInPhoneCalls($entity, $request);
     $response = new Vtiger_Response();
     $response->setResult(true);
     $response->emit();
 }
Пример #7
0
    if (!empty($search_onlyin) && $search_onlyin != '--USESELECTED--') {
        $search_onlyin = explode(',', $search_onlyin);
    } else {
        if ($search_onlyin == '--USESELECTED--') {
            $search_onlyin = $_SESSION['__UnifiedSearch_SelectedModules__'];
        } else {
            $search_onlyin = array();
        }
    }
    // Save the selection for future use (UnifiedSearchModules.php)
    $_SESSION['__UnifiedSearch_SelectedModules__'] = $search_onlyin;
    if (count($search_onlyin) > 0) {
        // we save this users preferences in a global variable
        global $current_user, $adb;
        include_once 'include/Webservices/Create.php';
        $checkrs = $adb->pquery('select crmid
			from vtiger_globalvariable
			inner join vtiger_crmentity on crmid=globalvariableid
			where deleted=0 and gvname=? and smownerid=?', array('Application_Global_Search_SelectedModules', $current_user->id));
        if ($adb->num_rows($checkrs) > 0) {
            $gvid = $adb->query_result($checkrs, 0, 0);
            $adb->pquery('update vtiger_globalvariable set value=? where globalvariableid=?', array(implode(',', $search_onlyin), $gvid));
        } else {
            $wsrs = $adb->pquery('select id from vtiger_ws_entity where name=?', array('Users'));
            if ($wsrs and $adb->num_rows($wsrs) == 1) {
                $usrwsid = $adb->query_result($wsrs, 0, 0) . 'x';
            }
            vtws_create('GlobalVariable', array('gvname' => 'Application_Global_Search_SelectedModules', 'default_check' => '0', 'value' => implode(',', $search_onlyin), 'mandatory' => '0', 'blocked' => '0', 'module_list' => '', 'category' => 'System', 'in_module_list' => '', 'assigned_user_id' => $usrwsid . $current_user->id), $current_user);
        }
    }
}
Пример #8
0
 /**
  * Create new record in module $moduleName by params $restData.
  * Return created record reference.
  * @param String $moduleName
  * @param Array $restData
  * @return String
  */
 public function create($moduleName, $restData)
 {
     $restData['assigned_user_id'] = $this->assignedUserReference;
     $result = vtws_create($moduleName, $restData, $this->restUser);
     return $result['id'];
 }
Пример #9
0
function vtws_convertlead($leadId, $assignedTo, $accountName, $avoidPotential, $potential, $user)
{
    global $adb, $log;
    if (empty($assignedTo)) {
        $assignedTo = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if ((bool) $avoidPotential !== true) {
        try {
            if (empty($potential)) {
                throw new WebServiceException(WebServiceErrorCode::$INVALID_POTENTIAL_FOR_CONVERT_LEAD, "Invalid lead information given for potential");
            }
        } catch (Zend_Json_Exception $e) {
            throw new WebServiceException(WebServiceErrorCode::$INVALID_POTENTIAL_FOR_CONVERT_LEAD, "Potentail information given is not in valid JSON format");
        }
    }
    $currencyInfo = getCurrencySymbolandCRate($user->currency_id);
    $rate = $currencyInfo['rate'];
    if ($potential['amount'] != '') {
        $potential['amount'] = convertToDollar($potential['amount'], $rate);
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadHandler->getMeta()->retrieveMeta();
    $leadInfo = vtws_retrieve($leadId, $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($leadId);
    $result = $adb->pquery($sql, array($leadIdComponents[1]));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount > 0) {
        throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    $customFieldMapping = vtws_getConvertLeadFieldMapping();
    //check if accountName given in request is empty then default to lead company field.
    if (empty($accountName)) {
        $accountName = $leadInfo['company'];
    }
    $sql = "select vtiger_account.accountid from vtiger_account\n\t\tleft join vtiger_crmentity on vtiger_account.accountid = vtiger_crmentity.crmid\n\t\twhere vtiger_crmentity.deleted=0 and vtiger_account.accountname = ?";
    $result = $adb->pquery($sql, array($accountName));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount != 0 && vtlib_isModuleActive('Accounts') === true) {
        $crmId = $adb->query_result($result, 0, "accountid");
        $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $crmId);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Account");
        }
        //Retrieve the lead related products and relate them with this new account
        $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $crmId, "Accounts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Account");
        }
        $status = vtws_saveLeadRelations($leadIdComponents[1], $crmId, "Accounts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Account");
        }
    } else {
        //don't create account if no company name is given in input and lead doest not have
        // company field populated, DONE TO RESPECT B2C model.
        if (!empty($accountName)) {
            $accountObject = VtigerWebserviceObject::fromName($adb, 'Accounts');
            $handlerPath = $accountObject->getHandlerPath();
            $handlerClass = $accountObject->getHandlerClass();
            require_once $handlerPath;
            $accountHandler = new $handlerClass($accountObject, $user, $adb, $log);
            if ($accountHandler->getMeta()->hasWriteAccess()) {
                $account = array();
                if (!empty($leadInfo["annualrevenue"])) {
                    $account['annual_revenue'] = $leadInfo["annualrevenue"];
                }
                if (!empty($leadInfo["noofemployees"])) {
                    $account['employees'] = $leadInfo["noofemployees"];
                }
                $account['accountname'] = $accountName;
                $account['industry'] = $leadInfo["industry"];
                $account['phone'] = $leadInfo["phone"];
                $account['fax'] = $leadInfo["fax"];
                $account['rating'] = $leadInfo["rating"];
                $account['email1'] = $leadInfo["email"];
                $account['website'] = $leadInfo["website"];
                $account['bill_city'] = $leadInfo["city"];
                $account['bill_code'] = $leadInfo["code"];
                $account['bill_country'] = $leadInfo["country"];
                $account['bill_state'] = $leadInfo["state"];
                $account['bill_street'] = $leadInfo["lane"];
                $account['bill_pobox'] = $leadInfo["pobox"];
                $account['ship_city'] = $leadInfo["city"];
                $account['ship_code'] = $leadInfo["code"];
                $account['ship_country'] = $leadInfo["country"];
                $account['ship_state'] = $leadInfo["state"];
                $account['ship_street'] = $leadInfo["lane"];
                $account['ship_pobox'] = $leadInfo["pobox"];
                $account['assigned_user_id'] = $assignedTo;
                $account['description'] = $leadInfo['description'];
                $leadFields = $leadHandler->getMeta()->getModuleFields();
                $accountFields = $accountHandler->getMeta()->getModuleFields();
                foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
                    $accountFieldId = $mappingDetails['Accounts'];
                    if (empty($accountFieldId)) {
                        continue;
                    }
                    $accountField = vtws_getFieldfromFieldId($accountFieldId, $accountFields);
                    if ($accountField == null) {
                        //user doesn't have access so continue.TODO update even if user doesn't have access
                        continue;
                    }
                    $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
                    if ($leadField == null) {
                        //user doesn't have access so continue.TODO update even if user doesn't have access
                        continue;
                    }
                    $leadFieldName = $leadField->getFieldName();
                    $accountFieldName = $accountField->getFieldName();
                    $account[$accountFieldName] = $leadInfo[$leadFieldName];
                }
                $account = vtws_create('Accounts', $account, $user);
                $accountIdComponents = vtws_getIdComponents($account['id']);
                $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $accountIdComponents[1]);
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Account");
                }
                //Retrieve the lead related products and relate them with this new account
                $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $accountIdComponents[1], "Accounts");
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Account");
                }
                $status = vtws_saveLeadRelations($leadIdComponents[1], $accountIdComponents[1], "Accounts");
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Account");
                }
            }
        }
    }
    $contactObject = VtigerWebserviceObject::fromName($adb, 'Contacts');
    $handlerPath = $contactObject->getHandlerPath();
    $handlerClass = $contactObject->getHandlerClass();
    require_once $handlerPath;
    $contactHandler = new $handlerClass($contactObject, $user, $adb, $log);
    if (!empty($crmId)) {
        $accountId = $crmId;
        $webserviceAccountId = vtws_getWebserviceEntityId('Accounts', $crmId);
    } elseif (!empty($accountName)) {
        if (count($accountIdComponents) === 2) {
            $accountId = $accountIdComponents[1];
            $webserviceAccountId = vtws_getId($accountIdComponents[0], $accountIdComponents[1]);
        }
    } else {
        $accountId = '';
        $webserviceAccountId = '';
    }
    if ($contactHandler->getMeta()->hasWriteAccess()) {
        $contact = array();
        $contact['assigned_user_id'] = $assignedTo;
        $contact['description'] = $leadInfo['description'];
        $contact['account_id'] = $webserviceAccountId;
        $contact['salutationtype'] = $leadInfo["salutationtype"];
        $contact['firstname'] = $leadInfo["firstname"];
        $contact['lastname'] = $leadInfo["lastname"];
        $contact['email'] = $leadInfo["email"];
        $contact['phone'] = $leadInfo["phone"];
        $contact['mobile'] = $leadInfo["mobile"];
        $contact['title'] = $leadInfo["designation"];
        $contact['fax'] = $leadInfo["fax"];
        $contact['yahooid'] = $leadInfo['yahooid'];
        $contact['leadsource'] = $leadInfo['leadsource'];
        $contact['mailingcity'] = $leadInfo["city"];
        $contact['mailingzip'] = $leadInfo["code"];
        $contact['mailingcountry'] = $leadInfo["country"];
        $contact['mailingstate'] = $leadInfo["state"];
        $contact['mailingstreet'] = $leadInfo["lane"];
        $contact['mailingpobox'] = $leadInfo["pobox"];
        $leadFields = $leadHandler->getMeta()->getModuleFields();
        $contactFields = $contactHandler->getMeta()->getModuleFields();
        foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
            $contactFieldId = $mappingDetails['Contacts'];
            if (empty($contactFieldId)) {
                continue;
            }
            $contactField = vtws_getFieldfromFieldId($contactFieldId, $contactFields);
            if ($contactField == null) {
                //user doesn't have access so continue.TODO update even if user doesn't have access
                continue;
            }
            $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
            if ($leadField == null) {
                //user doesn't have access so continue.TODO update even if user doesn't have access
                continue;
            }
            $leadFieldName = $leadField->getFieldName();
            $contactFieldName = $contactField->getFieldName();
            $contact[$contactFieldName] = $leadInfo[$leadFieldName];
        }
        $contact = vtws_create('Contacts', $contact, $user);
        $contactIdComponents = vtws_getIdComponents($contact['id']);
        $contactId = $contactIdComponents[1];
        //To convert relates Activites and Email.
        $status = vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Activities to the Contact");
        }
        $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Contact");
        }
        //Retrieve the lead related products and relate them with this new contact
        $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $contactIdComponents[1], "Contacts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Contact");
        }
        $status = vtws_saveLeadRelations($leadIdComponents[1], $contactIdComponents[1], "Contacts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Contact");
        }
        //Retrieve the lead related Campaigns and relate them with this new contact --Minnie
        $status = vtws_saveLeadRelatedCampaigns($leadIdComponents[1], $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Campaigns to the Contact");
        }
    }
    if ((bool) $avoidPotential != true) {
        $potentialObject = VtigerWebserviceObject::fromName($adb, 'Potentials');
        $handlerPath = $potentialObject->getHandlerPath();
        $handlerClass = $potentialObject->getHandlerClass();
        require_once $handlerPath;
        $potentialHandler = new $handlerClass($potentialObject, $user, $adb, $log);
        if ($potentialHandler->getMeta()->hasWriteAccess()) {
            if (!empty($webserviceAccountId)) {
                $relatedTo = $webserviceAccountId;
            } else {
                if (!empty($contactId)) {
                    $relatedTo = vtws_getWebserviceEntityId('Contacts', $contactId);
                }
            }
            $potential['assigned_user_id'] = $assignedTo;
            $potential['description'] = $leadInfo['description'];
            $potential['related_to'] = $relatedTo;
            $potential['leadsource'] = $leadInfo['leadsource'];
            $leadFields = $leadHandler->getMeta()->getModuleFields();
            $potentialFields = $potentialHandler->getMeta()->getModuleFields();
            foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
                $potentialFieldId = $mappingDetails['Potentials'];
                if (empty($potentialFieldId)) {
                    continue;
                }
                $potentialField = vtws_getFieldfromFieldId($potentialFieldId, $potentialFields);
                if ($potentialField == null) {
                    //user doesn't have access so continue.TODO update even if user doesn't have access
                    continue;
                }
                $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
                if ($leadField == null) {
                    //user doesn't have access so continue.TODO update even if user doesn't have access
                    continue;
                }
                $leadFieldName = $leadField->getFieldName();
                $potentialFieldName = $potentialField->getFieldName();
                $potential[$potentialFieldName] = $leadInfo[$leadFieldName];
            }
            $potential = vtws_create('Potentials', $potential, $user);
            $potentialIdComponents = vtws_getIdComponents($potential['id']);
            if (!empty($accountId) && !empty($contactId)) {
                $sql = "insert into vtiger_contpotentialrel values(?,?)";
                $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
                if ($result === false) {
                    throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
                }
            }
            //Retrieve the lead related products and relate them with this new potential
            $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $potentialIdComponents[1], "Potentials");
            if ($status === false) {
                throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Potential");
            }
            $status = vtws_saveLeadRelations($leadIdComponents[1], $potentialIdComponents[1], "Potentials");
            if ($status === false) {
                throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Potential");
            }
            $potentialId = $potentialIdComponents[1];
        }
    }
    //Updating the converted status
    if ($accountId != '' || $contactId != '') {
        $sql = "UPDATE vtiger_leaddetails SET converted = 1 where leadid=?";
        $result = $adb->pquery($sql, array($leadIdComponents[1]));
        if ($result === false) {
            throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_MARK_CONVERTED, "Failed mark lead converted");
        }
        //updating the campaign-lead relation --Minnie
        $sql = "delete from vtiger_campaignleadrel where leadid=?";
        $adb->pquery($sql, array($leadIdComponents[1]));
    }
    $result = array('leadId' => $leadId);
    if (!empty($webserviceAccountId)) {
        $result['accountId'] = $webserviceAccountId;
    } else {
        $result['accountId'] = '';
    }
    if (!empty($contactId)) {
        $result['contactId'] = vtws_getWebserviceEntityId('Contacts', $contactId);
    } else {
        $result['contactId'] = '';
    }
    if (!empty($potentialId)) {
        $result['potentialId'] = $potential['id'];
    } else {
        $result['potentialId'] = '';
    }
    return $result;
}
Пример #10
0
function csv_to_array($file = '', $length = 0, $delimiter = ',')
{
    $header = NULL;
    $data = array();
    if (($handle = fopen($file, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, $length, $delimiter)) !== FALSE) {
            if (!$header) {
                $header = $row;
            } else {
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}
include_once 'include/Webservices/Create.php';
$i = 0;
foreach (csv_to_array($file) as $row) {
    //print_r($row);
    try {
        $row = vtws_create('Emails', $row, $current_user);
        echo $row['id'] . PHP_EOL;
    } catch (WebServiceException $ex) {
        $msg = $ex->getMessage();
        $msg .= print_r($row, true) . "\n";
        error_log($msg, 3, $file . "-error.log");
        echo $msg;
    }
    //if ($i++>=1) break;  // for testing before full launch
}
Пример #11
0
            if (!$header) {
                $header = $row;
            } else {
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}
include_once 'include/Webservices/Create.php';
$i = 0;
foreach (csv_to_array($file) as $row) {
    //print_r($row);
    try {
        if ($row['activitytype'] == 'Task') {
            $mod = 'Calendar';
        } else {
            $mod = 'Events';
        }
        $row['recurringtype'] = '--None--';
        $row = vtws_create($mod, $row, $current_user);
        echo $mod . ": " . $row['id'] . PHP_EOL;
    } catch (WebServiceException $ex) {
        $msg = $ex->getMessage();
        $msg .= print_r($row, true) . "\n";
        error_log($msg, 3, $file . "-error.log");
        echo $msg;
    }
    //if ($i++==10) break;  // for testing before full launch
}
Пример #12
0
function vtws_createEntity($recordid, $originMod, $targetMod)
{
    global $adb, $current_user, $log;
    $return = 0;
    $newEntityInfo = CRMEntity::getInstance($targetMod);
    $mapfound = false;
    foreach ($originMod as $modName) {
        if ($recordid[$modName]) {
            $oldEntityInfo = CRMEntity::getInstance($modName);
            $oldEntityInfo->retrieve_entity_info(vtws_getIdComponents($recordid[$modName])[1], $modName);
            $map_name = $modName . '2' . $targetMod;
            $cbMapid = GlobalVariable::getVariable('BusinessMapping_' . $map_name, cbMap::getMapIdByName($map_name));
            if ($cbMapid) {
                $mapfound = true;
                $cbMap = cbMap::getMapByID($cbMapid);
                $newEntityInfo->column_fields = $cbMap->Mapping($oldEntityInfo->column_fields, $newEntityInfo->column_fields);
            }
        }
    }
    if ($mapfound) {
        try {
            $webserviceObject = VtigerWebserviceObject::fromName($adb, $targetMod);
            $handlerPath = $webserviceObject->getHandlerPath();
            $handlerClass = $webserviceObject->getHandlerClass();
            require_once $handlerPath;
            $handler = new $handlerClass($webserviceObject, $current_user, $adb, $log);
            $meta = $handler->getMeta();
            $values = DataTransform::sanitizeReferences($newEntityInfo->column_fields, $meta);
            $values = DataTransform::sanitizeOwnerFields($values, $meta);
            $return = vtws_create($targetMod, $values, $current_user);
        } catch (Exception $e) {
            throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $targetMod);
        }
    }
    return $return;
}
 public function put($recordDetails, $user)
 {
     $log = vglobal('log');
     $this->user = $user;
     $recordDetails = $this->syncToNativeFormat($recordDetails);
     $createdRecords = $recordDetails['created'];
     $updatedRecords = $recordDetails['updated'];
     $deletedRecords = $recordDetails['deleted'];
     if (count($createdRecords) > 0) {
         $createdRecords = $this->translateReferenceFieldNamesToIds($createdRecords, $user);
         $createdRecords = $this->fillNonExistingMandatoryPicklistValues($createdRecords);
         $createdRecords = $this->fillMandatoryFields($createdRecords, $user);
     }
     foreach ($createdRecords as $index => $record) {
         $createdRecords[$index] = vtws_create($record['module'], $record, $this->user);
     }
     if (count($updatedRecords) > 0) {
         $updatedRecords = $this->translateReferenceFieldNamesToIds($updatedRecords, $user);
     }
     $crmIds = array();
     foreach ($updatedRecords as $index => $record) {
         $webserviceRecordId = $record["id"];
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         $crmIds[] = $recordIdComp[1];
     }
     $assignedRecordIds = array();
     if ($this->isClientUserSyncType()) {
         $assignedRecordIds = wsapp_checkIfRecordsAssignToUser($crmIds, $this->user->id);
         // To check if the record assigned to group
         if ($this->isClientUserAndGroupSyncType()) {
             $getUserGroups = new GetUserGroups();
             $getUserGroups->getAllUserGroups($this->user->id);
             $groupIds = $getUserGroups->user_groups;
             if (!empty($groupIds)) {
                 $groupRecordId = wsapp_checkIfRecordsAssignToUser($crmIds, $groupIds);
                 $assignedRecordIds = array_merge($assignedRecordIds, $groupRecordId);
             }
         }
         // End
     }
     foreach ($updatedRecords as $index => $record) {
         $webserviceRecordId = $record["id"];
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         try {
             if (in_array($recordIdComp[1], $assignedRecordIds)) {
                 $updatedRecords[$index] = vtws_revise($record, $this->user);
             } else {
                 if (!$this->isClientUserSyncType()) {
                     $updatedRecords[$index] = vtws_revise($record, $this->user);
                 } else {
                     $this->assignToChangedRecords[$index] = $record;
                 }
             }
         } catch (Exception $e) {
             continue;
         }
         // Added to handle duplication
         if ($record['duplicate']) {
             $updatedRecords[$index]['duplicate'] = true;
         }
         // End
     }
     $hasDeleteAccess = null;
     $deletedCrmIds = array();
     foreach ($deletedRecords as $index => $record) {
         $webserviceRecordId = $record;
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         $deletedCrmIds[] = $recordIdComp[1];
     }
     $assignedDeletedRecordIds = wsapp_checkIfRecordsAssignToUser($deletedCrmIds, $this->user->id);
     // To get record id's assigned to group of the current user
     if ($this->isClientUserAndGroupSyncType()) {
         if (!empty($groupIds)) {
             foreach ($groupIds as $group) {
                 $groupRecordId = wsapp_checkIfRecordsAssignToUser($deletedCrmIds, $group);
                 $assignedDeletedRecordIds = array_merge($assignedDeletedRecordIds, $groupRecordId);
             }
         }
     }
     // End
     foreach ($deletedRecords as $index => $record) {
         $idComp = vtws_getIdComponents($record);
         if (empty($hasDeleteAccess)) {
             $handler = vtws_getModuleHandlerFromId($idComp[0], $this->user);
             $meta = $handler->getMeta();
             $hasDeleteAccess = $meta->hasDeleteAccess();
         }
         if ($hasDeleteAccess) {
             if (in_array($idComp[1], $assignedDeletedRecordIds)) {
                 try {
                     vtws_delete($record, $this->user);
                 } catch (Exception $e) {
                     continue;
                 }
             }
         }
     }
     $recordDetails['created'] = $createdRecords;
     $recordDetails['updated'] = $updatedRecords;
     $recordDetails['deleted'] = $deletedRecords;
     return $this->nativeToSyncFormat($recordDetails);
 }
Пример #14
0
    die;
}
function csv_to_array($file = '', $length = 0, $delimiter = ';')
{
    $header = NULL;
    $data = array();
    if (($handle = fopen($file, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, $length, $delimiter)) !== FALSE) {
            if (!$header) {
                $header = $row;
            } else {
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}
include_once 'include/Webservices/Create.php';
foreach (csv_to_array($file) as $row) {
    //print_r($row);
    try {
        $row = vtws_create('Accounts', $row, $current_user);
        echo "Organisation: " . $row['id'] . PHP_EOL;
    } catch (WebServiceException $ex) {
        $msg = $ex->getMessage();
        $msg .= print_r($row, true) . "\n";
        error_log($msg, 3, $file . "-error.log");
        echo $msg;
    }
}
Пример #15
0
function importRecord($obj, $inventoryFieldData, $lineItems)
{
    global $adb, $log;
    $moduleName = $obj->module;
    $inventoryHandler = vtws_getModuleHandlerFromName($moduleName, $obj->user);
    $inventoryMeta = $inventoryHandler->getMeta();
    $currency = '';
    if (isset($inventoryFieldData['currency_id'])) {
        $currency = $inventoryFieldData['currency_id'];
        unset($inventoryFieldData['currency_id']);
    }
    $fieldData = $obj->transformForImport($inventoryFieldData, $inventoryMeta);
    $fieldData['pdoInformation'] = $lineItems;
    if (empty($fieldData) || empty($fieldData['pdoInformation'])) {
        return null;
    }
    $wsrs = $adb->pquery('select id from vtiger_ws_entity where name=?', array('Currency'));
    if ($wsrs and $adb->num_rows($wsrs) == 1) {
        $wsid = $adb->query_result($wsrs, 0, 0);
    } else {
        $wsid = 0;
    }
    if ($currency == ' ' or empty($currency)) {
        $fieldData['currency_id'] = $wsid . 'x1';
    } else {
        $crrs = $adb->pquery('select id from vtiger_currency_info where currency_name=?', array($currency));
        if ($crrs and $adb->num_rows($crrs) > 0) {
            $fieldData['currency_id'] = $wsid . 'x' . $adb->query_result($crrs, 0, 0);
        } else {
            $fieldData['currency_id'] = $wsid . 'x1';
        }
    }
    $entityInfo = vtws_create($moduleName, $fieldData, $obj->user);
    $entityInfo['status'] = $obj->getImportRecordStatus('created');
    return $entityInfo;
}
 public function createEntityRecord($moduleName, $entityLabel)
 {
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleFields = $moduleMeta->getModuleFields();
     $mandatoryFields = $moduleMeta->getMandatoryFields();
     $entityNameFieldsString = $moduleMeta->getNameFields();
     $entityNameFields = explode(',', $entityNameFieldsString);
     $fieldData = array();
     foreach ($entityNameFields as $entityNameField) {
         $entityNameField = trim($entityNameField);
         if (in_array($entityNameField, $mandatoryFields)) {
             $fieldData[$entityNameField] = $entityLabel;
         }
     }
     foreach ($mandatoryFields as $mandatoryField) {
         if (empty($fieldData[$mandatoryField])) {
             $fieldInstance = $moduleFields[$mandatoryField];
             if ($fieldInstance->getFieldDataType() == 'owner') {
                 $fieldData[$mandatoryField] = $this->user->id;
             } else {
                 $defaultValue = $fieldInstance->getDefault();
                 if (!empty($defaultValue)) {
                     $fieldData[$mandatoryField] = $defaultValue;
                 } else {
                     $fieldData[$mandatoryField] = '????';
                 }
             }
         }
     }
     $fieldData = DataTransform::sanitizeData($fieldData, $moduleMeta);
     $entityIdInfo = vtws_create($moduleName, $fieldData, $this->user);
     $focus = CRMEntity::getInstance($moduleName);
     $focus->updateMissingSeqNumber($moduleName);
     return $entityIdInfo;
 }
Пример #17
0
function vtws_convertlead($entityvalues, $user)
{
    global $adb, $log;
    if (empty($entityvalues['assignedTo'])) {
        $entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if (empty($entityvalues['transferRelatedRecordsTo'])) {
        $entityvalues['transferRelatedRecordsTo'] = 'Contacts';
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadInfo = vtws_retrieve($entityvalues['leadId'], $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($entityvalues['leadId']);
    $result = $adb->pquery($sql, array($leadIdComponents[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::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    $entityIds = array();
    $availableModules = array('Accounts', 'Contacts', 'Potentials');
    if (!($entityvalues['entities']['Accounts']['create'] || $entityvalues['entities']['Contacts']['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_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo);
            //update potential related to property
            if ($entityvalue['name'] == 'Potentials') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['related_to'] = $entityIds['Accounts'];
                }
                if (!empty($entityIds['Contacts'])) {
                    $entityObjectValues['contact_id'] = $entityIds['Contacts'];
                }
            }
            //update the contacts relation
            if ($entityvalue['name'] == 'Contacts') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['account_id'] = $entityIds['Accounts'];
                }
            }
            try {
                $create = true;
                if ($entityvalue['name'] == 'Accounts') {
                    $sql = "SELECT vtiger_account.accountid FROM vtiger_account,vtiger_crmentity WHERE vtiger_crmentity.crmid=vtiger_account.accountid AND vtiger_account.accountname=? AND vtiger_crmentity.deleted=0";
                    $result = $adb->pquery($sql, array($entityvalue['accountname']));
                    if ($adb->num_rows($result) > 0) {
                        $entityIds[$entityName] = vtws_getWebserviceEntityId('Accounts', $adb->query_result($result, 0, 'accountid'));
                        $create = false;
                    }
                }
                if ($create) {
                    $entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user);
                    $entityIds[$entityName] = $entityRecord['id'];
                }
            } catch (Exception $e) {
                throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $entityvalue['name']);
            }
        }
    }
    try {
        $accountIdComponents = vtws_getIdComponents($entityIds['Accounts']);
        $accountId = $accountIdComponents[1];
        $contactIdComponents = vtws_getIdComponents($entityIds['Contacts']);
        $contactId = $contactIdComponents[1];
        if (!empty($accountId) && !empty($contactId) && !empty($entityIds['Potentials'])) {
            $potentialIdComponents = vtws_getIdComponents($entityIds['Potentials']);
            $potentialId = $potentialIdComponents[1];
            $sql = "insert into vtiger_contpotentialrel values(?,?)";
            $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
            if ($result === false) {
                throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
            }
        }
        $transfered = vtws_convertLeadTransferHandler($leadIdComponents, $entityIds, $entityvalues);
        $relatedIdComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]);
        vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $relatedIdComponents[1]);
        vtws_updateConvertLeadStatus($entityIds, $entityvalues['leadId'], $user);
    } catch (Exception $e) {
        foreach ($entityIds as $entity => $id) {
            vtws_delete($id, $user);
        }
        return null;
    }
    return $entityIds;
}
Пример #18
0
function webforms_init()
{
    global $defaultUserName, $defaultUserAccessKey, $defaultOwner, $adb, $enableAppKeyValidation, $application_unique_key;
    try {
        $active = vtlib_isModuleActive('Webforms');
        if ($active === false) {
            webforms_returnError(array('code' => "WEBFORMS_DISABLED", 'message' => 'Webforms module is disabled'), 'Webforms');
        }
        if ($enableAppKeyValidation == true) {
            if ($application_unique_key !== $_REQUEST['appKey']) {
                webforms_returnError(array('code' => "WEBFORMS_INVALID_APPKEY", 'message' => 'AppKey provided is invalid'), null);
                return;
            }
        }
        $module = $_REQUEST['moduleName'];
        $challengeResult = vtws_getchallenge($defaultUserName);
        $challengeToken = $challengeResult['token'];
        $user = vtws_login($defaultUserName, md5($challengeToken . $defaultUserAccessKey));
        $describeResult = vtws_describe($module, $user);
        $fields = $describeResult['fields'];
        $assignedUser = new Users();
        $ownerId = $assignedUser->retrieve_user_id($defaultOwner);
        $userData = webforms_getUserData(vtws_getId(VtigerWebserviceObject::fromName($adb, "Users")->getEntityId(), $ownerId), $fields, $_REQUEST);
        if ($userData === null) {
            webforms_returnError(array('code' => "WEBFORMS_INVALID_DATA", 'message' => 'data provided is invalid'), $module);
            return;
        }
        if (sizeof($userData) < 1) {
            webforms_returnError(array('code' => "WEBFORMS_INVALID_DATA", 'message' => 'data provided is invalid'), $module);
            return;
        }
        $createResult = vtws_create($module, $userData, $user);
        webforms_returnSuccess($createResult, $module);
    } catch (WebServiceException $e) {
        webforms_returnError($e, $module);
    }
}
Пример #19
0
 public function createEntityRecord($moduleName, $entityLabel)
 {
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleFields = $moduleMeta->getModuleFields();
     $mandatoryFields = $moduleMeta->getMandatoryFields();
     $entityNameFieldsString = $moduleMeta->getNameFields();
     $entityNameFields = explode(',', $entityNameFieldsString);
     $fieldData = array();
     foreach ($entityNameFields as $entityNameField) {
         $entityNameField = trim($entityNameField);
         if (in_array($entityNameField, $mandatoryFields)) {
             $fieldData[$entityNameField] = $entityLabel;
         }
     }
     foreach ($mandatoryFields as $mandatoryField) {
         if (empty($fieldData[$mandatoryField])) {
             $fieldInstance = $moduleFields[$mandatoryField];
             if ($fieldInstance->getFieldDataType() == 'owner') {
                 $fieldData[$mandatoryField] = $this->user->id;
             } else {
                 if (!in_array($mandatoryField, $entityNameFields) && $fieldInstance->getFieldDataType() != 'reference') {
                     $fieldData[$mandatoryField] = '????';
                 }
             }
         }
     }
     $fieldData = DataTransform::sanitizeData($fieldData, $moduleMeta);
     $entityIdInfo = vtws_create($moduleName, $fieldData, $this->user);
     $adb = PearDatabase::getInstance();
     $entityIdComponents = vtws_getIdComponents($entityIdInfo['id']);
     $recordId = $entityIdComponents[1];
     $entityfields = getEntityFieldNames($moduleName);
     switch ($moduleName) {
         case 'HelpDesk':
             $entityfields['fieldname'] = array('ticket_title');
             break;
         case 'Documents':
             $entityfields['fieldname'] = array('notes_title');
             break;
         case 'Documents':
             $entityfields['fieldname'] = array('notes_title');
             break;
     }
     $label = '';
     if (is_array($entityfields['fieldname'])) {
         foreach ($entityfields['fieldname'] as $field) {
             $label .= $fieldData[$field] . " ";
         }
     } else {
         $label = $fieldData[$entityfields['fieldname']];
     }
     $label = trim($label);
     $adb->pquery('UPDATE vtiger_crmentity SET label=? WHERE crmid=?', array($label, $recordId));
     $recordModel = Vtiger_Record_Model::getCleanInstance($moduleName);
     $focus = $recordModel->getEntity();
     $focus->id = $recordId;
     $focus->column_fields = $fieldData;
     $this->entityData[] = VTEntityData::fromCRMEntity($focus);
     $focus->updateMissingSeqNumber($moduleName);
     return $entityIdInfo;
 }
Пример #20
-9
 function captureNow($request)
 {
     $currentLanguage = Vtiger_Language_Handler::getLanguage();
     $moduleLanguageStrings = Vtiger_Language_Handler::getModuleStringsFromFile($currentLanguage);
     vglobal('app_strings', $moduleLanguageStrings['languageStrings']);
     $returnURL = false;
     try {
         if (!vtlib_isModuleActive('Webforms')) {
             throw new Exception('webforms is not active');
         }
         $webform = Webforms_Model::retrieveWithPublicId(vtlib_purify($request['publicid']));
         if (empty($webform)) {
             throw new Exception("Webform not found.");
         }
         $returnURL = $webform->getReturnUrl();
         $roundrobin = $webform->getRoundrobin();
         // Retrieve user information
         $user = CRMEntity::getInstance('Users');
         $user->id = $user->getActiveAdminId();
         $user->retrieve_entity_info($user->id, 'Users');
         // Prepare the parametets
         $parameters = array();
         $webformFields = $webform->getFields();
         foreach ($webformFields as $webformField) {
             if ($webformField->getDefaultValue() != null) {
                 $parameters[$webformField->getFieldName()] = decode_html($webformField->getDefaultValue());
             } else {
                 $webformNeutralizedField = html_entity_decode($webformField->getNeutralizedField(), ENT_COMPAT, "UTF-8");
                 if (is_array(vtlib_purify($request[$webformNeutralizedField]))) {
                     $fieldData = implode(" |##| ", vtlib_purify($request[$webformNeutralizedField]));
                 } else {
                     $fieldData = vtlib_purify($request[$webformNeutralizedField]);
                     $fieldData = decode_html($fieldData);
                 }
                 $parameters[$webformField->getFieldName()] = stripslashes($fieldData);
             }
             if ($webformField->getRequired()) {
                 if (!isset($parameters[$webformField->getFieldName()])) {
                     throw new Exception("Required fields not filled");
                 }
             }
         }
         if ($roundrobin) {
             $ownerId = $webform->getRoundrobinOwnerId();
             $ownerType = vtws_getOwnerType($ownerId);
             $parameters['assigned_user_id'] = vtws_getWebserviceEntityId($ownerType, $ownerId);
         } else {
             $ownerId = $webform->getOwnerId();
             $ownerType = vtws_getOwnerType($ownerId);
             $parameters['assigned_user_id'] = vtws_getWebserviceEntityId($ownerType, $ownerId);
         }
         // Create the record
         $record = vtws_create($webform->getTargetModule(), $parameters, $user);
         $this->sendResponse($returnURL, 'ok');
         return;
     } catch (Exception $e) {
         $this->sendResponse($returnURL, false, $e->getMessage());
         return;
     }
 }