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