3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Class CRM_Utils_Weight
15 class CRM_Utils_Weight
{
17 * List of GET fields which must be validated
19 * To reduce the size of this patch, we only sign the exploitable fields
20 * which make up "$baseURL" in addOrder() (eg 'filter' or 'dao').
21 * Less-exploitable fields (eg 'dir') are left unsigned.
22 * 'id','src','dst','dir'
25 public static $SIGNABLE_FIELDS = ['reset', 'dao', 'idName', 'url', 'filter'];
28 * Correct duplicate weight entries by putting them (duplicate weights) in sequence.
30 * @param string $daoName
31 * Full name of the DAO.
32 * @param array $fieldValues
33 * Field => value to be used in the WHERE.
34 * @param string $weightField
35 * Field which contains the weight value.
36 * defaults to 'weight'
40 public static function correctDuplicateWeights($daoName, $fieldValues = NULL, $weightField = 'weight') {
41 $selectField = "MIN(id) AS dupeId, count(id) as dupeCount, $weightField as dupeWeight";
42 $groupBy = "$weightField having count(id)>1";
44 $minDupeID = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField, NULL, NULL, $groupBy);
46 // return early if query returned empty
48 if (!$minDupeID->fetch()) {
52 if ($minDupeID->dupeId
) {
53 $additionalWhere = "id !=" . $minDupeID->dupeId
. " AND $weightField >= " . $minDupeID->dupeWeight
;
54 $update = "$weightField = $weightField + 1";
55 $status = CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
58 if ($minDupeID->dupeId
&& $status) {
59 // recursive call to correct all duplicate weight entries.
60 return CRM_Utils_Weight
::correctDuplicateWeights($daoName, $fieldValues, $weightField);
62 elseif (!$minDupeID->dupeId
) {
63 // case when no duplicate records are found.
67 // case when duplicate records are found but update status is false.
73 * Remove a row from the specified weight, and shift all rows below it up
75 * @param string $daoName
76 * Full name of the DAO.
77 * $param integer $weight the weight to be removed
79 * @param array $fieldValues
80 * Field => value to be used in the WHERE.
81 * @param string $weightField
82 * Field which contains the weight value.
83 * defaults to 'weight'
87 public static function delWeight($daoName, $fieldID, $fieldValues = NULL, $weightField = 'weight') {
88 $object = new $daoName();
89 $object->id
= $fieldID;
90 if (!$object->find(TRUE)) {
94 $weight = (int) $object->weight
;
100 $additionalWhere = "$weightField > $weight";
101 $update = "$weightField = $weightField - 1";
102 $status = CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
108 * Updates the weight fields of other rows according to the new and old weight passed in.
109 * And returns the new weight be used. If old-weight not present, Creates a gap for a new row to be inserted
110 * at the specified new weight
112 * @param string $daoName
113 * Full name of the DAO.
114 * @param int $oldWeight
115 * @param int $newWeight
116 * @param array $fieldValues
117 * Field => value to be used in the WHERE.
118 * @param string $weightField
119 * Field which contains the weight value,.
120 * defaults to 'weight'
124 public static function updateOtherWeights($daoName, $oldWeight, $newWeight, $fieldValues = NULL, $weightField = 'weight') {
125 $oldWeight = (int) $oldWeight;
126 $newWeight = (int) $newWeight;
128 // max weight is the highest current weight
129 $maxWeight = self
::getMax($daoName, $fieldValues, $weightField) ?
: 1;
131 if ($newWeight > $maxWeight) {
132 // calculate new weight, CRM-4133
133 $calNewWeight = CRM_Utils_Weight
::getNewWeight($daoName, $fieldValues, $weightField);
135 // no need to update weight for other fields.
136 if ($calNewWeight > $maxWeight) {
137 return $calNewWeight;
139 $newWeight = $maxWeight;
142 return $newWeight +
1;
145 elseif ($newWeight < 1) {
149 // if they're the same, nothing to do
150 if ($oldWeight == $newWeight) {
154 // Check for an existing record with this weight
155 $existing = self
::query('SELECT', $daoName, $fieldValues, "id", "$weightField = $newWeight");
156 // Nothing to do if no existing record has this weight
157 if (empty($existing->N
)) {
161 // if oldWeight not present, indicates new weight is to be added. So create a gap for a new row to be inserted.
163 $additionalWhere = "$weightField >= $newWeight";
164 $update = "$weightField = ($weightField + 1)";
165 CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
168 if ($newWeight > $oldWeight) {
169 $additionalWhere = "$weightField > $oldWeight AND $weightField <= $newWeight";
170 $update = "$weightField = ($weightField - 1)";
172 elseif ($newWeight < $oldWeight) {
173 $additionalWhere = "$weightField >= $newWeight AND $weightField < $oldWeight";
174 $update = "$weightField = ($weightField + 1)";
176 CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
182 * Returns the new calculated weight.
184 * @param string $daoName
185 * Full name of the DAO.
186 * @param array $fieldValues
187 * Field => value to be used in the WHERE.
188 * @param string $weightField
189 * Field which used to get the wt, default to 'weight'.
193 public static function getNewWeight($daoName, $fieldValues = NULL, $weightField = 'weight') {
194 $selectField = "id AS fieldID, $weightField AS weight";
195 $field = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField);
196 $sameWeightCount = 0;
198 while ($field->fetch()) {
199 if (in_array($field->weight
, $weights)) {
202 $weights[$field->fieldID
] = $field->weight
;
206 if ($sameWeightCount) {
207 $newWeight = max($weights) +
1;
209 // check for max wt, should not greater than cal max wt.
210 $calMaxWt = min($weights) +
count($weights) - 1;
211 if ($newWeight > $calMaxWt) {
212 $newWeight = $calMaxWt;
215 elseif (!empty($weights)) {
216 $newWeight = max($weights);
223 * Returns the highest weight.
225 * @param string $daoName
226 * Full name of the DAO.
227 * @param array $fieldValues
228 * Field => value to be used in the WHERE.
229 * @param string $weightField
230 * Field which contains the weight value.
231 * defaults to 'weight'
235 public static function getMax($daoName, $fieldValues = NULL, $weightField = 'weight') {
236 $selectField = "MAX(ROUND($weightField)) AS max_weight";
237 $weightDAO = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField);
239 if ($weightDAO->max_weight
) {
240 return $weightDAO->max_weight
;
246 * Returns the default weight ( highest weight + 1 ) to be used.
248 * @param string $daoName
249 * Full name of the DAO.
250 * @param array $fieldValues
251 * Field => value to be used in the WHERE.
252 * @param string $weightField
253 * Field which contains the weight value.
254 * defaults to 'weight'
258 public static function getDefaultWeight($daoName, $fieldValues = NULL, $weightField = 'weight') {
259 $maxWeight = CRM_Utils_Weight
::getMax($daoName, $fieldValues, $weightField);
260 return $maxWeight +
1;
264 * Execute a weight-related query
266 * @param string $queryType
267 * SELECT, UPDATE, DELETE.
268 * @param CRM_Core_DAO|string $daoName
269 * Full name of the DAO.
270 * @param array $fieldValues
271 * Field => value to be used in the WHERE.
272 * @param string $queryData
273 * Data to be used, dependent on the query type.
274 * @param string|null $additionalWhere
275 * Optional WHERE field.
276 * @param string|null $orderBy
277 * Optional ORDER BY field.
278 * @param string|null $groupBy
279 * Optional GROU{} BY field.
281 * @return CRM_Core_DAO
282 * objet that holds the results of the query
284 public static function &query(
289 $additionalWhere = NULL,
293 $table = $daoName::getTablename();
294 $fields = $daoName::getSupportedFields();
295 $fieldlist = array_keys($fields);
297 $whereConditions = [];
298 if ($additionalWhere) {
299 $whereConditions[] = $additionalWhere;
303 if (is_array($fieldValues)) {
304 foreach ($fieldValues as $fieldName => $value) {
305 if (!in_array($fieldName, $fieldlist)) {
306 // invalid field specified. abort.
307 throw new CRM_Core_Exception("Invalid field '$fieldName' for $daoName");
309 if (CRM_Utils_System
::isNull($value)) {
310 $whereConditions[] = "$fieldName IS NULL";
314 $whereConditions[] = "$fieldName = %$fieldNum";
315 $fieldType = $fields[$fieldName]['type'];
316 $params[$fieldNum] = [$value, CRM_Utils_Type
::typeToString($fieldType)];
320 $where = implode(' AND ', $whereConditions);
322 switch ($queryType) {
324 $query = "SELECT $queryData FROM $table";
326 $query .= " WHERE $where";
329 $query .= " GROUP BY $groupBy";
332 $query .= " ORDER BY $orderBy";
337 $query = "UPDATE $table SET $queryData";
339 $query .= " WHERE $where";
344 $query = "DELETE FROM $table WHERE $where AND $queryData";
348 throw new CRM_Core_Exception("Invalid query operation for $daoName");
351 $resultDAO = CRM_Core_DAO
::executeQuery($query, $params);
357 * @param string $daoName
358 * @param string $idName
359 * @param string $returnURL
360 * @param string|null $filter
362 public static function addOrder(&$rows, $daoName, $idName, $returnURL, $filter = NULL) {
367 $ids = array_keys($rows);
368 $numIDs = count($ids);
369 array_unshift($ids, 0);
372 $lastID = $ids[$numIDs];
373 if ($firstID == $lastID) {
374 $rows[$firstID]['order'] = NULL;
377 $config = CRM_Core_Config
::singleton();
378 $imageURL = $config->userFrameworkResourceURL
. 'i/arrow';
388 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$SIGNABLE_FIELDS);
389 $queryParams['_sgn'] = $signer->sign($queryParams);
390 $baseURL = CRM_Utils_System
::url('civicrm/admin/weight', $queryParams);
392 for ($i = 1; $i <= $numIDs; $i++
) {
394 $prevID = $ids[$i - 1];
395 $nextID = $ids[$i +
1];
398 $url = "{$baseURL}&src=$id";
401 $alt = ts('Move to top');
402 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$firstID}&dir=first\"><img src=\"{$imageURL}/first.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
404 $alt = ts('Move up one row');
405 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$prevID}&dir=swap\"><img src=\"{$imageURL}/up.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
408 $links[] = "<span class=\"order-icon\"></span>";
409 $links[] = "<span class=\"order-icon\"></span>";
413 $alt = ts('Move down one row');
414 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$nextID}&dir=swap\"><img src=\"{$imageURL}/down.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
416 $alt = ts('Move to bottom');
417 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$lastID}&dir=last\"><img src=\"{$imageURL}/last.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
420 $links[] = "<span class=\"order-icon\"></span>";
421 $links[] = "<span class=\"order-icon\"></span>";
423 $rows[$id]['weight'] = implode(' ', $links);
429 * @throws CRM_Core_Exception
431 public static function fixOrder() {
432 $signature = CRM_Utils_Request
::retrieve('_sgn', 'String');
433 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$SIGNABLE_FIELDS);
435 // Validate $_GET values b/c subsequent code reads $_GET (via CRM_Utils_Request::retrieve)
436 if (!$signer->validate($signature, $_GET)) {
437 throw new CRM_Core_Exception('Request signature is invalid');
440 // Note: Ensure this list matches self::$SIGNABLE_FIELDS
441 $daoName = CRM_Utils_Request
::retrieve('dao', 'String');
442 $id = CRM_Utils_Request
::retrieve('id', 'Integer');
443 $idName = CRM_Utils_Request
::retrieve('idName', 'String');
444 $url = CRM_Utils_Request
::retrieve('url', 'String');
445 $filter = CRM_Utils_Request
::retrieve('filter', 'String');
446 $src = CRM_Utils_Request
::retrieve('src', 'Integer');
447 $dst = CRM_Utils_Request
::retrieve('dst', 'Integer');
448 $dir = CRM_Utils_Request
::retrieve('dir', 'String');
449 $object = new $daoName();
450 $srcWeight = CRM_Core_DAO
::getFieldValue($daoName, $src, 'weight', $idName);
451 $dstWeight = CRM_Core_DAO
::getFieldValue($daoName, $dst, 'weight', $idName);
452 if ($srcWeight == $dstWeight) {
453 self
::fixOrderOutput($url);
456 $tableName = $object->tableName();
458 $query = "UPDATE $tableName SET weight = %1 WHERE $idName = %2";
460 1 => [$dstWeight, 'Integer'],
461 2 => [$src, 'Integer'],
463 CRM_Core_DAO
::executeQuery($query, $params);
465 if ($dir == 'swap') {
467 1 => [$srcWeight, 'Integer'],
468 2 => [$dst, 'Integer'],
470 CRM_Core_DAO
::executeQuery($query, $params);
472 elseif ($dir == 'first') {
473 // increment the rest by one
474 $query = "UPDATE $tableName SET weight = weight + 1 WHERE $idName != %1 AND weight < %2";
476 $query .= " AND $filter";
479 1 => [$src, 'Integer'],
480 2 => [$srcWeight, 'Integer'],
482 CRM_Core_DAO
::executeQuery($query, $params);
484 elseif ($dir == 'last') {
485 // increment the rest by one
486 $query = "UPDATE $tableName SET weight = weight - 1 WHERE $idName != %1 AND weight > %2";
488 $query .= " AND $filter";
491 1 => [$src, 'Integer'],
492 2 => [$srcWeight, 'Integer'],
494 CRM_Core_DAO
::executeQuery($query, $params);
497 self
::fixOrderOutput($url);
503 public static function fixOrderOutput($url) {
504 if (empty($_GET['snippet']) ||
$_GET['snippet'] !== 'json') {
505 CRM_Utils_System
::redirect($url);
508 CRM_Core_Page_AJAX
::returnJsonResponse([
509 'userContext' => $url,