Add consistency between checkTemplateFileExists functions,
[civicrm-core.git] / CRM / Profile / Page / Dynamic.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
b7edabe8 12use Civi\Api4\Email;
13
6a488035
TO
14/**
15 *
16 * @package CRM
ca5cec67 17 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
18 */
19
20/**
21 * Create a page for displaying CiviCRM Profile Fields.
22 *
23 * Heart of this class is the run method which checks
24 * for action type and then displays the appropriate
25 * page.
26 *
27 */
28class CRM_Profile_Page_Dynamic extends CRM_Core_Page {
29
30 /**
fe482240 31 * The contact id of the person we are viewing.
6a488035
TO
32 *
33 * @var int
6a488035
TO
34 */
35 protected $_id;
36
37 /**
fe482240 38 * The profile group are are interested in.
6a488035
TO
39 *
40 * @var int
6a488035
TO
41 */
42 protected $_gid;
43
44 /**
fe482240 45 * The profile types we restrict this page to display.
6a488035
TO
46 *
47 * @var string
6a488035
TO
48 */
49 protected $_restrict;
50
51 /**
fe482240 52 * Should we bypass permissions.
6a488035 53 *
d51c6add 54 * @var bool
6a488035
TO
55 */
56 protected $_skipPermission;
57
58 /**
59 * Store profile ids if multiple profile ids are passed using comma separated.
60 * Currently lets implement this functionality only for dialog mode
c86d4e7c 61 * @var array
6a488035 62 */
be2fb01f 63 protected $_profileIds = [];
6a488035
TO
64
65 /**
66 * Contact profile having activity fields?
67 *
68 * @var string
69 */
70 protected $_isContactActivityProfile = FALSE;
71
72 /**
fe482240 73 * Activity Id connected to the profile.
6a488035
TO
74 *
75 * @var string
76 */
77 protected $_activityId = NULL;
78
79 protected $_multiRecord = NULL;
80
81 protected $_recordId = NULL;
366fe2a3 82
b7edabe8 83 /**
84 * Should the primary email be converted into a link, if emailabe.
85 *
86 * @var bool
87 */
88 protected $isShowEmailTaskLink = FALSE;
89
c86d4e7c
SL
90 /**
91 *
6a488035 92 * fetch multirecord as well as non-multirecord fields
c86d4e7c 93 * @var int
6a488035
TO
94 */
95 protected $_allFields = NULL;
96
97 /**
fe482240 98 * Class constructor.
6a488035 99 *
68c9fb83
TO
100 * @param int $id
101 * The contact id.
102 * @param int $gid
103 * The group id.
6a488035 104 *
77b97be7
EM
105 * @param $restrict
106 * @param bool $skipPermission
107 * @param null $profileIds
108 *
b7edabe8 109 * @param bool $isShowEmailTaskLink
110 *
111 * @throws \CRM_Core_Exception
6a488035 112 */
b7edabe8 113 public function __construct($id, $gid, $restrict, $skipPermission = FALSE, $profileIds = NULL, $isShowEmailTaskLink = FALSE) {
6a488035
TO
114 parent::__construct();
115
116 $this->_id = $id;
117 $this->_gid = $gid;
118 $this->_restrict = $restrict;
119 $this->_skipPermission = $skipPermission;
b7edabe8 120 $this->isShowEmailTaskLink = $isShowEmailTaskLink;
6a488035
TO
121
122 if (!array_key_exists('multiRecord', $_GET)) {
123 $this->set('multiRecord', NULL);
124 }
125 if (!array_key_exists('recordId', $_GET)) {
126 $this->set('recordId', NULL);
127 }
128 if (!array_key_exists('allFields', $_GET)) {
129 $this->set('allFields', NULL);
130 }
366fe2a3 131
6a488035
TO
132 //specifies the action being done on a multi record field
133 $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
366fe2a3 134
dc98079b 135 $this->_multiRecord = (!is_numeric($multiRecordAction)) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
6a488035
TO
136 if ($this->_multiRecord) {
137 $this->set('multiRecord', $this->_multiRecord);
138 }
366fe2a3 139
6a488035 140 if ($this->_multiRecord & CRM_Core_Action::VIEW) {
353ffa53 141 $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
6a488035
TO
142 $this->_allFields = CRM_Utils_Request::retrieve('allFields', 'Integer', $this);
143 }
366fe2a3 144
6a488035
TO
145 if ($profileIds) {
146 $this->_profileIds = $profileIds;
147 }
148 else {
be2fb01f 149 $this->_profileIds = [$gid];
6a488035
TO
150 }
151
152 $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
153 if (is_numeric($this->_activityId)) {
154 $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
155 if ($latestRevisionId) {
156 $this->_activityId = $latestRevisionId;
157 }
158 }
159 $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
160 }
161
162 /**
163 * Get the action links for this page.
164 *
a6c01b45 165 * @return array
6a488035 166 */
00be9182 167 public function &actionLinks() {
6a488035
TO
168 return NULL;
169 }
170
171 /**
172 * Run the page.
173 *
174 * This method is called after the page is created. It checks for the
175 * type of action and executes that action.
176 *
6a488035 177 */
00be9182 178 public function run() {
6a488035
TO
179 $template = CRM_Core_Smarty::singleton();
180 if ($this->_id && $this->_gid) {
181
182 // first check that id is part of the limit group id, CRM-4822
183 $limitListingsGroupsID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup',
184 $this->_gid,
185 'limit_listings_group_id'
186 );
187 $config = CRM_Core_Config::singleton();
188 if ($limitListingsGroupsID) {
189
190 if (!CRM_Contact_BAO_GroupContact::isContactInGroup($this->_id,
353ffa53
TO
191 $limitListingsGroupsID
192 )
193 ) {
6a488035
TO
194 CRM_Utils_System::setTitle(ts('Profile View - Permission Denied'));
195 return CRM_Core_Session::setStatus(ts('You do not have permission to view this contact record. Contact the site administrator if you need assistance.'), ts('Permission Denied'), 'error');
196 }
197 }
198
199 $session = CRM_Core_Session::singleton();
200 $userID = $session->get('userID');
201
942d2374 202 $this->_isPermissionedChecksum = $allowPermission = FALSE;
6a488035 203 $permissionType = CRM_Core_Permission::VIEW;
942d2374 204 if (CRM_Core_Permission::check('administer users') || CRM_Core_Permission::check('view all contacts') || CRM_Contact_BAO_Contact_Permission::allow($this->_id)) {
c5c263ca 205 $allowPermission = TRUE;
942d2374 206 }
6a488035
TO
207 if ($this->_id != $userID) {
208 // do not allow edit for anon users in joomla frontend, CRM-4668, unless u have checksum CRM-5228
209 if ($config->userFrameworkFrontend) {
210 $this->_isPermissionedChecksum = CRM_Contact_BAO_Contact_Permission::validateOnlyChecksum($this->_id, $this, FALSE);
942d2374
WA
211 if (!$this->_isPermissionedChecksum) {
212 $this->_isPermissionedChecksum = $allowPermission;
213 }
6a488035
TO
214 }
215 else {
216 $this->_isPermissionedChecksum = CRM_Contact_BAO_Contact_Permission::validateChecksumContact($this->_id, $this, FALSE);
217 }
218 }
219 // CRM-10853
220 // Users with create or edit permission should be allowed to view their own profile
221 if ($this->_id == $userID || $this->_isPermissionedChecksum) {
222 if (!CRM_Core_Permission::check('profile view')) {
223 if (CRM_Core_Permission::check('profile create') || CRM_Core_Permission::check('profile edit')) {
224 $this->_skipPermission = TRUE;
225 }
226 }
227 }
228
229 // make sure we dont expose all fields based on permission
230 $admin = FALSE;
942d2374 231 if ((!$config->userFrameworkFrontend && $allowPermission) ||
6a488035
TO
232 $this->_id == $userID ||
233 $this->_isPermissionedChecksum
234 ) {
235 $admin = TRUE;
236 }
237
be2fb01f 238 $values = [];
6a488035
TO
239 $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileIds, FALSE, CRM_Core_Action::VIEW,
240 NULL, NULL, FALSE, $this->_restrict,
241 $this->_skipPermission, NULL,
242 $permissionType
243 );
244
245 if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId && !$this->_allFields) {
246 CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields);
247 $fields = $multiRecordFields;
248 }
249 if ($this->_isContactActivityProfile && $this->_gid) {
250 $errors = CRM_Profile_Form::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
251 if (!empty($errors)) {
79e11805 252 CRM_Core_Error::statusBounce(array_pop($errors));
6a488035
TO
253 }
254 }
255
256 //reformat fields array
257 foreach ($fields as $name => $field) {
258 // also eliminate all formatting fields
259 if (CRM_Utils_Array::value('field_type', $field) == 'Formatting') {
260 unset($fields[$name]);
261 }
262
263 // make sure that there is enough permission to expose this field
264 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
265 unset($fields[$name]);
266 }
267 }
268
269 if ($this->_isContactActivityProfile) {
be2fb01f 270 $contactFields = $activityFields = [];
6a488035
TO
271
272 foreach ($fields as $fieldName => $field) {
273 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
274 $activityFields[$fieldName] = $field;
275 }
276 else {
277 $contactFields[$fieldName] = $field;
278 }
279 }
280
281 CRM_Core_BAO_UFGroup::getValues($this->_id, $contactFields, $values);
282 if ($this->_activityId) {
283 CRM_Core_BAO_UFGroup::getValues(
284 NULL,
285 $activityFields,
286 $values,
287 TRUE,
be2fb01f 288 [['activity_id', '=', $this->_activityId, 0, 0]]
6a488035
TO
289 );
290 }
291 }
292 else {
293 $customWhereClause = NULL;
294 if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId) {
295 if ($this->_allFields) {
296 $copyFields = $fields;
297 CRM_Core_BAO_UFGroup::shiftMultiRecordFields($copyFields, $multiRecordFields);
298 $fieldKey = key($multiRecordFields);
0db6c3e1
TO
299 }
300 else {
6a488035
TO
301 $fieldKey = key($fields);
302 }
303 if ($fieldID = CRM_Core_BAO_CustomField::getKeyID($fieldKey)) {
304 $tableColumnGroup = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
305 $columnName = "{$tableColumnGroup[0]}.id";
306 $customWhereClause = $columnName . ' = ' . $this->_recordId;
307 }
308 }
309 CRM_Core_BAO_UFGroup::getValues($this->_id, $fields, $values, TRUE, NULL, FALSE, $customWhereClause);
310 }
311
312 // $profileFields array can be used for customized display of field labels and values in Profile/View.tpl
be2fb01f
CW
313 $profileFields = [];
314 $labels = [];
6a488035
TO
315
316 foreach ($fields as $name => $field) {
50bf705c
KJ
317 //CRM-14338
318 // Create a unique, non-empty index for each field.
319 $index = $field['title'];
ae93a14f
TO
320 if ($index === '') {
321 $index = ' ';
dc98079b
TO
322 }
323 while (array_key_exists($index, $labels)) {
50bf705c 324 $index .= ' ';
dc98079b 325 }
50bf705c
KJ
326
327 $labels[$index] = preg_replace('/\s+|\W+/', '_', $name);
6a488035
TO
328 }
329
b7edabe8 330 if ($this->isShowEmailTaskLink) {
331 foreach ($this->getEmailFields($fields) as $fieldName) {
332 $values[$fields[$fieldName]['title']] = $this->getLinkedEmail($values[$fields[$fieldName]['title']]);
333 }
334 }
6a488035 335 foreach ($values as $title => $value) {
be2fb01f 336 $profileFields[$labels[$title]] = [
6a488035
TO
337 'label' => $title,
338 'value' => $value,
be2fb01f 339 ];
6a488035
TO
340 }
341
342 $template->assign_by_ref('row', $values);
343 $template->assign_by_ref('profileFields', $profileFields);
344 }
345
346 $name = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
46312a4d 347 $this->assign('ufGroupName', $name);
a8387f19 348 CRM_Utils_Hook::viewProfile($name);
6a488035
TO
349
350 if (strtolower($name) == 'summary_overlay') {
351 $template->assign('overlayProfile', TRUE);
352 }
353
354 if (($this->_multiRecord & CRM_Core_Action::VIEW) && $this->_recordId && !$this->_allFields) {
355 $fieldDetail = reset($fields);
356 $fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldDetail['name']);
be2fb01f 357 $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles([$fieldId]);
fcc8f207 358 $multiRecTitle = $customGroupDetails[$fieldId]['groupTitle'];
0db6c3e1
TO
359 }
360 else {
6a488035
TO
361 $title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'title');
362 }
363
364 //CRM-4131.
365 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'display_name');
366 if ($displayName) {
367 $session = CRM_Core_Session::singleton();
368 $config = CRM_Core_Config::singleton();
369 if ($session->get('userID') &&
370 CRM_Core_Permission::check('access CiviCRM') &&
371 CRM_Contact_BAO_Contact_Permission::allow($session->get('userID'), CRM_Core_Permission::VIEW) &&
372 !$config->userFrameworkFrontend
373 ) {
374 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "action=view&reset=1&cid={$this->_id}", TRUE);
375 $this->assign('displayName', $displayName);
376 $displayName = "<a href=\"$contactViewUrl\">{$displayName}</a>";
377 }
378 $title .= ' - ' . $displayName;
379 }
380
be2fb01f 381 $title = isset($multiRecTitle) ? ts('View %1 Record', [1 => $multiRecTitle]) : $title;
6a488035
TO
382 CRM_Utils_System::setTitle($title);
383
384 // invoke the pagRun hook, CRM-3906
385 CRM_Utils_Hook::pageRun($this);
386
8aac22c8 387 return trim($template->fetch($this->getHookedTemplateFileName()));
6a488035
TO
388 }
389
ffd93213 390 /**
d7f0cce6 391 * Check template file exists.
ffd93213 392 *
d7f0cce6
BT
393 * @param string|null $suffix
394 *
395 * @return string|null
396 * Template file path, else null
ffd93213 397 */
d7f0cce6 398 public function checkTemplateFileExists($suffix = NULL) {
6a488035
TO
399 if ($this->_gid) {
400 $templateFile = "CRM/Profile/Page/{$this->_gid}/Dynamic.{$suffix}tpl";
401 $template = CRM_Core_Page::getTemplate();
402 if ($template->template_exists($templateFile)) {
403 return $templateFile;
404 }
405
406 // lets see if we have customized by name
407 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
408 if ($ufGroupName) {
409 $templateFile = "CRM/Profile/Page/{$ufGroupName}/Dynamic.{$suffix}tpl";
410 if ($template->template_exists($templateFile)) {
411 return $templateFile;
412 }
413 }
414 }
415 return NULL;
416 }
417
ffd93213 418 /**
fe482240 419 * Use the form name to create the tpl file name.
ffd93213
EM
420 *
421 * @return string
ffd93213 422 */
00be9182 423 public function getTemplateFileName() {
6a488035
TO
424 $fileName = $this->checkTemplateFileExists();
425 return $fileName ? $fileName : parent::getTemplateFileName();
426 }
427
ffd93213
EM
428 /**
429 * Default extra tpl file basically just replaces .tpl with .extra.tpl
430 * i.e. we dont override
431 *
432 * @return string
ffd93213 433 */
00be9182 434 public function overrideExtraTemplateFileName() {
6a488035
TO
435 $fileName = $this->checkTemplateFileExists('extra.');
436 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
437 }
96025800 438
b7edabe8 439 /**
440 * Get the email field as a task link, if not on hold or set to do_not_email.
441 *
442 * @param string $email
443 *
444 * @return string
445 * @throws \API_Exception
446 * @throws \Civi\API\Exception\UnauthorizedException
447 */
448 protected function getLinkedEmail($email): string {
449 if (!$email) {
450 return '';
451 }
7169ba07 452 $emailID = Email::get()->setOrderBy(['is_primary' => 'DESC'])->setWhere([['contact_id', '=', $this->_id], ['email', '=', $email], ['on_hold', '=', FALSE], ['contact_id.is_deceased', '=', FALSE], ['contact_id.is_deleted', '=', FALSE], ['contact_id.do_not_email', '=', FALSE]])->execute()->first()['id'];
b7edabe8 453 if (!$emailID) {
454 return $email;
455 }
456 $emailPopupUrl = CRM_Utils_System::url('civicrm/activity/email/add', [
457 'action' => 'add',
458 'reset' => '1',
459 'email_id' => $emailID,
460 ], TRUE);
461
462 return '<a class="crm-popup" href="' . $emailPopupUrl . '">' . $email . '</a>';
463 }
464
465 /**
466 * Get the email fields from within the fields array.
467 *
468 * @param array $fields
469 */
470 protected function getEmailFields(array $fields): array {
471 $emailFields = [];
472 foreach (array_keys($fields) as $fieldName) {
473 if (substr($fieldName, 0, 6) === 'email-'
474 && (is_numeric(substr($fieldName, 6)) || substr($fieldName, 6) ===
475 'Primary')) {
476 $emailFields[] = $fieldName;
477 }
478 }
479 return $emailFields;
480 }
481
6a488035 482}