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