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