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