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