3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Utils_Weight
31 class CRM_Utils_Weight
{
33 * @var array, list of GET fields which must be validated
35 * To reduce the size of this patch, we only sign the exploitable fields
36 * which make up "$baseURL" in addOrder() (eg 'filter' or 'dao').
37 * Less-exploitable fields (eg 'dir') are left unsigned.
38 * 'id','src','dst','dir'
40 public static $SIGNABLE_FIELDS = ['reset', 'dao', 'idName', 'url', 'filter'];
43 * Correct duplicate weight entries by putting them (duplicate weights) in sequence.
45 * @param string $daoName
46 * Full name of the DAO.
47 * @param array $fieldValues
48 * Field => value to be used in the WHERE.
49 * @param string $weightField
50 * Field which contains the weight value.
51 * defaults to 'weight'
55 public static function correctDuplicateWeights($daoName, $fieldValues = NULL, $weightField = 'weight') {
56 $selectField = "MIN(id) AS dupeId, count(id) as dupeCount, $weightField as dupeWeight";
57 $groupBy = "$weightField having count(id)>1";
59 $minDupeID = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField, NULL, NULL, $groupBy);
61 // return early if query returned empty
63 if (!$minDupeID->fetch()) {
67 if ($minDupeID->dupeId
) {
68 $additionalWhere = "id !=" . $minDupeID->dupeId
. " AND $weightField >= " . $minDupeID->dupeWeight
;
69 $update = "$weightField = $weightField + 1";
70 $status = CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
73 if ($minDupeID->dupeId
&& $status) {
74 // recursive call to correct all duplicate weight entries.
75 return CRM_Utils_Weight
::correctDuplicateWeights($daoName, $fieldValues, $weightField);
77 elseif (!$minDupeID->dupeId
) {
78 // case when no duplicate records are found.
82 // case when duplicate records are found but update status is false.
88 * Remove a row from the specified weight, and shift all rows below it up
90 * @param string $daoName
91 * Full name of the DAO.
92 * $param integer $weight the weight to be removed
94 * @param array $fieldValues
95 * Field => value to be used in the WHERE.
96 * @param string $weightField
97 * Field which contains the weight value.
98 * defaults to 'weight'
102 public static function delWeight($daoName, $fieldID, $fieldValues = NULL, $weightField = 'weight') {
103 $object = new $daoName();
104 $object->id
= $fieldID;
105 if (!$object->find(TRUE)) {
109 $weight = (int) $object->weight
;
115 $additionalWhere = "$weightField > $weight";
116 $update = "$weightField = $weightField - 1";
117 $status = CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
123 * Updates the weight fields of other rows according to the new and old weight passed in.
124 * And returns the new weight be used. If old-weight not present, Creates a gap for a new row to be inserted
125 * at the specified new weight
127 * @param string $daoName
128 * Full name of the DAO.
129 * @param int $oldWeight
130 * @param int $newWeight
131 * @param array $fieldValues
132 * Field => value to be used in the WHERE.
133 * @param string $weightField
134 * Field which contains the weight value,.
135 * defaults to 'weight'
139 public static function updateOtherWeights($daoName, $oldWeight, $newWeight, $fieldValues = NULL, $weightField = 'weight') {
140 $oldWeight = (int ) $oldWeight;
141 $newWeight = (int ) $newWeight;
143 // max weight is the highest current weight
144 $maxWeight = CRM_Utils_Weight
::getMax($daoName, $fieldValues, $weightField);
149 if ($newWeight > $maxWeight) {
150 // calculate new weight, CRM-4133
151 $calNewWeight = CRM_Utils_Weight
::getNewWeight($daoName, $fieldValues, $weightField);
153 // no need to update weight for other fields.
154 if ($calNewWeight > $maxWeight) {
155 return $calNewWeight;
157 $newWeight = $maxWeight;
160 return $newWeight +
1;
163 elseif ($newWeight < 1) {
167 // if they're the same, nothing to do
168 if ($oldWeight == $newWeight) {
172 // if oldWeight not present, indicates new weight is to be added. So create a gap for a new row to be inserted.
174 $additionalWhere = "$weightField >= $newWeight";
175 $update = "$weightField = ($weightField + 1)";
176 CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
180 if ($newWeight > $oldWeight) {
181 $additionalWhere = "$weightField > $oldWeight AND $weightField <= $newWeight";
182 $update = "$weightField = ($weightField - 1)";
184 elseif ($newWeight < $oldWeight) {
185 $additionalWhere = "$weightField >= $newWeight AND $weightField < $oldWeight";
186 $update = "$weightField = ($weightField + 1)";
188 CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
194 * Returns the new calculated weight.
196 * @param string $daoName
197 * Full name of the DAO.
198 * @param array $fieldValues
199 * Field => value to be used in the WHERE.
200 * @param string $weightField
201 * Field which used to get the wt, default to 'weight'.
205 public static function getNewWeight($daoName, $fieldValues = NULL, $weightField = 'weight') {
206 $selectField = "id AS fieldID, $weightField AS weight";
207 $field = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField);
208 $sameWeightCount = 0;
210 while ($field->fetch()) {
211 if (in_array($field->weight
, $weights)) {
214 $weights[$field->fieldID
] = $field->weight
;
218 if ($sameWeightCount) {
219 $newWeight = max($weights) +
1;
221 // check for max wt, should not greater than cal max wt.
222 $calMaxWt = min($weights) +
count($weights) - 1;
223 if ($newWeight > $calMaxWt) {
224 $newWeight = $calMaxWt;
227 elseif (!empty($weights)) {
228 $newWeight = max($weights);
235 * Returns the highest weight.
237 * @param string $daoName
238 * Full name of the DAO.
239 * @param array $fieldValues
240 * Field => value to be used in the WHERE.
241 * @param string $weightField
242 * Field which contains the weight value.
243 * defaults to 'weight'
247 public static function getMax($daoName, $fieldValues = NULL, $weightField = 'weight') {
248 $selectField = "MAX(ROUND($weightField)) AS max_weight";
249 $weightDAO = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField);
251 if ($weightDAO->max_weight
) {
252 return $weightDAO->max_weight
;
258 * Returns the default weight ( highest weight + 1 ) to be used.
260 * @param string $daoName
261 * Full name of the DAO.
262 * @param array $fieldValues
263 * Field => value to be used in the WHERE.
264 * @param string $weightField
265 * Field which contains the weight value.
266 * defaults to 'weight'
270 public static function getDefaultWeight($daoName, $fieldValues = NULL, $weightField = 'weight') {
271 $maxWeight = CRM_Utils_Weight
::getMax($daoName, $fieldValues, $weightField);
272 return $maxWeight +
1;
276 * Execute a weight-related query
278 * @param string $queryType
279 * SELECT, UPDATE, DELETE.
280 * @param string $daoName
281 * Full name of the DAO.
282 * @param array $fieldValues
283 * Field => value to be used in the WHERE.
284 * @param string $queryData
285 * Data to be used, dependent on the query type.
286 * @param null $additionalWhere
287 * @param string $orderBy
288 * Optional ORDER BY field.
290 * @param null $groupBy
292 * @return CRM_Core_DAO
293 * objet that holds the results of the query
295 public static function &query(
300 $additionalWhere = NULL,
305 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
307 $dao = new $daoName();
308 $table = $dao->getTablename();
309 $fields = &$dao->fields();
310 $fieldlist = array_keys($fields);
312 $whereConditions = [];
313 if ($additionalWhere) {
314 $whereConditions[] = $additionalWhere;
318 if (is_array($fieldValues)) {
319 foreach ($fieldValues as $fieldName => $value) {
320 if (!in_array($fieldName, $fieldlist)) {
321 // invalid field specified. abort.
325 $whereConditions[] = "$fieldName = %$fieldNum";
326 $fieldType = $fields[$fieldName]['type'];
327 $params[$fieldNum] = [$value, CRM_Utils_Type
::typeToString($fieldType)];
330 $where = implode(' AND ', $whereConditions);
332 switch ($queryType) {
334 $query = "SELECT $queryData FROM $table";
336 $query .= " WHERE $where";
339 $query .= " GROUP BY $groupBy";
342 $query .= " ORDER BY $orderBy";
347 $query = "UPDATE $table SET $queryData";
349 $query .= " WHERE $where";
354 $query = "DELETE FROM $table WHERE $where AND $queryData";
361 $resultDAO = CRM_Core_DAO
::executeQuery($query, $params);
367 * @param string $daoName
368 * @param string $idName
370 * @param null $filter
372 public static function addOrder(&$rows, $daoName, $idName, $returnURL, $filter = NULL) {
377 $ids = array_keys($rows);
378 $numIDs = count($ids);
379 array_unshift($ids, 0);
382 $lastID = $ids[$numIDs];
383 if ($firstID == $lastID) {
384 $rows[$firstID]['order'] = NULL;
387 $config = CRM_Core_Config
::singleton();
388 $imageURL = $config->userFrameworkResourceURL
. 'i/arrow';
398 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$SIGNABLE_FIELDS);
399 $queryParams['_sgn'] = $signer->sign($queryParams);
400 $baseURL = CRM_Utils_System
::url('civicrm/admin/weight', $queryParams);
402 for ($i = 1; $i <= $numIDs; $i++
) {
404 $prevID = $ids[$i - 1];
405 $nextID = $ids[$i +
1];
408 $url = "{$baseURL}&src=$id";
411 $alt = ts('Move to top');
412 $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>";
414 $alt = ts('Move up one row');
415 $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>";
418 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
419 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
423 $alt = ts('Move down one row');
424 $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>";
426 $alt = ts('Move to bottom');
427 $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>";
430 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
431 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
433 $rows[$id]['weight'] = implode(' ', $links);
437 public static function fixOrder() {
438 $signature = CRM_Utils_Request
::retrieve('_sgn', 'String');
439 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$SIGNABLE_FIELDS);
441 // Validate $_GET values b/c subsequent code reads $_GET (via CRM_Utils_Request::retrieve)
442 if (!$signer->validate($signature, $_GET)) {
443 CRM_Core_Error
::fatal('Request signature is invalid');
446 // Note: Ensure this list matches self::$SIGNABLE_FIELDS
447 $daoName = CRM_Utils_Request
::retrieve('dao', 'String');
448 $id = CRM_Utils_Request
::retrieve('id', 'Integer');
449 $idName = CRM_Utils_Request
::retrieve('idName', 'String');
450 $url = CRM_Utils_Request
::retrieve('url', 'String');
451 $filter = CRM_Utils_Request
::retrieve('filter', 'String');
452 $src = CRM_Utils_Request
::retrieve('src', 'Integer');
453 $dst = CRM_Utils_Request
::retrieve('dst', 'Integer');
454 $dir = CRM_Utils_Request
::retrieve('dir', 'String');
455 $object = new $daoName();
456 $srcWeight = CRM_Core_DAO
::getFieldValue($daoName, $src, 'weight', $idName);
457 $dstWeight = CRM_Core_DAO
::getFieldValue($daoName, $dst, 'weight', $idName);
458 if ($srcWeight == $dstWeight) {
459 self
::fixOrderOutput($url);
462 $tableName = $object->tableName();
464 $query = "UPDATE $tableName SET weight = %1 WHERE $idName = %2";
466 1 => [$dstWeight, 'Integer'],
467 2 => [$src, 'Integer'],
469 CRM_Core_DAO
::executeQuery($query, $params);
471 if ($dir == 'swap') {
473 1 => [$srcWeight, 'Integer'],
474 2 => [$dst, 'Integer'],
476 CRM_Core_DAO
::executeQuery($query, $params);
478 elseif ($dir == 'first') {
479 // increment the rest by one
480 $query = "UPDATE $tableName SET weight = weight + 1 WHERE $idName != %1 AND weight < %2";
482 $query .= " AND $filter";
485 1 => [$src, 'Integer'],
486 2 => [$srcWeight, 'Integer'],
488 CRM_Core_DAO
::executeQuery($query, $params);
490 elseif ($dir == 'last') {
491 // increment the rest by one
492 $query = "UPDATE $tableName SET weight = weight - 1 WHERE $idName != %1 AND weight > %2";
494 $query .= " AND $filter";
497 1 => [$src, 'Integer'],
498 2 => [$srcWeight, 'Integer'],
500 CRM_Core_DAO
::executeQuery($query, $params);
503 self
::fixOrderOutput($url);
509 public static function fixOrderOutput($url) {
510 if (empty($_GET['snippet']) ||
$_GET['snippet'] !== 'json') {
511 CRM_Utils_System
::redirect($url);
514 CRM_Core_Page_AJAX
::returnJsonResponse([
515 'userContext' => $url,