Merge pull request #17008 from ivan-compucorp/CPS-70-fix-radio-value
[civicrm-core.git] / CRM / Core / BAO / Dashboard.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 contains Contact dashboard related functions.
20 */
21 class CRM_Core_BAO_Dashboard extends CRM_Core_DAO_Dashboard {
22
23 /**
24 * Add Dashboard.
25 *
26 * @param array $params
27 * Values.
28 *
29 *
30 * @return object
31 */
32 public static function create($params) {
33 $hook = empty($params['id']) ? 'create' : 'edit';
34 CRM_Utils_Hook::pre($hook, 'Dashboard', CRM_Utils_Array::value('id', $params), $params);
35 $dao = self::addDashlet($params);
36 CRM_Utils_Hook::post($hook, 'Dashboard', $dao->id, $dao);
37 return $dao;
38 }
39
40 /**
41 * Get the list of dashlets enabled by admin.
42 *
43 * @param bool $all
44 * All or only active.
45 * @param bool $checkPermission
46 * All or only authorized for the current user.
47 *
48 * @return array
49 * array of dashlets
50 */
51 public static function getDashlets($all = TRUE, $checkPermission = TRUE) {
52 $dashlets = [];
53 $dao = new CRM_Core_DAO_Dashboard();
54
55 if (!$all) {
56 $dao->is_active = 1;
57 }
58
59 $dao->domain_id = CRM_Core_Config::domainID();
60
61 $dao->find();
62 while ($dao->fetch()) {
63 if ($checkPermission && !self::checkPermission($dao->permission, $dao->permission_operator)) {
64 continue;
65 }
66
67 $values = [];
68 CRM_Core_DAO::storeValues($dao, $values);
69 $dashlets[$dao->id] = $values;
70 }
71
72 return $dashlets;
73 }
74
75 /**
76 * Get the list of dashlets for the current user or the specified user.
77 *
78 * Additionlly, initializes the dashboard with defaults if this is the
79 * user's first visit to their dashboard.
80 *
81 * @param int $contactID
82 * Defaults to the current user.
83 *
84 * @return array
85 * array of dashlets
86 */
87 public static function getContactDashlets($contactID = NULL) {
88 $contactID = $contactID ? $contactID : CRM_Core_Session::getLoggedInContactID();
89 $dashlets = [];
90
91 // Get contact dashboard dashlets.
92 $results = civicrm_api3('DashboardContact', 'get', [
93 'contact_id' => $contactID,
94 'is_active' => 1,
95 'dashboard_id.is_active' => 1,
96 'dashboard_id.domain_id' => CRM_Core_Config::domainID(),
97 'options' => ['sort' => 'weight', 'limit' => 0],
98 'return' => [
99 'id',
100 'weight',
101 'column_no',
102 'dashboard_id',
103 'dashboard_id.name',
104 'dashboard_id.label',
105 'dashboard_id.url',
106 'dashboard_id.fullscreen_url',
107 'dashboard_id.cache_minutes',
108 'dashboard_id.permission',
109 'dashboard_id.permission_operator',
110 ],
111 ]);
112
113 foreach ($results['values'] as $item) {
114 if (self::checkPermission(CRM_Utils_Array::value('dashboard_id.permission', $item), CRM_Utils_Array::value('dashboard_id.permission_operator', $item))) {
115 $dashlets[$item['id']] = [
116 'dashboard_id' => $item['dashboard_id'],
117 'weight' => $item['weight'],
118 'column_no' => $item['column_no'],
119 'name' => $item['dashboard_id.name'],
120 'label' => $item['dashboard_id.label'],
121 'url' => $item['dashboard_id.url'],
122 'cache_minutes' => $item['dashboard_id.cache_minutes'],
123 'fullscreen_url' => $item['dashboard_id.fullscreen_url'] ?? NULL,
124 ];
125 }
126 }
127
128 // If empty, then initialize default dashlets for this user.
129 if (!$results['count']) {
130 // They may just have disabled all their dashlets. Check if any records exist for this contact.
131 if (!civicrm_api3('DashboardContact', 'getcount', ['contact_id' => $contactID, 'dashboard_id.domain_id' => CRM_Core_Config::domainID()])) {
132 $dashlets = self::initializeDashlets();
133 }
134 }
135
136 return $dashlets;
137 }
138
139 /**
140 * @return array
141 */
142 public static function getContactDashletsForJS() {
143 $data = [[], []];
144 foreach (self::getContactDashlets() as $item) {
145 $data[$item['column_no']][] = [
146 'id' => (int) $item['dashboard_id'],
147 'name' => $item['name'],
148 'title' => $item['label'],
149 'url' => self::parseUrl($item['url']),
150 'cacheMinutes' => $item['cache_minutes'],
151 'fullscreenUrl' => self::parseUrl($item['fullscreen_url']),
152 ];
153 }
154 return $data;
155 }
156
157 /**
158 * Setup default dashlets for new users.
159 *
160 * When a user accesses their dashboard for the first time, set up
161 * the default dashlets.
162 *
163 * @return array
164 * Array of dashboard_id's
165 * @throws \CiviCRM_API3_Exception
166 */
167 public static function initializeDashlets() {
168 $dashlets = [];
169 $getDashlets = civicrm_api3("Dashboard", "get", [
170 'domain_id' => CRM_Core_Config::domainID(),
171 'option.limit' => 0,
172 ]);
173 $contactID = CRM_Core_Session::getLoggedInContactID();
174 $allDashlets = CRM_Utils_Array::index(['name'], $getDashlets['values']);
175 $defaultDashlets = [];
176 $defaults = ['blog' => 1, 'getting-started' => '0'];
177 foreach ($defaults as $name => $column) {
178 if (!empty($allDashlets[$name]) && !empty($allDashlets[$name]['id'])) {
179 $defaultDashlets[$name] = [
180 'dashboard_id' => $allDashlets[$name]['id'],
181 'is_active' => 1,
182 'column_no' => $column,
183 'contact_id' => $contactID,
184 ];
185 }
186 }
187 CRM_Utils_Hook::dashboard_defaults($allDashlets, $defaultDashlets);
188 if (is_array($defaultDashlets) && !empty($defaultDashlets)) {
189 foreach ($defaultDashlets as $id => $defaultDashlet) {
190 $dashboard_id = $defaultDashlet['dashboard_id'];
191 $dashlet = $getDashlets['values'][$dashboard_id];
192 if (!self::checkPermission(CRM_Utils_Array::value('permission', $dashlet), CRM_Utils_Array::value('permission_operator', $dashlet))) {
193 continue;
194 }
195 else {
196 $assignDashlets = civicrm_api3("dashboard_contact", "create", $defaultDashlet);
197 $values = $assignDashlets['values'][$assignDashlets['id']];
198 $dashlets[$assignDashlets['id']] = [
199 'dashboard_id' => $values['dashboard_id'],
200 'weight' => $values['weight'],
201 'column_no' => $values['column_no'],
202 'name' => $dashlet['name'],
203 'label' => $dashlet['label'],
204 'cache_minutes' => $dashlet['cache_minutes'],
205 'url' => $dashlet['url'],
206 'fullscreen_url' => $dashlet['fullscreen_url'] ?? NULL,
207 ];
208 }
209 }
210 }
211 return $dashlets;
212 }
213
214 /**
215 * @param $url
216 * @return string
217 */
218 public static function parseUrl($url) {
219 // Check if it is already a fully-formed url
220 if ($url && substr($url, 0, 4) != 'http' && $url[0] != '/') {
221 $urlParam = explode('?', $url);
222 $url = CRM_Utils_System::url($urlParam[0], CRM_Utils_Array::value(1, $urlParam), FALSE, NULL, FALSE);
223 }
224 return $url;
225 }
226
227 /**
228 * Check dashlet permission for current user.
229 *
230 * @param string $permission
231 * Comma separated list.
232 * @param string $operator
233 *
234 * @return bool
235 * true if use has permission else false
236 */
237 public static function checkPermission($permission, $operator) {
238 if ($permission) {
239 $permissions = explode(',', $permission);
240 $config = CRM_Core_Config::singleton();
241
242 static $allComponents;
243 if (!$allComponents) {
244 $allComponents = CRM_Core_Component::getNames();
245 }
246
247 $hasPermission = FALSE;
248 foreach ($permissions as $key) {
249 $showDashlet = TRUE;
250
251 $componentName = NULL;
252 if (strpos($key, 'access') === 0) {
253 $componentName = trim(substr($key, 6));
254 if (!in_array($componentName, $allComponents)) {
255 $componentName = NULL;
256 }
257 }
258
259 // hack to handle case permissions
260 if (!$componentName
261 && in_array($key, ['access my cases and activities', 'access all cases and activities'])
262 ) {
263 $componentName = 'CiviCase';
264 }
265
266 //hack to determine if it's a component related permission
267 if ($componentName) {
268 if (!in_array($componentName, $config->enableComponents) ||
269 !CRM_Core_Permission::check($key)
270 ) {
271 $showDashlet = FALSE;
272 if ($operator == 'AND') {
273 return $showDashlet;
274 }
275 }
276 else {
277 $hasPermission = TRUE;
278 }
279 }
280 elseif (!CRM_Core_Permission::check($key)) {
281 $showDashlet = FALSE;
282 if ($operator == 'AND') {
283 return $showDashlet;
284 }
285 }
286 else {
287 $hasPermission = TRUE;
288 }
289 }
290
291 if (!$showDashlet && !$hasPermission) {
292 return FALSE;
293 }
294 else {
295 return TRUE;
296 }
297 }
298 else {
299 // if permission is not set consider everyone has permission to access it.
300 return TRUE;
301 }
302 }
303
304 /**
305 * Save changes made by user to the Dashlet.
306 *
307 * @param array $columns
308 *
309 * @param int $contactID
310 *
311 * @throws RuntimeException
312 */
313 public static function saveDashletChanges($columns, $contactID = NULL) {
314 if (!$contactID) {
315 $contactID = CRM_Core_Session::getLoggedInContactID();
316 }
317
318 if (empty($contactID)) {
319 throw new RuntimeException("Failed to determine contact ID");
320 }
321
322 $dashletIDs = [];
323 if (is_array($columns)) {
324 foreach ($columns as $colNo => $dashlets) {
325 if (!is_int($colNo)) {
326 continue;
327 }
328 $weight = 1;
329 foreach ($dashlets as $dashletID => $isMinimized) {
330 $dashletID = (int) $dashletID;
331 $query = "INSERT INTO civicrm_dashboard_contact
332 (weight, column_no, is_active, dashboard_id, contact_id)
333 VALUES({$weight}, {$colNo}, 1, {$dashletID}, {$contactID})
334 ON DUPLICATE KEY UPDATE weight = {$weight}, column_no = {$colNo}, is_active = 1";
335 // fire update query for each column
336 CRM_Core_DAO::executeQuery($query);
337
338 $dashletIDs[] = $dashletID;
339 $weight++;
340 }
341 }
342 }
343
344 // Find dashlets in this domain.
345 $domainDashlets = civicrm_api3('Dashboard', 'get', [
346 'return' => array('id'),
347 'domain_id' => CRM_Core_Config::domainID(),
348 'options' => ['limit' => 0],
349 ]);
350
351 // Get the array of IDs.
352 $domainDashletIDs = [];
353 if ($domainDashlets['is_error'] == 0) {
354 $domainDashletIDs = CRM_Utils_Array::collect('id', $domainDashlets['values']);
355 }
356
357 // Restrict query to Dashlets in this domain.
358 $domainDashletClause = !empty($domainDashletIDs) ? "dashboard_id IN (" . implode(',', $domainDashletIDs) . ")" : '(1)';
359
360 // Target only those Dashlets which are inactive.
361 $dashletClause = $dashletIDs ? "dashboard_id NOT IN (" . implode(',', $dashletIDs) . ")" : '(1)';
362
363 // Build params.
364 $params = [
365 1 => [$contactID, 'Integer'],
366 ];
367
368 // Build query.
369 $updateQuery = "UPDATE civicrm_dashboard_contact
370 SET is_active = 0
371 WHERE $domainDashletClause
372 AND $dashletClause
373 AND contact_id = %1";
374
375 // Disable inactive widgets.
376 CRM_Core_DAO::executeQuery($updateQuery, $params);
377 }
378
379 /**
380 * Add dashlets.
381 *
382 * @param array $params
383 *
384 * @return object
385 * $dashlet returns dashlet object
386 */
387 public static function addDashlet(&$params) {
388
389 // special case to handle duplicate entries for report instances
390 $dashboardID = $params['id'] ?? NULL;
391
392 if (!empty($params['instanceURL'])) {
393 $query = "SELECT id
394 FROM `civicrm_dashboard`
395 WHERE url LIKE '" . CRM_Utils_Array::value('instanceURL', $params) . "&%'";
396 $dashboardID = CRM_Core_DAO::singleValueQuery($query);
397 }
398
399 $dashlet = new CRM_Core_DAO_Dashboard();
400
401 if (!$dashboardID) {
402 // Assign domain before search to allow identical dashlets in different domains.
403 $dashlet->domain_id = $params['domain_id'] ?? CRM_Core_Config::domainID();
404
405 // Try and find an existing dashlet - it will be updated if found.
406 if (!empty($params['name']) || !empty($params['url'])) {
407 $dashlet->name = $params['name'] ?? NULL;
408 $dashlet->url = $params['url'] ?? NULL;
409 $dashlet->find(TRUE);
410 }
411 }
412 else {
413 $dashlet->id = $dashboardID;
414 }
415
416 $dashlet->copyValues($params);
417 $dashlet->save();
418
419 // now we need to make dashlet entries for each contact
420 self::addContactDashlet($dashlet);
421
422 return $dashlet;
423 }
424
425 /**
426 * Update contact dashboard with new dashlet.
427 *
428 * @param object $dashlet
429 */
430 public static function addContactDashlet($dashlet) {
431 $admin = CRM_Core_Permission::check('administer CiviCRM');
432
433 // if dashlet is created by admin then you need to add it all contacts.
434 // else just add to contact who is creating this dashlet
435 $contactIDs = [];
436 if ($admin) {
437 $query = "SELECT distinct( contact_id )
438 FROM civicrm_dashboard_contact";
439 $dao = CRM_Core_DAO::executeQuery($query);
440 while ($dao->fetch()) {
441 $contactIDs[$dao->contact_id] = NULL;
442 }
443 }
444 else {
445 //Get the id of Logged in User
446 $contactID = CRM_Core_Session::getLoggedInContactID();
447 if (!empty($contactID)) {
448 $contactIDs[$contactID] = NULL;
449 }
450 }
451
452 // Remove contact ids that already have this dashlet to avoid DB
453 // constraint violation.
454 $query = "SELECT distinct( contact_id )
455 FROM civicrm_dashboard_contact WHERE dashboard_id = {$dashlet->id}";
456 $dao = CRM_Core_DAO::executeQuery($query);
457 while ($dao->fetch()) {
458 if (array_key_exists($dao->contact_id, $contactIDs)) {
459 unset($contactIDs[$dao->contact_id]);
460 }
461 }
462 if (!empty($contactIDs)) {
463 foreach ($contactIDs as $contactID => $value) {
464 $valuesArray[] = " ( {$dashlet->id}, {$contactID} )";
465 }
466 $valuesString = implode(',', $valuesArray);
467 $query = "
468 INSERT INTO civicrm_dashboard_contact ( dashboard_id, contact_id )
469 VALUES {$valuesString}";
470
471 CRM_Core_DAO::executeQuery($query);
472 }
473 }
474
475 /**
476 * @param array $params
477 * Each item is a spec for a dashlet on the contact's dashboard.
478 * @return bool
479 */
480 public static function addContactDashletToDashboard(&$params) {
481 $valuesString = NULL;
482 $columns = [];
483 foreach ($params as $dashboardIDs) {
484 $contactID = $dashboardIDs['contact_id'] ?? NULL;
485 $dashboardID = $dashboardIDs['dashboard_id'] ?? NULL;
486 $column = $dashboardIDs['column_no'] ?? 0;
487 $columns[$column][$dashboardID] = 0;
488 }
489 self::saveDashletChanges($columns, $contactID);
490 return TRUE;
491 }
492
493 /**
494 * @deprecated
495 * @param int $dashletID
496 * @return bool
497 */
498 public static function deleteDashlet($dashletID) {
499 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_DAO_Dashboard::deleteRecord');
500 try {
501 CRM_Core_DAO_Dashboard::deleteRecord(['id' => $dashletID]);
502 }
503 catch (CRM_Core_Exception $e) {
504 return FALSE;
505 }
506 return TRUE;
507 }
508
509 }