CRM-16471 post refactoring - extract pending status from form
[civicrm-core.git] / CRM / Contribute / Form / ManagePremiums.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for Premiums
38 *
39 */
40class CRM_Contribute_Form_ManagePremiums extends CRM_Contribute_Form {
41
42 /**
07f8d162 43 * Pre process the form.
6a488035
TO
44 */
45 public function preProcess() {
46 parent::preProcess();
47 }
48
49 /**
c490a46a 50 * Set default values for the form. Manage Premiums that in edit/view mode
6a488035
TO
51 * the default values are retrieved from the database
52 *
6a488035 53 *
355ba699 54 * @return void
6a488035 55 */
00be9182 56 public function setDefaultValues() {
6a488035
TO
57 $defaults = parent::setDefaultValues();
58 if ($this->_id) {
59 $params = array('id' => $this->_id);
60 CRM_Contribute_BAO_ManagePremiums::retrieve($params, $tempDefaults);
61 $imageUrl = (isset($tempDefaults['image'])) ? $tempDefaults['image'] : "";
62 if (isset($tempDefaults['image']) && isset($tempDefaults['thumbnail'])) {
63 $defaults['imageUrl'] = $tempDefaults['image'];
64 $defaults['thumbnailUrl'] = $tempDefaults['thumbnail'];
65 $defaults['imageOption'] = 'thumbnail';
66 // assign thumbnailUrl to template so we can display current image in update mode
67 $this->assign('thumbnailUrl', $defaults['thumbnailUrl']);
68 }
69 else {
70 $defaults['imageOption'] = 'noImage';
71 }
72 if (isset($tempDefaults['thumbnail']) && isset($tempDefaults['image'])) {
73 $this->assign('thumbURL', $tempDefaults['thumbnail']);
74 $this->assign('imageURL', $tempDefaults['image']);
75 }
76 if (isset($tempDefaults['period_type'])) {
77 $this->assign('showSubscriptions', TRUE);
78 }
79 }
80
81 return $defaults;
82 }
83
84 /**
fe482240 85 * Build the form object.
6a488035 86 *
355ba699 87 * @return void
6a488035
TO
88 */
89 public function buildQuickForm() {
481a74f4 90 parent::buildQuickForm();
e2046b33 91 $this->setPageTitle(ts('Premium Product'));
6a488035
TO
92
93 if ($this->_action & CRM_Core_Action::PREVIEW) {
94 CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, $this->_id);
6a488035
TO
95 return;
96 }
97
98 if ($this->_action & CRM_Core_Action::DELETE) {
6a488035
TO
99 return;
100 }
101
102 $this->applyFilter('__ALL__', 'trim');
103 $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'name'), TRUE);
353ffa53
TO
104 $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', array(
105 'CRM_Contribute_DAO_Product',
317fceb4 106 $this->_id,
353ffa53 107 ));
6a488035
TO
108 $this->add('text', 'sku', ts('SKU'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'sku'));
109
110 $this->add('textarea', 'description', ts('Description'), 'rows=3, cols=60');
111
112 $image['image'] = $this->createElement('radio', NULL, NULL, ts('Upload from my computer'), 'image', 'onclick="add_upload_file_block(\'image\');');
113 $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\');');
114 $image['default_image'] = $this->createElement('radio', NULL, NULL, ts('Use default image'), 'default_image', 'onclick="add_upload_file_block(\'default\');');
115 $image['noImage'] = $this->createElement('radio', NULL, NULL, ts('Do not display an image'), 'noImage', 'onclick="add_upload_file_block(\'noImage\');');
116
117 $this->addGroup($image, 'imageOption', ts('Premium Image'));
118 $this->addRule('imageOption', ts('Please select an option for the premium image.'), 'required');
119
120 $this->addElement('text', 'imageUrl', ts('Image URL'));
6a488035 121 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
6a488035
TO
122
123 $this->add('file', 'uploadFile', ts('Image File Name'), 'onChange="select_option();"');
124
6a488035
TO
125 $this->add('text', 'price', ts('Market Value'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'price'), TRUE);
126 $this->addRule('price', ts('Please enter the Market Value for this product.'), 'money');
127
128 $this->add('text', 'cost', ts('Actual Cost of Product'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'cost'));
129 $this->addRule('price', ts('Please enter the Actual Cost of Product.'), 'money');
130
131 $this->add('text', 'min_contribution', ts('Minimum Contribution Amount'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'min_contribution'), TRUE);
132 $this->addRule('min_contribution', ts('Please enter a monetary value for the Minimum Contribution Amount.'), 'money');
133
134 $this->add('textarea', 'options', ts('Options'), 'rows=3, cols=60');
135
353ffa53
TO
136 $this->add('select', 'period_type', ts('Period Type'), array(
137 '' => '- select -',
138 'rolling' => 'Rolling',
317fceb4 139 'fixed' => 'Fixed',
353ffa53 140 ));
6a488035
TO
141
142 $this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
143
f80ce889 144 $this->add('Select', 'duration_unit', ts('Duration Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
6a488035
TO
145
146 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
147
f80ce889 148 $this->add('Select', 'frequency_unit', ts('Frequency Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
6a488035
TO
149
150 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
665e5ec7 151
6a488035 152 //Financial Type CRM-11106
481a74f4 153 $financialType = CRM_Contribute_PseudoConstant::financialType();
6a488035
TO
154 $premiumFinancialType = array();
155 CRM_Core_PseudoConstant::populate(
156 $premiumFinancialType,
157 'CRM_Financial_DAO_EntityFinancialAccount',
874c9be7 158 $all = TRUE,
665e5ec7 159 $retrieve = 'entity_id',
874c9be7 160 $filter = NULL,
665e5ec7 161 'account_relationship = 8'
6a488035 162 );
665e5ec7 163
6a488035
TO
164 $costFinancialType = array();
165 CRM_Core_PseudoConstant::populate(
166 $costFinancialType,
167 'CRM_Financial_DAO_EntityFinancialAccount',
874c9be7 168 $all = TRUE,
665e5ec7 169 $retrieve = 'entity_id',
874c9be7 170 $filter = NULL,
665e5ec7 171 'account_relationship = 7'
6a488035
TO
172 );
173 $productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
481a74f4
TO
174 foreach ($financialType as $key => $financialTypeName) {
175 if (!in_array($key, $productFinancialType)) {
176 unset($financialType[$key]);
874c9be7 177 }
6a488035 178 }
481a74f4
TO
179 if (count($financialType)) {
180 $this->assign('financialType', $financialType);
665e5ec7 181 }
6a488035 182 $this->add(
665e5ec7 183 'select',
184 'financial_type_id',
481a74f4 185 ts('Financial Type'),
874c9be7 186 array('' => ts('- select -')) + $financialType
6a488035 187 );
665e5ec7 188
6a488035
TO
189 $this->add('checkbox', 'is_active', ts('Enabled?'));
190
191 $this->addFormRule(array('CRM_Contribute_Form_ManagePremiums', 'formRule'));
192
9cd1bf80
RK
193 $this->addButtons(array(
194 array(
195 'type' => 'upload',
196 'name' => ts('Save'),
197 'isDefault' => TRUE,
198 ),
199 array(
200 'type' => 'cancel',
201 'name' => ts('Cancel'),
202 ),
203 )
204 );
6a488035
TO
205 $this->assign('productId', $this->_id);
206 }
207
208 /**
fe482240 209 * Function for validation.
6a488035 210 *
014c4014
TO
211 * @param array $params
212 * (ref.) an assoc array of name/value pairs.
6a488035 213 *
dd244018
EM
214 * @param $files
215 *
72b3a70c
CW
216 * @return bool|array
217 * mixed true or array of errors
6a488035 218 */
fcc5922d 219 public static function formRule($params, $files) {
6a488035
TO
220 if (isset($params['imageOption'])) {
221 if ($params['imageOption'] == 'thumbnail') {
222 if (!$params['imageUrl']) {
3b67ab13 223 $errors['imageUrl'] = ts('Image URL is Required');
6a488035
TO
224 }
225 if (!$params['thumbnailUrl']) {
3b67ab13 226 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
6a488035
TO
227 }
228 }
229 }
3b67ab13 230 // CRM-13231 financial type required if product has cost
8cc574cf 231 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
3b67ab13
PN
232 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
233 }
6a488035
TO
234 $fileLocation = $files['uploadFile']['tmp_name'];
235 if ($fileLocation != "") {
236 list($width, $height) = getimagesize($fileLocation);
237
238 if (($width < 80 || $width > 500) || ($height < 80 || $height > 500)) {
239 //$errors ['uploadFile'] = "Please Enter files with dimensions between 80 x 80 and 500 x 500," . " Dimensions of this file is ".$width."X".$height;
240 }
241 }
242
243 if (!$params['period_type']) {
244 if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
245 $params['frequency_unit'] || $params['frequency_interval']
246 ) {
247 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
248 }
249 }
250
251 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
252 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
253 }
254
255 if ($params['duration_unit'] && !$params['duration_interval']) {
256 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
257 }
258
259 if ($params['duration_interval'] && !$params['duration_unit']) {
260 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
261 }
262
263 if ($params['frequency_interval'] && !$params['frequency_unit']) {
264 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
265 }
266
267 if ($params['frequency_unit'] && !$params['frequency_interval']) {
268 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
269 }
270
6a488035
TO
271 return empty($errors) ? TRUE : $errors;
272 }
273
274 /**
fe482240 275 * Process the form submission.
6a488035 276 *
6a488035 277 *
355ba699 278 * @return void
6a488035
TO
279 */
280 public function postProcess() {
281
282 if ($this->_action & CRM_Core_Action::PREVIEW) {
283 return;
284 }
285
286 if ($this->_action & CRM_Core_Action::DELETE) {
287 CRM_Contribute_BAO_ManagePremiums::del($this->_id);
288 CRM_Core_Session::setStatus(ts('Selected Premium Product type has been deleted.'), ts('Deleted'), 'info');
289 }
290 else {
353ffa53 291 $params = $this->controller->exportValues($this->_name);
6a488035
TO
292 $imageFile = CRM_Utils_Array::value('uploadFile', $params);
293 $imageFile = $imageFile['name'];
294
295 $config = CRM_Core_Config::singleton();
296
297 $ids = array();
298 $error = FALSE;
299 // store the submitted values in an array
300
301 // FIX ME
302 if (CRM_Utils_Array::value('imageOption', $params, FALSE)) {
303 $value = CRM_Utils_Array::value('imageOption', $params, FALSE);
304 if ($value == 'image') {
305
306 // to check wether GD is installed or not
307 $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
22e263ad
TO
308 if ($gdSupport) {
309 if ($imageFile) {
874c9be7 310 $error = FALSE;
6a488035
TO
311 $params['image'] = $this->_resizeImage($imageFile, "_full", 200, 200);
312 $params['thumbnail'] = $this->_resizeImage($imageFile, "_thumb", 50, 50);
313 }
0db6c3e1
TO
314 }
315 else {
874c9be7 316 $error = TRUE;
6a488035
TO
317 $params['image'] = $config->resourceBase . 'i/contribute/default_premium.jpg';
318 $params['thumbnail'] = $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
319 }
0db6c3e1
TO
320 }
321 elseif ($value == 'thumbnail') {
6a488035
TO
322 $params['image'] = $params['imageUrl'];
323 $params['thumbnail'] = $params['thumbnailUrl'];
0db6c3e1
TO
324 }
325 elseif ($value == 'default_image') {
6a488035
TO
326 $url = parse_url($config->userFrameworkBaseURL);
327 $params['image'] = $config->resourceBase . 'i/contribute/default_premium.jpg';
328 $params['thumbnail'] = $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
0db6c3e1
TO
329 }
330 else {
6a488035
TO
331 $params['image'] = "";
332 $params['thumbnail'] = "";
333 }
334 }
335
336 if ($this->_action & CRM_Core_Action::UPDATE) {
337 $ids['premium'] = $this->_id;
338 }
339
340 // fix the money fields
341 foreach (array(
353ffa53
TO
342 'cost',
343 'price',
317fceb4 344 'min_contribution',
353ffa53 345 ) as $f) {
6a488035
TO
346 $params[$f] = CRM_Utils_Rule::cleanMoney($params[$f]);
347 }
348
349 $premium = CRM_Contribute_BAO_ManagePremiums::add($params, $ids);
350 if ($error) {
351 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');
352 }
353 else {
354 CRM_Core_Session::setStatus(ts("The Premium '%1' has been saved.", array(1 => $premium->name)), ts('Saved'), 'success');
355 }
356 }
357 }
358
359 /**
fe482240 360 * Resize a premium image to a different size.
6a488035 361 *
6a488035 362 *
100fef9d
CW
363 * @param string $filename
364 * @param string $resizedName
2a6da8d7
EM
365 * @param $width
366 * @param $height
367 *
72b3a70c
CW
368 * @return string
369 * Path to image
6a488035
TO
370 */
371 private function _resizeImage($filename, $resizedName, $width, $height) {
372 // figure out the new filename
373 $pathParts = pathinfo($filename);
92fcb95f 374 $newFilename = $pathParts['dirname'] . "/" . $pathParts['filename'] . $resizedName . "." . $pathParts['extension'];
6a488035
TO
375
376 // get image about original image
377 $imageInfo = getimagesize($filename);
378 $widthOrig = $imageInfo[0];
379 $heightOrig = $imageInfo[1];
380 $image = imagecreatetruecolor($width, $height);
22e263ad 381 if ($imageInfo['mime'] == 'image/gif') {
6a488035 382 $source = imagecreatefromgif($filename);
0db6c3e1 383 }
353ffa53 384 elseif ($imageInfo['mime'] == 'image/png') {
6a488035 385 $source = imagecreatefrompng($filename);
0db6c3e1
TO
386 }
387 else {
6a488035
TO
388 $source = imagecreatefromjpeg($filename);
389 }
390
391 // resize
392 imagecopyresized($image, $source, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
393
394 // save the resized image
395 $fp = fopen($newFilename, 'w+');
396 ob_start();
874c9be7 397 imagejpeg($image);
6a488035
TO
398 $image_buffer = ob_get_contents();
399 ob_end_clean();
874c9be7 400 imagedestroy($image);
6a488035
TO
401 fwrite($fp, $image_buffer);
402 rewind($fp);
403 fclose($fp);
404
405 // return the URL to link to
406 $config = CRM_Core_Config::singleton();
92fcb95f 407 return $config->imageUploadURL . basename($newFilename);
6a488035 408 }
e2046b33 409
6a488035 410}