Merge pull request #4654 from atif-shaikh/CRM-14840-fix
[civicrm-core.git] / CRM / Core / DAO.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 * Our base DAO class. All DAO classes should inherit from this class.
30 *
31 * @package CRM
06b69b18 32 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
33 * $Id$
34 *
35 */
36
37require_once 'PEAR.php';
38require_once 'DB/DataObject.php';
39
40require_once 'CRM/Core/I18n.php';
28518c90
EM
41
42/**
43 * Class CRM_Core_DAO
44 */
6a488035
TO
45class CRM_Core_DAO extends DB_DataObject {
46
47 /**
100fef9d 48 * A null object so we can pass it as reference if / when needed
6a488035
TO
49 */
50 static $_nullObject = NULL;
51 static $_nullArray = array();
52
53 static $_dbColumnValueCache = NULL;
54 CONST NOT_NULL = 1, IS_NULL = 2,
55 DB_DAO_NOTNULL = 128,
56 VALUE_SEPARATOR = "\ 1",
57 BULK_INSERT_COUNT = 200,
58 BULK_INSERT_HIGH_COUNT = 200,
59 // special value for mail bulk inserts to avoid
60 // potential duplication, assuming a smaller number reduces number of queries
61 // by some factor, so some tradeoff. CRM-8678
887a4028
A
62 BULK_MAIL_INSERT_COUNT = 10,
63 QUERY_FORMAT_WILDCARD = 1,
64 QUERY_FORMAT_NO_QUOTES = 2;
65
6a488035
TO
66 /*
67 * Define entities that shouldn't be created or deleted when creating/ deleting
68 * test objects - this prevents world regions, countries etc from being added / deleted
69 */
70 static $_testEntitiesToSkip = array();
71 /**
100fef9d 72 * The factory class for this application
6a488035
TO
73 * @var object
74 */
75 static $_factory = NULL;
76
aca2de91
CW
77 static $_checkedSqlFunctionsExist = FALSE;
78
6a488035
TO
79 /**
80 * Class constructor
81 *
77b97be7
EM
82 * @return \CRM_Core_DAO
83 @access public
6a488035
TO
84 */
85 function __construct() {
86 $this->initialize();
87 $this->__table = $this->getTableName();
88 }
89
90 /**
100fef9d 91 * Empty definition for virtual function
6a488035
TO
92 */
93 static function getTableName() {
94 return NULL;
95 }
96
97 /**
100fef9d 98 * Initialize the DAO object
6a488035
TO
99 *
100 * @param string $dsn the database connection string
101 *
102 * @return void
103 * @access private
104 * @static
105 */
106 static function init($dsn) {
107 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
108 $options['database'] = $dsn;
109 if (defined('CIVICRM_DAO_DEBUG')) {
110 self::DebugLevel(CIVICRM_DAO_DEBUG);
111 }
112 }
113
e1b64aab 114 /**
100fef9d 115 * @param string $fieldName
e1b64aab 116 * @param $fieldDef
c490a46a 117 * @param array $params
b3342109 118 *
e1b64aab 119 */
e79cd558 120 protected function assignTestFK($fieldName, $fieldDef, $params) {
e1b64aab
TO
121 $required = CRM_Utils_Array::value('required', $fieldDef);
122 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
123 $dbName = $fieldDef['name'];
e79cd558 124 $daoName = get_class($this);
e1b64aab
TO
125
126 // skip the FK if it is not required
127 // if it's contact id we should create even if not required
128 // we'll have a go @ fetching first though
129 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
130 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
131 $required = TRUE;
132 }
133 if (!$required && $dbName != 'contact_id') {
134 $fkDAO = new $FKClassName;
135 if ($fkDAO->find(TRUE)) {
e79cd558 136 $this->$dbName = $fkDAO->id;
e1b64aab
TO
137 }
138 unset($fkDAO);
139 }
140
141 elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) {
142 $depObject = new $FKClassName();
143 $depObject->find(TRUE);
e79cd558 144 $this->$dbName = $depObject->id;
e1b64aab
TO
145 unset($depObject);
146 }
147 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
148 // FIXME: the fields() metadata is not specific enough
149 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
e79cd558 150 $this->$dbName = $depObject->id;
e1b64aab
TO
151 unset($depObject);
152 }
153 else {
154 //if it is required we need to generate the dependency object first
155 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
e79cd558 156 $this->$dbName = $depObject->id;
e1b64aab
TO
157 unset($depObject);
158 }
159 }
160
161 /**
e79cd558
TO
162 * Generate and assign an arbitrary value to a field of a test object.
163 *
164 * @param string $fieldName
165 * @param array $fieldDef
166 * @param int $counter the globally-unique ID of the test object
e1b64aab 167 */
e79cd558
TO
168 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
169 $dbName = $fieldDef['name'];
170 $daoName = get_class($this);
e1b64aab
TO
171 $handled = FALSE;
172
e79cd558 173 if (!$handled && $dbName == 'contact_sub_type') {
e1b64aab
TO
174 //coming up with a rule to set this is too complex let's not set it
175 $handled = TRUE;
176 }
177
178 // Pick an option value if needed
179 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) {
180 $options = $daoName::buildOptions($dbName, 'create');
181 if ($options) {
e79cd558 182 $this->$dbName = key($options);
e1b64aab
TO
183 $handled = TRUE;
184 }
185 }
186
187 if (!$handled) {
188 switch ($fieldDef['type']) {
189 case CRM_Utils_Type::T_INT:
190 case CRM_Utils_Type::T_FLOAT:
191 case CRM_Utils_Type::T_MONEY:
192 if (isset($fieldDef['precision'])) {
193 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
e79cd558 194 $this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']);
e1b64aab
TO
195 }
196 else {
e79cd558 197 $this->$dbName = $counter;
e1b64aab
TO
198 }
199 break;
200
201 case CRM_Utils_Type::T_BOOLEAN:
202 if (isset($fieldDef['default'])) {
e79cd558 203 $this->$dbName = $fieldDef['default'];
e1b64aab
TO
204 }
205 elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') {
e79cd558 206 $this->$dbName = 0;
e1b64aab
TO
207 }
208 else {
e79cd558 209 $this->$dbName = 1;
e1b64aab
TO
210 }
211 break;
212
213 case CRM_Utils_Type::T_DATE:
214 case CRM_Utils_Type::T_TIMESTAMP:
215 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
e79cd558 216 $this->$dbName = '19700101';
e1b64aab
TO
217 if ($dbName == 'end_date') {
218 // put this in the future
e79cd558 219 $this->$dbName = '20200101';
e1b64aab
TO
220 }
221 break;
222
223 case CRM_Utils_Type::T_TIME:
224 CRM_Core_Error::fatal('T_TIME shouldnt be used.');
225 //$object->$dbName='000000';
226 //break;
227 case CRM_Utils_Type::T_CCNUM:
e79cd558 228 $this->$dbName = '4111 1111 1111 1111';
e1b64aab
TO
229 break;
230
231 case CRM_Utils_Type::T_URL:
e79cd558 232 $this->$dbName = 'http://www.civicrm.org';
e1b64aab
TO
233 break;
234
235 case CRM_Utils_Type::T_STRING:
236 case CRM_Utils_Type::T_BLOB:
237 case CRM_Utils_Type::T_MEDIUMBLOB:
238 case CRM_Utils_Type::T_TEXT:
239 case CRM_Utils_Type::T_LONGTEXT:
240 case CRM_Utils_Type::T_EMAIL:
241 default:
242 // WAS: if (isset($value['enumValues'])) {
243 // TODO: see if this works with all pseudoconstants
244 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
245 if (isset($fieldDef['default'])) {
e79cd558 246 $this->$dbName = $fieldDef['default'];
e1b64aab
TO
247 }
248 else {
249 $options = CRM_Core_PseudoConstant::get($daoName, $fieldName);
250 if (is_array($options)) {
e79cd558 251 $this->$dbName = $options[0];
e1b64aab
TO
252 }
253 else {
254 $defaultValues = explode(',', $options);
e79cd558 255 $this->$dbName = $defaultValues[0];
e1b64aab
TO
256 }
257 }
258 }
259 else {
e79cd558 260 $this->$dbName = $dbName . '_' . $counter;
e1b64aab 261 $maxlength = CRM_Utils_Array::value('maxlength', $fieldDef);
e79cd558
TO
262 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
263 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
e1b64aab
TO
264 }
265 }
266 }
267 }
268 }
269
6a488035 270 /**
100fef9d 271 * Reset the DAO object. DAO is kinda crappy in that there is an unwritten
6a488035
TO
272 * rule of one query per DAO. We attempt to get around this crappy restricrion
273 * by resetting some of DAO's internal fields. Use this with caution
274 *
275 * @return void
276 * @access public
277 *
278 */
279 function reset() {
280
281 foreach (array_keys($this->table()) as $field) {
282 unset($this->$field);
283 }
284
285 /**
286 * reset the various DB_DAO structures manually
287 */
288 $this->_query = array();
289 $this->whereAdd();
290 $this->selectAdd();
291 $this->joinAdd();
292 }
293
a0ee3941 294 /**
100fef9d 295 * @param string $tableName
a0ee3941
EM
296 *
297 * @return string
298 */
6a488035
TO
299 static function getLocaleTableName($tableName) {
300 global $dbLocale;
301 if ($dbLocale) {
302 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
303 if (in_array($tableName, $tables)) {
304 return $tableName . $dbLocale;
305 }
306 }
307 return $tableName;
308 }
309
310 /**
311 * Execute a query by the current DAO, localizing it along the way (if needed).
312 *
313 * @param string $query the SQL query for execution
314 * @param bool $i18nRewrite whether to rewrite the query
315 *
316 * @return object the current DAO object after the query execution
317 */
318 function query($query, $i18nRewrite = TRUE) {
319 // rewrite queries that should use $dbLocale-based views for multi-language installs
320 global $dbLocale;
321 if ($i18nRewrite and $dbLocale) {
322 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
323 }
324
325 return parent::query($query);
326 }
327
328 /**
329 * Static function to set the factory instance for this class.
330 *
331 * @param object $factory the factory application object
332 *
333 * @return void
334 * @access public
335 * @static
336 */
337 static function setFactory(&$factory) {
338 self::$_factory = &$factory;
339 }
340
341 /**
342 * Factory method to instantiate a new object from a table name.
343 *
da6b46f4
EM
344 * @param string $table
345 *
6a488035
TO
346 * @return void
347 * @access public
348 */
349 function factory($table = '') {
350 if (!isset(self::$_factory)) {
351 return parent::factory($table);
352 }
353
354 return self::$_factory->create($table);
355 }
356
357 /**
358 * Initialization for all DAO objects. Since we access DB_DO programatically
359 * we need to set the links manually.
360 *
361 * @return void
362 * @access protected
363 */
364 function initialize() {
6a488035 365 $this->_connect();
086c354c 366 $this->query("SET NAMES utf8");
6a488035
TO
367 }
368
369 /**
370 * Defines the default key as 'id'.
371 *
372 * @access protected
373 *
374 * @return array
375 */
376 function keys() {
377 static $keys;
378 if (!isset($keys)) {
379 $keys = array('id');
380 }
381 return $keys;
382 }
383
384 /**
385 * Tells DB_DataObject which keys use autoincrement.
386 * 'id' is autoincrementing by default.
387 *
388 * @access protected
389 *
390 * @return array
391 */
392 function sequenceKey() {
393 static $sequenceKeys;
394 if (!isset($sequenceKeys)) {
395 $sequenceKeys = array('id', TRUE);
396 }
397 return $sequenceKeys;
398 }
399
400 /**
100fef9d 401 * Returns list of FK relationships
6a488035 402 *
71e5aa5c 403 * @static
6a488035
TO
404 * @access public
405 *
11626cf1 406 * @return array of CRM_Core_Reference_Interface
6a488035 407 */
71e5aa5c
ARW
408 static function getReferenceColumns() {
409 return array();
6a488035
TO
410 }
411
412 /**
100fef9d 413 * Returns all the column names of this table
6a488035
TO
414 *
415 * @access public
416 *
417 * @return array
418 */
419 static function &fields() {
420 $result = NULL;
421 return $result;
422 }
423
b5c2afd0 424 /**
100fef9d 425 * Get/set an associative array of table columns
b5c2afd0
EM
426 *
427 * @access public
428 * @param array key=>type array
429 * @return array (associative)
430 */
6a488035
TO
431 function table() {
432 $fields = &$this->fields();
433
434 $table = array();
435 if ($fields) {
436 foreach ($fields as $name => $value) {
437 $table[$value['name']] = $value['type'];
a7488080 438 if (!empty($value['required'])) {
6a488035
TO
439 $table[$value['name']] += self::DB_DAO_NOTNULL;
440 }
441 }
442 }
443
6a488035
TO
444 return $table;
445 }
446
a0ee3941
EM
447 /**
448 * @return $this
449 */
6a488035
TO
450 function save() {
451 if (!empty($this->id)) {
452 $this->update();
8498c2b7 453
454 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
455 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
6a488035
TO
456 }
457 else {
458 $this->insert();
8498c2b7 459
460 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
461 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
6a488035
TO
462 }
463 $this->free();
464
465 CRM_Utils_Hook::postSave($this);
466
467 return $this;
468 }
469
97c4fe76 470 function delete($useWhere = FALSE) {
471 $result = parent::delete($useWhere);
8498c2b7 472
48d849b1 473 $event = new \Civi\Core\DAO\Event\PostDelete($this, $result);
8498c2b7 474 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
475
97c4fe76 476 return $result;
477 }
478
a0ee3941
EM
479 /**
480 * @param bool $created
481 */
6a488035
TO
482 function log($created = FALSE) {
483 static $cid = NULL;
484
485 if (!$this->getLog()) {
486 return;
487 }
488
489 if (!$cid) {
490 $session = CRM_Core_Session::singleton();
491 $cid = $session->get('userID');
492 }
493
494 // return is we dont have handle to FK
495 if (!$cid) {
496 return;
497 }
498
499 $dao = new CRM_Core_DAO_Log();
500 $dao->entity_table = $this->getTableName();
501 $dao->entity_id = $this->id;
502 $dao->modified_id = $cid;
503 $dao->modified_date = date("YmdHis");
504 $dao->insert();
505 }
506
507 /**
508 * Given an associative array of name/value pairs, extract all the values
509 * that belong to this object and initialize the object with said values
510 *
511 * @param array $params (reference ) associative array of name/value pairs
512 *
513 * @return boolean did we copy all null values into the object
514 * @access public
515 */
516 function copyValues(&$params) {
517 $fields = &$this->fields();
518 $allNull = TRUE;
519 foreach ($fields as $name => $value) {
520 $dbName = $value['name'];
521 if (array_key_exists($dbName, $params)) {
522 $pValue = $params[$dbName];
523 $exists = TRUE;
524 }
525 elseif (array_key_exists($name, $params)) {
526 $pValue = $params[$name];
527 $exists = TRUE;
528 }
529 else {
530 $exists = FALSE;
531 }
532
533 // if there is no value then make the variable NULL
534 if ($exists) {
535 if ($pValue === '') {
536 $this->$dbName = 'null';
537 }
538 else {
539 $this->$dbName = $pValue;
540 $allNull = FALSE;
541 }
542 }
543 }
544 return $allNull;
545 }
546
547 /**
548 * Store all the values from this object in an associative array
549 * this is a destructive store, calling function is responsible
550 * for keeping sanity of id's.
551 *
552 * @param object $object the object that we are extracting data from
553 * @param array $values (reference ) associative array of name/value pairs
554 *
555 * @return void
556 * @access public
557 * @static
558 */
559 static function storeValues(&$object, &$values) {
560 $fields = &$object->fields();
561 foreach ($fields as $name => $value) {
562 $dbName = $value['name'];
563 if (isset($object->$dbName) && $object->$dbName !== 'null') {
564 $values[$dbName] = $object->$dbName;
565 if ($name != $dbName) {
566 $values[$name] = $object->$dbName;
567 }
568 }
569 }
570 }
571
572 /**
100fef9d 573 * Create an attribute for this specific field. We only do this for strings and text
6a488035
TO
574 *
575 * @param array $field the field under task
576 *
577 * @return array|null the attributes for the object
578 * @access public
579 * @static
580 */
581 static function makeAttribute($field) {
582 if ($field) {
583 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
584 $maxLength = CRM_Utils_Array::value('maxlength', $field);
585 $size = CRM_Utils_Array::value('size', $field);
586 if ($maxLength || $size) {
587 $attributes = array();
588 if ($maxLength) {
589 $attributes['maxlength'] = $maxLength;
590 }
591 if ($size) {
592 $attributes['size'] = $size;
593 }
594 return $attributes;
595 }
596 }
597 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
598 $rows = CRM_Utils_Array::value('rows', $field);
599 if (!isset($rows)) {
600 $rows = 2;
601 }
602 $cols = CRM_Utils_Array::value('cols', $field);
603 if (!isset($cols)) {
604 $cols = 80;
605 }
606
607 $attributes = array();
608 $attributes['rows'] = $rows;
609 $attributes['cols'] = $cols;
610 return $attributes;
611 }
612 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_INT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_FLOAT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_MONEY) {
613 $attributes['size'] = 6;
614 $attributes['maxlength'] = 14;
615 return $attributes;
616 }
617 }
618 return NULL;
619 }
620
621 /**
622 * Get the size and maxLength attributes for this text field
623 * (or for all text fields) in the DAO object.
624 *
625 * @param string $class name of DAO class
626 * @param string $fieldName field that i'm interested in or null if
627 * you want the attributes for all DAO text fields
628 *
629 * @return array assoc array of name => attribute pairs
630 * @access public
631 * @static
632 */
633 static function getAttribute($class, $fieldName = NULL) {
634 $object = new $class( );
635 $fields = &$object->fields();
636 if ($fieldName != NULL) {
637 $field = CRM_Utils_Array::value($fieldName, $fields);
638 return self::makeAttribute($field);
639 }
640 else {
641 $attributes = array();
642 foreach ($fields as $name => $field) {
643 $attribute = self::makeAttribute($field);
644 if ($attribute) {
645 $attributes[$name] = $attribute;
646 }
647 }
648
649 if (!empty($attributes)) {
650 return $attributes;
651 }
652 }
653 return NULL;
654 }
655
a0ee3941
EM
656 /**
657 * @param $type
658 *
659 * @throws Exception
660 */
6a488035
TO
661 static function transaction($type) {
662 CRM_Core_Error::fatal('This function is obsolete, please use CRM_Core_Transaction');
663 }
664
665 /**
666 * Check if there is a record with the same name in the db
667 *
668 * @param string $value the value of the field we are checking
669 * @param string $daoName the dao object name
670 * @param string $daoID the id of the object being updated. u can change your name
671 * as long as there is no conflict
672 * @param string $fieldName the name of the field in the DAO
673 *
674 * @return boolean true if object exists
675 * @access public
676 * @static
677 */
678 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
679 $object = new $daoName( );
680 $object->$fieldName = $value;
681
682 $config = CRM_Core_Config::singleton();
683
684 if ($object->find(TRUE)) {
685 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
686 }
687 else {
688 return TRUE;
689 }
690 }
691
692 /**
693 * Check if there is a given column in a specific table
694 *
695 * @param string $tableName
696 * @param string $columnName
697 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
698 *
699 * @return boolean true if exists, else false
700 * @static
701 */
702 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
703 $query = "
704SHOW COLUMNS
705FROM $tableName
706LIKE %1
707";
708 $params = array(1 => array($columnName, 'String'));
709 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
710 $result = $dao->fetch() ? TRUE : FALSE;
711 $dao->free();
712 return $result;
713 }
714
715 /**
716 * Returns the storage engine used by given table-name(optional).
717 * Otherwise scans all the tables and return an array of all the
718 * distinct storage engines being used.
719 *
720 * @param string $tableName
721 *
2a6da8d7
EM
722 * @param int $maxTablesToCheck
723 * @param string $fieldName
724 *
6a488035
TO
725 * @return array
726 * @static
727 */
728 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
729 $values = array();
730 $query = "SHOW TABLE STATUS LIKE %1";
731
732 $params = array();
733
734 if (isset($tableName)) {
735 $params = array(1 => array($tableName, 'String'));
736 }
737 else {
738 $params = array(1 => array('civicrm_%', 'String'));
739 }
740
741 $dao = CRM_Core_DAO::executeQuery($query, $params);
742
743 $count = 0;
744 while ($dao->fetch()) {
745 if (isset($values[$dao->$fieldName]) ||
746 // ignore import and other temp tables
747 strpos($dao->Name, 'civicrm_import_job_') !== FALSE ||
748 strpos($dao->Name, '_temp') !== FALSE
749 ) {
750 continue;
751 }
752 $values[$dao->$fieldName] = 1;
753 $count++;
754 if ($maxTablesToCheck &&
755 $count >= $maxTablesToCheck
756 ) {
757 break;
758 }
759 }
760 $dao->free();
761 return $values;
762 }
763
a0ee3941
EM
764 /**
765 * @param int $maxTablesToCheck
766 *
767 * @return bool
768 */
6a488035
TO
769 static function isDBMyISAM($maxTablesToCheck = 10) {
770 // show error if any of the tables, use 'MyISAM' storage engine.
771 $engines = self::getStorageValues(NULL, $maxTablesToCheck);
772 if (array_key_exists('MyISAM', $engines)) {
773 return TRUE;
774 }
775 return FALSE;
776 }
777
778 /**
779 * Checks if a constraint exists for a specified table.
780 *
781 * @param string $tableName
782 * @param string $constraint
783 *
784 * @return boolean true if constraint exists, false otherwise
785 * @static
786 */
787 static function checkConstraintExists($tableName, $constraint) {
788 static $show = array();
789
790 if (!array_key_exists($tableName, $show)) {
791 $query = "SHOW CREATE TABLE $tableName";
792 $dao = CRM_Core_DAO::executeQuery($query);
793
794 if (!$dao->fetch()) {
795 CRM_Core_Error::fatal();
796 }
797
798 $dao->free();
799 $show[$tableName] = $dao->Create_Table;
800 }
801
802 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
803 }
804
805 /**
806 * Checks if CONSTRAINT keyword exists for a specified table.
807 *
2a6da8d7
EM
808 * @param array $tables
809 *
810 * @throws Exception
6a488035
TO
811 *
812 * @return boolean true if CONSTRAINT keyword exists, false otherwise
813 */
f59b722f 814 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
6a488035
TO
815 $show = array();
816 foreach($tables as $tableName){
817 if (!array_key_exists($tableName, $show)) {
818 $query = "SHOW CREATE TABLE $tableName";
819 $dao = CRM_Core_DAO::executeQuery($query);
820
821 if (!$dao->fetch()) {
822 CRM_Core_Error::fatal();
823 }
824
825 $dao->free();
826 $show[$tableName] = $dao->Create_Table;
827 }
828
829 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ? TRUE : FALSE;
c490a46a 830 if ($result == TRUE){
6a488035
TO
831 continue;
832 }
c490a46a 833 else {
6a488035
TO
834 return FALSE;
835 }
836 }
837 return TRUE;
838 }
839
840 /**
841 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
842 * for a specified column of a table.
843 *
844 * @param string $tableName
845 * @param string $columnName
846 *
847 * @return boolean true if in format, false otherwise
848 * @static
849 */
850 static function checkFKConstraintInFormat($tableName, $columnName) {
851 static $show = array();
852
853 if (!array_key_exists($tableName, $show)) {
854 $query = "SHOW CREATE TABLE $tableName";
855 $dao = CRM_Core_DAO::executeQuery($query);
856
857 if (!$dao->fetch()) {
858 CRM_Core_Error::fatal();
859 }
860
861 $dao->free();
862 $show[$tableName] = $dao->Create_Table;
863 }
864 $constraint = "`FK_{$tableName}_{$columnName}`";
865 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
866 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ? TRUE : FALSE;
867 }
868
869 /**
870 * Check whether a specific column in a specific table has always the same value
871 *
872 * @param string $tableName
873 * @param string $columnName
874 * @param string $columnValue
875 *
876 * @return boolean true if the value is always $columnValue, false otherwise
877 * @static
878 */
879 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
880 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
881 $dao = CRM_Core_DAO::executeQuery($query);
882 $result = $dao->fetch() ? FALSE : TRUE;
883 $dao->free();
884 return $result;
885 }
886
887 /**
888 * Check whether a specific column in a specific table is always NULL
889 *
890 * @param string $tableName
891 * @param string $columnName
892 *
893 * @return boolean true if if the value is always NULL, false otherwise
894 * @static
895 */
896 static function checkFieldIsAlwaysNull($tableName, $columnName) {
897 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
898 $dao = CRM_Core_DAO::executeQuery($query);
899 $result = $dao->fetch() ? FALSE : TRUE;
900 $dao->free();
901 return $result;
902 }
903
904 /**
905 * Check if there is a given table in the database
906 *
907 * @param string $tableName
908 *
909 * @return boolean true if exists, else false
910 * @static
911 */
912 static function checkTableExists($tableName) {
913 $query = "
914SHOW TABLES
915LIKE %1
916";
917 $params = array(1 => array($tableName, 'String'));
918
919 $dao = CRM_Core_DAO::executeQuery($query, $params);
920 $result = $dao->fetch() ? TRUE : FALSE;
921 $dao->free();
922 return $result;
923 }
924
a0ee3941
EM
925 /**
926 * @param $version
927 *
928 * @return bool
929 */
6a488035
TO
930 function checkVersion($version) {
931 $query = "
932SELECT version
933FROM civicrm_domain
934";
935 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
936 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
937 }
938
939 /**
940 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
941 *
942 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
943 * @param int $searchValue Value of the column you want to search by
944 * @param string $returnColumn Name of the column you want to GET the value of
945 * @param string $searchColumn Name of the column you want to search by
946 * @param boolean $force Skip use of the cache
947 *
948 * @return string|null Value of $returnColumn in the retrieved record
949 * @static
950 * @access public
951 */
032c9d10 952 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
6a488035
TO
953 if (
954 empty($searchValue) ||
955 trim(strtolower($searchValue)) == 'null'
956 ) {
957 // adding this year since developers forget to check for an id
958 // or for the 'null' (which is a bad DAO kludge)
959 // and hence we get the first value in the db
960 CRM_Core_Error::fatal();
961 }
962
963 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
964 if (self::$_dbColumnValueCache === NULL) {
965 self::$_dbColumnValueCache = array();
966 }
967
968 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
969 $object = new $daoName( );
970 $object->$searchColumn = $searchValue;
971 $object->selectAdd();
972 $object->selectAdd($returnColumn);
973
974 $result = NULL;
975 if ($object->find(TRUE)) {
976 $result = $object->$returnColumn;
977 }
978 $object->free();
979
980 self::$_dbColumnValueCache[$cacheKey] = $result;
981 }
982 return self::$_dbColumnValueCache[$cacheKey];
983 }
984
985 /**
986 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
987 *
988 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
989 * @param int $searchValue Value of the column you want to search by
990 * @param string $setColumn Name of the column you want to SET the value of
991 * @param string $setValue SET the setColumn to this value
992 * @param string $searchColumn Name of the column you want to search by
993 *
994 * @return boolean true if we found and updated the object, else false
995 * @static
996 * @access public
997 */
998 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
999 $object = new $daoName( );
1000 $object->selectAdd();
1001 $object->selectAdd("$searchColumn, $setColumn");
1002 $object->$searchColumn = $searchValue;
1003 $result = FALSE;
1004 if ($object->find(TRUE)) {
1005 $object->$setColumn = $setValue;
1006 if ($object->save()) {
1007 $result = TRUE;
1008 }
1009 }
1010 $object->free();
1011 return $result;
1012 }
1013
1014 /**
1015 * Get sort string
1016 *
1017 * @param array|object $sort either array or CRM_Utils_Sort
1018 * @param string $default - default sort value
1019 *
1020 * @return string - sortString
1021 * @access public
1022 * @static
1023 */
1024 static function getSortString($sort, $default = NULL) {
1025 // check if sort is of type CRM_Utils_Sort
1026 if (is_a($sort, 'CRM_Utils_Sort')) {
1027 return $sort->orderBy();
1028 }
1029
1030 // is it an array specified as $field => $sortDirection ?
1031 if ($sort) {
1032 foreach ($sort as $k => $v) {
1033 $sortString .= "$k $v,";
1034 }
1035 return rtrim($sortString, ',');
1036 }
1037 return $default;
1038 }
1039
1040 /**
c490a46a 1041 * Fetch object based on array of properties
6a488035
TO
1042 *
1043 * @param string $daoName name of the dao object
1044 * @param array $params (reference ) an assoc array of name/value pairs
1045 * @param array $defaults (reference ) an assoc array to hold the flattened values
1046 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1047 *
1048 * @return object an object of type referenced by daoName
1049 * @access public
1050 * @static
1051 */
1052 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1053 $object = new $daoName( );
1054 $object->copyValues($params);
1055
1056 // return only specific fields if returnproperties are sent
1057 if (!empty($returnProperities)) {
1058 $object->selectAdd();
1059 $object->selectAdd(implode(',', $returnProperities));
1060 }
1061
1062 if ($object->find(TRUE)) {
1063 self::storeValues($object, $defaults);
1064 return $object;
1065 }
1066 return NULL;
1067 }
1068
1069 /**
1070 * Delete the object records that are associated with this contact
1071 *
1072 * @param string $daoName name of the dao object
1073 * @param int $contactId id of the contact to delete
1074 *
1075 * @return void
1076 * @access public
1077 * @static
1078 */
1079 static function deleteEntityContact($daoName, $contactId) {
1080 $object = new $daoName( );
1081
1082 $object->entity_table = 'civicrm_contact';
1083 $object->entity_id = $contactId;
1084 $object->delete();
1085 }
1086
1087 /**
100fef9d 1088 * Execute a query
6a488035
TO
1089 *
1090 * @param string $query query to be executed
1091 *
2a6da8d7
EM
1092 * @param array $params
1093 * @param bool $abort
1094 * @param null $daoName
1095 * @param bool $freeDAO
1096 * @param bool $i18nRewrite
1097 * @param bool $trapException
1098 *
c490a46a 1099 * @return CRM_Core_DAO object that holds the results of the query
6a488035
TO
1100 * @static
1101 * @access public
1102 */
1103 static function &executeQuery(
1104 $query,
1105 $params = array(),
1106 $abort = TRUE,
1107 $daoName = NULL,
1108 $freeDAO = FALSE,
1109 $i18nRewrite = TRUE,
1110 $trapException = FALSE
1111 ) {
1112 $queryStr = self::composeQuery($query, $params, $abort);
6a488035
TO
1113
1114 if (!$daoName) {
1115 $dao = new CRM_Core_DAO();
1116 }
1117 else {
1118 $dao = new $daoName( );
1119 }
1120
1121 if ($trapException) {
6a4257d4 1122 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1123 }
1124
1125 $result = $dao->query($queryStr, $i18nRewrite);
1126
6a488035
TO
1127 if (is_a($result, 'DB_Error')) {
1128 return $result;
1129 }
1130
1131 if ($freeDAO ||
1132 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1133 ) {
1134 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1135 // free the dao
1136 $dao->free();
1137 }
1138 return $dao;
1139 }
1140
1141 /**
100fef9d 1142 * Execute a query and get the single result
6a488035
TO
1143 *
1144 * @param string $query query to be executed
e869b07d
CW
1145 * @param array $params
1146 * @param bool $abort
1147 * @param bool $i18nRewrite
1148 * @return string|null the result of the query if any
6a488035 1149 *
6a488035
TO
1150 * @static
1151 * @access public
1152 */
1153 static function &singleValueQuery($query,
1154 $params = array(),
1155 $abort = TRUE,
1156 $i18nRewrite = TRUE
1157 ) {
1158 $queryStr = self::composeQuery($query, $params, $abort);
1159
1160 static $_dao = NULL;
1161
1162 if (!$_dao) {
1163 $_dao = new CRM_Core_DAO();
1164 }
1165
1166 $_dao->query($queryStr, $i18nRewrite);
1167
1168 $result = $_dao->getDatabaseResult();
1169 $ret = NULL;
1170 if ($result) {
1171 $row = $result->fetchRow();
1172 if ($row) {
1173 $ret = $row[0];
1174 }
1175 }
1176 $_dao->free();
1177 return $ret;
1178 }
1179
a0ee3941
EM
1180 /**
1181 * @param $query
c490a46a 1182 * @param array $params
a0ee3941
EM
1183 * @param bool $abort
1184 *
1185 * @return string
1186 * @throws Exception
1187 */
6a488035
TO
1188 static function composeQuery($query, &$params, $abort = TRUE) {
1189 $tr = array();
1190 foreach ($params as $key => $item) {
1191 if (is_numeric($key)) {
1192 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
1193 $item[0] = self::escapeString($item[0]);
1194 if ($item[1] == 'String' ||
1195 $item[1] == 'Memo' ||
1196 $item[1] == 'Link'
1197 ) {
887a4028
A
1198 // Support class constants stipulating wildcard characters and/or
1199 // non-quoting of strings. Also support legacy code which may be
1200 // passing in TRUE or 1 for $item[2], which used to indicate the
1201 // use of wildcard characters.
1202 if (!empty($item[2])) {
1203 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
1204 $item[0] = "'%{$item[0]}%'";
1205 }
1206 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
1207 $item[0] = "'{$item[0]}'";
1208 }
6a488035
TO
1209 }
1210 else {
1211 $item[0] = "'{$item[0]}'";
1212 }
1213 }
1214
1215 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
1216 strlen($item[0]) == 0
1217 ) {
1218 $item[0] = 'null';
1219 }
1220
1221 $tr['%' . $key] = $item[0];
1222 }
1223 elseif ($abort) {
1224 CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}");
1225 }
1226 }
1227 }
1228
e2508c90 1229 return strtr($query, $tr);
6a488035
TO
1230 }
1231
a0ee3941
EM
1232 /**
1233 * @param null $ids
1234 */
6a488035
TO
1235 static function freeResult($ids = NULL) {
1236 global $_DB_DATAOBJECT;
1237
6a488035
TO
1238 if (!$ids) {
1239 if (!$_DB_DATAOBJECT ||
1240 !isset($_DB_DATAOBJECT['RESULTS'])
1241 ) {
1242 return;
1243 }
1244 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1245 }
1246
1247 foreach ($ids as $id) {
1248 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1249 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result)) {
1250 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result);
1251 }
1252 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1253 }
1254
1255 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1256 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1257 }
1258 }
1259 }
1260
1261 /**
1262 * This function is to make a shallow copy of an object
1263 * and all the fields in the object
1264 *
1265 * @param string $daoName name of the dao
1266 * @param array $criteria array of all the fields & values
1267 * on which basis to copy
1268 * @param array $newData array of all the fields & values
1269 * to be copied besides the other fields
1270 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1271 * @param string $blockCopyOfDependencies fields that you want to block from
1272 * getting copied
1273 *
1274 *
1275 * @return (reference ) the newly created copy of the object
1276 * @access public
1277 */
1278 static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1279 $object = new $daoName( );
1280 if (!$newData) {
1281 $object->id = $criteria['id'];
1282 }
1283 else {
1284 foreach ($criteria as $key => $value) {
1285 $object->$key = $value;
1286 }
1287 }
1288
1289 $object->find();
1290 while ($object->fetch()) {
1291
1292 // all the objects except with $blockCopyOfDependencies set
1293 // be copied - addresses #CRM-1962
1294
1295 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1296 break;
1297 }
1298
1299 $newObject = new $daoName( );
1300
1301 $fields = &$object->fields();
1302 if (!is_array($fieldsFix)) {
1303 $fieldsToPrefix = array();
1304 $fieldsToSuffix = array();
1305 $fieldsToReplace = array();
1306 }
a7488080 1307 if (!empty($fieldsFix['prefix'])) {
6a488035
TO
1308 $fieldsToPrefix = $fieldsFix['prefix'];
1309 }
a7488080 1310 if (!empty($fieldsFix['suffix'])) {
6a488035
TO
1311 $fieldsToSuffix = $fieldsFix['suffix'];
1312 }
a7488080 1313 if (!empty($fieldsFix['replace'])) {
6a488035
TO
1314 $fieldsToReplace = $fieldsFix['replace'];
1315 }
1316
1317 foreach ($fields as $name => $value) {
1318 if ($name == 'id' || $value['name'] == 'id') {
1319 // copy everything but the id!
1320 continue;
1321 }
1322
1323 $dbName = $value['name'];
a1305c92 1324 $type = CRM_Utils_Type::typeToString($value['type']);
6a488035
TO
1325 $newObject->$dbName = $object->$dbName;
1326 if (isset($fieldsToPrefix[$dbName])) {
1327 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1328 }
1329 if (isset($fieldsToSuffix[$dbName])) {
1330 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1331 }
1332 if (isset($fieldsToReplace[$dbName])) {
1333 $newObject->$dbName = $fieldsToReplace[$dbName];
1334 }
1335
6c71f6c7 1336 if ($type == 'Timestamp' || $type == 'Date') {
6a488035
TO
1337 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1338 }
1339
1340 if ($newData) {
1341 foreach ($newData as $k => $v) {
1342 $newObject->$k = $v;
1343 }
1344 }
1345 }
1346 $newObject->save();
1347 }
1348 return $newObject;
1349 }
1350
62933949 1351 static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1352 $object = new $daoName( );
1353 $object->id = $fromId;
1354
1355 if ($object->find(TRUE)) {
1356 $newObject = new $daoName( );
1357 $newObject->id = $toId;
1358
1359 if ($newObject->find(TRUE)) {
1360 $fields = &$object->fields();
1361 foreach ($fields as $name => $value) {
1362 if ($name == 'id' || $value['name'] == 'id') {
1363 // copy everything but the id!
1364 continue;
1365 }
1366
1367 $colName = $value['name'];
1368 $newObject->$colName = $object->$colName;
1369
1370 if (substr($name, -5) == '_date' ||
1371 substr($name, -10) == '_date_time'
1372 ) {
1373 $newObject->$colName = CRM_Utils_Date::isoToMysql($newObject->$colName);
1374 }
1375 }
1376 foreach ($newData as $k => $v) {
1377 $newObject->$k = $v;
1378 }
1379 $newObject->save();
1380 return $newObject;
1381 }
1382 }
1383 return CRM_Core_DAO::$_nullObject;
1384 }
1385
6a488035
TO
1386 /**
1387 * Given the component id, compute the contact id
1388 * since its used for things like send email
b3342109
EM
1389 *
1390 * @param $componentIDs
100fef9d 1391 * @param string $tableName
b3342109
EM
1392 *
1393 * @return array
6a488035 1394 */
a5611c8e 1395 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
6a488035
TO
1396 $contactIDs = array();
1397
1398 if (empty($componentIDs)) {
1399 return $contactIDs;
1400 }
1401
1402 $IDs = implode(',', $componentIDs);
1403 $query = "
1404SELECT contact_id
1405 FROM $tableName
1406 WHERE id IN ( $IDs )
1407";
1408
1409 $dao = CRM_Core_DAO::executeQuery($query);
1410 while ($dao->fetch()) {
1411 $contactIDs[] = $dao->contact_id;
1412 }
1413 return $contactIDs;
1414 }
1415
1416 /**
c490a46a 1417 * Fetch object based on array of properties
6a488035 1418 *
dd244018
EM
1419 * @param string $daoName name of the dao object
1420 * @param string $fieldIdName
100fef9d 1421 * @param int $fieldId
dd244018
EM
1422 * @param $details
1423 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1424 *
6a488035
TO
1425 * @return object an object of type referenced by daoName
1426 * @access public
1427 * @static
1428 */
1429 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1430 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
1431 $object = new $daoName( );
1432 $object->$fieldIdName = $fieldId;
1433
1434 // return only specific fields if returnproperties are sent
1435 if (!empty($returnProperities)) {
1436 $object->selectAdd();
1437 $object->selectAdd('id');
1438 $object->selectAdd(implode(',', $returnProperities));
1439 }
1440
1441 $object->find();
1442 while ($object->fetch()) {
1443 $defaults = array();
1444 self::storeValues($object, $defaults);
1445 $details[$object->id] = $defaults;
1446 }
1447
1448 return $details;
1449 }
1450
1451 static function dropAllTables() {
1452
1453 // first drop all the custom tables we've created
1454 CRM_Core_BAO_CustomGroup::dropAllTables();
1455
1456 // drop all multilingual views
1457 CRM_Core_I18n_Schema::dropAllViews();
1458
1459 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1460 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1461 '..' . DIRECTORY_SEPARATOR .
1462 '..' . DIRECTORY_SEPARATOR .
1463 'sql' . DIRECTORY_SEPARATOR .
1464 'civicrm_drop.mysql'
1465 );
1466 }
1467
a0ee3941
EM
1468 /**
1469 * @param $string
1470 *
1471 * @return string
1472 */
6a488035
TO
1473 static function escapeString($string) {
1474 static $_dao = NULL;
1475
1476 if (!$_dao) {
74032946
TO
1477 // If this is an atypical case (e.g. preparing .sql files
1478 // before Civi has been installed), then we fallback to
1479 // DB-less escaping helper (mysql_real_escape_string).
1480 // Note: In typical usage, escapeString() will only
1481 // check one conditional ("if !$_dao") rather than
1482 // two conditionals ("if !defined(DSN)")
1483 if (!defined('CIVICRM_DSN')) {
1484 if (function_exists('mysql_real_escape_string')) {
1485 return mysql_real_escape_string($string);
1486 } else {
1487 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1488 }
1489 }
1490
6a488035
TO
1491 $_dao = new CRM_Core_DAO();
1492 }
1493
1494 return $_dao->escape($string);
1495 }
1496
1497 /**
1498 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1499 *
1500 * @param $strings array
1501 * @param $default string the value to use if $strings has no elements
1502 * @return string eg "abc","def","ghi"
1503 */
1504 static function escapeStrings($strings, $default = NULL) {
1505 static $_dao = NULL;
1506 if (!$_dao) {
1507 $_dao = new CRM_Core_DAO();
1508 }
1509
1510 if (empty($strings)) {
1511 return $default;
1512 }
1513
1514 $escapes = array_map(array($_dao, 'escape'), $strings);
1515 return '"' . implode('","', $escapes) . '"';
1516 }
1517
a0ee3941
EM
1518 /**
1519 * @param $string
1520 *
1521 * @return string
1522 */
6a488035
TO
1523 static function escapeWildCardString($string) {
1524 // CRM-9155
1525 // ensure we escape the single characters % and _ which are mysql wild
1526 // card characters and could come in via sortByCharacter
1527 // note that mysql does not escape these characters
1528 if ($string && in_array($string,
1529 array('%', '_', '%%', '_%')
1530 )) {
1531 return '\\' . $string;
1532 }
1533
1534 return self::escapeString($string);
1535 }
1536
92b83508
EM
1537 /**
1538 * Creates a test object, including any required objects it needs via recursion
b3342109
EM
1539 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1540 * ONLY USE FOR TESTING
1541 *
c490a46a 1542 * @param string $daoName
b3342109
EM
1543 * @param array $params
1544 * @param int $numObjects
1545 * @param bool $createOnly
1546 *
1547 * @return
92b83508 1548 */
6a488035
TO
1549 static function createTestObject(
1550 $daoName,
1551 $params = array(),
1552 $numObjects = 1,
1553 $createOnly = FALSE
1554 ) {
b6262a4c
EM
1555 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1556 // so we re-set here in case
1557 $config = CRM_Core_Config::singleton();
1558 $config->backtrace = TRUE;
1559
6a488035
TO
1560 static $counter = 0;
1561 CRM_Core_DAO::$_testEntitiesToSkip = array(
1562 'CRM_Core_DAO_Worldregion',
1563 'CRM_Core_DAO_StateProvince',
1564 'CRM_Core_DAO_Country',
1565 'CRM_Core_DAO_Domain',
806e9b71 1566 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
6a488035
TO
1567 );
1568
6a488035
TO
1569 for ($i = 0; $i < $numObjects; ++$i) {
1570
1571 ++$counter;
e79cd558 1572 /** @var CRM_Core_DAO $object */
ab9aa379 1573 $object = new $daoName();
6a488035 1574
f290b6ef 1575 $fields = & $object->fields();
e1b64aab
TO
1576 foreach ($fields as $fieldName => $fieldDef) {
1577 $dbName = $fieldDef['name'];
f290b6ef 1578 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
e1b64aab 1579 $required = CRM_Utils_Array::value('required', $fieldDef);
f290b6ef 1580
6a488035
TO
1581 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1582 $object->$dbName = $params[$dbName];
1583 }
1584
1585 elseif ($dbName != 'id') {
f290b6ef 1586 if ($FKClassName != NULL) {
e79cd558 1587 $object->assignTestFK($fieldName, $fieldDef, $params);
6a488035 1588 continue;
f290b6ef
TO
1589 } else {
1590 $object->assignTestValue($fieldName, $fieldDef, $counter);
6a488035 1591 }
6a488035
TO
1592 }
1593 }
b3342109 1594
6a488035
TO
1595 $object->save();
1596
1597 if (!$createOnly) {
6a488035 1598 $objects[$i] = $object;
6a488035 1599 }
f290b6ef
TO
1600 else {
1601 unset($object);
1602 }
6a488035
TO
1603 }
1604
1605 if ($createOnly) {
6a488035 1606 return;
6a488035 1607 }
f290b6ef
TO
1608 elseif ($numObjects == 1) {
1609 return $objects[0];
1610 }
1611 else {
1612 return $objects;
1613 }
6a488035
TO
1614 }
1615
92b83508 1616 /**
100fef9d 1617 * Deletes the this object plus any dependent objects that are associated with it
92b83508 1618 * ONLY USE FOR TESTING
b3342109 1619 *
c490a46a 1620 * @param string $daoName
b3342109 1621 * @param array $params
92b83508 1622 */
c490a46a 1623 static function deleteTestObjects($daoName, $params = array()) {
b6262a4c
EM
1624 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1625 // so we re-set here in case
1626 $config = CRM_Core_Config::singleton();
1627 $config->backtrace = TRUE;
6a488035 1628
b6262a4c 1629 $object = new $daoName();
6a488035
TO
1630 $object->id = CRM_Utils_Array::value('id', $params);
1631
1632 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1633 if ($object->find(TRUE)) {
1634
1635 $fields = &$object->fields();
1636 foreach ($fields as $name => $value) {
1637
1638 $dbName = $value['name'];
1639
1640 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1641 $required = CRM_Utils_Array::value('required', $value);
1642 if ($FKClassName != NULL
1643 && $object->$dbName
1644 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
806e9b71
EM
1645 && ($required || $dbName == 'contact_id')
1646 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1647 // to make this test process pass - line below makes pass for now
1648 && $dbName != 'member_of_contact_id') {
6a488035
TO
1649 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1650 }
1651 }
1652 }
1653
1654 $object->delete();
1655
1656 foreach ($deletions as $deletion) {
1657 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1658 }
1659 }
1660
64d24a64
EM
1661 /**
1662 * Set defaults when creating new entity
1663 * (don't call this set defaults as already in use with different signature in some places)
1664 *
c490a46a 1665 * @param array $params
64d24a64
EM
1666 * @param $defaults
1667 */
1668 static function setCreateDefaults(&$params, $defaults) {
1669 if (isset($params['id'])) {
1670 return;
1671 }
1672 foreach ($defaults as $key => $value) {
1673 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
1674 $params[$key] = $value;
1675 }
1676 }
1677 }
1678
a0ee3941
EM
1679 /**
1680 * @param string $prefix
1681 * @param bool $addRandomString
1682 * @param null $string
1683 *
1684 * @return string
1685 */
6a488035
TO
1686 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1687 $tableName = $prefix . "_temp";
1688
1689 if ($addRandomString) {
1690 if ($string) {
1691 $tableName .= "_" . $string;
1692 }
1693 else {
1694 $tableName .= "_" . md5(uniqid('', TRUE));
1695 }
1696 }
1697 return $tableName;
1698 }
1699
a0ee3941
EM
1700 /**
1701 * @param bool $view
1702 * @param bool $trigger
1703 *
1704 * @return bool
1705 */
6a488035
TO
1706 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1707 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1708 // and logging
1709 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
6a4257d4 1710 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1711 $dao = new CRM_Core_DAO();
1712 if ($view) {
1713 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1714 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1715 return FALSE;
1716 }
1717 }
1718
1719 if ($trigger) {
1720 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1721 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
1722 if ($view) {
1723 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1724 }
1725 return FALSE;
1726 }
1727
1728 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1729 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1730 if ($view) {
1731 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1732 }
1733 return FALSE;
1734 }
1735 }
1736
1737 if ($view) {
1738 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1739 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1740 return FALSE;
1741 }
1742 }
6a488035
TO
1743
1744 return TRUE;
1745 }
1746
a0ee3941
EM
1747 /**
1748 * @param null $message
1749 * @param bool $printDAO
1750 */
6a488035
TO
1751 static function debugPrint($message = NULL, $printDAO = TRUE) {
1752 CRM_Utils_System::xMemory("{$message}: ");
1753
1754 if ($printDAO) {
1755 global $_DB_DATAOBJECT;
1756 $q = array();
1757 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1758 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1759 }
1760 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1761 }
1762 }
1763
77b97be7
EM
1764 /**
1765 * Build a list of triggers via hook and add them to (err, reconcile them
1766 * with) the database.
1767 *
1768 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1769 * @param bool $force
1770 *
1771 * @see CRM-9716
1772 */
e53944ef 1773 static function triggerRebuild($tableName = NULL, $force = FALSE) {
6a488035
TO
1774 $info = array();
1775
1776 $logging = new CRM_Logging_Schema;
e53944ef 1777 $logging->triggerInfo($info, $tableName, $force);
6a488035
TO
1778
1779 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1780 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1781
1782 CRM_Utils_Hook::triggerInfo($info, $tableName);
1783
1784 // drop all existing triggers on all tables
1785 $logging->dropTriggers($tableName);
1786
1787 // now create the set of new triggers
0590c631 1788 self::createTriggers($info, $tableName);
6a488035
TO
1789 }
1790
aca2de91
CW
1791 /**
1792 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1793 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1794 * TODO: Alternative solutions might be
1795 * * Stop using functions and find another way to strip numeric characters from phones
1796 * * Give better error messages (currently a missing fn fatals with "unknown error")
1797 */
1798 static function checkSqlFunctionsExist() {
1799 if (!self::$_checkedSqlFunctionsExist) {
1800 self::$_checkedSqlFunctionsExist = TRUE;
1801 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1802 if (!$dao->fetch()) {
1803 self::triggerRebuild();
1804 }
1805 }
1806 }
1807
6a488035
TO
1808 /**
1809 * Wrapper function to drop triggers
1810 *
1811 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1812 */
1813 static function dropTriggers($tableName = NULL) {
1814 $info = array();
1815
1816 $logging = new CRM_Logging_Schema;
1817 $logging->triggerInfo($info, $tableName);
1818
1819 // drop all existing triggers on all tables
1820 $logging->dropTriggers($tableName);
1821 }
1822
1823 /**
1824 * @param $info array per hook_civicrm_triggerInfo
1825 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1826 */
1827 static function createTriggers(&$info, $onlyTableName = NULL) {
1828 // Validate info array, should probably raise errors?
1829 if (is_array($info) == FALSE) {
1830 return;
1831 }
1832
1833 $triggers = array();
1834
1835 // now enumerate the tables and the events and collect the same set in a different format
1836 foreach ($info as $value) {
1837
1838 // clean the incoming data, skip malformed entries
1839 // TODO: malformed entries should raise errors or get logged.
1840 if (isset($value['table']) == FALSE ||
1841 isset($value['event']) == FALSE ||
1842 isset($value['when']) == FALSE ||
1843 isset($value['sql']) == FALSE
1844 ) {
1845 continue;
1846 }
1847
1848 if (is_string($value['table']) == TRUE) {
1849 $tables = array($value['table']);
1850 }
1851 else {
1852 $tables = $value['table'];
1853 }
1854
1855 if (is_string($value['event']) == TRUE) {
1856 $events = array(strtolower($value['event']));
1857 }
1858 else {
1859 $events = array_map('strtolower', $value['event']);
1860 }
1861
1862 $whenName = strtolower($value['when']);
1863
1864 foreach ($tables as $tableName) {
1865 if (!isset($triggers[$tableName])) {
1866 $triggers[$tableName] = array();
1867 }
1868
1869 foreach ($events as $eventName) {
1870 $template_params = array('{tableName}', '{eventName}');
1871 $template_values = array($tableName, $eventName);
1872
1873 $sql = str_replace($template_params,
1874 $template_values,
1875 $value['sql']
1876 );
1877 $variables = str_replace($template_params,
1878 $template_values,
1879 CRM_Utils_Array::value('variables', $value)
1880 );
1881
1882 if (!isset($triggers[$tableName][$eventName])) {
1883 $triggers[$tableName][$eventName] = array();
1884 }
1885
1886 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1887 // We're leaving out cursors, conditions, and handlers for now
1888 // they are kind of dangerous in this context anyway
1889 // better off putting them in stored procedures
1890 $triggers[$tableName][$eventName][$whenName] = array(
1891 'variables' => array(),
1892 'sql' => array(),
1893 );
1894 }
1895
1896 if ($variables) {
1897 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1898 }
1899
1900 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1901 }
1902 }
1903 }
1904
1905 // now spit out the sql
1906 foreach ($triggers as $tableName => $tables) {
1907 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1908 continue;
1909 }
1910 foreach ($tables as $eventName => $events) {
1911 foreach ($events as $whenName => $parts) {
1912 $varString = implode("\n", $parts['variables']);
1913 $sqlString = implode("\n", $parts['sql']);
6842bb53
DL
1914 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
1915 $triggerName = "{$validName}_{$whenName}_{$eventName}";
6a488035
TO
1916 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1917
1918 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1919 CRM_Core_DAO::executeQuery(
1920 $triggerSQL,
1921 array(),
1922 TRUE,
1923 NULL,
1924 FALSE,
1925 FALSE
1926 );
1927 }
1928 }
1929 }
1930 }
1931
ffcef054
TO
1932 /**
1933 * Given a list of fields, create a list of references.
1934 *
1935 * @param string $className BAO/DAO class name
1936 * @return array<CRM_Core_Reference_Interface>
1937 */
1938 static function createReferenceColumns($className) {
1939 $result = array();
1940 $fields = $className::fields();
1941 foreach ($fields as $field) {
1942 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1943 $result[] = new CRM_Core_Reference_OptionValue(
1944 $className::getTableName(),
1945 $field['name'],
1946 'civicrm_option_value',
1947 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
1948 $field['pseudoconstant']['optionGroupName']
1949 );
1950 }
1951 }
1952 return $result;
1953 }
1954
6a488035 1955 /**
71e5aa5c
ARW
1956 * Find all records which refer to this entity.
1957 *
1958 * @return array of objects referencing this
1959 */
1960 function findReferences() {
1961 $links = self::getReferencesToTable(static::getTableName());
1962
1963 $occurrences = array();
1964 foreach ($links as $refSpec) {
11626cf1 1965 /** @var $refSpec CRM_Core_Reference_Interface */
31bed28c 1966 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
de49f39c 1967 $result = $refSpec->findReferences($this);
ffcef054
TO
1968 if ($result) {
1969 while ($result->fetch()) {
1970 $obj = new $daoName();
1971 $obj->id = $result->id;
1972 $occurrences[] = $obj;
1973 }
71e5aa5c
ARW
1974 }
1975 }
1976
1977 return $occurrences;
1978 }
1979
a0ee3941 1980 /**
1c369249
TO
1981 * @return array each item has keys:
1982 * - name: string
1983 * - type: string
1984 * - count: int
1985 * - table: string|null SQL table name
1986 * - key: string|null SQL column name
a0ee3941 1987 */
1256c139
TO
1988 function getReferenceCounts() {
1989 $links = self::getReferencesToTable(static::getTableName());
1990
1991 $counts = array();
1992 foreach ($links as $refSpec) {
1993 /** @var $refSpec CRM_Core_Reference_Interface */
1994 $count = $refSpec->getReferenceCount($this);
1995 if ($count['count'] != 0) {
1996 $counts[] = $count;
1997 }
1998 }
1999
91dee34b
TO
2000 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2001 /** @var $component CRM_Core_Component_Info */
2002 $counts = array_merge($counts, $component->getReferenceCounts($this));
2003 }
2004 CRM_Utils_Hook::referenceCounts($this, $counts);
2005
1256c139
TO
2006 return $counts;
2007 }
2008
71e5aa5c
ARW
2009 /**
2010 * List all tables which have hard foreign keys to this table.
6a488035 2011 *
71e5aa5c
ARW
2012 * For now, this returns a description of every entity_id/entity_table
2013 * reference.
2014 * TODO: filter dynamic entity references on the $tableName, based on
2015 * schema metadata in dynamicForeignKey which enumerates a restricted
2016 * set of possible entity_table's.
6a488035 2017 *
71e5aa5c 2018 * @param string $tableName table referred to
6a488035 2019 *
71e5aa5c
ARW
2020 * @return array structure of table and column, listing every table with a
2021 * foreign key reference to $tableName, and the column where the key appears.
6a488035 2022 */
71e5aa5c
ARW
2023 static function getReferencesToTable($tableName) {
2024 $refsFound = array();
31bed28c 2025 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
71e5aa5c
ARW
2026 $links = $daoClassName::getReferenceColumns();
2027 $daoTableName = $daoClassName::getTableName();
2028
2029 foreach ($links as $refSpec) {
11626cf1
TO
2030 /** @var $refSpec CRM_Core_Reference_Interface */
2031 if ($refSpec->matchesTargetTable($tableName)) {
71e5aa5c
ARW
2032 $refsFound[] = $refSpec;
2033 }
6a488035
TO
2034 }
2035 }
71e5aa5c 2036 return $refsFound;
6a488035 2037 }
032c9d10
TO
2038
2039 /**
2040 * Lookup the value of a MySQL global configuration variable.
2041 *
2042 * @param string $name e.g. "thread_stack"
2043 * @param mixed $default
2044 * @return mixed
2045 */
2046 public static function getGlobalSetting($name, $default = NULL) {
2047 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2048 // that has been reported to fail under MySQL 5.0 for OS X
2049 $escapedName = self::escapeString($name);
2050 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2051 if ($dao->fetch()) {
2052 return $dao->Value;
ab00f69d
DL
2053 }
2054 else {
032c9d10
TO
2055 return $default;
2056 }
2057 }
dc86f881
CW
2058
2059 /**
2060 * Get options for the called BAO object's field.
2061 * This function can be overridden by each BAO to add more logic related to context.
2158332a 2062 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
dc86f881 2063 *
2a3f958d 2064 * @param string $fieldName
9a1b1948
EM
2065 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2066 * @param array $props : whatever is known about this bao object
2067 *
2068 * @return Array|bool
dc86f881
CW
2069 */
2070 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2158332a 2071 // If a given bao does not override this function
dc86f881 2072 $baoName = get_called_class();
786ad6e1 2073 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
dc86f881 2074 }
786ad6e1 2075
2a3f958d
CW
2076 /**
2077 * Populate option labels for this object's fields.
2078 *
2079 * @throws exception if called directly on the base class
2080 */
2081 public function getOptionLabels() {
2082 $fields = $this->fields();
2083 if ($fields === NULL) {
395d8dc6 2084 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2a3f958d
CW
2085 }
2086 foreach ($fields as $field) {
2087 $name = CRM_Utils_Array::value('name', $field);
2088 if ($name && isset($this->$name)) {
a8c23526 2089 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2a3f958d
CW
2090 if ($label !== FALSE) {
2091 // Append 'label' onto the field name
2092 $labelName = $name . '_label';
2093 $this->$labelName = $label;
2094 }
2095 }
2096 }
2097 }
2098
786ad6e1
CW
2099 /**
2100 * Provides documentation and validation for the buildOptions $context param
2101 *
2102 * @param String $context
77b97be7
EM
2103 *
2104 * @throws Exception
2105 * @return array
786ad6e1
CW
2106 */
2107 public static function buildOptionsContext($context = NULL) {
2108 $contexts = array(
2109 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2110 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2111 'search' => "Searchable options are returned. Labels are translated.",
2112 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2113 );
2114 // Validation: enforce uniformity of this param
2115 if ($context !== NULL && !isset($contexts[$context])) {
395d8dc6 2116 throw new Exception("'$context' is not a valid context for buildOptions.");
786ad6e1
CW
2117 }
2118 return $contexts;
2119 }
2120
5fafc9b0 2121 /**
100fef9d 2122 * @param string $fieldName
5fafc9b0
CW
2123 * @return bool|array
2124 */
2125 function getFieldSpec($fieldName) {
2126 $fields = $this->fields();
2127 $fieldKeys = $this->fieldKeys();
2128
2129 // Support "unique names" as well as sql names
2130 $fieldKey = $fieldName;
2131 if (empty($fields[$fieldKey])) {
2132 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
2133 }
2134 // If neither worked then this field doesn't exist. Return false.
2135 if (empty($fields[$fieldKey])) {
2136 return FALSE;
2137 }
2138 return $fields[$fieldKey];
2139 }
2140
faf8c53b 2141 /**
2142 * SQL version of api function to assign filters to the DAO based on the syntax
2143 * $field => array('IN' => array(4,6,9))
2144 * OR
2145 * $field => array('LIKE' => array('%me%))
2146 * etc
2147 *
c490a46a 2148 * @param string $fieldName name of fields
a038992c 2149 * @param $filter array filter to be applied indexed by operator
2150 * @param $type String type of field (not actually used - nor in api @todo )
2151 * @param $alias String alternative field name ('as') @todo- not actually used
78c0bfc0 2152 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
2153 * this is primarily so we can add filters @ the api level to the Query object based fields
9a1b1948
EM
2154 *
2155 * @throws Exception
c490a46a 2156 *
a75c13cc 2157 * @todo a better solution would be for the query object to apply these filters based on the
78c0bfc0 2158 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
9a1b1948 2159 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
06f48f96 2160 * required to extend further & it may be the comments per above should be implemented. It may be
2161 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2162 * in one place has some advantages as we try to extend this format
2163 *
9a1b1948 2164 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
06f48f96 2165 * depending on whether it is supported as yet
9a1b1948 2166 */
3f2d6002 2167 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
faf8c53b 2168 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2169 // support for other syntaxes is discussed in ticket but being put off for now
faf8c53b 2170 foreach ($filter as $operator => $criteria) {
e4176358 2171 if (in_array($operator, self::acceptedSQLOperators())) {
faf8c53b 2172 switch ($operator) {
2173 // unary operators
faf8c53b 2174 case 'IS NULL':
2175 case 'IS NOT NULL':
c490a46a 2176 if (!$returnSanitisedArray) {
78c0bfc0 2177 return (sprintf('%s %s', $fieldName, $operator));
2178 }
c490a46a 2179 else {
a75c13cc 2180 return (sprintf('%s %s ', $fieldName, $operator));
06f48f96 2181 }
faf8c53b 2182 break;
2183
2184 // ternary operators
2185 case 'BETWEEN':
2186 case 'NOT BETWEEN':
2187 if (empty($criteria[0]) || empty($criteria[1])) {
395d8dc6 2188 throw new Exception("invalid criteria for $operator");
faf8c53b 2189 }
c490a46a 2190 if (!$returnSanitisedArray) {
78c0bfc0 2191 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2192 }
c490a46a 2193 else {
06f48f96 2194 return NULL; // not yet implemented (tests required to implement)
2195 }
faf8c53b 2196 break;
2197
2198 // n-ary operators
2199 case 'IN':
2200 case 'NOT IN':
2201 if (empty($criteria)) {
395d8dc6 2202 throw new Exception("invalid criteria for $operator");
faf8c53b 2203 }
2204 $escapedCriteria = array_map(array(
2205 'CRM_Core_DAO',
2206 'escapeString'
2207 ), $criteria);
c490a46a 2208 if (!$returnSanitisedArray) {
78c0bfc0 2209 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2210 }
2211 return $escapedCriteria;
faf8c53b 2212 break;
2213
2214 // binary operators
6a488035 2215
faf8c53b 2216 default:
c490a46a 2217 if (!$returnSanitisedArray) {
78c0bfc0 2218 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
2219 }
c490a46a 2220 else {
06f48f96 2221 return NULL; // not yet implemented (tests required to implement)
2222 }
faf8c53b 2223 }
2224 }
2225 }
2226 }
6842bb53 2227
e4176358
CW
2228 /**
2229 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2230 * support for other syntaxes is discussed in ticket but being put off for now
2231 * @return array
2232 */
2233 public static function acceptedSQLOperators() {
a75c13cc 2234 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
e4176358
CW
2235 }
2236
6842bb53
DL
2237 /**
2238 * SQL has a limit of 64 characters on various names:
2239 * table name, trigger name, column name ...
2240 *
2241 * For custom groups and fields we generated names from user entered input
2242 * which can be longer than this length, this function helps with creating
2243 * strings that meet various criteria.
2244 *
2245 * @param string $string - the string to be shortened
9a1b1948
EM
2246 * @param int $length - the max length of the string
2247 *
2248 * @param bool $makeRandom
2249 *
2250 * @return string
6842bb53
DL
2251 */
2252 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2253 // early return for strings that meet the requirements
2254 if (strlen($string) <= $length) {
2255 return $string;
2256 }
2257
2258 // easy return for calls that dont need a randomized uniq string
c490a46a 2259 if (!$makeRandom) {
6842bb53
DL
2260 return substr($string, 0, $length);
2261 }
2262
2263 // the string is longer than the length and we need a uniq string
2264 // for the same tablename we need the same uniq string everytime
2265 // hence we use md5 on the string, which is not random
a8dd306e
DL
2266 // we'll append 8 characters to the end of the tableName
2267 $md5string = substr(md5($string), 0, 8);
2268 return substr($string, 0, $length - 8) . "_{$md5string}";
6842bb53
DL
2269 }
2270
a0ee3941 2271 /**
c490a46a 2272 * @param array $params
a0ee3941 2273 */
6e1bb60c
N
2274 function setApiFilter(&$params) {}
2275
232624b1 2276}