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