Merge pull request #21261 from totten/master-test-jwt
[civicrm-core.git] / CRM / Profile / Page / Dynamic.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 use Civi\Api4\Email;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
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 */
28 class CRM_Profile_Page_Dynamic extends CRM_Core_Page {
29
30 /**
31 * The contact id of the person we are viewing.
32 *
33 * @var int
34 */
35 protected $_id;
36
37 /**
38 * The profile group are are interested in.
39 *
40 * @var int
41 */
42 protected $_gid;
43
44 /**
45 * The profile types we restrict this page to display.
46 *
47 * @var string
48 */
49 protected $_restrict;
50
51 /**
52 * Should we bypass permissions.
53 *
54 * @var bool
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
61 * @var array
62 */
63 protected $_profileIds = [];
64
65 /**
66 * Contact profile having activity fields?
67 *
68 * @var string
69 */
70 protected $_isContactActivityProfile = FALSE;
71
72 /**
73 * Activity Id connected to the profile.
74 *
75 * @var string
76 */
77 protected $_activityId = NULL;
78
79 protected $_multiRecord = NULL;
80
81 protected $_recordId = NULL;
82
83 /**
84 * Should the primary email be converted into a link, if emailabe.
85 *
86 * @var bool
87 */
88 protected $isShowEmailTaskLink = FALSE;
89
90 /**
91 *
92 * fetch multirecord as well as non-multirecord fields
93 * @var int
94 */
95 protected $_allFields = NULL;
96
97 /**
98 * Class constructor.
99 *
100 * @param int $id
101 * The contact id.
102 * @param int $gid
103 * The group id.
104 *
105 * @param $restrict
106 * @param bool $skipPermission
107 * @param null $profileIds
108 *
109 * @param bool $isShowEmailTaskLink
110 *
111 * @throws \CRM_Core_Exception
112 */
113 public function __construct($id, $gid, $restrict, $skipPermission = FALSE, $profileIds = NULL, $isShowEmailTaskLink = FALSE) {
114 parent::__construct();
115
116 $this->_id = $id;
117 $this->_gid = $gid;
118 $this->_restrict = $restrict;
119 $this->_skipPermission = $skipPermission;
120 $this->isShowEmailTaskLink = $isShowEmailTaskLink;
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 }
131
132 //specifies the action being done on a multi record field
133 $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
134
135 $this->_multiRecord = (!is_numeric($multiRecordAction)) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
136 if ($this->_multiRecord) {
137 $this->set('multiRecord', $this->_multiRecord);
138 }
139
140 if ($this->_multiRecord & CRM_Core_Action::VIEW) {
141 $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
142 $this->_allFields = CRM_Utils_Request::retrieve('allFields', 'Integer', $this);
143 }
144
145 if ($profileIds) {
146 $this->_profileIds = $profileIds;
147 }
148 else {
149 $this->_profileIds = [$gid];
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 *
165 * @return array
166 */
167 public function &actionLinks() {
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 *
177 */
178 public function run() {
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,
191 $limitListingsGroupsID
192 )
193 ) {
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
202 $this->_isPermissionedChecksum = $allowPermission = FALSE;
203 $permissionType = CRM_Core_Permission::VIEW;
204 if (CRM_Core_Permission::check('administer users') || CRM_Core_Permission::check('view all contacts') || CRM_Contact_BAO_Contact_Permission::allow($this->_id)) {
205 $allowPermission = TRUE;
206 }
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);
211 if (!$this->_isPermissionedChecksum) {
212 $this->_isPermissionedChecksum = $allowPermission;
213 }
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;
231 if ((!$config->userFrameworkFrontend && $allowPermission) ||
232 $this->_id == $userID ||
233 $this->_isPermissionedChecksum
234 ) {
235 $admin = TRUE;
236 }
237
238 $values = [];
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)) {
252 CRM_Core_Error::statusBounce(array_pop($errors));
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) {
270 $contactFields = $activityFields = [];
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,
288 [['activity_id', '=', $this->_activityId, 0, 0]]
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);
299 }
300 else {
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
313 $profileFields = [];
314 $labels = [];
315
316 foreach ($fields as $name => $field) {
317 //CRM-14338
318 // Create a unique, non-empty index for each field.
319 $index = $field['title'];
320 if ($index === '') {
321 $index = ' ';
322 }
323 while (array_key_exists($index, $labels)) {
324 $index .= ' ';
325 }
326
327 $labels[$index] = preg_replace('/\s+|\W+/', '_', $name);
328 }
329
330 if ($this->isShowEmailTaskLink) {
331 foreach ($this->getEmailFields($fields) as $fieldName) {
332 $values[$fields[$fieldName]['title']] = $this->getLinkedEmail($values[$fields[$fieldName]['title']]);
333 }
334 }
335 foreach ($values as $title => $value) {
336 $profileFields[$labels[$title]] = [
337 'label' => $title,
338 'value' => $value,
339 ];
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');
347 $this->assign('ufGroupName', $name);
348 CRM_Utils_Hook::viewProfile($name);
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']);
357 $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles([$fieldId]);
358 $multiRecTitle = $customGroupDetails[$fieldId]['groupTitle'];
359 }
360 else {
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
381 $title = isset($multiRecTitle) ? ts('View %1 Record', [1 => $multiRecTitle]) : $title;
382 CRM_Utils_System::setTitle($title);
383
384 // invoke the pagRun hook, CRM-3906
385 CRM_Utils_Hook::pageRun($this);
386
387 return trim($template->fetch($this->getHookedTemplateFileName()));
388 }
389
390 /**
391 * @param string $suffix
392 *
393 * @return null|string
394 */
395 public function checkTemplateFileExists($suffix = '') {
396 if ($this->_gid) {
397 $templateFile = "CRM/Profile/Page/{$this->_gid}/Dynamic.{$suffix}tpl";
398 $template = CRM_Core_Page::getTemplate();
399 if ($template->template_exists($templateFile)) {
400 return $templateFile;
401 }
402
403 // lets see if we have customized by name
404 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
405 if ($ufGroupName) {
406 $templateFile = "CRM/Profile/Page/{$ufGroupName}/Dynamic.{$suffix}tpl";
407 if ($template->template_exists($templateFile)) {
408 return $templateFile;
409 }
410 }
411 }
412 return NULL;
413 }
414
415 /**
416 * Use the form name to create the tpl file name.
417 *
418 * @return string
419 */
420 public function getTemplateFileName() {
421 $fileName = $this->checkTemplateFileExists();
422 return $fileName ? $fileName : parent::getTemplateFileName();
423 }
424
425 /**
426 * Default extra tpl file basically just replaces .tpl with .extra.tpl
427 * i.e. we dont override
428 *
429 * @return string
430 */
431 public function overrideExtraTemplateFileName() {
432 $fileName = $this->checkTemplateFileExists('extra.');
433 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
434 }
435
436 /**
437 * Get the email field as a task link, if not on hold or set to do_not_email.
438 *
439 * @param string $email
440 *
441 * @return string
442 * @throws \API_Exception
443 * @throws \Civi\API\Exception\UnauthorizedException
444 */
445 protected function getLinkedEmail($email): string {
446 if (!$email) {
447 return '';
448 }
449 $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'];
450 if (!$emailID) {
451 return $email;
452 }
453 $emailPopupUrl = CRM_Utils_System::url('civicrm/activity/email/add', [
454 'action' => 'add',
455 'reset' => '1',
456 'email_id' => $emailID,
457 ], TRUE);
458
459 return '<a class="crm-popup" href="' . $emailPopupUrl . '">' . $email . '</a>';
460 }
461
462 /**
463 * Get the email fields from within the fields array.
464 *
465 * @param array $fields
466 */
467 protected function getEmailFields(array $fields): array {
468 $emailFields = [];
469 foreach (array_keys($fields) as $fieldName) {
470 if (substr($fieldName, 0, 6) === 'email-'
471 && (is_numeric(substr($fieldName, 6)) || substr($fieldName, 6) ===
472 'Primary')) {
473 $emailFields[] = $fieldName;
474 }
475 }
476 return $emailFields;
477 }
478
479 }