Merge pull request #19438 from colemanw/afformDropAttrSupport
[civicrm-core.git] / CRM / Utils / JSON.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Class handles functions for JSON format
20 */
21 class CRM_Utils_JSON {
22
23 /**
24 * Output json to the client.
25 * @param mixed $input
26 */
27 public static function output($input) {
28 if (CIVICRM_UF === 'UnitTests') {
29 throw new CRM_Core_Exception_PrematureExitException('civiExit called', $input);
30 }
31 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
32 echo json_encode($input);
33 CRM_Utils_System::civiExit();
34 }
35
36 /**
37 * Test whether the input string is valid JSON.
38 * @param string $str
39 * @return boolean
40 */
41 public static function isValidJSON($str) {
42 json_decode($str);
43 return json_last_error() == JSON_ERROR_NONE;
44 }
45
46 /**
47 * Do not use this function. See CRM-16353.
48 * @deprecated
49 *
50 * @param array $params
51 * Associated array of row elements.
52 * @param int $sEcho
53 * Datatable needs this to make it more secure.
54 * @param int $iTotal
55 * Total records.
56 * @param int $iFilteredTotal
57 * Total records on a page.
58 * @param array $selectorElements
59 * Selector elements.
60 * @return string
61 */
62 public static function encodeDataTableSelector($params, $sEcho, $iTotal, $iFilteredTotal, $selectorElements) {
63 $sOutput = '{';
64 $sOutput .= '"sEcho": ' . intval($sEcho) . ', ';
65 $sOutput .= '"iTotalRecords": ' . $iTotal . ', ';
66 $sOutput .= '"iTotalDisplayRecords": ' . $iFilteredTotal . ', ';
67 $sOutput .= '"aaData": [ ';
68 foreach ((array) $params as $key => $value) {
69 $addcomma = FALSE;
70 $sOutput .= "[";
71 foreach ($selectorElements as $element) {
72 if ($addcomma) {
73 $sOutput .= ",";
74 }
75 // CRM-7130 --lets addslashes to only double quotes,
76 // since we are using it to quote the field value.
77 // str_replace helps to provide a break for new-line
78 $sOutput .= '"' . addcslashes(str_replace(["\r\n", "\n", "\r"], '<br />', $value[$element]), '"\\') . '"';
79
80 // remove extra spaces and tab character that breaks dataTable CRM-12551
81 $sOutput = preg_replace("/\s+/", " ", $sOutput);
82 $addcomma = TRUE;
83 }
84 $sOutput .= "],";
85 }
86 $sOutput = substr_replace($sOutput, "", -1);
87 $sOutput .= '] }';
88
89 return $sOutput;
90 }
91
92 }