INFRA-132 - Newline after "{"
[civicrm-core.git] / CRM / Profile / Form.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for custom data
38 *
39 * It delegates the work to lower level subclasses and integrates the changes
40 * back in. It also uses a lot of functionality with the CRM API's, so any change
41 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
42 *
43 */
44class CRM_Profile_Form extends CRM_Core_Form {
7da04cde 45 const
6a488035
TO
46 MODE_REGISTER = 1,
47 MODE_SEARCH = 2,
48 MODE_CREATE = 4,
49 MODE_EDIT = 8;
50
51 protected $_mode;
52
53 protected $_skipPermission = FALSE;
54
55 /**
56 * The contact id that we are editing
57 *
58 * @var int
59 */
60 protected $_id;
61
62 /**
63 * The group id that we are editing
64 *
65 * @var int
66 */
67 protected $_gid;
68
a8387f19 69 /**
a3dbd1bc 70 * @var array details of the UFGroup used on this page
a8387f19 71 */
a3dbd1bc 72 protected $_ufGroup = array('name' => 'unknown');
a8387f19 73
6a488035
TO
74 /**
75 * The group id that we are passing in url
76 *
77 * @var int
78 */
79 public $_grid;
80
426ac5e0
EM
81 /**
82 * Name of button for saving matching contacts
83 * @var
84 */
85 protected $_duplicateButtonName;
6a488035
TO
86 /**
87 * The title of the category we are editing
88 *
89 * @var string
90 */
91 protected $_title;
92
93 /**
100fef9d 94 * The fields needed to build this form
6a488035
TO
95 *
96 * @var array
97 */
98 public $_fields;
99
100 /**
100fef9d 101 * To store contact details
6a488035
TO
102 *
103 * @var array
104 */
105 protected $_contact;
106
6a488035
TO
107 /**
108 * Do we allow updates of the contact
109 *
110 * @var int
111 */
112 public $_isUpdateDupe = 0;
113
114 public $_isAddCaptcha = FALSE;
115
116 protected $_isPermissionedChecksum = FALSE;
117
118 /**
119 * THe context from which we came from, allows us to go there if redirect not set
120 *
121 * @var string
122 */
123 protected $_context;
124
125 /**
126 * THe contact type for registration case
127 *
128 * @var string
129 */
130 protected $_ctype = NULL;
131
132 protected $_defaults = NULL;
133
134 /**
135 * Store profile ids if multiple profile ids are passed using comma separated.
136 * Currently lets implement this functionality only for dialog mode
137 */
138 protected $_profileIds = array();
139
140 /**
141 * Contact profile having activity fields?
142 *
143 * @var string
144 */
145 protected $_isContactActivityProfile = FALSE;
146
147 /**
148 * Activity Id connected to the profile
149 *
150 * @var string
151 */
152 protected $_activityId = NULL;
153
154
155 protected $_multiRecordFields = NULL;
156
157 protected $_recordId = NULL;
158
159 /**
100fef9d 160 * Action for multi record profile (create/edit/delete)
6a488035
TO
161 *
162 * @var string
163 */
164 protected $_multiRecord = NULL;
165
166 protected $_multiRecordProfile = FALSE;
167
168 protected $_recordExists = TRUE;
169
170 protected $_customGroupTitle = NULL;
171
172 protected $_deleteButtonName = NULL;
173
174 protected $_customGroupId = NULL;
175
176 protected $_currentUserID = NULL;
177 protected $_session = NULL;
178
179 /**
100fef9d 180 * Pre processing work done here.
6a488035
TO
181 *
182 * gets session variables for table name, id of entity in table, type of entity and stores them.
183 *
184 * @param
185 *
186 * @return void
187 *
6a488035 188 */
00be9182 189 public function preProcess() {
6a488035 190 $this->_id = $this->get('id');
6a488035
TO
191 $this->_profileIds = $this->get('profileIds');
192 $this->_grid = CRM_Utils_Request::retrieve('grid', 'Integer', $this);
193 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
194
195 //unset from session when $_GET doesn't have it
196 //except when the form is submitted
197 if (empty($_POST)) {
198 if (!array_key_exists('multiRecord', $_GET)) {
199 $this->set('multiRecord', NULL);
200 }
201 if (!array_key_exists('recordId', $_GET)) {
202 $this->set('recordId', NULL);
203 }
204 }
205
206 $this->_session = CRM_Core_Session::singleton();
207 $this->_currentUserID = $this->_session->get('userID');
208
209 if ($this->_mode == self::MODE_EDIT) {
210 //specifies the action being done on a multi record field
211 $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
dc98079b 212 $this->_multiRecord = (!is_numeric($multiRecordAction)) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
6a488035
TO
213 if ($this->_multiRecord) {
214 $this->set('multiRecord', $this->_multiRecord);
215 }
216
217 if ($this->_multiRecord &&
218 !in_array($this->_multiRecord, array(CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::DELETE))) {
219 CRM_Core_Error::fatal(ts('Proper action not specified for this custom value record profile'));
220 }
221 }
222 $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
223
a3dbd1bc 224 $gids = explode(',', CRM_Utils_Request::retrieve('gid', 'String', CRM_Core_DAO::$_nullObject, FALSE, 0));
6a488035
TO
225
226 if ((count($gids) > 1) && !$this->_profileIds && empty($this->_profileIds)) {
227 if (!empty($gids)) {
228 foreach ($gids as $pfId) {
229 $this->_profileIds[] = CRM_Utils_Type::escape($pfId, 'Positive');
230 }
231 }
232
233 // check if we are rendering mixed profiles
234 if (CRM_Core_BAO_UFGroup::checkForMixProfiles($this->_profileIds)) {
235 CRM_Core_Error::fatal(ts('You cannot combine profiles of multiple types.'));
236 }
237
238 // for now consider 1'st profile as primary profile and validate it
239 // i.e check for profile type etc.
240 // FIX ME: validations for other than primary
241 $this->_gid = $this->_profileIds[0];
242 $this->set('gid', $this->_gid);
243 $this->set('profileIds', $this->_profileIds);
244 }
245
246 if (!$this->_gid) {
a3dbd1bc
TO
247 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0);
248 $this->set('gid', $this->_gid);
249 }
250
6a488035
TO
251 $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
252 if (is_numeric($this->_activityId)) {
253 $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
254 if ($latestRevisionId) {
255 $this->_activityId = $latestRevisionId;
256 }
257 }
258 $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
259
46312a4d 260 //get values for ufGroupName, captch and dupe update.
6a488035
TO
261 if ($this->_gid) {
262 $dao = new CRM_Core_DAO_UFGroup();
263 $dao->id = $this->_gid;
264 if ($dao->find(TRUE)) {
265 $this->_isUpdateDupe = $dao->is_update_dupe;
266 $this->_isAddCaptcha = $dao->add_captcha;
a3dbd1bc 267 $this->_ufGroup = (array) $dao;
6a488035
TO
268 }
269 $dao->free();
a3dbd1bc 270
cacc57d7
TO
271 if (!CRM_Utils_Array::value('is_active', $this->_ufGroup)) {
272 CRM_Core_Error::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', array(
273 1 => $this->_gid,
274 )));
275 }
a3dbd1bc 276 }
cacc57d7 277 $this->assign('ufGroupName', $this->_ufGroup['name']);
6a488035
TO
278
279 $gids = empty($this->_profileIds) ? $this->_gid : $this->_profileIds;
280
281 // if we dont have a gid use the default, else just use that specific gid
282 if (($this->_mode == self::MODE_REGISTER || $this->_mode == self::MODE_CREATE) && !$this->_gid) {
283 $this->_ctype = CRM_Utils_Request::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
284 $this->_fields = CRM_Core_BAO_UFGroup::getRegistrationFields($this->_action, $this->_mode, $this->_ctype);
285 }
286 elseif ($this->_mode == self::MODE_SEARCH) {
287 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields($this->_action,
288 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
289 FALSE,
290 $gids,
291 TRUE, NULL,
292 $this->_skipPermission,
293 CRM_Core_Permission::SEARCH
294 );
295 }
296 else {
297 $this->_fields = CRM_Core_BAO_UFGroup::getFields($gids, FALSE, NULL,
298 NULL, NULL,
299 FALSE, NULL,
300 $this->_skipPermission,
301 NULL,
302 ($this->_action == CRM_Core_Action::ADD) ? CRM_Core_Permission::CREATE : CRM_Core_Permission::EDIT
303 );
304 $multiRecordFieldListing = FALSE;
305 //using selector for listing of multirecord fields
306 if ($this->_mode == self::MODE_EDIT && $this->_gid) {
307 CRM_Core_BAO_UFGroup::shiftMultiRecordFields($this->_fields, $this->_multiRecordFields);
308
309 if ($this->_multiRecord) {
310 if ($this->_multiRecord != CRM_Core_Action::ADD) {
311 $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
0db6c3e1
TO
312 }
313 else {
6a488035
TO
314 $this->_recordId = NULL;
315 $this->set('recordId', NULL);
316 }
317 //record id is neccessary for _multiRecord view and update/edit action
318 if (!$this->_recordId
319 && ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE)) {
320 CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
321 array(1 => $this->_gid)
322 ));
0db6c3e1
TO
323 }
324 elseif (empty($this->_multiRecordFields)) {
dc98079b 325 CRM_Core_Error::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
6a488035
TO
326 array(1 => $this->_gid)
327 ));
328 }
329
330 $fieldId = CRM_Core_BAO_CustomField::getKeyID(key($this->_multiRecordFields));
331 $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles(array($fieldId));
332 $this->_customGroupTitle = $customGroupDetails[$fieldId]['groupTitle'];
333 $this->_customGroupId = $customGroupDetails[$fieldId]['groupID'];
334
335 if ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE) {
336 //record exists check
337 foreach ($this->_multiRecordFields as $key => $field) {
338 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
339 }
340 $getValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
341
342 if (array_key_exists($this->_recordId, $getValues)) {
343 $this->_recordExists = TRUE;
0db6c3e1
TO
344 }
345 else {
6a488035
TO
346 $this->_recordExists = FALSE;
347 if ($this->_multiRecord & CRM_Core_Action::UPDATE) {
348 CRM_Core_Session::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', array(1 => $this->_recordId)), ts('Record doesnot exist'), 'alert');
349 }
350 }
351 }
352 if ($this->_multiRecord & CRM_Core_Action::ADD) {
353 $this->_maxRecordLimit = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id);
354 if ($this->_maxRecordLimit) {
355 CRM_Core_Session::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
356 }
357 }
358
0db6c3e1
TO
359 }
360 elseif (!empty($this->_multiRecordFields)
6a488035 361 && (!$this->_multiRecord || !in_array($this->_multiRecord, array(CRM_Core_Action::DELETE, CRM_Core_Action::UPDATE)) )) {
96ed17aa 362 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
6a488035
TO
363 //multirecord listing page
364 $multiRecordFieldListing = TRUE;
365 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
366 $cs = $this->get('cs');
367 $page->set('pageCheckSum', $cs);
368 $page->set('contactId', $this->_id);
369 $page->set('profileId', $this->_gid);
370 $page->set('action', CRM_Core_Action::BROWSE);
371 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
372 $page->run();
373 }
374 }
375 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
376
377 // is profile double-opt in?
a7488080 378 if (!empty($this->_fields['group']) &&
6a488035
TO
379 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
380 ) {
381 $emailField = FALSE;
382 foreach ($this->_fields as $name => $values) {
383 if (substr($name, 0, 6) == 'email-') {
384 $emailField = TRUE;
385 }
386 }
387
388 if (!$emailField) {
389 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
390 $this->_session->setStatus($status);
391 }
392 }
393
426ac5e0 394 //transferring all the multi-record custom fields in _fields
6a488035
TO
395 if ($this->_multiRecord && !empty($this->_multiRecordFields)) {
396 $this->_fields = $this->_multiRecordFields;
397 $this->_multiRecordProfile = TRUE;
0db6c3e1
TO
398 }
399 elseif ($this->_multiRecord && empty($this->_multiRecordFields)) {
6a488035 400 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
426ac5e0 401 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
6a488035
TO
402 }
403 }
404
405 if (!is_array($this->_fields)) {
406 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
426ac5e0 407 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
6a488035
TO
408 }
409 }
410
411 /**
c490a46a 412 * Set default values for the form. Note that in edit/view mode
6a488035
TO
413 * the default values are retrieved from the database
414 *
6a488035
TO
415 *
416 * @return void
417 */
00be9182 418 public function setDefaultsValues() {
6a488035
TO
419 $this->_defaults = array();
420 if ($this->_multiRecordProfile && ($this->_multiRecord == CRM_Core_Action::DELETE)) {
421 return;
422 }
423
424 if ($this->_mode != self::MODE_SEARCH) {
425 // set default values for country / state to start with
426 CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $this->_defaults);
427 }
428
429 if ($this->_id && !$this->_multiRecordProfile) {
430 if ($this->_isContactActivityProfile) {
431 $contactFields = $activityFields = array();
432 foreach ($this->_fields as $fieldName => $field) {
433 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
434 $activityFields[$fieldName] = $field;
435 }
436 else {
437 $contactFields[$fieldName] = $field;
438 }
439 }
440
441 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $contactFields, $this->_defaults, TRUE);
442 if ($this->_activityId) {
443 CRM_Core_BAO_UFGroup::setComponentDefaults($activityFields, $this->_activityId, 'Activity', $this->_defaults, TRUE);
444 }
445 }
446 else {
447 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $this->_fields, $this->_defaults, TRUE);
448 }
449 }
450
451 //set custom field defaults
452 if ($this->_multiRecordProfile) {
453 foreach ($this->_multiRecordFields as $key => $field) {
454 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
455 }
456
dc98079b 457 $defaultValues = array();
6a488035
TO
458 if ($this->_multiRecord && $this->_multiRecord == CRM_Core_Action::UPDATE) {
459 $defaultValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
460 if ($this->_recordExists == TRUE) {
461 $defaultValues = $defaultValues[$this->_recordId];
0db6c3e1
TO
462 }
463 else {
6a488035
TO
464 $defaultValues = NULL;
465 }
466 }
467
468 if (!empty($defaultValues)) {
469 foreach ($defaultValues as $key => $value) {
470 $name = "custom_{$key}";
471 $htmlType = $this->_multiRecordFields[$name]['html_type'];
472 if ($htmlType != 'File') {
473 if (isset($value)) {
474 CRM_Core_BAO_CustomField::setProfileDefaults($key,
475 $name,
476 $this->_defaults,
477 $this->_id,
478 $this->_mode,
479 $value
480 );
0db6c3e1
TO
481 }
482 else {
6a488035
TO
483 $this->_defaults[$name] = "";
484 }
485 }
486
487 if ($htmlType == 'File') {
488 $entityId = $this->_id;
489 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' &&
490 $this->_activityId
491 ) {
492 $entityId = $this->_activityId;
493 }
494 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $key);
495
496 if ($url) {
497 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
498
499 $deleteExtra = ts("Are you sure you want to delete attached file?");
500 $fileId = $url['file_id'];
501 $deleteURL = CRM_Utils_System::url('civicrm/file',
502 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
503 );
504 $text = ts("Delete Attached File");
505 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
506
507 // also delete the required rule that we've set on the form element
508 $this->removeFileRequiredRules($name);
509 }
510 }
511 }
512 }
455d8c42 513 }
514 else {
6a488035
TO
515 foreach ($this->_fields as $name => $field) {
516 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
517 $htmlType = $field['html_type'];
518 if ((!isset($this->_defaults[$name]) || $htmlType == 'File') &&
519 (CRM_Utils_Array::value('field_type', $field) != 'Activity')
520 ) {
521 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
522 $name,
523 $this->_defaults,
524 $this->_id,
525 $this->_mode
526 );
527 }
528
529 if ($htmlType == 'File') {
530 $entityId = $this->_id;
455d8c42 531 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' && $this->_activityId) {
6a488035
TO
532 $entityId = $this->_activityId;
533 }
534 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $customFieldID);
535
536 if ($url) {
537 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
538
539 $deleteExtra = ts("Are you sure you want to delete attached file?");
540 $fileId = $url['file_id'];
541 $deleteURL = CRM_Utils_System::url('civicrm/file',
542 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
543 );
544 $text = ts("Delete Attached File");
545 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
546
547 // also delete the required rule that we've set on the form element
548 $this->removeFileRequiredRules($field['name']);
549 }
550 }
551 }
552 }
553 }
554 if (isset($customFiles)) {
555 $this->assign('customFiles', $customFiles);
556 }
557
558 if ($this->_multiRecordProfile) {
559 $this->setDefaults($this->_defaults);
560 return;
561 }
562
a7488080 563 if (!empty($this->_defaults['image_URL'])) {
77d45291 564 list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String::unstupifyUrl($this->_defaults['image_URL']));
6a488035
TO
565 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
566 $this->assign("imageWidth", $imageWidth);
567 $this->assign("imageHeight", $imageHeight);
568 $this->assign("imageThumbWidth", $imageThumbWidth);
569 $this->assign("imageThumbHeight", $imageThumbHeight);
570 $this->assign("imageURL", $this->_defaults['image_URL']);
455d8c42 571 $this->removeFileRequiredRules('image_URL');
6a488035
TO
572 }
573
574 if (array_key_exists('contact_sub_type', $this->_defaults) &&
575 !empty($this->_defaults['contact_sub_type'])
576 ) {
577 $this->_defaults['contact_sub_type'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
578 trim($this->_defaults['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
579 );
580 }
581
582 $this->setDefaults($this->_defaults);
583 }
584
585 /**
c490a46a 586 * Build the form object
6a488035
TO
587 *
588 * @return void
6a488035
TO
589 */
590 public function buildQuickForm() {
a3dbd1bc
TO
591 $this->add('hidden', 'gid', $this->_gid);
592
a8387f19
TO
593 switch ($this->_mode) {
594 case self::MODE_CREATE:
595 case self::MODE_EDIT:
596 case self::MODE_REGISTER:
a3dbd1bc 597 CRM_Utils_Hook::buildProfile($this->_ufGroup['name']);
a8387f19 598 break;
dc98079b 599
a8387f19 600 case self::MODE_SEARCH:
a3dbd1bc 601 CRM_Utils_Hook::searchProfile($this->_ufGroup['name']);
a8387f19 602 break;
dc98079b 603
a8387f19
TO
604 default:
605 }
606
6a488035
TO
607 //lets have single status message, CRM-4363
608 $return = FALSE;
609 $statusMessage = NULL;
610 if (($this->_multiRecord & CRM_Core_Action::ADD) && $this->_maxRecordLimit) {
611 return;
612 }
613
614 if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
615 if (!$this->_recordExists) {
616 CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId)), ts('Record doesnot exists'), 'alert');
617 }
618 else {
619 $this->assign('deleteRecord', TRUE);
620 }
621 return;
622 }
623
624 CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id);
625
626 // we should not allow component and mix profiles in search mode
627 if ($this->_mode != self::MODE_REGISTER) {
628 //check for mix profile fields (eg: individual + other contact type)
629 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
630 if (($this->_mode & self::MODE_EDIT) && $this->_isContactActivityProfile) {
631 $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
632 if (!empty($errors)) {
633 $statusMessage = array_pop($errors);
634 $return = TRUE;
635 }
636 }
637 else {
638 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
639 $return = TRUE;
640 }
641 }
642
643 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
644
645 if ($this->_id) {
646 $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id);
647 $contactType = $contactTypes[0];
648
649 array_shift($contactTypes);
650 $contactSubtypes = $contactTypes;
651
652 $profileSubType = FALSE;
653 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
654 $profileSubType = $profileType;
655 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
656 }
657
658 if (
659 ($profileType != 'Contact' && !$this->_isContactActivityProfile) &&
dc98079b 660 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
6a488035
TO
661 ($profileType != $contactType))
662 ) {
663 $return = TRUE;
664 if (!$statusMessage) {
665 $statusMessage =
666 ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
667 array(1 => $profileSubType ? $profileSubType : $profileType));
668 }
669 }
670 }
671
672 if (
673 in_array(
674 $profileType,
675 array("Membership", "Participant", "Contribution")
676 )
677 ) {
678 $return = TRUE;
679 if (!$statusMessage) {
680 $statusMessage = ts('Profile is not configured for the selected action.');
681 }
682 }
683 }
684
426ac5e0 685 //lets have single status message,
6a488035
TO
686 $this->assign('statusMessage', $statusMessage);
687 if ($return) {
688 return FALSE;
689 }
690
691 $this->assign('id', $this->_id);
692 $this->assign('mode', $this->_mode);
693 $this->assign('action', $this->_action);
694 $this->assign('fields', $this->_fields);
695 $this->assign('fieldset', (isset($this->_fieldset)) ? $this->_fieldset : "");
696
697 // should we restrict what we display
698 $admin = TRUE;
699 if ($this->_mode == self::MODE_EDIT) {
700 $admin = FALSE;
701 // show all fields that are visibile:
702 // if we are a admin OR the same user OR acl-user with access to the profile
703 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
704 if (
705 CRM_Core_Permission::check('administer users') ||
706 $this->_id == $this->_currentUserID ||
707 $this->_isPermissionedChecksum ||
708 in_array(
709 $this->_gid,
710 CRM_ACL_API::group(
711 CRM_Core_Permission::EDIT,
712 NULL,
713 'civicrm_uf_group',
ff4f7744 714 CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')
6a488035
TO
715 )
716 )
717 ) {
718 $admin = TRUE;
719 }
720 }
721
722 // if false, user is not logged-in.
723 $anonUser = FALSE;
724 if (!$this->_currentUserID) {
725 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
726 $primaryLocationType = $defaultLocationType->id;
727 $anonUser = TRUE;
728 }
729 $this->assign('anonUser', $anonUser);
730
731 $addCaptcha = array();
732 $emailPresent = FALSE;
733
6a488035
TO
734 // add the form elements
735 foreach ($this->_fields as $name => $field) {
736 // make sure that there is enough permission to expose this field
737 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
738 unset($this->_fields[$name]);
739 continue;
740 }
741
742 // since the CMS manages the email field, suppress the email display if in
743 // register mode which occur within the CMS form
744 if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') {
745 unset($this->_fields[$name]);
746 continue;
747 }
748
749 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
6a488035
TO
750
751 CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode);
752
dd78acd9
TO
753 if ($field['add_to_group_id']) {
754 $addToGroupId = $field['add_to_group_id'];
755 }
756
6a488035
TO
757 //build array for captcha
758 if ($field['add_captcha']) {
759 $addCaptcha[$field['group_id']] = $field['add_captcha'];
760 }
761
762 if (($name == 'email-Primary') || ($name == 'email-' . isset($primaryLocationType) ? $primaryLocationType : "")) {
763 $emailPresent = TRUE;
764 $this->_mail = $name;
765 }
766 }
767
768 // add captcha only for create mode.
769 if ($this->_mode == self::MODE_CREATE) {
770 // suppress captcha for logged in users only
771 if ($this->_currentUserID) {
772 $this->_isAddCaptcha = FALSE;
773 }
774 else if (!$this->_isAddCaptcha && !empty($addCaptcha)) {
775 $this->_isAddCaptcha = TRUE;
776 }
777
778 if ($this->_gid) {
779 $dao = new CRM_Core_DAO_UFGroup();
780 $dao->id = $this->_gid;
781 $dao->addSelect();
782 $dao->addSelect('is_update_dupe');
783 if ($dao->find(TRUE)) {
784 if ($dao->is_update_dupe) {
785 $this->_isUpdateDupe = $dao->is_update_dupe;
786 }
787 }
788 }
789 }
790 else {
791 $this->_isAddCaptcha = FALSE;
792 }
793
794 //finally add captcha to form.
795 if ($this->_isAddCaptcha) {
796 $captcha = CRM_Utils_ReCAPTCHA::singleton();
797 $captcha->add($this);
798 }
799 $this->assign("isCaptcha", $this->_isAddCaptcha);
800
dd78acd9
TO
801 if ($this->_mode != self::MODE_SEARCH) {
802 if (isset($addToGroupId)) {
803 $this->_ufGroup['add_to_group_id'] = $addToGroupId;
804 }
805 }
806
7f1a247f 807 //let's do set defaults for the profile
808 $this->setDefaultsValues();
809
6a488035
TO
810 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
811 if ($this->_mode == self::MODE_CREATE) {
812 CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action);
813 }
814 else {
815 $this->assign('showCMS', FALSE);
816 }
817
818 $this->assign('groupId', $this->_gid);
819
6a488035
TO
820 // if view mode pls freeze it with the done button.
821 if ($this->_action & CRM_Core_Action::VIEW) {
822 $this->freeze();
823 }
824
825 if ($this->_context == 'dialog') {
826 $this->addElement(
827 'submit',
828 $this->_duplicateButtonName,
829 ts('Save Matching Contact')
830 );
831 }
832 }
833
ffd93213 834 /**
c490a46a
CW
835 * Validate profile and provided activity Id
836 *
837 * @param int $activityId
838 * @param int $contactId
839 * @param int $gid
ffd93213
EM
840 *
841 * @return array
842 */
00be9182 843 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
6a488035
TO
844 $errors = array();
845 if (!$activityId) {
846 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
847 return $errors;
848 }
849
850 $activityDetails = array();
851 $activityParams = array('id' => $activityId);
852 CRM_Activity_BAO_Activity::retrieve($activityParams, $activityDetails);
853
854 if (empty($activityDetails)) {
855 $errors[] = 'Invalid Activity Id (aid).';
856 return $errors;
857 }
858
859 $profileActivityTypes = CRM_Core_BAO_UFGroup::groupTypeValues($gid, 'Activity');
860
8cc574cf 861 if ((!empty($profileActivityTypes['Activity']) &&
6a488035
TO
862 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
863 ) ||
864 (!in_array($contactId, $activityDetails['assignee_contact']) &&
865 !in_array($contactId, $activityDetails['target_contact'])
866 )
867 ) {
868 $errors[] = 'This activity cannot be edited or viewed via this profile.';
869 }
870
871 return $errors;
872 }
873
874 /**
100fef9d 875 * Global form rule
6a488035 876 *
68c9fb83
TO
877 * @param array $fields
878 * The input form values.
879 * @param array $files
880 * The uploaded files if any.
881 * @param CRM_Core_Form $form
882 * The form object.
6a488035
TO
883 *
884 * @return true if no errors, else array of errors
6a488035
TO
885 * @static
886 */
00be9182 887 public static function formRule($fields, $files, $form) {
a3dbd1bc 888 CRM_Utils_Hook::validateProfile($form->_ufGroup['name']);
a8387f19 889
6a488035
TO
890 $errors = array();
891 // if no values, return
892 if (empty($fields)) {
893 return TRUE;
894 }
895
896 $register = NULL;
897
898 // hack we use a -1 in options to indicate that its registration
899 if ($form->_id) {
900 $form->_isUpdateDupe = 1;
901 }
902
903 if ($form->_mode == CRM_Profile_Form::MODE_REGISTER) {
904 $register = TRUE;
905 }
906
907 // dont check for duplicates during registration validation: CRM-375
8cc574cf 908 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
6a488035 909 // fix for CRM-3240
a7488080 910 if (!empty($fields['email-Primary'])) {
6a488035
TO
911 $fields['email'] = CRM_Utils_Array::value('email-Primary', $fields);
912 }
913
914 // fix for CRM-6141
8cc574cf 915 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
6a488035
TO
916 $fields['phone-Primary'] = $fields['phone-Primary-1'];
917 }
918
919 $ctype = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
920 // If all profile fields is of Contact Type then consider
921 // profile is of Individual type(default).
922 if (!$ctype) {
923 $ctype = 'Individual';
924 }
925 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $ctype);
926 if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
927 // fix for CRM-2888
928 $exceptions = array();
929 }
930 else {
931 // for edit mode we need to allow our own record to be a dupe match!
932 $exceptions = array($form->_session->get('userID'));
933 }
934
935 // for dialog mode we should always use fuzzy rule.
936 $ruleType = 'Unsupervised';
937 if ($form->_context == 'dialog') {
938 $ruleType = 'Supervised';
939 }
940
941 $dedupeParams['check_permission'] = FALSE;
942 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams,
943 $ctype,
944 $ruleType,
945 $exceptions
946 );
947 if ($ids) {
948 if ($form->_isUpdateDupe == 2) {
949 CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
950 }
951 elseif ($form->_isUpdateDupe == 1) {
952 if (!$form->_id) {
953 $form->_id = $ids[0];
954 }
955 }
956 else {
957 if ($form->_context == 'dialog') {
958 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
959
960 $duplicateContactsLinks = '<div class="matching-contacts-found">';
961 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
962 if ($contactLinks['msg'] == 'view') {
963 $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
964 }
965 else {
966 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
967 }
968 $duplicateContactsLinks .= '</div>';
969 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
970 $row = '';
971 for ($i = 0; $i < sizeof($contactLinks['rows']); $i++) {
972 $row .= ' <tr> ';
973 $row .= ' <td class="matching-contacts-name"> ';
974 $row .= $contactLinks['rows'][$i]['display_name'];
975 $row .= ' </td>';
976 $row .= ' <td class="matching-contacts-email"> ';
977 $row .= $contactLinks['rows'][$i]['primary_email'];
978 $row .= ' </td>';
979 $row .= ' <td class="action-items"> ';
980 $row .= $contactLinks['rows'][$i]['view'] . ' ';
981 $row .= $contactLinks['rows'][$i]['edit'];
982 $row .= ' </td>';
983 $row .= ' </tr> ';
984 }
985
986 $duplicateContactsLinks .= $row . '</table>';
987 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
988
989 $errors['_qf_default'] = $duplicateContactsLinks;
990
991 // let smarty know that there are duplicates
992 $template = CRM_Core_Smarty::singleton();
993 $template->assign('isDuplicate', 1);
994 }
995 else {
996 $errors['_qf_default'] = ts('A record already exists with the same information.');
997 }
998 }
999 }
1000 }
1001
1002 foreach ($fields as $key => $value) {
1003 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $key, 3);
1004 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1005 // Validate Country - State list
1006 $countryId = $fields["country-{$locTypeId}"];
1007 $stateProvinceId = $value;
1008
1009 if ($stateProvinceId && $countryId) {
1010 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1011 $stateProvinceDAO->id = $stateProvinceId;
1012 $stateProvinceDAO->find(TRUE);
1013
1014 if ($stateProvinceDAO->country_id != $countryId) {
1015 // country mismatch hence display error
1016 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1017 $countries = CRM_Core_PseudoConstant::country();
1018 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
1019 }
1020 }
1021 }
1022
1023 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1024 // Validate County - State list
1025 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1026 $countyId = $value;
1027
1028 if ($countyId && $stateProvinceId) {
1029 $countyDAO = new CRM_Core_DAO_County();
1030 $countyDAO->id = $countyId;
1031 $countyDAO->find(TRUE);
1032
1033 if ($countyDAO->state_province_id != $stateProvinceId) {
1034 // state province mismatch hence display error
1035 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1036 $counties = CRM_Core_PseudoConstant::county();
1037 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id] . ".";
1038 }
1039 }
1040 }
1041 }
1042 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1043 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1044 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
1045 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1046 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1047 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1048 );
1049 }
1050 }
1051 }
1052
1053 return empty($errors) ? TRUE : $errors;
1054 }
1055
1056 /**
1057 * Process the user submitted custom data values.
1058 *
6a488035
TO
1059 *
1060 * @return void
1061 */
1062 public function postProcess() {
1063 $params = $this->controller->exportValues($this->_name);
1064
1065 //if the delete record button is clicked
1066 if ($this->_deleteButtonName) {
a7488080 1067 if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
6a488035 1068 $filterParams['id'] = $this->_customGroupId;
426ac5e0
EM
1069 $returnProperties = array('is_multiple', 'table_name');
1070 CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
a7488080 1071 if (!empty($returnValues['is_multiple'])) {
6a488035
TO
1072 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
1073 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1074 $sqlParams = array(
1075 1 => array($this->_recordId, 'Integer'),
1076 2 => array($this->_id, 'Integer')
1077 );
dc98079b
TO
1078 CRM_Core_DAO::executeQuery($sql, $sqlParams);
1079 CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
6a488035
TO
1080 }
1081 }
1082 return;
1083 }
1084 }
a3dbd1bc 1085 CRM_Utils_Hook::processProfile($this->_ufGroup['name']);
a7488080 1086 if (!empty($params['image_URL'])) {
6a488035
TO
1087 CRM_Contact_BAO_Contact::processImageParams($params);
1088 }
1089
1090 $greetingTypes = array(
1091 'addressee' => 'addressee_id',
1092 'email_greeting' => 'email_greeting_id',
1093 'postal_greeting' => 'postal_greeting_id',
1094 );
1095
1096 $details = array();
1097 if ($this->_id) {
1098 $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id,
1099 $greetingTypes
1100 );
1101 $details = $contactDetails[0][$this->_id];
1102 }
8cc574cf 1103 if (!(!empty($details['addressee_id']) || !empty($details['email_greeting_id']) ||
6a488035
TO
1104 CRM_Utils_Array::value('postal_greeting_id', $details)
1105 )) {
1106
1107 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
1108 //Though Profile type is contact we need
1109 //Individual/Household/Organization for setting Greetings.
1110 if ($profileType == 'Contact') {
1111 $profileType = 'Individual';
1112 //if we editing Household/Organization.
1113 if ($this->_id) {
1114 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
1115 }
1116 }
1117 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
1118 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
1119 }
1120
1121 foreach ($greetingTypes as $key => $value) {
1122 if (!array_key_exists($key, $params)) {
1123 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
1124 }
1125 }
1126 }
1127
1128 $transaction = new CRM_Core_Transaction();
1129
426ac5e0 1130 //used to send subscribe mail to the group which user want.
6a488035
TO
1131 //if the profile double option in is enabled
1132 $mailingType = array();
6a488035
TO
1133
1134 $result = NULL;
1135 foreach ($params as $name => $values) {
1136 if (substr($name, 0, 6) == 'email-') {
1137 $result['email'] = $values;
1138 }
1139 }
1140
1141 //array of group id, subscribed by contact
1142 $contactGroup = array();
a7488080 1143 if (!empty($params['group']) &&
6a488035
TO
1144 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
1145 ) {
1146 $groupSubscribed = array();
a7488080 1147 if (!empty($result['email'])) {
6a488035
TO
1148 if ($this->_id) {
1149 $contactGroups = new CRM_Contact_DAO_GroupContact();
1150 $contactGroups->contact_id = $this->_id;
1151 $contactGroups->status = 'Added';
1152 $contactGroups->find();
1153 $contactGroup = array();
1154 while ($contactGroups->fetch()) {
1155 $contactGroup[] = $contactGroups->group_id;
1156 $groupSubscribed[$contactGroups->group_id] = 1;
1157 }
1158 }
1159 foreach ($params['group'] as $key => $val) {
1160 if (!$val) {
1161 unset($params['group'][$key]);
1162 continue;
1163 }
1164 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1165 $key, 'group_type', 'id'
1166 );
1167 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1168 substr($groupTypes, 1, -1)
1169 );
1170 //filter group of mailing type and unset it from params
1171 if (in_array(2, $groupType)) {
1172 //if group is already subscribed , ignore it
1173 $groupExist = CRM_Utils_Array::key($key, $contactGroup);
1174 if (!isset($groupExist)) {
1175 $mailingType[] = $key;
1176 unset($params['group'][$key]);
1177 }
1178 }
1179 }
1180 }
1181 }
1182
a3dbd1bc 1183 $addToGroupId = CRM_Utils_Array::value('add_to_group_id', $this->_ufGroup);
bada0f66 1184 if (!empty($addToGroupId)) {
6a488035
TO
1185 //run same check whether group is a mailing list
1186 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1187 $addToGroupId, 'group_type', 'id'
1188 );
1189 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1190 substr($groupTypes, 1, -1)
1191 );
1192 //filter group of mailing type and unset it from params
8cc574cf 1193 if (in_array(2, $groupType) && !empty($result['email']) &&
6a488035
TO
1194 CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()
1195 ) {
1196 if (!count($contactGroup)) {
1197 //array of group id, subscribed by contact
1198 $contactGroup = array();
1199 if ($this->_id) {
1200 $contactGroups = new CRM_Contact_DAO_GroupContact();
1201 $contactGroups->contact_id = $this->_id;
1202 $contactGroups->status = 'Added';
1203 $contactGroups->find();
1204 $contactGroup = array();
1205 while ($contactGroups->fetch()) {
1206 $contactGroup[] = $contactGroups->group_id;
1207 $groupSubscribed[$contactGroups->group_id] = 1;
1208 }
1209 }
1210 }
1211 //if group is already subscribed , ignore it
1212 $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
1213 if (!isset($groupExist)) {
1214 $mailingType[] = $addToGroupId;
1215 $addToGroupId = NULL;
1216 }
1217 }
1218 else {
1219 // since we are directly adding contact to group lets unset it from mailing
1220 if ($key = array_search($addToGroupId, $mailingType)) {
1221 unset($mailingType[$key]);
1222 }
1223 }
1224 }
1225
1226 if ($this->_grid) {
1227 $params['group'] = $groupSubscribed;
1228 }
1229
1230 // commenting below code, since we potentially
1231 // triggered maximum name field formatting cases during CRM-4430.
1232 // CRM-4343
1233 // $params['preserveDBName'] = true;
1234
1235 $profileFields = $this->_fields;
1236 if (($this->_mode & self::MODE_EDIT) && $this->_activityId && $this->_isContactActivityProfile) {
1237 $profileFields = $activityParams = array();
1238 foreach ($this->_fields as $fieldName => $field) {
1239 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
1240 if (isset($params[$fieldName])) {
1241 $activityParams[$fieldName] = $params[$fieldName];
1242 }
1243 if (isset($params['activity_date_time'])) {
1244 $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1245 }
a7488080 1246 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
6a488035
TO
1247 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1248 }
1249 }
1250 else {
1251 $profileFields[$fieldName] = $field;
1252 }
1253 }
1254
1255 if (!empty($activityParams)) {
1256 $activityParams['version'] = 3;
1257 $activityParams['id'] = $this->_activityId;
1258 $activityParams['skipRecentView'] = TRUE;
1259 civicrm_api('Activity', 'create', $activityParams);
1260 }
1261 }
1262
1263 if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
1264 $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
1265 }
1266
1267 $this->_id = CRM_Contact_BAO_Contact::createProfileContact(
1268 $params,
1269 $profileFields,
1270 $this->_id,
1271 $addToGroupId,
1272 $this->_gid,
1273 $this->_ctype,
1274 TRUE
1275 );
1276
1277 //mailing type group
1278 if (!empty($mailingType)) {
1279 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1280 // CRM-8710
1281 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
1282 }
1283
1284 $ufGroups = array();
1285 if ($this->_gid) {
1286 $ufGroups[$this->_gid] = 1;
1287 }
1288 elseif ($this->_mode == self::MODE_REGISTER) {
1289 $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
1290 }
1291
1292 foreach ($ufGroups as $gId => $val) {
1293 if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1294 $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
1295 CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
1296 }
1297 }
1298
1299 //create CMS user (if CMS user option is selected in profile)
a7488080 1300 if (!empty($params['cms_create_account']) &&
6a488035
TO
1301 $this->_mode == self::MODE_CREATE
1302 ) {
1303 $params['contactID'] = $this->_id;
1304 if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
1305 CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
b24f69db 1306 CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
6a488035
TO
1307 $transaction->rollback();
1308 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create',
1309 'reset=1&gid=' . $this->_gid
1310 ));
1311 }
1312 }
1313
1314 $transaction->commit();
1315 }
1316
ffd93213
EM
1317 /**
1318 * @param null $suffix
1319 *
1320 * @return null|string
1321 */
00be9182 1322 public function checkTemplateFileExists($suffix = NULL) {
6a488035
TO
1323 if ($this->_gid) {
1324 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1325 $template = CRM_Core_Form::getTemplate();
1326 if ($template->template_exists($templateFile)) {
1327 return $templateFile;
1328 }
1329
1330 // lets see if we have customized by name
1331 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
1332 if ($ufGroupName) {
1333 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1334 if ($template->template_exists($templateFile)) {
1335 return $templateFile;
1336 }
1337 }
1338 }
1339 return NULL;
1340 }
1341
ffd93213
EM
1342 /**
1343 * Use the form name to create the tpl file name
1344 *
1345 * @return string
ffd93213
EM
1346 */
1347 /**
1348 * @return string
1349 */
00be9182 1350 public function getTemplateFileName() {
6a488035
TO
1351 $fileName = $this->checkTemplateFileExists();
1352 return $fileName ? $fileName : parent::getTemplateFileName();
1353 }
1354
ffd93213
EM
1355 /**
1356 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1357 * i.e. we dont override
1358 *
1359 * @return string
ffd93213
EM
1360 */
1361 /**
1362 * @return string
1363 */
00be9182 1364 public function overrideExtraTemplateFileName() {
6a488035
TO
1365 $fileName = $this->checkTemplateFileExists('extra.');
1366 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1367 }
1368}