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