Merge pull request #15834 from francescbassas/patch-16
[civicrm-core.git] / CRM / Contribute / Form / ContributionPage.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Contribution Page form.
20 */
21 class CRM_Contribute_Form_ContributionPage extends CRM_Core_Form {
22
23 /**
24 * The page id saved to the session for an update.
25 *
26 * @var int
27 */
28 protected $_id;
29
30 /**
31 * The pledgeBlock id saved to the session for an update.
32 *
33 * @var int
34 */
35 protected $_pledgeBlockID;
36
37 /**
38 * Are we in single form mode or wizard mode?
39 *
40 * @var bool
41 */
42 protected $_single;
43
44 /**
45 * Is this the first page?
46 *
47 * @var bool
48 */
49 protected $_first = FALSE;
50
51 /**
52 * Is this the last page?
53 *
54 * @var bool
55 */
56 protected $_last = FALSE;
57
58 /**
59 * Store price set id.
60 *
61 * @var int
62 */
63 protected $_priceSetID = NULL;
64
65 protected $_values;
66
67 /**
68 * Explicitly declare the entity api name.
69 */
70 public function getDefaultEntity() {
71 return 'Contribution';
72 }
73
74 /**
75 * Explicitly declare the form context.
76 */
77 public function getDefaultContext() {
78 return 'create';
79 }
80
81 /**
82 * Set variables up before form is built.
83 */
84 public function preProcess() {
85 // current contribution page id
86 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive',
87 $this, FALSE, NULL, 'REQUEST'
88 );
89 $this->assign('contributionPageID', $this->_id);
90
91 // get the requested action
92 $this->_action = CRM_Utils_Request::retrieve('action', 'String',
93 // default to 'browse'
94 $this, FALSE, 'browse'
95 );
96
97 // setting title and 3rd level breadcrumb for html page if contrib page exists
98 if ($this->_id) {
99 $title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'title');
100
101 if ($this->_action == CRM_Core_Action::UPDATE) {
102 $this->_single = TRUE;
103 }
104 }
105
106 // CRM-16776 - show edit/copy/create buttons on Profiles Tab if user has required permission.
107 if (CRM_Core_Permission::check('administer CiviCRM')) {
108 $this->assign('perm', TRUE);
109 }
110 // set up tabs
111 CRM_Contribute_Form_ContributionPage_TabHeader::build($this);
112
113 if ($this->_action == CRM_Core_Action::UPDATE) {
114 $this->setTitle(ts('Configure Page - %1', [1 => $title]));
115 }
116 elseif ($this->_action == CRM_Core_Action::VIEW) {
117 $this->setTitle(ts('Preview Page - %1', [1 => $title]));
118 }
119 elseif ($this->_action == CRM_Core_Action::DELETE) {
120 $this->setTitle(ts('Delete Page - %1', [1 => $title]));
121 }
122
123 //cache values.
124 $this->_values = $this->get('values');
125 if (!is_array($this->_values)) {
126 $this->_values = [];
127 if (isset($this->_id) && $this->_id) {
128 $params = ['id' => $this->_id];
129 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $this->_values);
130 CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
131 }
132 $this->set('values', $this->_values);
133 }
134
135 // Check permission to edit contribution page
136 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && $this->_action & CRM_Core_Action::UPDATE) {
137 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
138 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
139 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
140 }
141 }
142
143 // Preload libraries required by the "Profiles" tab
144 $schemas = ['IndividualModel', 'OrganizationModel', 'ContributionModel'];
145 if (in_array('CiviMember', CRM_Core_Config::singleton()->enableComponents)) {
146 $schemas[] = 'MembershipModel';
147 }
148 CRM_UF_Page_ProfileEditor::registerProfileScripts();
149 CRM_UF_Page_ProfileEditor::registerSchemas($schemas);
150 }
151
152 /**
153 * Build the form object.
154 */
155 public function buildQuickForm() {
156 $this->applyFilter('__ALL__', 'trim');
157
158 $session = CRM_Core_Session::singleton();
159 $this->_cancelURL = CRM_Utils_Array::value('cancelURL', $_POST);
160
161 if (!$this->_cancelURL) {
162 $this->_cancelURL = CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1');
163 }
164
165 if ($this->_cancelURL) {
166 $this->addElement('hidden', 'cancelURL', $this->_cancelURL);
167 }
168
169 if ($this->_single) {
170 $buttons = [
171 [
172 'type' => 'next',
173 'name' => ts('Save'),
174 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
175 'isDefault' => TRUE,
176 ],
177 [
178 'type' => 'upload',
179 'name' => ts('Save and Done'),
180 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
181 'subName' => 'done',
182 ],
183 ];
184 if (!$this->_last) {
185 $buttons[] = [
186 'type' => 'submit',
187 'name' => ts('Save and Next'),
188 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
189 'subName' => 'savenext',
190 ];
191 }
192 $buttons[] = [
193 'type' => 'cancel',
194 'name' => ts('Cancel'),
195 ];
196 $this->addButtons($buttons);
197 }
198 else {
199 $buttons = [];
200 if (!$this->_first) {
201 $buttons[] = [
202 'type' => 'back',
203 'name' => ts('Previous'),
204 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
205 ];
206 }
207 $buttons[] = [
208 'type' => 'next',
209 'name' => ts('Continue'),
210 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
211 'isDefault' => TRUE,
212 ];
213 $buttons[] = [
214 'type' => 'cancel',
215 'name' => ts('Cancel'),
216 ];
217
218 $this->addButtons($buttons);
219 }
220
221 $session->replaceUserContext($this->_cancelURL);
222 // views are implemented as frozen form
223 if ($this->_action & CRM_Core_Action::VIEW) {
224 $this->freeze();
225 $this->addElement('button', 'done', ts('Done'), ['onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"]);
226 }
227
228 // don't show option for contribution amounts section if membership price set
229 // this flag is sent to template
230
231 $membershipBlock = new CRM_Member_DAO_MembershipBlock();
232 $membershipBlock->entity_table = 'civicrm_contribution_page';
233 $membershipBlock->entity_id = $this->_id;
234 $membershipBlock->is_active = 1;
235 $hasMembershipBlk = FALSE;
236 if ($membershipBlock->find(TRUE) &&
237 ($setID = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, NULL, 1))
238 ) {
239 $extends = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'extends');
240 if ($extends && $extends == CRM_Core_Component::getComponentID('CiviMember')) {
241 $hasMembershipBlk = TRUE;
242 }
243 }
244 // set value in DOM that membership price set exists
245 CRM_Core_Resources::singleton()->addSetting(['memberPriceset' => $hasMembershipBlk]);
246 }
247
248 /**
249 * Set default values for the form. Note that in edit/view mode
250 * the default values are retrieved from the database
251 *
252 *
253 * @return array
254 * defaults
255 */
256 public function setDefaultValues() {
257 //some child classes calling setdefaults directly w/o preprocess.
258 $this->_values = $this->get('values');
259 if (!is_array($this->_values)) {
260 $this->_values = [];
261 if (isset($this->_id) && $this->_id) {
262 $params = ['id' => $this->_id];
263 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $this->_values);
264 }
265 $this->set('values', $this->_values);
266 }
267 $defaults = $this->_values;
268
269 $config = CRM_Core_Config::singleton();
270 if (isset($this->_id)) {
271
272 //set defaults for pledgeBlock values.
273 $pledgeBlockParams = [
274 'entity_id' => $this->_id,
275 'entity_table' => ts('civicrm_contribution_page'),
276 ];
277 $pledgeBlockDefaults = [];
278 CRM_Pledge_BAO_PledgeBlock::retrieve($pledgeBlockParams, $pledgeBlockDefaults);
279 if ($this->_pledgeBlockID = CRM_Utils_Array::value('id', $pledgeBlockDefaults)) {
280 $defaults['is_pledge_active'] = TRUE;
281 }
282 $pledgeBlock = [
283 'is_pledge_interval',
284 'max_reminders',
285 'initial_reminder_day',
286 'additional_reminder_day',
287 'pledge_start_date',
288 'is_pledge_start_date_visible',
289 'is_pledge_start_date_editable',
290 ];
291 foreach ($pledgeBlock as $key) {
292 $defaults[$key] = CRM_Utils_Array::value($key, $pledgeBlockDefaults);
293 if ($key == 'pledge_start_date' && !empty($pledgeBlockDefaults[$key])) {
294 $defaultPledgeDate = (array) json_decode($pledgeBlockDefaults['pledge_start_date']);
295 $pledgeDateFields = [
296 'pledge_calendar_date' => 'calendar_date',
297 'pledge_calendar_month' => 'calendar_month',
298 ];
299 $defaults['pledge_default_toggle'] = key($defaultPledgeDate);
300 foreach ($pledgeDateFields as $key => $value) {
301 if (array_key_exists($value, $defaultPledgeDate)) {
302 $defaults[$key] = reset($defaultPledgeDate);
303 $this->assign($key, reset($defaultPledgeDate));
304 }
305 }
306 }
307 }
308 if (!empty($pledgeBlockDefaults['pledge_frequency_unit'])) {
309 $defaults['pledge_frequency_unit'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
310 $pledgeBlockDefaults['pledge_frequency_unit']
311 ), '1');
312 }
313
314 // fix the display of the monetary value, CRM-4038
315 if (isset($defaults['goal_amount'])) {
316 $defaults['goal_amount'] = CRM_Utils_Money::format($defaults['goal_amount'], NULL, '%a');
317 }
318
319 // get price set of type contributions
320 //this is the value for stored in db if price set extends contribution
321 $usedFor = 2;
322 $this->_priceSetID = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, $usedFor, 1);
323 if ($this->_priceSetID) {
324 $defaults['price_set_id'] = $this->_priceSetID;
325 }
326 }
327 else {
328 $defaults['is_active'] = 1;
329 // set current date as start date
330 // @todo look to change to $defaults['start_date'] = date('Ymd His');
331 // main settings form overrides this to implement above but this is left here
332 // 'in case' another extending form uses start_date - for now
333 $defaults['start_date'] = date('Y-m-d H:i:s');
334 }
335
336 if (!empty($defaults['recur_frequency_unit'])) {
337 $defaults['recur_frequency_unit'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
338 $defaults['recur_frequency_unit']
339 ), '1');
340 }
341 else {
342 // CRM-10860
343 $defaults['recur_frequency_unit'] = ['month' => 1];
344 }
345
346 // confirm page starts out enabled
347 if (!isset($defaults['is_confirm_enabled'])) {
348 $defaults['is_confirm_enabled'] = 1;
349 }
350
351 return $defaults;
352 }
353
354 /**
355 * Process the form.
356 */
357 public function postProcess() {
358 $pageId = $this->get('id');
359 //page is newly created.
360 if ($pageId && !$this->_id) {
361 $session = CRM_Core_Session::singleton();
362 $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1'));
363 }
364 }
365
366 public function endPostProcess() {
367 // make submit buttons keep the current working tab opened, or save and next tab
368 if ($this->_action & CRM_Core_Action::UPDATE) {
369 $className = CRM_Utils_String::getClassName($this->_name);
370
371 //retrieve list of pages from StateMachine and find next page
372 //this is quite painful because StateMachine is full of protected variables
373 //so we have to retrieve all pages, find current page, and then retrieve next
374 $stateMachine = new CRM_Contribute_StateMachine_ContributionPage($this);
375 $states = $stateMachine->getStates();
376 $statesList = array_keys($states);
377 $currKey = array_search($className, $statesList);
378 $nextPage = (array_key_exists($currKey + 1, $statesList)) ? $statesList[$currKey + 1] : '';
379
380 //unfortunately, some classes don't map to subpage names, so we alter the exceptions
381
382 switch ($className) {
383 case 'Contribute':
384 $attributes = $this->getVar('_attributes');
385 $subPage = CRM_Utils_Request::retrieveComponent($attributes);
386 if ($subPage == 'friend') {
387 $nextPage = 'custom';
388 }
389 else {
390 $nextPage = 'settings';
391 }
392 break;
393
394 case 'MembershipBlock':
395 $subPage = 'membership';
396 $nextPage = 'thankyou';
397 break;
398
399 case 'Widget':
400 $subPage = 'widget';
401 $nextPage = 'pcp';
402 break;
403
404 default:
405 $subPage = strtolower($className);
406 $nextPage = strtolower($nextPage);
407
408 if ($subPage == 'amount') {
409 $nextPage = 'membership';
410 }
411 elseif ($subPage == 'thankyou') {
412 $nextPage = 'friend';
413 }
414 break;
415 }
416
417 CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
418 [1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className)]
419 ), $this->getTitle(), 'success');
420
421 $this->postProcessHook();
422
423 if ($this->controller->getButtonName('submit') == "_qf_{$className}_next") {
424 CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute/{$subPage}",
425 "action=update&reset=1&id={$this->_id}"
426 ));
427 }
428 elseif ($this->controller->getButtonName('submit') == "_qf_{$className}_submit_savenext") {
429 if ($nextPage) {
430 CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute/{$nextPage}",
431 "action=update&reset=1&id={$this->_id}"
432 ));
433 }
434 else {
435 CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute",
436 "reset=1"
437 ));
438 }
439 }
440 else {
441 CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute", 'reset=1'));
442 }
443 }
444 }
445
446 /**
447 * Use the form name to create the tpl file name.
448 *
449 * @return string
450 */
451
452 /**
453 * @return string
454 */
455 public function getTemplateFileName() {
456 if ($this->controller->getPrint() || $this->getVar('_id') <= 0 ||
457 ($this->_action & CRM_Core_Action::DELETE) ||
458 (CRM_Utils_String::getClassName($this->_name) == 'AddProduct')
459 ) {
460 return parent::getTemplateFileName();
461 }
462 else {
463 // hack lets suppress the form rendering for now
464 self::$_template->assign('isForm', FALSE);
465 return 'CRM/Contribute/Form/ContributionPage/Tab.tpl';
466 }
467 }
468
469 }