Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape backslashes in company names (and just in case, contact emails) #5835

Merged
merged 2 commits into from
Mar 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
77 changes: 65 additions & 12 deletions plugins/MauticCrmBundle/Api/SalesforceApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public function getPerson(array $data)
$fields = $this->integration->getFieldsForQuery('Contact');
$fields[] = 'Id';
$fields = implode(', ', array_unique($fields));
$findContact = 'select '.$fields.' from Contact where email = \''.str_replace("'", "\'", $this->integration->cleanPushData($data['Contact']['Email'])).'\'';
$findContact = 'select '.$fields.' from Contact where email = \''.$this->escapeQueryValue($data['Contact']['Email']).'\'';
$response = $this->request('query', ['q' => $findContact], 'GET', false, null, $queryUrl);

if (!empty($response['records'])) {
Expand All @@ -120,7 +120,7 @@ public function getPerson(array $data)
$fields = $this->integration->getFieldsForQuery('Lead');
$fields[] = 'Id';
$fields = implode(', ', array_unique($fields));
$findLead = 'select '.$fields.' from Lead where email = \''.str_replace("'", "\'", $this->integration->cleanPushData($data['Lead']['Email'])).'\' and ConvertedContactId = NULL';
$findLead = 'select '.$fields.' from Lead where email = \''.$this->escapeQueryValue($data['Lead']['Email']).'\' and ConvertedContactId = NULL';
$response = $this->request('queryAll', ['q' => $findLead], 'GET', false, null, $queryUrl);

if (!empty($response['records'])) {
Expand Down Expand Up @@ -152,20 +152,20 @@ public function getCompany(array $data)
if (isset($config['objects']) && false !== array_search('company', $config['objects']) && !empty($data['company']['Name'])) {
$fields = $this->integration->getFieldsForQuery('Account');

if (isset($data['company']['BillingCountry']) && !empty($data['company']['BillingCountry'])) {
$appendToQuery .= ' and BillingCountry = \''.str_replace("'", "\'", $this->integration->cleanPushData($data['company']['BillingCountry'])).'\'';
if (!empty($data['company']['BillingCountry'])) {
$appendToQuery .= ' and BillingCountry = \''.$this->escapeQueryValue($data['company']['BillingCountry']).'\'';
}
if (isset($data['company']['BillingCity']) && !empty($data['company']['BillingCity'])) {
$appendToQuery .= ' and BillingCity = \''.str_replace("'", "\'", $this->integration->cleanPushData($data['company']['BillingCity'])).'\'';
if (!empty($data['company']['BillingCity'])) {
$appendToQuery .= ' and BillingCity = \''.$this->escapeQueryValue($data['company']['BillingCity']).'\'';
}
if (isset($data['company']['BillingState']) && !empty($data['company']['BillingState'])) {
$appendToQuery .= ' and BillingState = \''.str_replace("'", "\'", $this->integration->cleanPushData($data['company']['BillingState'])).'\'';
if (!empty($data['company']['BillingState'])) {
$appendToQuery .= ' and BillingState = \''.$this->escapeQueryValue($data['company']['BillingState']).'\'';
}

$fields[] = 'Id';
$fields = implode(', ', array_unique($fields));
$findContact = 'select '.$fields.' from Account where Name = \''.str_replace("'", "\'", $this->integration->cleanPushData($data['company']['Name'])).'\''.$appendToQuery;
$response = $this->request('queryAll', ['q' => $findContact], 'GET', false, null, $queryUrl);
$fields[] = 'Id';
$fields = implode(', ', array_unique($fields));
$query = 'select '.$fields.' from Account where Name = \''.$this->escapeQueryValue($data['company']['Name']).'\''.$appendToQuery;
$response = $this->request('queryAll', ['q' => $query], 'GET', false, null, $queryUrl);

if (!empty($response['records'])) {
$sfRecords['company'] = $response['records'];
Expand Down Expand Up @@ -487,6 +487,39 @@ public function getRequestCounter()
return $count;
}

/**
* @param array $names
* @param null $requiredFieldString
*
* @return mixed|string
*
* @throws ApiErrorException
*/
public function getCompaniesByName(array $names, $requiredFieldString)
{
$names = array_map([$this, 'escapeQueryValue'], $names);
$queryUrl = $this->integration->getQueryUrl();
$findQuery = 'select Id, '.$requiredFieldString.' from Account where isDeleted = false and Name in (\''.implode("','", $names).'\')';

return $this->request('query', ['q' => $findQuery], 'GET', false, null, $queryUrl);
}

/**
* @param array $ids
* @param $requiredFieldString
*
* @return mixed|string
*
* @throws ApiErrorException
*/
public function getCompaniesById(array $ids, $requiredFieldString)
{
$findQuery = 'select isDeleted, Id, '.$requiredFieldString.' from Account where Id in (\''.implode("','", $ids).'\')';
$queryUrl = $this->integration->getQueryUrl();

return $this->request('queryAll', ['q' => $findQuery], 'GET', false, null, $queryUrl);
}

/**
* @param mixed $response
* @param bool $isRetry
Expand Down Expand Up @@ -574,4 +607,24 @@ private function checkIfLockedRequestShouldBeRetried()

return false;
}

/**
* @param $value
*
* @return bool|float|mixed|string
*/
private function escapeQueryValue($value)
{
// SF uses backslashes as escape delimeter
// Remember that PHP uses \ as an escape. Therefore, to replace a single backslash with 2, must use 2 and 4
$value = str_replace('\\', '\\\\', $value);

// Escape single quotes
$value = str_replace("'", "\'", $value);

// Apply general formatting/cleanup
$value = $this->integration->cleanPushData($value);

return $value;
}
}
62 changes: 27 additions & 35 deletions plugins/MauticCrmBundle/Integration/SalesforceIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -2830,7 +2830,7 @@ public function pushCompanies($params = [])
}

if ($checkCompaniesInSF) {
$sfEntityRecords = $this->getSalesforceAccountsByName($sfObject, $checkCompaniesInSF, implode(',', array_keys($config['companyFields'])));
$sfEntityRecords = $this->getSalesforceAccountsByName($checkCompaniesInSF, implode(',', array_keys($config['companyFields'])));

if (!isset($sfEntityRecords['records'])) {
// Something is wrong so throw an exception to prevent creating a bunch of new companies
Expand Down Expand Up @@ -3122,62 +3122,54 @@ protected function getMauticEntitesToCreate(
}

/**
* @param $sfObject
* @param $checkIdsInSF
* @param $requiredFieldString
*
* @return array
*
* @throws ApiErrorException
* @throws \Doctrine\ORM\ORMException
* @throws \Exception
*/
protected function getSalesforceAccountsByName($sfObject, &$checkIdsInSF, $requiredFieldString)
protected function getSalesforceAccountsByName(&$checkIdsInSF, $requiredFieldString)
{
$field = [];
$fieldId = [];
$queryById = [];

foreach ($checkIdsInSF as $items) {
if (!isset($items['integration_entity_id'])) {
foreach ($items as $key => $item) {
if ($key == 'companyname') {
$field[] = str_replace("'", "\'", $this->cleanPushData($item));
}
}
} else {
foreach ($items as $key => $item) {
if ($key == 'integration_entity_id') {
$fieldId[$item] = $item;
}
}
}
}
$searchForIds = [];
$searchForNames = [];

$fieldString = "'".implode("','", $field)."'";
foreach ($checkIdsInSF as $key => $company) {
if (!empty($company['integration_entity_id'])) {
$searchForIds[$key] = $company['integration_entity_id'];

$queryUrl = $this->getQueryUrl();
$findQuery = 'select Id, '.$requiredFieldString.' from '.$sfObject.' where isDeleted = false and Name in ('.$fieldString.')';
$queryByName = $this->getApiHelper()->request('query', ['q' => $findQuery], 'GET', false, null, $queryUrl);
continue;
}

if (!empty($fieldId)) {
$idString = "'".implode("','", $fieldId)."'";
$findQuery = 'select isDeleted, Id, '.$requiredFieldString.' from '.$sfObject.' where Id in ('.$idString.')';
$queryById = $this->getApiHelper()->request('queryAll', ['q' => $findQuery], 'GET', false, null, $queryUrl);
if (!empty($company['companyname'])) {
$searchForNames[$key] = $company['companyname'];
}
}

$resultsByName = $this->getApiHelper()->getCompaniesByName($searchForNames, $requiredFieldString);
$resultsById = [];
if (!empty($searchForIds)) {
$resultsById = $this->getApiHelper()->getCompaniesById($searchForIds, $requiredFieldString);

//mark as deleleted
foreach ($queryById['records'] as $sfId => $record) {
foreach ($resultsById['records'] as $sfId => $record) {
if (isset($record['IsDeleted']) && $record['IsDeleted'] == 1) {
$foundKey = array_search($record['Id'], $fieldId);
if ($foundKey) {
if ($foundKey = array_search($record['Id'], $searchForIds)) {
$integrationEntity = $this->em->getReference('MauticPluginBundle:IntegrationEntity', $checkIdsInSF[$foundKey]['id']);
$integrationEntity->setInternalEntity('company-deleted');
$this->persistIntegrationEntities[] = $integrationEntity;
unset($checkIdsInSF[$foundKey]);
}
unset($queryById['records'][$sfId]);

unset($resultsById['records'][$sfId]);
}
}
}

$this->cleanupFromSync();
$result = array_merge($queryByName, $queryById);
$result = array_merge($resultsByName, $resultsById);

return $result;
}
Expand Down
137 changes: 137 additions & 0 deletions plugins/MauticCrmBundle/Tests/Api/SalesforceApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,141 @@ public function testErrorDoesNotRetryRequest()
$this->assertEquals($message, $exception->getMessage());
}
}

/**
* @testdox Test that a backslash and a single quote are escaped for SF queries
*
* @covers \MauticPlugin\MauticCrmBundle\Api\SalesforceApi::escapeQueryValue()
*/
public function testCompanyQueryIsEscapedCorrectly()
{
$integration = $this->getMockBuilder(SalesforceIntegration::class)
->disableOriginalConstructor()
->setMethodsExcept(['cleanPushData'])
->getMock();

$integration->expects($this->exactly(1))
->method('mergeConfigToFeatureSettings')
->willReturn(
[
'objects' => [
'company',
],
]
);

$integration->expects($this->exactly(1))
->method('makeRequest')
->willReturnCallback(
function ($url, $parameters = [], $method = 'GET', $settings = []) {
$this->assertEquals(
$parameters,
[
'q' => 'select Id from Account where Name = \'Some\\\\thing E\\\'lse\' and BillingCountry = \'Some\\\\Where E\\\'lse\' and BillingCity = \'Some\\\\Where E\\\'lse\' and BillingState = \'Some\\\\Where E\\\'lse\'',
]
);
}
);

$api = new SalesforceApi($integration);

$api->getCompany(
[
'company' => [
'BillingCountry' => 'Some\\Where E\'lse',
'BillingCity' => 'Some\\Where E\'lse',
'BillingState' => 'Some\\Where E\'lse',
'Name' => 'Some\\thing E\'lse',
],
]
);
}

/**
* @testdox Test that a backslash and a single quote are escaped for SF queries
*
* @covers \MauticPlugin\MauticCrmBundle\Api\SalesforceApi::escapeQueryValue()
*/
public function testContactQueryIsEscapedCorrectly()
{
$integration = $this->getMockBuilder(SalesforceIntegration::class)
->disableOriginalConstructor()
->setMethodsExcept(['cleanPushData'])
->getMock();

$integration->expects($this->exactly(1))
->method('mergeConfigToFeatureSettings')
->willReturn(
[
'objects' => [
'Contact',
],
]
);

$integration->expects($this->exactly(1))
->method('makeRequest')
->willReturnCallback(
function ($url, $parameters = [], $method = 'GET', $settings = []) {
$this->assertEquals(
$parameters,
[
'q' => 'select Id from Contact where email = \'con\\\\tact\\\'email@email.com\'',
]
);
}
);

$api = new SalesforceApi($integration);

$api->getPerson([
'Contact' => [
'Email' => 'con\\tact\'email@email.com',
],
]);
}

/**
* @testdox Test that a backslash and a single quote are escaped for SF queries
*
* @covers \MauticPlugin\MauticCrmBundle\Api\SalesforceApi::escapeQueryValue()
*/
public function testLeadQueryIsEscapedCorrectly()
{
$integration = $this->getMockBuilder(SalesforceIntegration::class)
->disableOriginalConstructor()
->setMethodsExcept(['cleanPushData'])
->getMock();

$integration->expects($this->exactly(1))
->method('mergeConfigToFeatureSettings')
->willReturn(
[
'objects' => [
'Lead',
],
]
);

$integration->expects($this->exactly(1))
->method('makeRequest')
->willReturnCallback(
function ($url, $parameters = [], $method = 'GET', $settings = []) {
$this->assertEquals(
$parameters,
[
'q' => 'select Id from Lead where email = \'con\\\\tact\\\'email@email.com\' and ConvertedContactId = NULL',
]
);
}
);

$api = new SalesforceApi($integration);

$api->getPerson([
'Lead' => [
'Email' => 'con\\tact\'email@email.com',
],
]);
}
}