Skip to content

Commit 9d455d9

Browse files
authored
Merge pull request #28 from itosho/21-potential-security-problem
#21 fix potential security problem
2 parents 5a5da53 + 1df3146 commit 9d455d9

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/Model/Behavior/InsertBehavior.php

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,6 @@ public function insertOnce(Entity $entity, array $conditions = null)
7878
$insertData['modified'] = FrozenTime::now()->toDateTimeString();
7979
}
8080

81-
$escape = function ($content) {
82-
return is_null($content) ? 'NULL' : '\'' . addslashes($content) . '\'';
83-
};
84-
85-
$escapedInsertData = array_map($escape, $insertData);
8681
$fields = array_keys($insertData);
8782
$existsConditions = $conditions;
8883
if (is_null($existsConditions)) {
@@ -94,7 +89,7 @@ public function insertOnce(Entity $entity, array $conditions = null)
9489
->insert($fields)
9590
->epilog(
9691
$this
97-
->buildTmpTableSelectQuery($escapedInsertData)
92+
->buildTmpTableSelectQuery($insertData)
9893
->where(function (QueryExpression $exp) use ($existsConditions) {
9994
$query = $this->_table
10095
->find()
@@ -111,32 +106,42 @@ public function insertOnce(Entity $entity, array $conditions = null)
111106
/**
112107
* build tmp table's select query for insert select query
113108
*
114-
* @param array $escapedData escaped array data
109+
* @param array $insertData insert data
115110
* @throws LogicException select query is invalid
116111
* @return Query tmp table's select query
117112
*/
118-
private function buildTmpTableSelectQuery($escapedData)
113+
private function buildTmpTableSelectQuery($insertData)
119114
{
120115
$driver = $this->_table
121116
->getConnection()
122117
->getDriver();
123118
$schema = [];
124-
foreach ($escapedData as $key => $value) {
119+
$binds = [];
120+
foreach ($insertData as $key => $value) {
125121
$col = $driver->quoteIdentifier($key);
126-
$schema[] = "{$value} AS {$col}";
122+
if (is_null($value)) {
123+
$schema[] = "NULL AS {$col}";
124+
} else {
125+
$bindKey = ':' . strtolower($key);
126+
$binds[$bindKey] = $value;
127+
$schema[] = "{$bindKey} AS {$col}";
128+
}
127129
}
128130

129131
$tmpTable = TableRegistry::getTableLocator()->get('tmp', [
130132
'schema' => $this->_table->getSchema(),
131133
]);
132134
$query = $tmpTable
133135
->find()
134-
->select(array_keys($escapedData))
136+
->select(array_keys($insertData))
135137
->from(
136138
sprintf('(SELECT %s) as tmp', implode(',', $schema))
137139
);
138140
/** @var Query $selectQuery */
139141
$selectQuery = $query;
142+
foreach ($binds as $key => $value) {
143+
$selectQuery->bind($key, $value);
144+
}
140145

141146
return $selectQuery;
142147
}

0 commit comments

Comments
 (0)