CRM-19184 remove old old old suppress group functionality by defining 'CIVICRM_GROUPTREE'
[civicrm-core.git] / CRM / Contribute / Form / ManagePremiums.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 = 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 /**
78 * Build the form object.
79 */
80 public function buildQuickForm() {
81 parent::buildQuickForm();
82 $this->setPageTitle(ts('Premium Product'));
83
84 if ($this->_action & CRM_Core_Action::PREVIEW) {
85 CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, $this->_id);
86 return;
87 }
88
89 if ($this->_action & CRM_Core_Action::DELETE) {
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);
95 $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', array(
96 'CRM_Contribute_DAO_Product',
97 $this->_id,
98 ));
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'));
112 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
113
114 $this->add('file', 'uploadFile', ts('Image File Name'), 'onChange="select_option();"');
115
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
127 $this->add('select', 'period_type', ts('Period Type'), array(
128 '' => '- select -',
129 'rolling' => 'Rolling',
130 'fixed' => 'Fixed',
131 ));
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
135 $this->add('Select', 'duration_unit', ts('Duration Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
136
137 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
138
139 $this->add('Select', 'frequency_unit', ts('Frequency Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
140
141 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
142
143 //Financial Type CRM-11106
144 $financialType = CRM_Contribute_PseudoConstant::financialType();
145 $premiumFinancialType = array();
146 CRM_Core_PseudoConstant::populate(
147 $premiumFinancialType,
148 'CRM_Financial_DAO_EntityFinancialAccount',
149 $all = TRUE,
150 $retrieve = 'entity_id',
151 $filter = NULL,
152 'account_relationship = 8'
153 );
154
155 $costFinancialType = array();
156 CRM_Core_PseudoConstant::populate(
157 $costFinancialType,
158 'CRM_Financial_DAO_EntityFinancialAccount',
159 $all = TRUE,
160 $retrieve = 'entity_id',
161 $filter = NULL,
162 'account_relationship = 7'
163 );
164 $productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
165 foreach ($financialType as $key => $financialTypeName) {
166 if (!in_array($key, $productFinancialType)) {
167 unset($financialType[$key]);
168 }
169 }
170 if (count($financialType)) {
171 $this->assign('financialType', $financialType);
172 }
173 $this->add(
174 'select',
175 'financial_type_id',
176 ts('Financial Type'),
177 array('' => ts('- select -')) + $financialType
178 );
179
180 $this->add('checkbox', 'is_active', ts('Enabled?'));
181
182 $this->addFormRule(array('CRM_Contribute_Form_ManagePremiums', 'formRule'));
183
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 );
196 $this->assign('productId', $this->_id);
197 }
198
199 /**
200 * Function for validation.
201 *
202 * @param array $params
203 * (ref.) an assoc array of name/value pairs.
204 *
205 * @param $files
206 *
207 * @return bool|array
208 * mixed true or array of errors
209 */
210 public static function formRule($params, $files) {
211 if (isset($params['imageOption'])) {
212 if ($params['imageOption'] == 'thumbnail') {
213 if (!$params['imageUrl']) {
214 $errors['imageUrl'] = ts('Image URL is Required');
215 }
216 if (!$params['thumbnailUrl']) {
217 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
218 }
219 }
220 }
221 // CRM-13231 financial type required if product has cost
222 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
223 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
224 }
225 $fileLocation = $files['uploadFile']['tmp_name'];
226 if ($fileLocation != "") {
227 list($width, $height) = getimagesize($fileLocation);
228
229 if (($width < 80 || $width > 500) || ($height < 80 || $height > 500)) {
230 //$errors ['uploadFile'] = "Please Enter files with dimensions between 80 x 80 and 500 x 500," . " Dimensions of this file is ".$width."X".$height;
231 }
232 }
233
234 if (!$params['period_type']) {
235 if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
236 $params['frequency_unit'] || $params['frequency_interval']
237 ) {
238 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
239 }
240 }
241
242 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
243 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
244 }
245
246 if ($params['duration_unit'] && !$params['duration_interval']) {
247 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
248 }
249
250 if ($params['duration_interval'] && !$params['duration_unit']) {
251 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
252 }
253
254 if ($params['frequency_interval'] && !$params['frequency_unit']) {
255 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
256 }
257
258 if ($params['frequency_unit'] && !$params['frequency_interval']) {
259 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
260 }
261
262 return empty($errors) ? TRUE : $errors;
263 }
264
265 /**
266 * Process the form submission.
267 */
268 public function postProcess() {
269
270 if ($this->_action & CRM_Core_Action::PREVIEW) {
271 return;
272 }
273
274 if ($this->_action & CRM_Core_Action::DELETE) {
275 CRM_Contribute_BAO_ManagePremiums::del($this->_id);
276 CRM_Core_Session::setStatus(ts('Selected Premium Product type has been deleted.'), ts('Deleted'), 'info');
277 }
278 else {
279 $params = $this->controller->exportValues($this->_name);
280 $imageFile = CRM_Utils_Array::value('uploadFile', $params);
281 $imageFile = $imageFile['name'];
282
283 $config = CRM_Core_Config::singleton();
284
285 $ids = array();
286 $error = FALSE;
287 // store the submitted values in an array
288
289 // FIX ME
290 if (CRM_Utils_Array::value('imageOption', $params, FALSE)) {
291 $value = CRM_Utils_Array::value('imageOption', $params, FALSE);
292 if ($value == 'image') {
293
294 // to check wether GD is installed or not
295 $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
296 if ($gdSupport) {
297 if ($imageFile) {
298 $error = FALSE;
299 $params['image'] = $this->_resizeImage($imageFile, "_full", 200, 200);
300 $params['thumbnail'] = $this->_resizeImage($imageFile, "_thumb", 50, 50);
301 }
302 }
303 else {
304 $error = TRUE;
305 $params['image'] = $config->resourceBase . 'i/contribute/default_premium.jpg';
306 $params['thumbnail'] = $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
307 }
308 }
309 elseif ($value == 'thumbnail') {
310 $params['image'] = $params['imageUrl'];
311 $params['thumbnail'] = $params['thumbnailUrl'];
312 }
313 elseif ($value == 'default_image') {
314 $url = parse_url($config->userFrameworkBaseURL);
315 $params['image'] = $config->resourceBase . 'i/contribute/default_premium.jpg';
316 $params['thumbnail'] = $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
317 }
318 else {
319 $params['image'] = "";
320 $params['thumbnail'] = "";
321 }
322 }
323
324 if ($this->_action & CRM_Core_Action::UPDATE) {
325 $ids['premium'] = $this->_id;
326 }
327
328 // fix the money fields
329 foreach (array(
330 'cost',
331 'price',
332 'min_contribution',
333 ) as $f) {
334 $params[$f] = CRM_Utils_Rule::cleanMoney($params[$f]);
335 }
336
337 $premium = CRM_Contribute_BAO_ManagePremiums::add($params, $ids);
338 if ($error) {
339 CRM_Core_Session::setStatus(ts('No thumbnail of your image was created because the GD image library is not currently compiled in your PHP installation. Product is currently configured to use default thumbnail image. If you have a local thumbnail image you can upload it separately and input the thumbnail URL by editing this premium.'), ts('Notice'), 'alert');
340 }
341 else {
342 CRM_Core_Session::setStatus(ts("The Premium '%1' has been saved.", array(1 => $premium->name)), ts('Saved'), 'success');
343 }
344 }
345 }
346
347 /**
348 * Resize a premium image to a different size.
349 *
350 *
351 * @param string $filename
352 * @param string $resizedName
353 * @param $width
354 * @param $height
355 *
356 * @return string
357 * Path to image
358 */
359 private function _resizeImage($filename, $resizedName, $width, $height) {
360 // figure out the new filename
361 $pathParts = pathinfo($filename);
362 $newFilename = $pathParts['dirname'] . "/" . $pathParts['filename'] . $resizedName . "." . $pathParts['extension'];
363
364 // get image about original image
365 $imageInfo = getimagesize($filename);
366 $widthOrig = $imageInfo[0];
367 $heightOrig = $imageInfo[1];
368 $image = imagecreatetruecolor($width, $height);
369 if ($imageInfo['mime'] == 'image/gif') {
370 $source = imagecreatefromgif($filename);
371 }
372 elseif ($imageInfo['mime'] == 'image/png') {
373 $source = imagecreatefrompng($filename);
374 }
375 else {
376 $source = imagecreatefromjpeg($filename);
377 }
378
379 // resize
380 imagecopyresized($image, $source, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
381
382 // save the resized image
383 $fp = fopen($newFilename, 'w+');
384 ob_start();
385 imagejpeg($image);
386 $image_buffer = ob_get_contents();
387 ob_end_clean();
388 imagedestroy($image);
389 fwrite($fp, $image_buffer);
390 rewind($fp);
391 fclose($fp);
392
393 // return the URL to link to
394 $config = CRM_Core_Config::singleton();
395 return $config->imageUploadURL . basename($newFilename);
396 }
397
398 }