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