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