Merge pull request #4607 from samuelsov/CRM-15637
[civicrm-core.git] / CRM / Core / BAO / LabelFormat.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright (C) 2011 Marty Wright |
7 | Licensed to CiviCRM under the Academic Free License version 3.0. |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36
37 /**
38 * This class contains functions for managing Label Formats
39 */
40 class CRM_Core_BAO_LabelFormat extends CRM_Core_DAO_OptionValue {
41
42 /**
43 * Static holder for the Label Formats Option Group ID
44 */
45 private static $_gid = NULL;
46
47 /**
48 * Label Format fields stored in the 'value' field of the Option Value table.
49 */
50 private static $optionValueFields = array(
51 'paper-size' => array(
52 // Paper size: names defined in option_value table (option_group = 'paper_size')
53 'name' => 'paper-size',
54 'type' => CRM_Utils_Type::T_STRING,
55 'default' => 'letter',
56 ),
57 'orientation' => array(
58 // Paper orientation: 'portrait' or 'landscape'
59 'name' => 'orientation',
60 'type' => CRM_Utils_Type::T_STRING,
61 'default' => 'portrait',
62 ),
63 'font-name' => array(
64 // Font name: 'courier', 'helvetica', 'times'
65 'name' => 'font-name',
66 'type' => CRM_Utils_Type::T_STRING,
67 'default' => 'helvetica',
68 ),
69 'font-size' => array(
70 // Font size: always in points
71 'name' => 'font-size',
72 'type' => CRM_Utils_Type::T_INT,
73 'default' => 8,
74 ),
75 'font-style' => array(
76 // Font style: 'B' bold, 'I' italic, 'BI' bold+italic
77 'name' => 'font-style',
78 'type' => CRM_Utils_Type::T_STRING,
79 'default' => '',
80 ),
81 'NX' => array(
82 // Number of labels horizontally
83 'name' => 'NX',
84 'type' => CRM_Utils_Type::T_INT,
85 'default' => 3,
86 ),
87 'NY' => array(
88 // Number of labels vertically
89 'name' => 'NY',
90 'type' => CRM_Utils_Type::T_INT,
91 'default' => 10,
92 ),
93 'metric' => array(
94 // Unit of measurement for all of the following fields
95 'name' => 'metric',
96 'type' => CRM_Utils_Type::T_STRING,
97 'default' => 'mm',
98 ),
99 'lMargin' => array(
100 // Left margin
101 'name' => 'lMargin',
102 'type' => CRM_Utils_Type::T_FLOAT,
103 'metric' => TRUE,
104 'default' => 4.7625,
105 ),
106 'tMargin' => array(
107 // Right margin
108 'name' => 'tMargin',
109 'type' => CRM_Utils_Type::T_FLOAT,
110 'metric' => TRUE,
111 'default' => 12.7,
112 ),
113 'SpaceX' => array(
114 // Horizontal space between two labels
115 'name' => 'SpaceX',
116 'type' => CRM_Utils_Type::T_FLOAT,
117 'metric' => TRUE,
118 'default' => 3.96875,
119 ),
120 'SpaceY' => array(
121 // Vertical space between two labels
122 'name' => 'SpaceY',
123 'type' => CRM_Utils_Type::T_FLOAT,
124 'metric' => TRUE,
125 'default' => 0,
126 ),
127 'width' => array(
128 // Width of label
129 'name' => 'width',
130 'type' => CRM_Utils_Type::T_FLOAT,
131 'metric' => TRUE,
132 'default' => 65.875,
133 ),
134 'height' => array(
135 // Height of label
136 'name' => 'height',
137 'type' => CRM_Utils_Type::T_FLOAT,
138 'metric' => TRUE,
139 'default' => 25.4,
140 ),
141 'lPadding' => array(
142 // Space between text and left edge of label
143 'name' => 'lPadding',
144 'type' => CRM_Utils_Type::T_FLOAT,
145 'metric' => TRUE,
146 'default' => 5.08,
147 ),
148 'tPadding' => array(
149 // Space between text and top edge of label
150 'name' => 'tPadding',
151 'type' => CRM_Utils_Type::T_FLOAT,
152 'metric' => TRUE,
153 'default' => 5.08,
154 ),
155 );
156
157 /**
158 * Get page orientations recognized by the DOMPDF package used to create PDF letters.
159 *
160 * @param void
161 *
162 * @return array array of page orientations
163 * @static
164 */
165 public static function getPageOrientations() {
166 return array(
167 'portrait' => ts('Portrait'),
168 'landscape' => ts('Landscape'),
169 );
170 }
171
172 /**
173 * Get font names supported by the TCPDF package used to create PDF labels.
174 *
175 * @param string $name group name
176 *
177 * @return array array of font names
178 * @static
179 */
180 public static function getFontNames($name='label_format') {
181 $label = new CRM_Utils_PDF_Label(self::getDefaultValues($name));
182 return $label->getFontNames();
183 }
184
185 /**
186 * Get font sizes supported by the TCPDF package used to create PDF labels.
187 *
188 * @param void
189 *
190 * @return array array of font sizes
191 * @static
192 */
193 public static function getFontSizes() {
194 $fontSizes = array();
195 for ($i = 6; $i <= 60; $i++) {
196 $fontSizes[$i] = ts('%1 pt', array(1 => $i));
197 }
198
199 return $fontSizes;
200 }
201
202 /**
203 * Get measurement units recognized by the TCPDF package used to create PDF labels.
204 *
205 * @param void
206 *
207 * @return array array of measurement units
208 * @static
209 */
210 public static function getUnits() {
211 return array(
212 'in' => ts('Inches'),
213 'cm' => ts('Centimeters'),
214 'mm' => ts('Millimeters'),
215 'pt' => ts('Points'),
216 );
217 }
218
219 /**
220 * Get text alignment recognized by the TCPDF package used to create PDF labels.
221 *
222 * @param void
223 *
224 * @return array array of alignments
225 * @static
226 */
227 public static function getTextAlignments() {
228 return array(
229 'R' => ts('Right'),
230 'L' => ts('Left'),
231 'C' => ts('Center'),
232 );
233 }
234
235 /**
236 * Get text alignment recognized by the TCPDF package used to create PDF labels.
237 *
238 * @param void
239 *
240 * @return array array of alignments
241 * @static
242 */
243 public static function getFontStyles() {
244 return array(
245 '' => ts('Normal'),
246 'B' => ts('Bold'),
247 'I' => ts('Italic'),
248 );
249 }
250
251 /**
252 * Get Option Group ID for Label Formats
253 *
254 * @param string $name
255 *
256 * @return int Group ID (null if Group ID doesn't exist)
257 */
258 private static function _getGid($name='label_format') {
259 if (!isset(self::$_gid[$name]) || !self::$_gid[$name]) {
260 self::$_gid[$name] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $name, 'id', 'name');
261 if (!self::$_gid[$name]) {
262 CRM_Core_Error::fatal(ts('Label Format Option Group not found in database.'));
263 }
264 }
265 return self::$_gid[$name];
266 }
267
268 /**
269 * Add ordering fields to Label Format list
270 *
271 * @param array (reference) $list List of Label Formats
272 * @param string $returnURL URL of page calling this function
273 *
274 * @return array (reference) List of Label Formats
275 * @static
276 */
277 public static function addOrder(&$list, $returnURL) {
278 $filter = "option_group_id = " . self::_getGid();
279 CRM_Utils_Weight::addOrder($list, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
280 }
281
282 /**
283 * Retrieve list of Label Formats.
284 *
285 * @param bool $namesOnly return simple list of names
286 * @param string $groupName group name of the label format option group
287 *
288 * @return array (reference) label format list
289 * @static
290 */
291 public static function &getList($namesOnly = FALSE, $groupName='label_format') {
292 static $list = array();
293 if (self::_getGid($groupName)) {
294 // get saved label formats from Option Value table
295 $dao = new CRM_Core_DAO_OptionValue();
296 $dao->option_group_id = self::_getGid($groupName);
297 $dao->is_active = 1;
298 $dao->orderBy('weight');
299 $dao->find();
300 while ($dao->fetch()) {
301 if ($namesOnly) {
302 $list[$groupName][$dao->name] = $dao->label;
303 }
304 else {
305 CRM_Core_DAO::storeValues($dao, $list[$groupName][$dao->id]);
306 }
307 }
308 }
309 return $list[$groupName];
310 }
311
312 /**
313 * Retrieve the default Label Format values
314 *
315 * @param string $groupName label format group name
316 *
317 * @return array Name/value pairs containing the default Label Format values.
318 * @static
319 */
320 public static function &getDefaultValues($groupName = 'label_format') {
321 $params = array('is_active' => 1, 'is_default' => 1);
322 $defaults = array();
323 if (!self::retrieve($params, $defaults, $groupName)) {
324 foreach (self::$optionValueFields as $name => $field) {
325 $defaults[$name] = $field['default'];
326 }
327 $filter = array('option_group_id' => self::_getGid($groupName));
328 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $filter);
329 }
330 return $defaults;
331 }
332
333 /**
334 * Get Label Format from the DB
335 *
336 * @param string $field Field name to search by
337 * @param int $val Field value to search for
338 *
339 * @param string $groupName
340 *
341 * @return array $values (reference) associative array of name/value pairs
342 */
343 public static function &getLabelFormat($field, $val, $groupName = 'label_format') {
344 $params = array('is_active' => 1, $field => $val);
345 $labelFormat = array();
346 if (self::retrieve($params, $labelFormat, $groupName)) {
347 return $labelFormat;
348 }
349 else {
350 return self::getDefaultValues($groupName);
351 }
352 }
353
354 /**
355 * Get Label Format by Name
356 *
357 * @param int $name Label format name. Empty = get default label format
358 *
359 * @return array $values (reference) associative array of name/value pairs
360 */
361 public static function &getByName($name) {
362 return self::getLabelFormat('name', $name);
363 }
364
365 /**
366 * Get Label Format by ID
367 *
368 * @param int $id label format id. 0 = get default label format
369 * @param string $groupName group name
370 *
371 * @return array $values (reference) associative array of name/value pairs
372 */
373 public static function &getById($id, $groupName = 'label_format') {
374 return self::getLabelFormat('id', $id, $groupName);
375 }
376
377 /**
378 * Get Label Format field from associative array
379 *
380 * @param string $field name of a label format field
381 * @param array (reference) $values associative array of name/value pairs containing
382 * label format field selections
383 *
384 * @param null $default
385 *
386 * @return value
387 * @static
388 */
389 public static function getValue($field, &$values, $default = NULL) {
390 if (array_key_exists($field, self::$optionValueFields)) {
391 switch (self::$optionValueFields[$field]['type']) {
392 case CRM_Utils_Type::T_INT:
393 return (int)CRM_Utils_Array::value($field, $values, $default);
394
395 case CRM_Utils_Type::T_FLOAT:
396 // Round float values to three decimal places and trim trailing zeros.
397 // Add a leading zero to values less than 1.
398 $f = sprintf('%05.3f', $values[$field]);
399 $f = rtrim($f, '0');
400 $f = rtrim($f, '.');
401 return (float)(empty($f) ? '0' : $f);
402 }
403 return CRM_Utils_Array::value($field, $values, $default);
404 }
405 return $default;
406 }
407
408 /**
409 * Takes a bunch of params that are needed to match certain criteria and
410 * retrieves the relevant objects. Typically the valid params are only
411 * label id. It also stores all the retrieved values in the default array.
412 *
413 * @param array $params (reference ) an assoc array of name/value pairs
414 * @param array $values (reference ) an assoc array to hold the flattened values
415 *
416 * @param string $groupName
417 *
418 * @return CRM_Core_DAO_OptionValue object
419 * @static
420 */
421 public static function retrieve(&$params, &$values, $groupName='label_format') {
422 $optionValue = new CRM_Core_DAO_OptionValue();
423 $optionValue->copyValues($params);
424 $optionValue->option_group_id = self::_getGid($groupName);
425 if ($optionValue->find(TRUE)) {
426 // Extract fields that have been serialized in the 'value' column of the Option Value table.
427 $values = json_decode($optionValue->value, TRUE);
428 // Add any new fields that don't yet exist in the saved values.
429 foreach (self::$optionValueFields as $name => $field) {
430 if (!isset($values[$name])) {
431 $values[$name] = $field['default'];
432 if ($field['metric']) {
433 $values[$name] = CRM_Utils_PDF_Utils::convertMetric($field['default'],
434 self::$optionValueFields['metric']['default'],
435 $values['metric'], 3
436 );
437 }
438 }
439 }
440 // Add fields from the OptionValue base class
441 CRM_Core_DAO::storeValues($optionValue, $values);
442 return $optionValue;
443 }
444 return NULL;
445 }
446
447 /**
448 * Return the name of the group for customized labels
449 *
450 * @param void
451 *
452 * @return void
453 */
454 public static function customGroupName() {
455 return ts('Custom');
456 }
457
458 /**
459 * Save the Label Format in the DB
460 *
461 * @param array (reference) $values associative array of name/value pairs
462 * @param int $id id of the database record (null = new record)
463 * @param string $groupName group name of the label format
464 *
465 * @return void
466 */
467 public function saveLabelFormat(&$values, $id = NULL, $groupName = 'label_format') {
468 // get the Option Group ID for Label Formats (create one if it doesn't exist)
469 $group_id = self::_getGid($groupName);
470
471 // clear other default if this is the new default label format
472 if ($values['is_default']) {
473 $query = "UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = $group_id";
474 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
475 }
476 if ($id) {
477 // fetch existing record
478 $this->id = $id;
479 if ($this->find()) {
480 $this->fetch();
481 }
482 }
483 else {
484 // new record
485 $list = self::getList(TRUE,$groupName);
486 $cnt = 1;
487 while (array_key_exists("custom_$cnt", $list)) $cnt++;
488 $values['name'] = "custom_$cnt";
489 $values['grouping'] = self::customGroupName();
490 }
491 // copy the supplied form values to the corresponding Option Value fields in the base class
492 foreach ($this->fields() as $name => $field) {
493 $this->$name = trim(CRM_Utils_Array::value($name, $values, $this->$name));
494 if (empty($this->$name)) {
495 $this->$name = 'null';
496 }
497 }
498 $this->id = $id;
499 $this->option_group_id = $group_id;
500 $this->is_active = 1;
501
502 // serialize label format fields into a single string to store in the 'value' column of the Option Value table
503 $v = json_decode($this->value, TRUE);
504 foreach (self::$optionValueFields as $name => $field) {
505 if (!isset($v[$name])) {
506 $v[$name] = NULL;
507 }
508 $v[$name] = self::getValue($name, $values, $v[$name]);
509 }
510 $this->value = json_encode($v);
511
512 // make sure serialized array will fit in the 'value' column
513 $attribute = CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat', 'value');
514 if (strlen($this->value) > $attribute['maxlength']) {
515 CRM_Core_Error::fatal(ts('Label Format does not fit in database.'));
516 }
517 $this->save();
518
519 // fix duplicate weights
520 $filter = array('option_group_id' => self::_getGid());
521 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $filter);
522 }
523
524 /**
525 * Delete a Label Format
526 *
527 * @param int $id ID of the label format to be deleted.
528 * @param string $groupName group name
529 * @static
530 */
531 public static function del($id, $groupName) {
532 if ($id) {
533 $dao = new CRM_Core_DAO_OptionValue();
534 $dao->id = $id;
535 if ($dao->find(TRUE)) {
536 if ($dao->option_group_id == self::_getGid($groupName)) {
537 $filter = array('option_group_id' => self::_getGid($groupName));
538 CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $id, $filter);
539 $dao->delete();
540 return;
541 }
542 }
543 }
544 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
545 }
546 }