Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2014-12-01-14-40-22
[civicrm-core.git] / CRM / Contribute / Form / ManagePremiums.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * @access public
46 *
47 * @return void
48 */
49 public function preProcess() {
50 parent::preProcess();
51 }
52
53 /**
54 * Set 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 *
59 * @return void
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 * Build the form object
91 *
92 * @return void
93 * @access public
94 */
95 public function buildQuickForm() {
96 parent::buildQuickForm( );
97 $this->setPageTitle(ts('Premium Product'));
98
99 if ($this->_action & CRM_Core_Action::PREVIEW) {
100 CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, $this->_id);
101 return;
102 }
103
104 if ($this->_action & CRM_Core_Action::DELETE) {
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'));
124 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
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
144 $this->add('Select', 'duration_unit', ts('Duration Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
145
146 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
147
148 $this->add('Select', 'frequency_unit', ts('Frequency Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
149
150 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
151
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',
158 $all = True,
159 $retrieve = 'entity_id',
160 $filter = null,
161 'account_relationship = 8'
162 );
163
164 $costFinancialType = array();
165 CRM_Core_PseudoConstant::populate(
166 $costFinancialType,
167 'CRM_Financial_DAO_EntityFinancialAccount',
168 $all = True,
169 $retrieve = 'entity_id',
170 $filter = null,
171 'account_relationship = 7'
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 );
180 }
181 $this->add(
182 'select',
183 'financial_type_id',
184 ts( 'Financial Type' ),
185 array(''=>ts('- select -')) + $financialType
186 );
187
188 $this->add('checkbox', 'is_active', ts('Enabled?'));
189
190 $this->addFormRule(array('CRM_Contribute_Form_ManagePremiums', 'formRule'));
191
192 $this->addButtons(array(
193 array(
194 'type' => 'upload',
195 'name' => ts('Save'),
196 'isDefault' => TRUE,
197 ),
198 array(
199 'type' => 'cancel',
200 'name' => ts('Cancel'),
201 ),
202 )
203 );
204 $this->assign('productId', $this->_id);
205 }
206
207 /**
208 * Function for validation
209 *
210 * @param array $params (ref.) an assoc array of name/value pairs
211 *
212 * @param $files
213 *
214 * @return mixed true or array of errors
215 * @access public
216 * @static
217 */
218 public static function formRule($params, $files) {
219 if (isset($params['imageOption'])) {
220 if ($params['imageOption'] == 'thumbnail') {
221 if (!$params['imageUrl']) {
222 $errors['imageUrl'] = ts('Image URL is Required');
223 }
224 if (!$params['thumbnailUrl']) {
225 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
226 }
227 }
228 }
229 // CRM-13231 financial type required if product has cost
230 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
231 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
232 }
233 $fileLocation = $files['uploadFile']['tmp_name'];
234 if ($fileLocation != "") {
235 list($width, $height) = getimagesize($fileLocation);
236
237 if (($width < 80 || $width > 500) || ($height < 80 || $height > 500)) {
238 //$errors ['uploadFile'] = "Please Enter files with dimensions between 80 x 80 and 500 x 500," . " Dimensions of this file is ".$width."X".$height;
239 }
240 }
241
242 if (!$params['period_type']) {
243 if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
244 $params['frequency_unit'] || $params['frequency_interval']
245 ) {
246 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
247 }
248 }
249
250 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
251 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
252 }
253
254 if ($params['duration_unit'] && !$params['duration_interval']) {
255 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
256 }
257
258 if ($params['duration_interval'] && !$params['duration_unit']) {
259 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
260 }
261
262 if ($params['frequency_interval'] && !$params['frequency_unit']) {
263 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
264 }
265
266 if ($params['frequency_unit'] && !$params['frequency_interval']) {
267 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
268 }
269
270
271 return empty($errors) ? TRUE : $errors;
272 }
273
274 /**
275 * Process the form submission
276 *
277 * @access public
278 *
279 * @return void
280 */
281 public function postProcess() {
282
283 if ($this->_action & CRM_Core_Action::PREVIEW) {
284 return;
285 }
286
287 if ($this->_action & CRM_Core_Action::DELETE) {
288 CRM_Contribute_BAO_ManagePremiums::del($this->_id);
289 CRM_Core_Session::setStatus(ts('Selected Premium Product type has been deleted.'), ts('Deleted'), 'info');
290 }
291 else {
292 $params = $this->controller->exportValues($this->_name);
293 $imageFile = CRM_Utils_Array::value('uploadFile', $params);
294 $imageFile = $imageFile['name'];
295
296 $config = CRM_Core_Config::singleton();
297
298 $ids = array();
299 $error = FALSE;
300 // store the submitted values in an array
301
302 // FIX ME
303 if (CRM_Utils_Array::value('imageOption', $params, FALSE)) {
304 $value = CRM_Utils_Array::value('imageOption', $params, FALSE);
305 if ($value == 'image') {
306
307 // to check wether GD is installed or not
308 $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
309 if($gdSupport) {
310 if($imageFile) {
311 $error = false;
312 $params['image'] = $this->_resizeImage($imageFile, "_full", 200, 200);
313 $params['thumbnail'] = $this->_resizeImage($imageFile, "_thumb", 50, 50);
314 }
315 } else {
316 $error = true;
317 $params['image'] = $config->resourceBase . 'i/contribute/default_premium.jpg';
318 $params['thumbnail'] = $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
319 }
320 } elseif ($value == 'thumbnail') {
321 $params['image'] = $params['imageUrl'];
322 $params['thumbnail'] = $params['thumbnailUrl'];
323 } elseif ($value == 'default_image') {
324 $url = parse_url($config->userFrameworkBaseURL);
325 $params['image'] = $config->resourceBase . 'i/contribute/default_premium.jpg';
326 $params['thumbnail'] = $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
327 } else {
328 $params['image'] = "";
329 $params['thumbnail'] = "";
330 }
331 }
332
333 if ($this->_action & CRM_Core_Action::UPDATE) {
334 $ids['premium'] = $this->_id;
335 }
336
337 // fix the money fields
338 foreach (array(
339 'cost', 'price', 'min_contribution') as $f) {
340 $params[$f] = CRM_Utils_Rule::cleanMoney($params[$f]);
341 }
342
343 $premium = CRM_Contribute_BAO_ManagePremiums::add($params, $ids);
344 if ($error) {
345 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');
346 }
347 else {
348 CRM_Core_Session::setStatus(ts("The Premium '%1' has been saved.", array(1 => $premium->name)), ts('Saved'), 'success');
349 }
350 }
351 }
352
353 /**
354 * Resize a premium image to a different size
355 *
356 * @access private
357 *
358 * @param $filename
359 * @param $resizedName
360 * @param $width
361 * @param $height
362 *
363 * @return Path to image
364 */
365 private function _resizeImage($filename, $resizedName, $width, $height) {
366 // figure out the new filename
367 $pathParts = pathinfo($filename);
368 $newFilename = $pathParts['dirname']."/".$pathParts['filename'].$resizedName.".".$pathParts['extension'];
369
370 // get image about original image
371 $imageInfo = getimagesize($filename);
372 $widthOrig = $imageInfo[0];
373 $heightOrig = $imageInfo[1];
374 $image = imagecreatetruecolor($width, $height);
375 if($imageInfo['mime'] == 'image/gif') {
376 $source = imagecreatefromgif($filename);
377 } elseif($imageInfo['mime'] == 'image/png') {
378 $source = imagecreatefrompng($filename);
379 } else {
380 $source = imagecreatefromjpeg($filename);
381 }
382
383 // resize
384 imagecopyresized($image, $source, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
385
386 // save the resized image
387 $fp = fopen($newFilename, 'w+');
388 ob_start();
389 ImageJPEG($image);
390 $image_buffer = ob_get_contents();
391 ob_end_clean();
392 ImageDestroy($image);
393 fwrite($fp, $image_buffer);
394 rewind($fp);
395 fclose($fp);
396
397 // return the URL to link to
398 $config = CRM_Core_Config::singleton();
399 return $config->imageUploadURL.basename($newFilename);
400 }
401
402 }
403