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