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