remove newly introduced trailing spaces & tabs, new windows line-breaks also present...
[civicrm-core.git] / CRM / Campaign / Form / Petition / Signature.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for processing a petition signature
38 *
39 */
40class 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
430ae6dd
TO
141 protected $_defaults = NULL;
142
143 function __construct() {
6a488035
TO
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 None
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);
2efcf0c2 286
2c6b0601
XD
287 // add in all state country selectors for enabled countries
288 CRM_Core_BAO_Address::fixAllStateSelects($this, $this->_defaults);
6a488035
TO
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 * @return None
326 * @access public
327 * @see valid_date
328 */
329
330 static function formRule($fields, $files, $errors) {
331 $errors = array();
332
333 return empty($errors) ? TRUE : $errors;
334 }
335
336 /**
337 * Form submission of petition signature
338 *
339 * @access public
340 *
341 * @return None
342 */
343 public function postProcess() {
344 $tag_name = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME,
345 'tag_unconfirmed'
346 );
347
348
349 if ($tag_name) {
350 // Check if contact 'email confirmed' tag exists, else create one
351 // This should be in the petition module initialise code to create a default tag for this
352 $tag_params['name'] = $tag_name;
353 $tag_params['version'] = 3;
354 $tag = civicrm_api('tag', 'get', $tag_params);
355 if ($tag['count'] == 0) {
356 //create tag
357 $tag_params['description'] = $tag_name;
358 $tag_params['is_reserved'] = 1;
359 $tag_params['used_for'] = 'civicrm_contact';
360 $tag = civicrm_api('tag', 'create', $tag_params);
361 }
362 $this->_tagId = $tag['id'];
363 }
364
365 // export the field values to be used for saving the profile form
366 $params = $this->controller->exportValues($this->_name);
367
368 $session = CRM_Core_Session::singleton();
369 // format params
370 $params['last_modified_id'] = $session->get('userID');
371 $params['last_modified_date'] = date('YmdHis');
372
373 if ($this->_action & CRM_Core_Action::ADD) {
374 $params['created_id'] = $session->get('userID');
375 $params['created_date'] = date('YmdHis');
376 }
377
378 if (isset($this->_surveyId)) {
379 $params['sid'] = $this->_surveyId;
380 }
381
382 if (isset($this->_contactId)) {
383 $params['contactId'] = $this->_contactId;
384 }
385
386 // if logged in user, skip dedupe
387 if ($this->_loggedIn) {
388 $ids[0] = $this->_contactId;
389 }
390 else {
391 // dupeCheck - check if contact record already exists
392 // code modified from api/v2/Contact.php-function civicrm_contact_check_params()
393 $params['contact_type'] = $this->_ctype;
394 //TODO - current dedupe finds soft deleted contacts - adding param is_deleted not working
395 // ignore soft deleted contacts
396 //$params['is_deleted'] = 0;
397 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
398 $dedupeParams['check_permission'] = '';
399
400 //dupesByParams($params, $ctype, $level = 'Unsupervised', $except = array())
401 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type']);
402 }
403
404 $petition_params['id'] = $this->_surveyId;
405 $petition = array();
406 CRM_Campaign_BAO_Survey::retrieve($petition_params, $petition);
407
408 switch (count($ids)) {
409 case 0:
410 //no matching contacts - create a new contact
411 // Add a source for this new contact
412 $params['source'] = ts('Petition Signature') . ' ' . $this->petition['title'];
413
414 if ($this->petition['bypass_confirm']) {
415 // send thank you email directly, bypassing confirmation
416 $this->_sendEmailMode = self::EMAIL_THANK;
417 // Set status for signature activity to completed
418 $params['statusId'] = 2;
419 }
420 else {
421 $this->_sendEmailMode = self::EMAIL_CONFIRM;
422
423 // Set status for signature activity to scheduled until email is verified
424 $params['statusId'] = 1;
425 }
426 break;
427
428 case 1:
429 $this->_contactId = $params['contactId'] = $ids[0];
430
431 // check if user has already signed this petition - redirects to Thank You if true
432 $this->redirectIfSigned($params);
433
434 if ($this->petition['bypass_confirm']) {
435 // send thank you email directly, bypassing confirmation
436 $this->_sendEmailMode = self::EMAIL_THANK;
437 // Set status for signature activity to completed
438 $params['statusId'] = 2;
439 break;
440 }
441
442 // dedupe matched single contact, check for 'unconfirmed' tag
443 if ($tag_name) {
444 $tag = new CRM_Core_DAO_EntityTag();
445 $tag->entity_id = $this->_contactId;
446 $tag->tag_id = $this->_tagId;
447
448 if (!($tag->find())) {
449 // send thank you email directly, the user is known and validated
450 $this->_sendEmailMode = self::EMAIL_THANK;
451 // Set status for signature activity to completed
452 $params['statusId'] = 2;
453 }
454 else {
455 // send email verification email
456 $this->_sendEmailMode = self::EMAIL_CONFIRM;
457 // Set status for signature activity to scheduled until email is verified
458 $params['statusId'] = 1;
459 }
460 }
461 break;
462
463 default:
464 // more than 1 matching contact
465 // for time being, take the first matching contact (not sure that's the best strategy, but better than creating another duplicate)
466 $this->_contactId = $params['contactId'] = $ids[0];
467
468 // check if user has already signed this petition - redirects to Thank You if true
469 $this->redirectIfSigned($params);
470
471 if ($this->petition['bypass_confirm']) {
472 // send thank you email directly, bypassing confirmation
473 $this->_sendEmailMode = self::EMAIL_THANK;
474 // Set status for signature activity to completed
475 $params['statusId'] = 2;
476 break;
477 }
478
479 if ($tag_name) {
480 $tag = new CRM_Core_DAO_EntityTag();
481 $tag->entity_id = $this->_contactId;
482 $tag->tag_id = $this->_tagId;
483
484 if (!($tag->find())) {
485 // send thank you email
486 $this->_sendEmailMode = self::EMAIL_THANK;
487 // Set status for signature activity to completed
488 $params['statusId'] = 2;
489 }
490 else {
491 // send email verification email
492 $this->_sendEmailMode = self::EMAIL_CONFIRM;
493 // Set status for signature activity to scheduled until email is verified
494 $params['statusId'] = 1;
495 }
496 }
497 break;
498 }
499
500
501
502 $transaction = new CRM_Core_Transaction();
503
504 $addToGroupID = isset($this->_addToGroupID) ? $this->_addToGroupID : NULL;
505 $this->_contactId = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_contactProfileFields,
506 $this->_contactId, $addToGroupID,
507 $this->_contactProfileId, $this->_ctype,
508 TRUE
509 );
510
511 // get additional custom activity profile field data
512 // to save with new signature activity record
513 $surveyInfo = $this->bao->getSurveyInfo($this->_surveyId);
514 $customActivityFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
515 $surveyInfo['activity_type_id']
516 );
517 $customActivityFields = CRM_Utils_Array::crmArrayMerge($customActivityFields,
518 CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
519 NULL, NULL, TRUE
520 )
521 );
522
523 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
524 $customActivityFields,
525 NULL,
526 'Activity'
527 );
528
529 // create the signature activity record
530 $params['contactId'] = $this->_contactId;
43427a24 531 $params['activity_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->petition);
6a488035
TO
532 $result = $this->bao->createSignature($params);
533
534 // send thank you or email verification emails
535
536 // if logged in using Facebook connect and email on form matches Fb email,
537 // no need for email confirmation, send thank you email
538 if ($this->forceEmailConfirmed['flag'] &&
539 ($this->forceEmailConfirmed['email'] == $params['email-Primary'])
540 ) {
541 $this->_sendEmailMode = self::EMAIL_THANK;
542 }
543
544 switch ($this->_sendEmailMode) {
545 case self::EMAIL_THANK:
546 // mark the signature activity as completed and set confirmed cookie
547 $this->bao->confirmSignature($result->id, $this->_contactId, $this->_surveyId);
548 break;
549
550 case self::EMAIL_CONFIRM:
551 // set 'Unconfirmed' tag for this new contact
552 if ($tag_name) {
553 unset($tag_params);
554 $tag_params['contact_id'] = $this->_contactId;
555 $tag_params['tag_id'] = $this->_tagId;
556 $tag_value = civicrm_api('entity_tag', 'create', $tag_params);
557 }
558 break;
559 }
560
561 //send email
562 $params['activityId'] = $result->id;
563 $params['tagId'] = $this->_tagId;
564 $this->bao->sendEmail($params, $this->_sendEmailMode);
565
566 $transaction->commit();
567
568 if ($result) {
569 // call the hook before we redirect
570 $this->postProcessHook();
571
572 // set the template to thank you
573 $url =
574 CRM_Utils_System::url(
575 'civicrm/petition/thankyou',
576 'pid=' . $this->_surveyId . '&id=' . $this->_sendEmailMode . '&reset=1'
577 );
578 CRM_Utils_System::redirect($url);
579 }
580 }
581
582 /**
583 * Function to build the petition profile form
584 *
585 * @return None
586 * @access public
587 */
588 function buildCustom($id, $name, $viewOnly = FALSE) {
589
2efcf0c2 590 // create state country map array to hold selectors
2c6b0601
XD
591 $stateCountryMap = array();
592
6a488035
TO
593 if ($id) {
594 $session = CRM_Core_Session::singleton();
595 $this->assign("petition", $this->petition);
596 //$contactID = $this->_contactId;
597 $contactID = NULL;
598 $this->assign('contact_id', $this->_contactId);
599
600 $fields = NULL;
601 // TODO: contactID is never set (commented above)
602 if ($contactID) {
603 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
604 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD);
605 }
606 }
607 else {
608 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD);
609 }
610
611 if ($fields) {
612 /*
613 // unset any email-* fields since we already collect it, CRM-2888
614 foreach ( array_keys( $fields ) as $fieldName ) {
615 if ( substr( $fieldName, 0, 6 ) == 'email-' ) {
616 unset( $fields[$fieldName] );
617 }
618 }
619 */
620
621
622 $this->assign($name, $fields);
623
624 $addCaptcha = FALSE;
625 foreach ($fields as $key => $field) {
626 if ($viewOnly &&
627 isset($field['data_type']) &&
628 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
629 ) {
630 // ignore file upload fields
631 continue;
632 }
2efcf0c2 633
634 // if state or country in the profile, create map
2c6b0601
XD
635 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
636 if ($prefixName == 'state_province' || $prefixName == 'country' || $prefixName == 'county') {
637 if (!array_key_exists($index, $stateCountryMap)) {
638 $stateCountryMap[$index] = array();
639 }
640 $stateCountryMap[$index][$prefixName] = $key;
2efcf0c2 641 }
6a488035
TO
642
643 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
644 $this->_fields[$key] = $field;
645 if ($field['add_captcha']) {
646 $addCaptcha = TRUE;
647 }
648 }
649
2efcf0c2 650 // initialize the state country map
2c6b0601
XD
651 CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap);
652
6a488035
TO
653 if ($addCaptcha &&
654 !$viewOnly
655 ) {
656 $captcha = CRM_Utils_ReCAPTCHA::singleton();
657 $captcha->add($this);
658 $this->assign("isCaptcha", TRUE);
659 }
660 }
661 }
662 }
663
664 function getTemplateFileName() {
665 if (isset($this->thankyou)) {
666 return ('CRM/Campaign/Page/Petition/ThankYou.tpl');
667 }
668 else {}
669 return parent::getTemplateFileName();
670 }
671
672 // check if user has already signed this petition
673 function redirectIfSigned($params) {
674 $signature = $this->bao->checkSignature($this->_surveyId, $this->_contactId);
675 //TODO: error case when more than one signature found for this petition and this contact
676 if (!empty($signature) && (count($signature) == 1)) {
677 $signature_id = array_keys($signature);
678 switch ($signature[$signature_id[0]]['status_id']) {
679 case 1:
680 //status is scheduled - email is unconfirmed
681 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=4&reset=1'));
682 break;
683
684 case 2:
685 //status is completed
686 $this->bao->sendEmail($params, 1);
687 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=5&reset=1'));
688 break;
689 }
690 }
691 }
692}
693
694
695