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