PageRenderTime 37ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/sites/all/modules/ctools/includes/export.inc

https://bitbucket.org/hjain/trinet
Pascal | 1250 lines | 666 code | 111 blank | 473 comment | 123 complexity | 93e609d2618165d257323d5ed299a782 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0, AGPL-1.0
  1. <?php
  2. /**
  3. * @file
  4. * Contains code to make it easier to have exportable objects.
  5. *
  6. * Documentation for exportable objects is contained in help/export.html
  7. */
  8. /**
  9. * A bit flag used to let us know if an object is in the database.
  10. */
  11. define('EXPORT_IN_DATABASE', 0x01);
  12. /**
  13. * A bit flag used to let us know if an object is a 'default' in code.
  14. */
  15. define('EXPORT_IN_CODE', 0x02);
  16. /**
  17. * @defgroup export_crud CRUD functions for export.
  18. * @{
  19. * export.inc supports a small number of CRUD functions that should always
  20. * work for every exportable object, no matter how complicated. These
  21. * functions allow complex objects to provide their own callbacks, but
  22. * in most cases, the default callbacks will be used.
  23. *
  24. * Note that defaults are NOT set in the $schema because it is presumed
  25. * that a module's personalized CRUD functions will already know which
  26. * $table to use and not want to clutter up the arguments with it.
  27. */
  28. /**
  29. * Create a new object for the given $table.
  30. *
  31. * @param $table
  32. * The name of the table to use to retrieve $schema values. This table
  33. * must have an 'export' section containing data or this function
  34. * will fail.
  35. * @param $set_defaults
  36. * If TRUE, which is the default, then default values will be retrieved
  37. * from schema fields and set on the object.
  38. *
  39. * @return
  40. * The loaded object.
  41. */
  42. function ctools_export_crud_new($table, $set_defaults = TRUE) {
  43. $schema = ctools_export_get_schema($table);
  44. $export = $schema['export'];
  45. if (!empty($export['create callback']) && function_exists($export['create callback'])) {
  46. return $export['create callback']($set_defaults);
  47. }
  48. else {
  49. return ctools_export_new_object($table, $set_defaults);
  50. }
  51. }
  52. /**
  53. * Load a single exportable object.
  54. *
  55. * @param $table
  56. * The name of the table to use to retrieve $schema values. This table
  57. * must have an 'export' section containing data or this function
  58. * will fail.
  59. * @param $name
  60. * The unique ID to load. The field for this ID will be specified by
  61. * the export key, which normally defaults to 'name'.
  62. *
  63. * @return
  64. * The loaded object.
  65. */
  66. function ctools_export_crud_load($table, $name) {
  67. $schema = ctools_export_get_schema($table);
  68. $export = $schema['export'];
  69. if (!empty($export['load callback']) && function_exists($export['load callback'])) {
  70. return $export['load callback']($name);
  71. }
  72. else {
  73. $result = ctools_export_load_object($table, 'names', array($name));
  74. if (isset($result[$name])) {
  75. return $result[$name];
  76. }
  77. }
  78. }
  79. /**
  80. * Load multiple exportable objects.
  81. *
  82. * @param $table
  83. * The name of the table to use to retrieve $schema values. This table
  84. * must have an 'export' section containing data or this function
  85. * will fail.
  86. * @param $names
  87. * An array of unique IDs to load. The field for these IDs will be specified
  88. * by the export key, which normally defaults to 'name'.
  89. *
  90. * @return
  91. * An array of the loaded objects.
  92. */
  93. function ctools_export_crud_load_multiple($table, array $names) {
  94. $schema = ctools_export_get_schema($table);
  95. $export = $schema['export'];
  96. $results = array();
  97. if (!empty($export['load multiple callback']) && function_exists($export['load multiple callback'])) {
  98. $results = $export['load multiple callback']($names);
  99. }
  100. else {
  101. $results = ctools_export_load_object($table, 'names', $names);
  102. }
  103. // Ensure no empty results are returned.
  104. return array_filter($results);
  105. }
  106. /**
  107. * Load all exportable objects of a given type.
  108. *
  109. * @param $table
  110. * The name of the table to use to retrieve $schema values. This table
  111. * must have an 'export' section containing data or this function
  112. * will fail.
  113. * @param $reset
  114. * If TRUE, the static cache of all objects will be flushed prior to
  115. * loading all. This can be important on listing pages where items
  116. * might have changed on the page load.
  117. * @return
  118. * An array of all loaded objects, keyed by the unique IDs of the export key.
  119. */
  120. function ctools_export_crud_load_all($table, $reset = FALSE) {
  121. $schema = ctools_export_get_schema($table);
  122. if (empty($schema['export'])) {
  123. return array();
  124. }
  125. $export = $schema['export'];
  126. if ($reset) {
  127. ctools_export_load_object_reset($table);
  128. }
  129. if (!empty($export['load all callback']) && function_exists($export['load all callback'])) {
  130. return $export['load all callback']($reset);
  131. }
  132. else {
  133. return ctools_export_load_object($table, 'all');
  134. }
  135. }
  136. /**
  137. * Save a single exportable object.
  138. *
  139. * @param $table
  140. * The name of the table to use to retrieve $schema values. This table
  141. * must have an 'export' section containing data or this function
  142. * will fail.
  143. * @param $object
  144. * The fully populated object to save.
  145. *
  146. * @return
  147. * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
  148. * SAVED_UPDATED is returned depending on the operation performed. The
  149. * $object parameter contains values for any serial fields defined by the $table
  150. */
  151. function ctools_export_crud_save($table, &$object) {
  152. $schema = ctools_export_get_schema($table);
  153. $export = $schema['export'];
  154. if (!empty($export['save callback']) && function_exists($export['save callback'])) {
  155. return $export['save callback']($object);
  156. }
  157. else {
  158. // Objects should have a serial primary key. If not, simply fail to write.
  159. if (empty($export['primary key'])) {
  160. return FALSE;
  161. }
  162. $key = $export['primary key'];
  163. if ($object->export_type & EXPORT_IN_DATABASE) {
  164. // Existing record.
  165. $update = array($key);
  166. }
  167. else {
  168. // New record.
  169. $update = array();
  170. $object->export_type = EXPORT_IN_DATABASE;
  171. }
  172. return drupal_write_record($table, $object, $update);
  173. }
  174. }
  175. /**
  176. * Delete a single exportable object.
  177. *
  178. * This only deletes from the database, which means that if an item is in
  179. * code, then this is actually a revert.
  180. *
  181. * @param $table
  182. * The name of the table to use to retrieve $schema values. This table
  183. * must have an 'export' section containing data or this function
  184. * will fail.
  185. * @param $object
  186. * The fully populated object to delete, or the export key.
  187. */
  188. function ctools_export_crud_delete($table, $object) {
  189. $schema = ctools_export_get_schema($table);
  190. $export = $schema['export'];
  191. if (!empty($export['delete callback']) && function_exists($export['delete callback'])) {
  192. return $export['delete callback']($object);
  193. }
  194. else {
  195. // If we were sent an object, get the export key from it. Otherwise
  196. // assume we were sent the export key.
  197. $value = is_object($object) ? $object->{$export['key']} : $object;
  198. db_delete($table)
  199. ->condition($export['key'], $value)
  200. ->execute();
  201. }
  202. }
  203. /**
  204. * Get the exported code of a single exportable object.
  205. *
  206. * @param $table
  207. * The name of the table to use to retrieve $schema values. This table
  208. * must have an 'export' section containing data or this function
  209. * will fail.
  210. * @param $object
  211. * The fully populated object to delete, or the export key.
  212. * @param $indent
  213. * Any indentation to apply to the code, in case this object is embedded
  214. * into another, for example.
  215. *
  216. * @return
  217. * A string containing the executable export of the object.
  218. */
  219. function ctools_export_crud_export($table, $object, $indent = '') {
  220. $schema = ctools_export_get_schema($table);
  221. $export = $schema['export'];
  222. if (!empty($export['export callback']) && function_exists($export['export callback'])) {
  223. return $export['export callback']($object, $indent);
  224. }
  225. else {
  226. return ctools_export_object($table, $object, $indent);
  227. }
  228. }
  229. /**
  230. * Turn exported code into an object.
  231. *
  232. * Note: If the code is poorly formed, this could crash and there is no
  233. * way to prevent this.
  234. *
  235. * @param $table
  236. * The name of the table to use to retrieve $schema values. This table
  237. * must have an 'export' section containing data or this function
  238. * will fail.
  239. * @param $code
  240. * The code to eval to create the object.
  241. *
  242. * @return
  243. * An object created from the export. This object will NOT have been saved
  244. * to the database. In the case of failure, a string containing all errors
  245. * that the system was able to determine.
  246. */
  247. function ctools_export_crud_import($table, $code) {
  248. $schema = ctools_export_get_schema($table);
  249. $export = $schema['export'];
  250. if (!empty($export['import callback']) && function_exists($export['import callback'])) {
  251. return $export['import callback']($code);
  252. }
  253. else {
  254. ob_start();
  255. eval($code);
  256. ob_end_clean();
  257. if (empty(${$export['identifier']})) {
  258. $errors = ob_get_contents();
  259. if (empty($errors)) {
  260. $errors = t('No item found.');
  261. }
  262. return $errors;
  263. }
  264. $item = ${$export['identifier']};
  265. // Set these defaults just the same way that ctools_export_new_object sets
  266. // them.
  267. $item->export_type = NULL;
  268. $item->{$export['export type string']} = t('Local');
  269. return $item;
  270. }
  271. }
  272. /**
  273. * Change the status of a certain object.
  274. *
  275. * @param $table
  276. * The name of the table to use to enable a certain object. This table
  277. * must have an 'export' section containing data or this function
  278. * will fail.
  279. * @param $object
  280. * The fully populated object to enable, or the machine readable name.
  281. * @param $status
  282. * The status, in this case, is whether or not it is 'disabled'.
  283. */
  284. function ctools_export_crud_set_status($table, $object, $status) {
  285. $schema = ctools_export_get_schema($table);
  286. $export = $schema['export'];
  287. if (!empty($export['status callback']) && function_exists($export['status callback'])) {
  288. $export['status callback']($object, $status);
  289. }
  290. else {
  291. if (is_object($object)) {
  292. ctools_export_set_object_status($object, $status);
  293. }
  294. else {
  295. ctools_export_set_status($table, $object, $status);
  296. }
  297. }
  298. }
  299. /**
  300. * Enable a certain object.
  301. *
  302. * @param $table
  303. * The name of the table to use to enable a certain object. This table
  304. * must have an 'export' section containing data or this function
  305. * will fail.
  306. * @param $object
  307. * The fully populated object to enable, or the machine readable name.
  308. */
  309. function ctools_export_crud_enable($table, $object) {
  310. return ctools_export_crud_set_status($table, $object, FALSE);
  311. }
  312. /**
  313. * Disable a certain object.
  314. *
  315. * @param $table
  316. * The name of the table to use to disable a certain object. This table
  317. * must have an 'export' section containing data or this function
  318. * will fail.
  319. * @param $object
  320. * The fully populated object to disable, or the machine readable name.
  321. */
  322. function ctools_export_crud_disable($table, $object) {
  323. return ctools_export_crud_set_status($table, $object, TRUE);
  324. }
  325. /**
  326. * @}
  327. */
  328. /**
  329. * Load some number of exportable objects.
  330. *
  331. * This function will cache the objects, load subsidiary objects if necessary,
  332. * check default objects in code and properly set them up. It will cache
  333. * the results so that multiple calls to load the same objects
  334. * will not cause problems.
  335. *
  336. * It attempts to reduce, as much as possible, the number of queries
  337. * involved.
  338. *
  339. * @param $table
  340. * The name of the table to be loaded from. Data is expected to be in the
  341. * schema to make all this work.
  342. * @param $type
  343. * A string to notify the loader what the argument is
  344. * - all: load all items. This is the default. $args is unused.
  345. * - names: $args will be an array of specific named objects to load.
  346. * - conditions: $args will be a keyed array of conditions. The conditions
  347. * must be in the schema for this table or errors will result.
  348. * @param $args
  349. * An array of arguments whose actual use is defined by the $type argument.
  350. */
  351. function ctools_export_load_object($table, $type = 'all', $args = array()) {
  352. $cache = &drupal_static(__FUNCTION__);
  353. $cached_database = &drupal_static('ctools_export_load_object_all');
  354. $schema = ctools_export_get_schema($table);
  355. if (empty($schema) || !db_table_exists($table)) {
  356. return array();
  357. }
  358. $export = $schema['export'];
  359. if (!isset($cache[$table])) {
  360. $cache[$table] = array();
  361. }
  362. // If fetching all and cached all, we've done so and we are finished.
  363. if ($type == 'all' && !empty($cached_database[$table])) {
  364. return $cache[$table];
  365. }
  366. $return = array();
  367. // Don't load anything we've already cached.
  368. if ($type == 'names' && !empty($args)) {
  369. foreach ($args as $id => $name) {
  370. if (isset($cache[$table][$name])) {
  371. $return[$name] = $cache[$table][$name];
  372. unset($args[$id]);
  373. }
  374. }
  375. // If nothing left to load, return the result.
  376. if (empty($args)) {
  377. return $return;
  378. }
  379. }
  380. // Build the query
  381. $query = db_select($table, 't__0')->fields('t__0');
  382. $alias_count = 1;
  383. if (!empty($schema['join'])) {
  384. foreach ($schema['join'] as $join_key => $join) {
  385. if ($join_schema = drupal_get_schema($join['table'])) {
  386. $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
  387. $query->fields('t__' . $alias_count);
  388. $alias_count++;
  389. // Allow joining tables to alter the query through a callback.
  390. if (isset($join['callback']) && function_exists($join['callback'])) {
  391. $join['callback']($query, $schema, $join_schema);
  392. }
  393. }
  394. }
  395. }
  396. $conditions = array();
  397. $query_args = array();
  398. // If they passed in names, add them to the query.
  399. if ($type == 'names') {
  400. $query->condition($export['key'], $args, 'IN');
  401. }
  402. else if ($type == 'conditions') {
  403. foreach ($args as $key => $value) {
  404. if (isset($schema['fields'][$key])) {
  405. $query->condition($key, $value);
  406. }
  407. }
  408. }
  409. $result = $query->execute();
  410. $status = variable_get($export['status'], array());
  411. // Unpack the results of the query onto objects and cache them.
  412. foreach ($result as $data) {
  413. if (isset($schema['export']['object factory']) && function_exists($schema['export']['object factory'])) {
  414. $object = $schema['export']['object factory']($schema, $data);
  415. }
  416. else {
  417. $object = _ctools_export_unpack_object($schema, $data, $export['object']);
  418. }
  419. $object->table = $table;
  420. $object->{$export['export type string']} = t('Normal');
  421. $object->export_type = EXPORT_IN_DATABASE;
  422. // Determine if default object is enabled or disabled.
  423. if (isset($status[$object->{$export['key']}])) {
  424. $object->disabled = $status[$object->{$export['key']}];
  425. }
  426. $cache[$table][$object->{$export['key']}] = $object;
  427. if ($type == 'conditions') {
  428. $return[$object->{$export['key']}] = $object;
  429. }
  430. }
  431. // Load subrecords.
  432. if (isset($export['subrecords callback']) && function_exists($export['subrecords callback'])) {
  433. $export['subrecords callback']($cache[$table]);
  434. }
  435. if ($type == 'names' && !empty($args) && !empty($export['cache defaults'])) {
  436. $defaults = _ctools_export_get_some_defaults($table, $export, $args);
  437. }
  438. else {
  439. $defaults = _ctools_export_get_defaults($table, $export);
  440. }
  441. if ($defaults) {
  442. foreach ($defaults as $object) {
  443. if ($type == 'conditions') {
  444. // if this does not match all of our conditions, skip it.
  445. foreach ($args as $key => $value) {
  446. if (!isset($object->$key)) {
  447. continue 2;
  448. }
  449. if (is_array($value)) {
  450. if (!in_array($object->$key, $value)) {
  451. continue 2;
  452. }
  453. }
  454. else if ($object->$key != $value) {
  455. continue 2;
  456. }
  457. }
  458. }
  459. else if ($type == 'names') {
  460. if (!in_array($object->{$export['key']}, $args)) {
  461. continue;
  462. }
  463. }
  464. // Determine if default object is enabled or disabled.
  465. if (isset($status[$object->{$export['key']}])) {
  466. $object->disabled = $status[$object->{$export['key']}];
  467. }
  468. if (!empty($cache[$table][$object->{$export['key']}])) {
  469. $cache[$table][$object->{$export['key']}]->{$export['export type string']} = t('Overridden');
  470. $cache[$table][$object->{$export['key']}]->export_type |= EXPORT_IN_CODE;
  471. $cache[$table][$object->{$export['key']}]->export_module = isset($object->export_module) ? $object->export_module : NULL;
  472. if ($type == 'conditions') {
  473. $return[$object->{$export['key']}] = $cache[$table][$object->{$export['key']}];
  474. }
  475. }
  476. else {
  477. $object->{$export['export type string']} = t('Default');
  478. $object->export_type = EXPORT_IN_CODE;
  479. $object->in_code_only = TRUE;
  480. $object->table = $table;
  481. $cache[$table][$object->{$export['key']}] = $object;
  482. if ($type == 'conditions') {
  483. $return[$object->{$export['key']}] = $object;
  484. }
  485. }
  486. }
  487. }
  488. // If fetching all, we've done so and we are finished.
  489. if ($type == 'all') {
  490. $cached_database[$table] = TRUE;
  491. return $cache[$table];
  492. }
  493. if ($type == 'names') {
  494. foreach ($args as $name) {
  495. if (isset($cache[$table][$name])) {
  496. $return[$name] = $cache[$table][$name];
  497. }
  498. }
  499. }
  500. // For conditions,
  501. return $return;
  502. }
  503. /**
  504. * Reset all static caches in ctools_export_load_object() or static caches for
  505. * a given table in ctools_export_load_object().
  506. *
  507. * @param $table
  508. * String that is the name of a table. If not defined, all static caches in
  509. * ctools_export_load_object() will be reset.
  510. */
  511. function ctools_export_load_object_reset($table = NULL) {
  512. // Reset plugin cache to make sure new include files are picked up.
  513. ctools_include('plugins');
  514. ctools_get_plugins_reset();
  515. if (empty($table)) {
  516. drupal_static_reset('ctools_export_load_object');
  517. drupal_static_reset('ctools_export_load_object_all');
  518. drupal_static_reset('_ctools_export_get_defaults');
  519. }
  520. else {
  521. $cache = &drupal_static('ctools_export_load_object');
  522. $cached_database = &drupal_static('ctools_export_load_object_all');
  523. $cached_defaults = &drupal_static('_ctools_export_get_defaults');
  524. unset($cache[$table]);
  525. unset($cached_database[$table]);
  526. unset($cached_defaults[$table]);
  527. }
  528. }
  529. /**
  530. * Get the default version of an object, if it exists.
  531. *
  532. * This function doesn't care if an object is in the database or not and
  533. * does not check. This means that export_type could appear to be incorrect,
  534. * because a version could exist in the database. However, it's not
  535. * incorrect for this function as it is *only* used for the default
  536. * in code version.
  537. */
  538. function ctools_get_default_object($table, $name) {
  539. $schema = ctools_export_get_schema($table);
  540. $export = $schema['export'];
  541. if (!$export['default hook']) {
  542. return;
  543. }
  544. // Try to load individually from cache if this cache is enabled.
  545. if (!empty($export['cache defaults'])) {
  546. $defaults = _ctools_export_get_some_defaults($table, $export, array($name));
  547. }
  548. else {
  549. $defaults = _ctools_export_get_defaults($table, $export);
  550. }
  551. $status = variable_get($export['status'], array());
  552. if (!isset($defaults[$name])) {
  553. return;
  554. }
  555. $object = $defaults[$name];
  556. // Determine if default object is enabled or disabled.
  557. if (isset($status[$object->{$export['key']}])) {
  558. $object->disabled = $status[$object->{$export['key']}];
  559. }
  560. $object->{$export['export type string']} = t('Default');
  561. $object->export_type = EXPORT_IN_CODE;
  562. $object->in_code_only = TRUE;
  563. return $object;
  564. }
  565. /**
  566. * Call the hook to get all default objects of the given type from the
  567. * export. If configured properly, this could include loading up an API
  568. * to get default objects.
  569. */
  570. function _ctools_export_get_defaults($table, $export) {
  571. $cache = &drupal_static(__FUNCTION__, array());
  572. // If defaults may be cached, first see if we can load from cache.
  573. if (!isset($cache[$table]) && !empty($export['cache defaults'])) {
  574. $cache[$table] = _ctools_export_get_defaults_from_cache($table, $export);
  575. }
  576. if (!isset($cache[$table])) {
  577. // If we're caching, attempt to get a lock. We will wait a short time
  578. // on the lock, but not too long, because it's better to just rebuild
  579. // and throw away results than wait too long on a lock.
  580. if (!empty($export['cache defaults'])) {
  581. for ($counter = 0; !($lock = lock_acquire('ctools_export:' . $table)) && $counter > 5; $counter++) {
  582. lock_wait('ctools_export:' . $table, 1);
  583. ++$counter;
  584. }
  585. }
  586. $cache[$table] = array();
  587. if ($export['default hook']) {
  588. if (!empty($export['api'])) {
  589. ctools_include('plugins');
  590. $info = ctools_plugin_api_include($export['api']['owner'], $export['api']['api'],
  591. $export['api']['minimum_version'], $export['api']['current_version']);
  592. $modules = array_keys($info);
  593. }
  594. else {
  595. $modules = module_implements($export['default hook']);
  596. }
  597. foreach ($modules as $module) {
  598. $function = $module . '_' . $export['default hook'];
  599. if (function_exists($function)) {
  600. foreach ((array) $function($export) as $name => $object) {
  601. // Record the module that provides this exportable.
  602. $object->export_module = $module;
  603. if (empty($export['api'])) {
  604. $cache[$table][$name] = $object;
  605. }
  606. else {
  607. // If version checking is enabled, ensure that the object can be used.
  608. if (isset($object->api_version) &&
  609. version_compare($object->api_version, $export['api']['minimum_version']) >= 0 &&
  610. version_compare($object->api_version, $export['api']['current_version']) <= 0) {
  611. $cache[$table][$name] = $object;
  612. }
  613. }
  614. }
  615. }
  616. }
  617. drupal_alter($export['default hook'], $cache[$table]);
  618. // If we acquired a lock earlier, cache the results and release the
  619. // lock.
  620. if (!empty($lock)) {
  621. // Cache the index.
  622. $index = array_keys($cache[$table]);
  623. cache_set('ctools_export_index:' . $table, $index, $export['default cache bin']);
  624. // Cache each object.
  625. foreach ($cache[$table] as $name => $object) {
  626. cache_set('ctools_export:' . $table . ':' . $name, $object, $export['default cache bin']);
  627. }
  628. lock_release('ctools_export:' . $table);
  629. }
  630. }
  631. }
  632. return $cache[$table];
  633. }
  634. /**
  635. * Attempt to load default objects from cache.
  636. *
  637. * We can be instructed to cache default objects by the schema. If so
  638. * we cache them as an index which is a list of all default objects, and
  639. * then each default object is cached individually.
  640. *
  641. * @return Either an array of cached objects, or NULL indicating a cache
  642. * rebuild is necessary.
  643. */
  644. function _ctools_export_get_defaults_from_cache($table, $export) {
  645. $data = cache_get('ctools_export_index:' . $table, $export['default cache bin']);
  646. if (!$data || !is_array($data->data)) {
  647. return;
  648. }
  649. // This is the perfectly valid case where there are no default objects,
  650. // and we have cached this state.
  651. if (empty($data->data)) {
  652. return array();
  653. }
  654. $keys = array();
  655. foreach ($data->data as $name) {
  656. $keys[] = 'ctools_export:' . $table . ':' . $name;
  657. }
  658. $data = cache_get_multiple($keys, $export['default cache bin']);
  659. // If any of our indexed keys missed, then we have a fail and we need to
  660. // rebuild.
  661. if (!empty($keys)) {
  662. return;
  663. }
  664. // Now, translate the returned cache objects to actual objects.
  665. $cache = array();
  666. foreach ($data as $cached_object) {
  667. $cache[$cached_object->data->{$export['key']}] = $cached_object->data;
  668. }
  669. return $cache;
  670. }
  671. /**
  672. * Get a limited number of default objects.
  673. *
  674. * This attempts to load the objects directly from cache. If it cannot,
  675. * the cache is rebuilt. This does not disturb the general get defaults
  676. * from cache object.
  677. *
  678. * This function should ONLY be called if default caching is enabled.
  679. * It does not check, it is assumed the caller has already done so.
  680. */
  681. function _ctools_export_get_some_defaults($table, $export, $names) {
  682. foreach ($names as $name) {
  683. $keys[] = 'ctools_export:' . $table . ':' . $name;
  684. }
  685. $data = cache_get_multiple($keys, $export['default cache bin']);
  686. // Cache hits remove the $key from $keys by reference. Cache
  687. // misses do not. A cache miss indicates we may have to rebuild.
  688. if (!empty($keys)) {
  689. return _ctools_export_get_defaults($table, $export);
  690. }
  691. // Now, translate the returned cache objects to actual objects.
  692. $cache = array();
  693. foreach ($data as $cached_object) {
  694. $cache[$cached_object->data->{$export['key']}] = $cached_object->data;
  695. }
  696. return $cache;
  697. }
  698. /**
  699. * Unpack data loaded from the database onto an object.
  700. *
  701. * @param $schema
  702. * The schema from drupal_get_schema().
  703. * @param $data
  704. * The data as loaded from the database.
  705. * @param $object
  706. * If an object, data will be unpacked onto it. If a string
  707. * an object of that type will be created.
  708. */
  709. function _ctools_export_unpack_object($schema, $data, $object = 'stdClass') {
  710. if (is_string($object)) {
  711. if (class_exists($object)) {
  712. $object = new $object;
  713. }
  714. else {
  715. $object = new stdClass;
  716. }
  717. }
  718. // Go through our schema and build correlations.
  719. foreach ($schema['fields'] as $field => $info) {
  720. if (isset($data->$field)) {
  721. $object->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
  722. }
  723. else {
  724. $object->$field = NULL;
  725. }
  726. }
  727. if (isset($schema['join'])) {
  728. foreach ($schema['join'] as $join_key => $join) {
  729. $join_schema = ctools_export_get_schema($join['table']);
  730. if (!empty($join['load'])) {
  731. foreach ($join['load'] as $field) {
  732. $info = $join_schema['fields'][$field];
  733. $object->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
  734. }
  735. }
  736. }
  737. }
  738. return $object;
  739. }
  740. /**
  741. * Unpack data loaded from the database onto an object.
  742. *
  743. * @param $table
  744. * The name of the table this object represents.
  745. * @param $data
  746. * The data as loaded from the database.
  747. */
  748. function ctools_export_unpack_object($table, $data) {
  749. $schema = ctools_export_get_schema($table);
  750. return _ctools_export_unpack_object($schema, $data, $schema['export']['object']);
  751. }
  752. /**
  753. * Export a field.
  754. *
  755. * This is a replacement for var_export(), allowing us to more nicely
  756. * format exports. It will recurse down into arrays and will try to
  757. * properly export bools when it can, though PHP has a hard time with
  758. * this since they often end up as strings or ints.
  759. */
  760. function ctools_var_export($var, $prefix = '') {
  761. if (is_array($var)) {
  762. if (empty($var)) {
  763. $output = 'array()';
  764. }
  765. else {
  766. $output = "array(\n";
  767. foreach ($var as $key => $value) {
  768. $output .= $prefix . " " . ctools_var_export($key) . " => " . ctools_var_export($value, $prefix . ' ') . ",\n";
  769. }
  770. $output .= $prefix . ')';
  771. }
  772. }
  773. else if (is_object($var) && get_class($var) === 'stdClass') {
  774. // var_export() will export stdClass objects using an undefined
  775. // magic method __set_state() leaving the export broken. This
  776. // workaround avoids this by casting the object as an array for
  777. // export and casting it back to an object when evaluated.
  778. $output = '(object) ' . ctools_var_export((array) $var, $prefix);
  779. }
  780. else if (is_bool($var)) {
  781. $output = $var ? 'TRUE' : 'FALSE';
  782. }
  783. else {
  784. $output = var_export($var, TRUE);
  785. }
  786. return $output;
  787. }
  788. /**
  789. * Export an object into code.
  790. */
  791. function ctools_export_object($table, $object, $indent = '', $identifier = NULL, $additions = array(), $additions2 = array()) {
  792. $schema = ctools_export_get_schema($table);
  793. if (!isset($identifier)) {
  794. $identifier = $schema['export']['identifier'];
  795. }
  796. $output = $indent . '$' . $identifier . ' = new ' . get_class($object) . "();\n";
  797. if ($schema['export']['can disable']) {
  798. $output .= $indent . '$' . $identifier . '->disabled = FALSE; /* Edit this to true to make a default ' . $identifier . ' disabled initially */' . "\n";
  799. }
  800. if (!empty($schema['export']['api']['current_version'])) {
  801. $output .= $indent . '$' . $identifier . '->api_version = ' . $schema['export']['api']['current_version'] . ";\n";
  802. }
  803. // Put top additions here:
  804. foreach ($additions as $field => $value) {
  805. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  806. }
  807. $fields = $schema['fields'];
  808. if (!empty($schema['join'])) {
  809. foreach ($schema['join'] as $join) {
  810. if (!empty($join['load'])) {
  811. foreach ($join['load'] as $join_field) {
  812. $fields[$join_field] = $join['fields'][$join_field];
  813. }
  814. }
  815. }
  816. }
  817. // Go through our schema and joined tables and build correlations.
  818. foreach ($fields as $field => $info) {
  819. if (!empty($info['no export'])) {
  820. continue;
  821. }
  822. if (!isset($object->$field)) {
  823. if (isset($info['default'])) {
  824. $object->$field = $info['default'];
  825. }
  826. else {
  827. $object->$field = '';
  828. }
  829. }
  830. // Note: This is the *field* export callback, not the table one!
  831. if (!empty($info['export callback']) && function_exists($info['export callback'])) {
  832. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . $info['export callback']($object, $field, $object->$field, $indent) . ";\n";
  833. }
  834. else {
  835. $value = $object->$field;
  836. if ($info['type'] == 'int') {
  837. $value = (isset($info['size']) && $info['size'] == 'tiny') ? (bool) $value : (int) $value;
  838. }
  839. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  840. }
  841. }
  842. // And bottom additions here
  843. foreach ($additions2 as $field => $value) {
  844. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  845. }
  846. return $output;
  847. }
  848. /**
  849. * Get the schema for a given table.
  850. *
  851. * This looks for data the export subsystem needs and applies defaults so
  852. * that it's easily available.
  853. */
  854. function ctools_export_get_schema($table) {
  855. $cache = &drupal_static(__FUNCTION__);
  856. if (empty($cache[$table])) {
  857. $schema = drupal_get_schema($table);
  858. // If our schema isn't loaded, it's possible we're in a state where it
  859. // simply hasn't been cached. If we've been asked, let's force the
  860. // issue.
  861. if (!$schema || empty($schema['export'])) {
  862. // force a schema reset:
  863. $schema = drupal_get_schema($table, TRUE);
  864. }
  865. if (!isset($schema['export'])) {
  866. return array();
  867. }
  868. if (empty($schema['module'])) {
  869. return array();
  870. }
  871. // Add some defaults
  872. $schema['export'] += array(
  873. 'key' => 'name',
  874. 'key name' => 'Name',
  875. 'object' => 'stdClass',
  876. 'status' => 'default_' . $table,
  877. 'default hook' => 'default_' . $table,
  878. 'can disable' => TRUE,
  879. 'identifier' => $table,
  880. 'primary key' => !empty($schema['primary key']) ? $schema['primary key'][0] : '',
  881. 'bulk export' => TRUE,
  882. 'list callback' => "$schema[module]_{$table}_list",
  883. 'to hook code callback' => "$schema[module]_{$table}_to_hook_code",
  884. 'cache defaults' => FALSE,
  885. 'default cache bin' => 'cache',
  886. 'export type string' => 'type',
  887. );
  888. // If the export definition doesn't have the "primary key" then the CRUD
  889. // save callback won't work.
  890. if (empty($schema['export']['primary key']) && user_access('administer site configuration')) {
  891. drupal_set_message(t('The export definition of @table is missing the "primary key" property.', array('@table' => $table)), 'error');
  892. }
  893. // Notes:
  894. // The following callbacks may be defined to override default behavior
  895. // when using CRUD functions:
  896. //
  897. // create callback
  898. // load callback
  899. // load multiple callback
  900. // load all callback
  901. // save callback
  902. // delete callback
  903. // export callback
  904. // import callback
  905. //
  906. // See the appropriate ctools_export_crud function for details on what
  907. // arguments these callbacks should accept. Please do not call these
  908. // directly, always use the ctools_export_crud_* wrappers to ensure
  909. // that default implementations are honored.
  910. $cache[$table] = $schema;
  911. }
  912. return $cache[$table];
  913. }
  914. /**
  915. * Gets the schemas for all tables with ctools object metadata.
  916. */
  917. function ctools_export_get_schemas($for_export = FALSE) {
  918. static $export_tables;
  919. if (is_null($export_tables)) {
  920. $export_tables = array();
  921. $schemas = drupal_get_schema();
  922. foreach ($schemas as $table => $schema) {
  923. if (!isset($schema['export'])) {
  924. unset($schemas[$table]);
  925. continue;
  926. }
  927. $export_tables[$table] = ctools_export_get_schema($table);
  928. }
  929. }
  930. return $for_export ? array_filter($export_tables, '_ctools_export_filter_export_tables') : $export_tables;
  931. }
  932. function _ctools_export_filter_export_tables($schema) {
  933. return !empty($schema['export']['bulk export']);
  934. }
  935. function ctools_export_get_schemas_by_module($modules = array(), $for_export = FALSE) {
  936. $export_tables = array();
  937. $list = ctools_export_get_schemas($for_export);
  938. foreach ($list as $table => $schema) {
  939. $export_tables[$schema['module']][$table] = $schema;
  940. }
  941. return empty($modules) ? $export_tables : array_keys($export_tables, $modules);
  942. }
  943. /**
  944. * Set the status of a default $object as a variable.
  945. *
  946. * The status, in this case, is whether or not it is 'disabled'.
  947. * This function does not check to make sure $object actually
  948. * exists.
  949. */
  950. function ctools_export_set_status($table, $name, $new_status = TRUE) {
  951. $schema = ctools_export_get_schema($table);
  952. $status = variable_get($schema['export']['status'], array());
  953. $status[$name] = $new_status;
  954. variable_set($schema['export']['status'], $status);
  955. }
  956. /**
  957. * Set the status of a default $object as a variable.
  958. *
  959. * This is more efficient than ctools_export_set_status because it
  960. * will actually unset the variable entirely if it's not necessary,
  961. * this saving a bit of space.
  962. */
  963. function ctools_export_set_object_status($object, $new_status = TRUE) {
  964. $table = $object->table;
  965. $schema = ctools_export_get_schema($table);
  966. $export = $schema['export'];
  967. $status = variable_get($export['status'], array());
  968. // Compare
  969. if (!$new_status && $object->export_type & EXPORT_IN_DATABASE) {
  970. unset($status[$object->{$export['key']}]);
  971. }
  972. else {
  973. $status[$object->{$export['key']}] = $new_status;
  974. }
  975. variable_set($export['status'], $status);
  976. }
  977. /**
  978. * Provide a form for displaying an export.
  979. *
  980. * This is a simple form that should be invoked like this:
  981. * @code
  982. * $output = drupal_get_form('ctools_export_form', $code, $object_title);
  983. * @endcode
  984. */
  985. function ctools_export_form($form, &$form_state, $code, $title = '') {
  986. $lines = substr_count($code, "\n");
  987. $form['code'] = array(
  988. '#type' => 'textarea',
  989. '#title' => $title,
  990. '#default_value' => $code,
  991. '#rows' => $lines,
  992. );
  993. return $form;
  994. }
  995. /**
  996. * Create a new object based upon schema values.
  997. *
  998. * Because 'default' has ambiguous meaning on some fields, we will actually
  999. * use 'object default' to fill in default values if default is not set
  1000. * That's a little safer to use as it won't cause weird database default
  1001. * situations.
  1002. */
  1003. function ctools_export_new_object($table, $set_defaults = TRUE) {
  1004. $schema = ctools_export_get_schema($table);
  1005. $export = $schema['export'];
  1006. $object = new $export['object'];
  1007. foreach ($schema['fields'] as $field => $info) {
  1008. if (isset($info['object default'])) {
  1009. $object->$field = $info['object default'];
  1010. }
  1011. else if (isset($info['default'])) {
  1012. $object->$field = $info['default'];
  1013. }
  1014. else {
  1015. $object->$field = NULL;
  1016. }
  1017. }
  1018. if ($set_defaults) {
  1019. // Set some defaults so this data always exists.
  1020. // We don't set the export_type property here, as this object is not saved
  1021. // yet. We do give it NULL so we don't generate notices trying to read it.
  1022. $object->export_type = NULL;
  1023. $object->{$export['export type string']} = t('Local');
  1024. }
  1025. return $object;
  1026. }
  1027. /**
  1028. * Convert a group of objects to code based upon input and return this as a larger
  1029. * export.
  1030. */
  1031. function ctools_export_to_hook_code(&$code, $table, $names = array(), $name = 'foo') {
  1032. $schema = ctools_export_get_schema($table);
  1033. $export = $schema['export'];
  1034. // Use the schema-specified function for generating hook code, if one exists
  1035. if (function_exists($export['to hook code callback'])) {
  1036. $output = $export['to hook code callback']($names, $name);
  1037. }
  1038. // Otherwise, the following code generates basic hook code
  1039. else {
  1040. $output = ctools_export_default_to_hook_code($schema, $table, $names, $name);
  1041. }
  1042. if (!empty($output)) {
  1043. if (isset($export['api'])) {
  1044. if (isset($code[$export['api']['owner']][$export['api']['api']]['version'])) {
  1045. $code[$export['api']['owner']][$export['api']['api']]['version'] = max($code[$export['api']['owner']][$export['api']['api']]['version'], $export['api']['minimum_version']);
  1046. }
  1047. else {
  1048. $code[$export['api']['owner']][$export['api']['api']]['version'] = $export['api']['minimum_version'];
  1049. $code[$export['api']['owner']][$export['api']['api']]['code'] = '';
  1050. }
  1051. $code[$export['api']['owner']][$export['api']['api']]['code'] .= $output;
  1052. }
  1053. else {
  1054. if (empty($code['general'])) {
  1055. $code['general'] = '';
  1056. }
  1057. $code['general'] .= $output;
  1058. }
  1059. }
  1060. }
  1061. /**
  1062. * Default function to export objects to code.
  1063. *
  1064. * Note that if your module provides a 'to hook code callback' then it will
  1065. * receive only $names and $name as arguments. Your module is presumed to
  1066. * already know the rest.
  1067. */
  1068. function ctools_export_default_to_hook_code($schema, $table, $names, $name) {
  1069. $export = $schema['export'];
  1070. $output = '';
  1071. $objects = ctools_export_crud_load_multiple($table, $names);
  1072. if ($objects) {
  1073. $output = "/**\n";
  1074. $output .= " * Implements hook_{$export['default hook']}().\n";
  1075. $output .= " */\n";
  1076. $output .= "function " . $name . "_{$export['default hook']}() {\n";
  1077. $output .= " \${$export['identifier']}s = array();\n\n";
  1078. foreach ($objects as $object) {
  1079. $output .= ctools_export_crud_export($table, $object, ' ');
  1080. $output .= " \${$export['identifier']}s['" . check_plain($object->$export['key']) . "'] = \${$export['identifier']};\n\n";
  1081. }
  1082. $output .= " return \${$export['identifier']}s;\n";
  1083. $output .= "}\n";
  1084. }
  1085. return $output;
  1086. }
  1087. /**
  1088. * Default function for listing bulk exportable objects.
  1089. */
  1090. function ctools_export_default_list($table, $schema) {
  1091. $list = array();
  1092. $items = ctools_export_crud_load_all($table);
  1093. $export_key = $schema['export']['key'];
  1094. foreach ($items as $item) {
  1095. // Try a couple of possible obvious title keys:
  1096. $keys = array('admin_title', 'title');
  1097. if (isset($schema['export']['admin_title'])) {
  1098. array_unshift($keys, $schema['export']['admin_title']);
  1099. }
  1100. $string = '';
  1101. foreach ($keys as $key) {
  1102. if (!empty($item->$key)) {
  1103. $string = $item->$key . " (" . $item->$export_key . ")";
  1104. break;
  1105. }
  1106. }
  1107. if (empty($string)) {
  1108. $string = $item->$export_key;
  1109. }
  1110. $list[$item->$export_key] = check_plain($string);
  1111. }
  1112. return $list;
  1113. }