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