Merge pull request #15976 from eileenmcnaughton/5.20
[civicrm-core.git] / CRM / Contribute / Form / ManagePremiums.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 /**
35 * This class generates form components for Premiums.
36 */
37 class CRM_Contribute_Form_ManagePremiums extends CRM_Contribute_Form {
38
39 /**
40 * Pre process the form.
41 */
42 public function preProcess() {
43 parent::preProcess();
44 }
45
46 /**
47 * Set default values for the form.
48 */
49 public function setDefaultValues() {
50 $defaults = parent::setDefaultValues();
51 if ($this->_id) {
52 $params = ['id' => $this->_id];
53 CRM_Contribute_BAO_Product::retrieve($params, $tempDefaults);
54 if (isset($tempDefaults['image']) && isset($tempDefaults['thumbnail'])) {
55 $defaults['imageUrl'] = $tempDefaults['image'];
56 $defaults['thumbnailUrl'] = $tempDefaults['thumbnail'];
57 $defaults['imageOption'] = 'thumbnail';
58 // assign thumbnailUrl to template so we can display current image in update mode
59 $this->assign('thumbnailUrl', $defaults['thumbnailUrl']);
60 }
61 else {
62 $defaults['imageOption'] = 'noImage';
63 }
64 if (isset($tempDefaults['thumbnail']) && isset($tempDefaults['image'])) {
65 $this->assign('thumbURL', $tempDefaults['thumbnail']);
66 $this->assign('imageURL', $tempDefaults['image']);
67 }
68 if (isset($tempDefaults['period_type'])) {
69 $this->assign('showSubscriptions', TRUE);
70 }
71 }
72
73 return $defaults;
74 }
75
76 /**
77 * Build the form object.
78 */
79 public function buildQuickForm() {
80 parent::buildQuickForm();
81 $this->setPageTitle(ts('Premium Product'));
82
83 if ($this->_action & CRM_Core_Action::PREVIEW) {
84 CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, $this->_id);
85 return;
86 }
87
88 if ($this->_action & CRM_Core_Action::DELETE) {
89 return;
90 }
91
92 $this->applyFilter('__ALL__', 'trim');
93 $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'name'), TRUE);
94 $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', [
95 'CRM_Contribute_DAO_Product',
96 $this->_id,
97 ]);
98 $this->add('text', 'sku', ts('SKU'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'sku'));
99
100 $this->add('textarea', 'description', ts('Description'), 'rows=3, cols=60');
101
102 $image['image'] = $this->createElement('radio', NULL, NULL, ts('Upload from my computer'), 'image', 'onclick="add_upload_file_block(\'image\');');
103 $image['thumbnail'] = $this->createElement('radio', NULL, NULL, ts('Display image and thumbnail from these locations on the web:'), 'thumbnail', 'onclick="add_upload_file_block(\'thumbnail\');');
104 $image['default_image'] = $this->createElement('radio', NULL, NULL, ts('Use default image'), 'default_image', 'onclick="add_upload_file_block(\'default\');');
105 $image['noImage'] = $this->createElement('radio', NULL, NULL, ts('Do not display an image'), 'noImage', 'onclick="add_upload_file_block(\'noImage\');');
106
107 $this->addGroup($image, 'imageOption', ts('Premium Image'));
108 $this->addRule('imageOption', ts('Please select an option for the premium image.'), 'required');
109
110 $this->addElement('text', 'imageUrl', ts('Image URL'));
111 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
112
113 $this->add('file', 'uploadFile', ts('Image File Name'), 'onChange="select_option();"');
114
115 $this->add('text', 'price', ts('Market Value'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'price'), TRUE);
116 $this->addRule('price', ts('Please enter the Market Value for this product.'), 'money');
117
118 $this->add('text', 'cost', ts('Actual Cost of Product'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'cost'));
119 $this->addRule('price', ts('Please enter the Actual Cost of Product.'), 'money');
120
121 $this->add('text', 'min_contribution', ts('Minimum Contribution Amount'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'min_contribution'), TRUE);
122 $this->addRule('min_contribution', ts('Please enter a monetary value for the Minimum Contribution Amount.'), 'money');
123
124 $this->add('textarea', 'options', ts('Options'), 'rows=3, cols=60');
125
126 $this->add('select', 'period_type', ts('Period Type'), [
127 '' => '- select -',
128 'rolling' => 'Rolling',
129 'fixed' => 'Fixed',
130 ]);
131
132 $this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
133
134 $this->add('Select', 'duration_unit', ts('Duration Unit'), ['' => '- select period -'] + CRM_Core_SelectValues::getPremiumUnits());
135
136 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
137
138 $this->add('Select', 'frequency_unit', ts('Frequency Unit'), ['' => '- select period -'] + CRM_Core_SelectValues::getPremiumUnits());
139
140 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
141
142 //Financial Type CRM-11106
143 $financialType = CRM_Contribute_PseudoConstant::financialType();
144 $premiumFinancialType = [];
145 CRM_Core_PseudoConstant::populate(
146 $premiumFinancialType,
147 'CRM_Financial_DAO_EntityFinancialAccount',
148 $all = TRUE,
149 $retrieve = 'entity_id',
150 $filter = NULL,
151 'account_relationship = 8'
152 );
153
154 $costFinancialType = [];
155 CRM_Core_PseudoConstant::populate(
156 $costFinancialType,
157 'CRM_Financial_DAO_EntityFinancialAccount',
158 $all = TRUE,
159 $retrieve = 'entity_id',
160 $filter = NULL,
161 'account_relationship = 7'
162 );
163 $productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
164 foreach ($financialType as $key => $financialTypeName) {
165 if (!in_array($key, $productFinancialType)) {
166 unset($financialType[$key]);
167 }
168 }
169 if (count($financialType)) {
170 $this->assign('financialType', $financialType);
171 }
172 $this->add(
173 'select',
174 'financial_type_id',
175 ts('Financial Type'),
176 ['' => ts('- select -')] + $financialType
177 );
178
179 $this->add('checkbox', 'is_active', ts('Enabled?'));
180
181 $this->addFormRule(['CRM_Contribute_Form_ManagePremiums', 'formRule']);
182
183 $this->addButtons([
184 [
185 'type' => 'upload',
186 'name' => ts('Save'),
187 'isDefault' => TRUE,
188 ],
189 [
190 'type' => 'cancel',
191 'name' => ts('Cancel'),
192 ],
193 ]);
194 $this->assign('productId', $this->_id);
195 }
196
197 /**
198 * Function for validation.
199 *
200 * @param array $params
201 * (ref.) an assoc array of name/value pairs.
202 * @param $files
203 *
204 * @return bool|array
205 * mixed true or array of errors
206 */
207 public static function formRule($params, $files) {
208
209 // If choosing to upload an image, then an image must be provided
210 if (CRM_Utils_Array::value('imageOption', $params) == 'image'
211 && empty($files['uploadFile']['name'])
212 ) {
213 $errors['uploadFile'] = ts('A file must be selected');
214 }
215
216 // If choosing to use image URLs, then both URLs must be present
217 if (CRM_Utils_Array::value('imageOption', $params) == 'thumbnail') {
218 if (!$params['imageUrl']) {
219 $errors['imageUrl'] = ts('Image URL is Required');
220 }
221 if (!$params['thumbnailUrl']) {
222 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
223 }
224 }
225
226 // CRM-13231 financial type required if product has cost
227 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
228 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
229 }
230
231 if (!$params['period_type']) {
232 if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
233 $params['frequency_unit'] || $params['frequency_interval']
234 ) {
235 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
236 }
237 }
238
239 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
240 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
241 }
242
243 if ($params['duration_unit'] && !$params['duration_interval']) {
244 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
245 }
246
247 if ($params['duration_interval'] && !$params['duration_unit']) {
248 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
249 }
250
251 if ($params['frequency_interval'] && !$params['frequency_unit']) {
252 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
253 }
254
255 if ($params['frequency_unit'] && !$params['frequency_interval']) {
256 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
257 }
258
259 return empty($errors) ? TRUE : $errors;
260 }
261
262 /**
263 * Process the form submission.
264 */
265 public function postProcess() {
266 // If previewing, don't do any post-processing
267 if ($this->_action & CRM_Core_Action::PREVIEW) {
268 return;
269 }
270
271 // If deleting, then only delete and skip the rest of the post-processing
272 if ($this->_action & CRM_Core_Action::DELETE) {
273 try {
274 CRM_Contribute_BAO_Product::del($this->_id);
275 }
276 catch (CRM_Core_Exception $e) {
277 $message = ts("This Premium is linked to an <a href='%1'>Online Contribution page</a>. Please remove it before deleting this Premium.", [1 => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1')]);
278 CRM_Core_Session::setStatus($message, ts('Cannot delete Premium'), 'error');
279 CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
280 return;
281 }
282 CRM_Core_Session::setStatus(
283 ts('Selected Premium Product type has been deleted.'),
284 ts('Deleted'), 'info');
285 return;
286 }
287
288 $params = $this->controller->exportValues($this->_name);
289
290 // Clean the the money fields
291 $moneyFields = ['cost', 'price', 'min_contribution'];
292 foreach ($moneyFields as $field) {
293 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
294 }
295
296 // If we're updating, we need to pass in the premium product Id
297 if ($this->_action & CRM_Core_Action::UPDATE) {
298 $params['id'] = $this->_id;
299 }
300
301 $this->_processImages($params);
302
303 // Save the premium product to database
304 $premium = CRM_Contribute_BAO_Product::create($params);
305
306 CRM_Core_Session::setStatus(
307 ts("The Premium '%1' has been saved.", [1 => $premium->name]),
308 ts('Saved'), 'success');
309 }
310
311 /**
312 * Look at $params to find form info about images. Manipulate images if
313 * necessary. Then alter $params to point to the newly manipulated images.
314 *
315 * @param array $params
316 */
317 protected function _processImages(&$params) {
318 $defaults = [
319 'imageOption' => 'noImage',
320 'uploadFile' => ['name' => ''],
321 'image' => '',
322 'thumbnail' => '',
323 'imageUrl' => '',
324 'thumbnailUrl' => '',
325 ];
326 $params = array_merge($defaults, $params);
327
328 // User is uploading an image
329 if ($params['imageOption'] == 'image') {
330 $imageFile = $params['uploadFile']['name'];
331 try {
332 $params['image'] = CRM_Utils_File::resizeImage($imageFile, 200, 200, "_full");
333 $params['thumbnail'] = CRM_Utils_File::resizeImage($imageFile, 50, 50, "_thumb");
334 }
335 catch (CRM_Core_Exception $e) {
336 $params['image'] = self::_defaultImage();
337 $params['thumbnail'] = self::_defaultThumbnail();
338 $msg = ts('The product has been configured to use a default image.');
339 CRM_Core_Session::setStatus($e->getMessage() . " $msg", ts('Notice'), 'alert');
340 }
341 }
342
343 // User is specifying existing URLs for the images
344 elseif ($params['imageOption'] == 'thumbnail') {
345 $params['image'] = $params['imageUrl'];
346 $params['thumbnail'] = $params['thumbnailUrl'];
347 }
348
349 // User wants a default image
350 elseif ($params['imageOption'] == 'default_image') {
351 $params['image'] = self::_defaultImage();
352 $params['thumbnail'] = self::_defaultThumbnail();
353 }
354 }
355
356 /**
357 * Returns the path to the default premium image
358 * @return string
359 */
360 protected static function _defaultImage() {
361 $config = CRM_Core_Config::singleton();
362 return $config->resourceBase . 'i/contribute/default_premium.jpg';
363 }
364
365 /**
366 * Returns the path to the default premium thumbnail
367 * @return string
368 */
369 protected static function _defaultThumbnail() {
370 $config = CRM_Core_Config::singleton();
371 return $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
372 }
373
374 }