Merge pull request #3152 from pradpnayak/CRM-14112
[civicrm-core.git] / CRM / Campaign / Form / Petition / Signature.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for processing a petition signature
38 *
39 */
40 class CRM_Campaign_Form_Petition_Signature extends CRM_Core_Form {
41 CONST EMAIL_THANK = 1, EMAIL_CONFIRM = 2, MODE_CREATE = 4;
42
43 protected $_mode;
44
45 /**
46 * the id of the contact associated with this signature
47 *
48 * @var int
49 * @public
50 */
51 public $_contactId;
52
53 /**
54 * Is this a logged in user
55 *
56 * @var int
57 */
58 protected $_loggedIn = FALSE;
59
60 /**
61 * The contact type
62 *
63 * @var string ("Individual"/"Household"/"Organization"). Never been tested for something else than Individual
64 */
65 protected $_ctype = 'Individual';
66
67 /**
68 * The contact profile id attached with this petition
69 *
70 * @var int
71 */
72 protected $_contactProfileId;
73
74 /**
75 * the contact profile fields used for this petition
76 *
77 * @var array
78 */
79 public $_contactProfileFields;
80
81 /**
82 * The activity profile id attached with this petition
83 *
84 * @var int
85 */
86 protected $_activityProfileId;
87
88 /**
89 * the activity profile fields used for this petition
90 *
91 * @var array
92 */
93 public $_activityProfileFields;
94
95 /**
96 * the id of the survey (petition) we are proceessing
97 *
98 * @var int
99 * @protected
100 */
101 public $_surveyId;
102
103 /**
104 * The tag id used to set against contacts with unconfirmed email
105 *
106 * @var int
107 */
108 protected $_tagId;
109
110 /**
111 * values to use for custom profiles
112 *
113 * @var array
114 * @protected
115 */
116 public $_values;
117
118 /**
119 * The params submitted by the form
120 *
121 * @var array
122 * @protected
123 */
124 protected $_params;
125
126 /**
127 * which email send mode do we use
128 *
129 * @var int
130 * EMAIL_THANK = 1,
131 * connected user via login/pwd - thank you
132 * or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
133 * or login using fb connect - thank you + click to add msg to fb wall
134 * EMAIL_CONFIRM = 2;
135 * send a confirmation request email
136 */
137 protected $_sendEmailMode;
138
139 protected $_image_URL;
140
141 protected $_defaults = NULL;
142
143 function __construct() {
144 parent::__construct();
145 // this property used by civicrm_fb module and if true, forces thank you email to be sent
146 // for users signing in via Facebook connect; also sets Fb email to check against
147 $this->forceEmailConfirmed['flag'] = FALSE;
148 $this->forceEmailConfirmed['email'] = '';
149 }
150
151 function getContactID() {
152 $tempID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
153
154 // force to ignore the authenticated user
155 if ($tempID === '0') {
156 return $tempID;
157 }
158
159 //check if this is a checksum authentication
160 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
161 if ($userChecksum) {
162 //check for anonymous user.
163 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
164 if ($validUser) {
165 return $tempID;
166 }
167 }
168
169 // check if the user is registered and we have a contact ID
170 $session = CRM_Core_Session::singleton();
171 return $session->get('userID');
172 }
173
174 public function preProcess() {
175 $this->bao = new CRM_Campaign_BAO_Petition();
176 $this->_mode = self::MODE_CREATE;
177
178 //get the survey id
179 $this->_surveyId = CRM_Utils_Request::retrieve('sid', 'Positive', $this);
180
181 //some sanity checks
182 if (!$this->_surveyId) {
183 CRM_Core_Error::fatal('Petition id is not valid. (it needs a "sid" in the url).');
184 return;
185 }
186 //check petition is valid and active
187 $params['id'] = $this->_surveyId;
188 $this->petition = array();
189 CRM_Campaign_BAO_Survey::retrieve($params, $this->petition);
190 if (empty($this->petition)) {
191 CRM_Core_Error::fatal('Petition doesn\'t exist.');
192 }
193 if ($this->petition['is_active'] == 0) {
194 CRM_Core_Error::fatal('Petition is no longer active.');
195 }
196
197 //get userID from session
198 $session = CRM_Core_Session::singleton();
199
200 //get the contact id for this user if logged in
201 $this->_contactId = $this->getContactId();
202 if (isset($this->_contactId)) {
203 $this->_loggedIn = TRUE;
204 }
205
206 // add the custom contact and activity profile fields to the signature form
207
208 $ufJoinParams = array(
209 'entity_id' => $this->_surveyId,
210 'entity_table' => 'civicrm_survey',
211 'module' => 'CiviCampaign',
212 'weight' => 2,
213 );
214
215 $this->_contactProfileId = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
216 if ($this->_contactProfileId) {
217 $this->_contactProfileFields = CRM_Core_BAO_UFGroup::getFields($this->_contactProfileId, FALSE, CRM_Core_Action::ADD);
218 }
219 if (!isset($this->_contactProfileFields['email-Primary'])) {
220 CRM_Core_Error::fatal('The contact profile needs to contain the primary email address field');
221 }
222
223
224 $ufJoinParams['weight'] = 1;
225 $this->_activityProfileId = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
226
227 if ($this->_activityProfileId) {
228 $this->_activityProfileFields = CRM_Core_BAO_UFGroup::getFields($this->_activityProfileId, FALSE, CRM_Core_Action::ADD);
229 }
230
231 $this->setDefaultValues();
232 CRM_Utils_System::setTitle($this->petition['title']);
233 }
234
235 /**
236 * This function sets the default values for the form.
237 *
238 * @access public
239 *
240 * @return void
241 */
242 function setDefaultValues() {
243 $this->_defaults = array();
244 if ($this->_contactId) {
245 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $this->_contactProfileFields, $this->_defaults, TRUE);
246 if ($this->_activityProfileId) {
247 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $this->_activityProfileFields, $this->_defaults, TRUE);
248 }
249 }
250
251 //set custom field defaults
252
253 foreach ($this->_contactProfileFields as $name => $field) {
254 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
255 $htmlType = $field['html_type'];
256
257 if (!isset($this->_defaults[$name])) {
258 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
259 $name,
260 $this->_defaults,
261 $this->_contactId,
262 $this->_mode
263 );
264 }
265 }
266 }
267
268 if ($this->_activityProfileFields) {
269 foreach ($this->_activityProfileFields as $name => $field) {
270 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
271 $htmlType = $field['html_type'];
272
273 if (!isset($this->_defaults[$name])) {
274 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
275 $name,
276 $this->_defaults,
277 $this->_contactId,
278 $this->_mode
279 );
280 }
281 }
282 }
283 }
284
285 $this->setDefaults($this->_defaults);
286
287 // add in all state country selectors for enabled countries
288 CRM_Core_BAO_Address::fixAllStateSelects($this, $this->_defaults);
289 }
290
291 public function buildQuickForm() {
292 $this->assign('survey_id', $this->_surveyId);
293 $this->assign('petitionTitle', $this->petition['title']);
294 if (isset($_COOKIE['signed_' . $this->_surveyId])) {
295 if (isset($_COOKIE['confirmed_' . $this->_surveyId])) {
296 $this->assign('duplicate', "confirmed");
297 }
298 else {
299 $this->assign('duplicate', "unconfirmed");
300 }
301 return;
302 }
303
304 $this->applyFilter('__ALL__', 'trim');
305
306 $this->buildCustom($this->_contactProfileId, 'petitionContactProfile');
307 if ($this->_activityProfileId) {
308 $this->buildCustom($this->_activityProfileId, 'petitionActivityProfile');
309 }
310 // add buttons
311 $this->addButtons(array(
312 array(
313 'type' => 'next',
314 'name' => ts('Sign the Petition'),
315 'isDefault' => TRUE,
316 ),
317 )
318 );
319 }
320
321 /**
322 * This function is used to add the rules (mainly global rules) for form.
323 * All local rules are added near the element
324 *
325 * @param $fields
326 * @param $files
327 * @param $errors
328 *
329 * @return void
330 * @access public
331 * @see valid_date
332 */
333
334 static function formRule($fields, $files, $errors) {
335 $errors = array();
336
337 return empty($errors) ? TRUE : $errors;
338 }
339
340 /**
341 * Form submission of petition signature
342 *
343 * @access public
344 *
345 * @return void
346 */
347 public function postProcess() {
348 $tag_name = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME,
349 'tag_unconfirmed'
350 );
351
352
353 if ($tag_name) {
354 // Check if contact 'email confirmed' tag exists, else create one
355 // This should be in the petition module initialise code to create a default tag for this
356 $tag_params['name'] = $tag_name;
357 $tag_params['version'] = 3;
358 $tag = civicrm_api('tag', 'get', $tag_params);
359 if ($tag['count'] == 0) {
360 //create tag
361 $tag_params['description'] = $tag_name;
362 $tag_params['is_reserved'] = 1;
363 $tag_params['used_for'] = 'civicrm_contact';
364 $tag = civicrm_api('tag', 'create', $tag_params);
365 }
366 $this->_tagId = $tag['id'];
367 }
368
369 // export the field values to be used for saving the profile form
370 $params = $this->controller->exportValues($this->_name);
371
372 $session = CRM_Core_Session::singleton();
373 // format params
374 $params['last_modified_id'] = $session->get('userID');
375 $params['last_modified_date'] = date('YmdHis');
376
377 if ($this->_action & CRM_Core_Action::ADD) {
378 $params['created_id'] = $session->get('userID');
379 $params['created_date'] = date('YmdHis');
380 }
381
382 if (isset($this->_surveyId)) {
383 $params['sid'] = $this->_surveyId;
384 }
385
386 if (isset($this->_contactId)) {
387 $params['contactId'] = $this->_contactId;
388 }
389
390 // if logged in user, skip dedupe
391 if ($this->_loggedIn) {
392 $ids[0] = $this->_contactId;
393 }
394 else {
395 // dupeCheck - check if contact record already exists
396 // code modified from api/v2/Contact.php-function civicrm_contact_check_params()
397 $params['contact_type'] = $this->_ctype;
398 //TODO - current dedupe finds soft deleted contacts - adding param is_deleted not working
399 // ignore soft deleted contacts
400 //$params['is_deleted'] = 0;
401 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
402 $dedupeParams['check_permission'] = '';
403
404 //dupesByParams($params, $ctype, $level = 'Unsupervised', $except = array())
405 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type']);
406 }
407
408 $petition_params['id'] = $this->_surveyId;
409 $petition = array();
410 CRM_Campaign_BAO_Survey::retrieve($petition_params, $petition);
411
412 switch (count($ids)) {
413 case 0:
414 //no matching contacts - create a new contact
415 // Add a source for this new contact
416 $params['source'] = ts('Petition Signature') . ' ' . $this->petition['title'];
417
418 if ($this->petition['bypass_confirm']) {
419 // send thank you email directly, bypassing confirmation
420 $this->_sendEmailMode = self::EMAIL_THANK;
421 // Set status for signature activity to completed
422 $params['statusId'] = 2;
423 }
424 else {
425 $this->_sendEmailMode = self::EMAIL_CONFIRM;
426
427 // Set status for signature activity to scheduled until email is verified
428 $params['statusId'] = 1;
429 }
430 break;
431
432 case 1:
433 $this->_contactId = $params['contactId'] = $ids[0];
434
435 // check if user has already signed this petition - redirects to Thank You if true
436 $this->redirectIfSigned($params);
437
438 if ($this->petition['bypass_confirm']) {
439 // send thank you email directly, bypassing confirmation
440 $this->_sendEmailMode = self::EMAIL_THANK;
441 // Set status for signature activity to completed
442 $params['statusId'] = 2;
443 break;
444 }
445
446 // dedupe matched single contact, check for 'unconfirmed' tag
447 if ($tag_name) {
448 $tag = new CRM_Core_DAO_EntityTag();
449 $tag->entity_id = $this->_contactId;
450 $tag->tag_id = $this->_tagId;
451
452 if (!($tag->find())) {
453 // send thank you email directly, the user is known and validated
454 $this->_sendEmailMode = self::EMAIL_THANK;
455 // Set status for signature activity to completed
456 $params['statusId'] = 2;
457 }
458 else {
459 // send email verification email
460 $this->_sendEmailMode = self::EMAIL_CONFIRM;
461 // Set status for signature activity to scheduled until email is verified
462 $params['statusId'] = 1;
463 }
464 }
465 break;
466
467 default:
468 // more than 1 matching contact
469 // for time being, take the first matching contact (not sure that's the best strategy, but better than creating another duplicate)
470 $this->_contactId = $params['contactId'] = $ids[0];
471
472 // check if user has already signed this petition - redirects to Thank You if true
473 $this->redirectIfSigned($params);
474
475 if ($this->petition['bypass_confirm']) {
476 // send thank you email directly, bypassing confirmation
477 $this->_sendEmailMode = self::EMAIL_THANK;
478 // Set status for signature activity to completed
479 $params['statusId'] = 2;
480 break;
481 }
482
483 if ($tag_name) {
484 $tag = new CRM_Core_DAO_EntityTag();
485 $tag->entity_id = $this->_contactId;
486 $tag->tag_id = $this->_tagId;
487
488 if (!($tag->find())) {
489 // send thank you email
490 $this->_sendEmailMode = self::EMAIL_THANK;
491 // Set status for signature activity to completed
492 $params['statusId'] = 2;
493 }
494 else {
495 // send email verification email
496 $this->_sendEmailMode = self::EMAIL_CONFIRM;
497 // Set status for signature activity to scheduled until email is verified
498 $params['statusId'] = 1;
499 }
500 }
501 break;
502 }
503
504
505
506 $transaction = new CRM_Core_Transaction();
507
508 $addToGroupID = isset($this->_addToGroupID) ? $this->_addToGroupID : NULL;
509 $this->_contactId = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_contactProfileFields,
510 $this->_contactId, $addToGroupID,
511 $this->_contactProfileId, $this->_ctype,
512 TRUE
513 );
514
515 // get additional custom activity profile field data
516 // to save with new signature activity record
517 $surveyInfo = $this->bao->getSurveyInfo($this->_surveyId);
518 $customActivityFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
519 $surveyInfo['activity_type_id']
520 );
521 $customActivityFields = CRM_Utils_Array::crmArrayMerge($customActivityFields,
522 CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
523 NULL, NULL, TRUE
524 )
525 );
526
527 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
528 $customActivityFields,
529 NULL,
530 'Activity'
531 );
532
533 // create the signature activity record
534 $params['contactId'] = $this->_contactId;
535 $params['activity_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->petition);
536 $result = $this->bao->createSignature($params);
537
538 // send thank you or email verification emails
539
540 // if logged in using Facebook connect and email on form matches Fb email,
541 // no need for email confirmation, send thank you email
542 if ($this->forceEmailConfirmed['flag'] &&
543 ($this->forceEmailConfirmed['email'] == $params['email-Primary'])
544 ) {
545 $this->_sendEmailMode = self::EMAIL_THANK;
546 }
547
548 switch ($this->_sendEmailMode) {
549 case self::EMAIL_THANK:
550 // mark the signature activity as completed and set confirmed cookie
551 $this->bao->confirmSignature($result->id, $this->_contactId, $this->_surveyId);
552 break;
553
554 case self::EMAIL_CONFIRM:
555 // set 'Unconfirmed' tag for this new contact
556 if ($tag_name) {
557 unset($tag_params);
558 $tag_params['contact_id'] = $this->_contactId;
559 $tag_params['tag_id'] = $this->_tagId;
560 $tag_params['version'] = 3;
561 $tag_value = civicrm_api('entity_tag', 'create', $tag_params);
562 }
563 break;
564 }
565
566 //send email
567 $params['activityId'] = $result->id;
568 $params['tagId'] = $this->_tagId;
569
570 $transaction->commit();
571
572 $this->bao->sendEmail($params, $this->_sendEmailMode);
573
574 if ($result) {
575 // call the hook before we redirect
576 $this->postProcessHook();
577
578 // set the template to thank you
579 $url =
580 CRM_Utils_System::url(
581 'civicrm/petition/thankyou',
582 'pid=' . $this->_surveyId . '&id=' . $this->_sendEmailMode . '&reset=1'
583 );
584 CRM_Utils_System::redirect($url);
585 }
586 }
587
588 /**
589 * Function to build the petition profile form
590 *
591 * @param $id
592 * @param $name
593 * @param bool $viewOnly
594 *
595 * @return void
596 * @access public
597 */
598 function buildCustom($id, $name, $viewOnly = FALSE) {
599
600 // create state country map array to hold selectors
601 $stateCountryMap = array();
602
603 if ($id) {
604 $session = CRM_Core_Session::singleton();
605 $this->assign("petition", $this->petition);
606 //$contactID = $this->_contactId;
607 $contactID = NULL;
608 $this->assign('contact_id', $this->_contactId);
609
610 $fields = NULL;
611 // TODO: contactID is never set (commented above)
612 if ($contactID) {
613 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
614 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD);
615 }
616 }
617 else {
618 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD);
619 }
620
621 if ($fields) {
622 /*
623 // unset any email-* fields since we already collect it, CRM-2888
624 foreach ( array_keys( $fields ) as $fieldName ) {
625 if ( substr( $fieldName, 0, 6 ) == 'email-' ) {
626 unset( $fields[$fieldName] );
627 }
628 }
629 */
630
631
632 $this->assign($name, $fields);
633
634 $addCaptcha = FALSE;
635 foreach ($fields as $key => $field) {
636 if ($viewOnly &&
637 isset($field['data_type']) &&
638 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
639 ) {
640 // ignore file upload fields
641 continue;
642 }
643
644 // if state or country in the profile, create map
645 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
646 if ($prefixName == 'state_province' || $prefixName == 'country' || $prefixName == 'county') {
647 if (!array_key_exists($index, $stateCountryMap)) {
648 $stateCountryMap[$index] = array();
649 }
650 $stateCountryMap[$index][$prefixName] = $key;
651 }
652
653 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
654 $this->_fields[$key] = $field;
655 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
656 if ($field['add_captcha'] && !$this->_contactId) {
657 $addCaptcha = TRUE;
658 }
659 }
660
661 // initialize the state country map
662 CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap);
663
664 if ($addCaptcha && !$viewOnly) {
665 $captcha = CRM_Utils_ReCAPTCHA::singleton();
666 $captcha->add($this);
667 $this->assign("isCaptcha", TRUE);
668 }
669 }
670 }
671 }
672
673 function getTemplateFileName() {
674 if (isset($this->thankyou)) {
675 return ('CRM/Campaign/Page/Petition/ThankYou.tpl');
676 }
677 else {}
678 return parent::getTemplateFileName();
679 }
680
681 // check if user has already signed this petition
682 function redirectIfSigned($params) {
683 $signature = $this->bao->checkSignature($this->_surveyId, $this->_contactId);
684 //TODO: error case when more than one signature found for this petition and this contact
685 if (!empty($signature) && (count($signature) == 1)) {
686 $signature_id = array_keys($signature);
687 switch ($signature[$signature_id[0]]['status_id']) {
688 case 1:
689 //status is scheduled - email is unconfirmed
690 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=4&reset=1'));
691 break;
692
693 case 2:
694 //status is completed
695 $this->bao->sendEmail($params, 1);
696 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=5&reset=1'));
697 break;
698 }
699 }
700 }
701 }
702
703
704