export.inc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. $cache_table_exists = &drupal_static(__FUNCTION__ . '_table_exists', array());
  354. $cached_database = &drupal_static('ctools_export_load_object_all');
  355. if (!array_key_exists($table, $cache_table_exists)) {
  356. $cache_table_exists[$table] = db_table_exists($table);
  357. }
  358. $schema = ctools_export_get_schema($table);
  359. if (empty($schema) || !$cache_table_exists[$table]) {
  360. return array();
  361. }
  362. $export = $schema['export'];
  363. if (!isset($cache[$table])) {
  364. $cache[$table] = array();
  365. }
  366. // If fetching all and cached all, we've done so and we are finished.
  367. if ($type == 'all' && !empty($cached_database[$table])) {
  368. return $cache[$table];
  369. }
  370. $return = array();
  371. // Don't load anything we've already cached.
  372. if ($type == 'names' && !empty($args)) {
  373. foreach ($args as $id => $name) {
  374. if (isset($cache[$table][$name])) {
  375. $return[$name] = $cache[$table][$name];
  376. unset($args[$id]);
  377. }
  378. }
  379. // If nothing left to load, return the result.
  380. if (empty($args)) {
  381. return $return;
  382. }
  383. }
  384. // Build the query
  385. $query = db_select($table, 't__0')->fields('t__0');
  386. $alias_count = 1;
  387. if (!empty($schema['join'])) {
  388. foreach ($schema['join'] as $join_key => $join) {
  389. if ($join_schema = drupal_get_schema($join['table'])) {
  390. $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
  391. $query->fields('t__' . $alias_count);
  392. $alias_count++;
  393. // Allow joining tables to alter the query through a callback.
  394. if (isset($join['callback']) && function_exists($join['callback'])) {
  395. $join['callback']($query, $schema, $join_schema);
  396. }
  397. }
  398. }
  399. }
  400. $conditions = array();
  401. $query_args = array();
  402. // If they passed in names, add them to the query.
  403. if ($type == 'names') {
  404. $query->condition($export['key'], $args, 'IN');
  405. }
  406. else if ($type == 'conditions') {
  407. foreach ($args as $key => $value) {
  408. if (isset($schema['fields'][$key])) {
  409. $query->condition($key, $value);
  410. }
  411. }
  412. }
  413. $result = $query->execute();
  414. $status = variable_get($export['status'], array());
  415. // Unpack the results of the query onto objects and cache them.
  416. foreach ($result as $data) {
  417. if (isset($schema['export']['object factory']) && function_exists($schema['export']['object factory'])) {
  418. $object = $schema['export']['object factory']($schema, $data);
  419. }
  420. else {
  421. $object = _ctools_export_unpack_object($schema, $data, $export['object']);
  422. }
  423. $object->table = $table;
  424. $object->{$export['export type string']} = t('Normal');
  425. $object->export_type = EXPORT_IN_DATABASE;
  426. // Determine if default object is enabled or disabled.
  427. if (isset($status[$object->{$export['key']}])) {
  428. $object->disabled = $status[$object->{$export['key']}];
  429. }
  430. $cache[$table][$object->{$export['key']}] = $object;
  431. if ($type == 'conditions') {
  432. $return[$object->{$export['key']}] = $object;
  433. }
  434. }
  435. // Load subrecords.
  436. if (isset($export['subrecords callback']) && function_exists($export['subrecords callback'])) {
  437. $export['subrecords callback']($cache[$table]);
  438. }
  439. if ($type == 'names' && !empty($args) && !empty($export['cache defaults'])) {
  440. $defaults = _ctools_export_get_some_defaults($table, $export, $args);
  441. }
  442. else {
  443. $defaults = _ctools_export_get_defaults($table, $export);
  444. }
  445. if ($defaults) {
  446. foreach ($defaults as $object) {
  447. if ($type == 'conditions') {
  448. // if this does not match all of our conditions, skip it.
  449. foreach ($args as $key => $value) {
  450. if (!isset($object->$key)) {
  451. continue 2;
  452. }
  453. if (is_array($value)) {
  454. if (!in_array($object->$key, $value)) {
  455. continue 2;
  456. }
  457. }
  458. else if ($object->$key != $value) {
  459. continue 2;
  460. }
  461. }
  462. }
  463. else if ($type == 'names') {
  464. if (!in_array($object->{$export['key']}, $args)) {
  465. continue;
  466. }
  467. }
  468. // Determine if default object is enabled or disabled.
  469. if (isset($status[$object->{$export['key']}])) {
  470. $object->disabled = $status[$object->{$export['key']}];
  471. }
  472. if (!empty($cache[$table][$object->{$export['key']}])) {
  473. $cache[$table][$object->{$export['key']}]->{$export['export type string']} = t('Overridden');
  474. $cache[$table][$object->{$export['key']}]->export_type |= EXPORT_IN_CODE;
  475. $cache[$table][$object->{$export['key']}]->export_module = isset($object->export_module) ? $object->export_module : NULL;
  476. if ($type == 'conditions') {
  477. $return[$object->{$export['key']}] = $cache[$table][$object->{$export['key']}];
  478. }
  479. }
  480. else {
  481. $object->{$export['export type string']} = t('Default');
  482. $object->export_type = EXPORT_IN_CODE;
  483. $object->in_code_only = TRUE;
  484. $object->table = $table;
  485. $cache[$table][$object->{$export['key']}] = $object;
  486. if ($type == 'conditions') {
  487. $return[$object->{$export['key']}] = $object;
  488. }
  489. }
  490. }
  491. }
  492. // If fetching all, we've done so and we are finished.
  493. if ($type == 'all') {
  494. $cached_database[$table] = TRUE;
  495. return $cache[$table];
  496. }
  497. if ($type == 'names') {
  498. foreach ($args as $name) {
  499. if (isset($cache[$table][$name])) {
  500. $return[$name] = $cache[$table][$name];
  501. }
  502. }
  503. }
  504. // For conditions,
  505. return $return;
  506. }
  507. /**
  508. * Reset all static caches in ctools_export_load_object() or static caches for
  509. * a given table in ctools_export_load_object().
  510. *
  511. * @param $table
  512. * String that is the name of a table. If not defined, all static caches in
  513. * ctools_export_load_object() will be reset.
  514. */
  515. function ctools_export_load_object_reset($table = NULL) {
  516. // Reset plugin cache to make sure new include files are picked up.
  517. ctools_include('plugins');
  518. ctools_get_plugins_reset();
  519. if (empty($table)) {
  520. drupal_static_reset('ctools_export_load_object');
  521. drupal_static_reset('ctools_export_load_object_all');
  522. drupal_static_reset('_ctools_export_get_defaults');
  523. }
  524. else {
  525. $cache = &drupal_static('ctools_export_load_object');
  526. $cached_database = &drupal_static('ctools_export_load_object_all');
  527. $cached_defaults = &drupal_static('_ctools_export_get_defaults');
  528. unset($cache[$table]);
  529. unset($cached_database[$table]);
  530. unset($cached_defaults[$table]);
  531. }
  532. }
  533. /**
  534. * Get the default version of an object, if it exists.
  535. *
  536. * This function doesn't care if an object is in the database or not and
  537. * does not check. This means that export_type could appear to be incorrect,
  538. * because a version could exist in the database. However, it's not
  539. * incorrect for this function as it is *only* used for the default
  540. * in code version.
  541. */
  542. function ctools_get_default_object($table, $name) {
  543. $schema = ctools_export_get_schema($table);
  544. $export = $schema['export'];
  545. if (!$export['default hook']) {
  546. return;
  547. }
  548. // Try to load individually from cache if this cache is enabled.
  549. if (!empty($export['cache defaults'])) {
  550. $defaults = _ctools_export_get_some_defaults($table, $export, array($name));
  551. }
  552. else {
  553. $defaults = _ctools_export_get_defaults($table, $export);
  554. }
  555. $status = variable_get($export['status'], array());
  556. if (!isset($defaults[$name])) {
  557. return;
  558. }
  559. $object = $defaults[$name];
  560. // Determine if default object is enabled or disabled.
  561. if (isset($status[$object->{$export['key']}])) {
  562. $object->disabled = $status[$object->{$export['key']}];
  563. }
  564. $object->{$export['export type string']} = t('Default');
  565. $object->export_type = EXPORT_IN_CODE;
  566. $object->in_code_only = TRUE;
  567. return $object;
  568. }
  569. /**
  570. * Call the hook to get all default objects of the given type from the
  571. * export. If configured properly, this could include loading up an API
  572. * to get default objects.
  573. */
  574. function _ctools_export_get_defaults($table, $export) {
  575. $cache = &drupal_static(__FUNCTION__, array());
  576. // If defaults may be cached, first see if we can load from cache.
  577. if (!isset($cache[$table]) && !empty($export['cache defaults'])) {
  578. $cache[$table] = _ctools_export_get_defaults_from_cache($table, $export);
  579. }
  580. if (!isset($cache[$table])) {
  581. // If we're caching, attempt to get a lock. We will wait a short time
  582. // on the lock, but not too long, because it's better to just rebuild
  583. // and throw away results than wait too long on a lock.
  584. if (!empty($export['cache defaults'])) {
  585. for ($counter = 0; !($lock = lock_acquire('ctools_export:' . $table)) && $counter > 5; $counter++) {
  586. lock_wait('ctools_export:' . $table, 1);
  587. ++$counter;
  588. }
  589. }
  590. $cache[$table] = array();
  591. if ($export['default hook']) {
  592. if (!empty($export['api'])) {
  593. ctools_include('plugins');
  594. $info = ctools_plugin_api_include($export['api']['owner'], $export['api']['api'],
  595. $export['api']['minimum_version'], $export['api']['current_version']);
  596. $modules = array_keys($info);
  597. }
  598. else {
  599. $modules = module_implements($export['default hook']);
  600. }
  601. foreach ($modules as $module) {
  602. $function = $module . '_' . $export['default hook'];
  603. if (function_exists($function)) {
  604. foreach ((array) $function($export) as $name => $object) {
  605. // Record the module that provides this exportable.
  606. $object->export_module = $module;
  607. if (empty($export['api'])) {
  608. $cache[$table][$name] = $object;
  609. }
  610. else {
  611. // If version checking is enabled, ensure that the object can be used.
  612. if (isset($object->api_version) &&
  613. version_compare($object->api_version, $export['api']['minimum_version']) >= 0 &&
  614. version_compare($object->api_version, $export['api']['current_version']) <= 0) {
  615. $cache[$table][$name] = $object;
  616. }
  617. }
  618. }
  619. }
  620. }
  621. drupal_alter($export['default hook'], $cache[$table]);
  622. // If we acquired a lock earlier, cache the results and release the
  623. // lock.
  624. if (!empty($lock)) {
  625. // Cache the index.
  626. $index = array_keys($cache[$table]);
  627. cache_set('ctools_export_index:' . $table, $index, $export['default cache bin']);
  628. // Cache each object.
  629. foreach ($cache[$table] as $name => $object) {
  630. cache_set('ctools_export:' . $table . ':' . $name, $object, $export['default cache bin']);
  631. }
  632. lock_release('ctools_export:' . $table);
  633. }
  634. }
  635. }
  636. return $cache[$table];
  637. }
  638. /**
  639. * Attempt to load default objects from cache.
  640. *
  641. * We can be instructed to cache default objects by the schema. If so
  642. * we cache them as an index which is a list of all default objects, and
  643. * then each default object is cached individually.
  644. *
  645. * @return Either an array of cached objects, or NULL indicating a cache
  646. * rebuild is necessary.
  647. */
  648. function _ctools_export_get_defaults_from_cache($table, $export) {
  649. $data = cache_get('ctools_export_index:' . $table, $export['default cache bin']);
  650. if (!$data || !is_array($data->data)) {
  651. return;
  652. }
  653. // This is the perfectly valid case where there are no default objects,
  654. // and we have cached this state.
  655. if (empty($data->data)) {
  656. return array();
  657. }
  658. $keys = array();
  659. foreach ($data->data as $name) {
  660. $keys[] = 'ctools_export:' . $table . ':' . $name;
  661. }
  662. $data = cache_get_multiple($keys, $export['default cache bin']);
  663. // If any of our indexed keys missed, then we have a fail and we need to
  664. // rebuild.
  665. if (!empty($keys)) {
  666. return;
  667. }
  668. // Now, translate the returned cache objects to actual objects.
  669. $cache = array();
  670. foreach ($data as $cached_object) {
  671. $cache[$cached_object->data->{$export['key']}] = $cached_object->data;
  672. }
  673. return $cache;
  674. }
  675. /**
  676. * Get a limited number of default objects.
  677. *
  678. * This attempts to load the objects directly from cache. If it cannot,
  679. * the cache is rebuilt. This does not disturb the general get defaults
  680. * from cache object.
  681. *
  682. * This function should ONLY be called if default caching is enabled.
  683. * It does not check, it is assumed the caller has already done so.
  684. */
  685. function _ctools_export_get_some_defaults($table, $export, $names) {
  686. foreach ($names as $name) {
  687. $keys[] = 'ctools_export:' . $table . ':' . $name;
  688. }
  689. $data = cache_get_multiple($keys, $export['default cache bin']);
  690. // Cache hits remove the $key from $keys by reference. Cache
  691. // misses do not. A cache miss indicates we may have to rebuild.
  692. if (!empty($keys)) {
  693. return _ctools_export_get_defaults($table, $export);
  694. }
  695. // Now, translate the returned cache objects to actual objects.
  696. $cache = array();
  697. foreach ($data as $cached_object) {
  698. $cache[$cached_object->data->{$export['key']}] = $cached_object->data;
  699. }
  700. return $cache;
  701. }
  702. /**
  703. * Unpack data loaded from the database onto an object.
  704. *
  705. * @param $schema
  706. * The schema from drupal_get_schema().
  707. * @param $data
  708. * The data as loaded from the database.
  709. * @param $object
  710. * If an object, data will be unpacked onto it. If a string
  711. * an object of that type will be created.
  712. */
  713. function _ctools_export_unpack_object($schema, $data, $object = 'stdClass') {
  714. if (is_string($object)) {
  715. if (class_exists($object)) {
  716. $object = new $object;
  717. }
  718. else {
  719. $object = new stdClass;
  720. }
  721. }
  722. // Go through our schema and build correlations.
  723. foreach ($schema['fields'] as $field => $info) {
  724. if (isset($data->$field)) {
  725. $object->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
  726. }
  727. else {
  728. $object->$field = NULL;
  729. }
  730. }
  731. if (isset($schema['join'])) {
  732. foreach ($schema['join'] as $join_key => $join) {
  733. $join_schema = ctools_export_get_schema($join['table']);
  734. if (!empty($join['load'])) {
  735. foreach ($join['load'] as $field) {
  736. $info = $join_schema['fields'][$field];
  737. $object->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
  738. }
  739. }
  740. }
  741. }
  742. return $object;
  743. }
  744. /**
  745. * Unpack data loaded from the database onto an object.
  746. *
  747. * @param $table
  748. * The name of the table this object represents.
  749. * @param $data
  750. * The data as loaded from the database.
  751. */
  752. function ctools_export_unpack_object($table, $data) {
  753. $schema = ctools_export_get_schema($table);
  754. return _ctools_export_unpack_object($schema, $data, $schema['export']['object']);
  755. }
  756. /**
  757. * Export a field.
  758. *
  759. * This is a replacement for var_export(), allowing us to more nicely
  760. * format exports. It will recurse down into arrays and will try to
  761. * properly export bools when it can, though PHP has a hard time with
  762. * this since they often end up as strings or ints.
  763. */
  764. function ctools_var_export($var, $prefix = '') {
  765. if (is_array($var)) {
  766. if (empty($var)) {
  767. $output = 'array()';
  768. }
  769. else {
  770. $output = "array(\n";
  771. foreach ($var as $key => $value) {
  772. $output .= $prefix . " " . ctools_var_export($key) . " => " . ctools_var_export($value, $prefix . ' ') . ",\n";
  773. }
  774. $output .= $prefix . ')';
  775. }
  776. }
  777. else if (is_object($var) && get_class($var) === 'stdClass') {
  778. // var_export() will export stdClass objects using an undefined
  779. // magic method __set_state() leaving the export broken. This
  780. // workaround avoids this by casting the object as an array for
  781. // export and casting it back to an object when evaluated.
  782. $output = '(object) ' . ctools_var_export((array) $var, $prefix);
  783. }
  784. else if (is_bool($var)) {
  785. $output = $var ? 'TRUE' : 'FALSE';
  786. }
  787. else {
  788. $output = var_export($var, TRUE);
  789. }
  790. return $output;
  791. }
  792. /**
  793. * Export an object into code.
  794. */
  795. function ctools_export_object($table, $object, $indent = '', $identifier = NULL, $additions = array(), $additions2 = array()) {
  796. $schema = ctools_export_get_schema($table);
  797. if (!isset($identifier)) {
  798. $identifier = $schema['export']['identifier'];
  799. }
  800. $output = $indent . '$' . $identifier . ' = new ' . get_class($object) . "();\n";
  801. if ($schema['export']['can disable']) {
  802. $output .= $indent . '$' . $identifier . '->disabled = FALSE; /* Edit this to true to make a default ' . $identifier . ' disabled initially */' . "\n";
  803. }
  804. if (!empty($schema['export']['api']['current_version'])) {
  805. $output .= $indent . '$' . $identifier . '->api_version = ' . $schema['export']['api']['current_version'] . ";\n";
  806. }
  807. // Put top additions here:
  808. foreach ($additions as $field => $value) {
  809. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  810. }
  811. $fields = $schema['fields'];
  812. if (!empty($schema['join'])) {
  813. foreach ($schema['join'] as $join) {
  814. if (!empty($join['load'])) {
  815. foreach ($join['load'] as $join_field) {
  816. $fields[$join_field] = $join['fields'][$join_field];
  817. }
  818. }
  819. }
  820. }
  821. // Go through our schema and joined tables and build correlations.
  822. foreach ($fields as $field => $info) {
  823. if (!empty($info['no export'])) {
  824. continue;
  825. }
  826. if (!isset($object->$field)) {
  827. if (isset($info['default'])) {
  828. $object->$field = $info['default'];
  829. }
  830. else {
  831. $object->$field = '';
  832. }
  833. }
  834. // Note: This is the *field* export callback, not the table one!
  835. if (!empty($info['export callback']) && function_exists($info['export callback'])) {
  836. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . $info['export callback']($object, $field, $object->$field, $indent) . ";\n";
  837. }
  838. else {
  839. $value = $object->$field;
  840. if ($info['type'] == 'int') {
  841. $value = (isset($info['size']) && $info['size'] == 'tiny') ? (bool) $value : (int) $value;
  842. }
  843. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  844. }
  845. }
  846. // And bottom additions here
  847. foreach ($additions2 as $field => $value) {
  848. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  849. }
  850. return $output;
  851. }
  852. /**
  853. * Get the schema for a given table.
  854. *
  855. * This looks for data the export subsystem needs and applies defaults so
  856. * that it's easily available.
  857. */
  858. function ctools_export_get_schema($table) {
  859. $cache = &drupal_static(__FUNCTION__);
  860. if (empty($cache[$table])) {
  861. $schema = drupal_get_schema($table);
  862. // If our schema isn't loaded, it's possible we're in a state where it
  863. // simply hasn't been cached. If we've been asked, let's force the
  864. // issue.
  865. if (!$schema || empty($schema['export'])) {
  866. // force a schema reset:
  867. $schema = drupal_get_schema($table, TRUE);
  868. }
  869. if (!isset($schema['export'])) {
  870. return array();
  871. }
  872. if (empty($schema['module'])) {
  873. return array();
  874. }
  875. // Add some defaults
  876. $schema['export'] += array(
  877. 'key' => 'name',
  878. 'key name' => 'Name',
  879. 'object' => 'stdClass',
  880. 'status' => 'default_' . $table,
  881. 'default hook' => 'default_' . $table,
  882. 'can disable' => TRUE,
  883. 'identifier' => $table,
  884. 'primary key' => !empty($schema['primary key']) ? $schema['primary key'][0] : '',
  885. 'bulk export' => TRUE,
  886. 'list callback' => "$schema[module]_{$table}_list",
  887. 'to hook code callback' => "$schema[module]_{$table}_to_hook_code",
  888. 'cache defaults' => FALSE,
  889. 'default cache bin' => 'cache',
  890. 'export type string' => 'type',
  891. );
  892. // If the export definition doesn't have the "primary key" then the CRUD
  893. // save callback won't work.
  894. if (empty($schema['export']['primary key']) && user_access('administer site configuration')) {
  895. drupal_set_message(t('The export definition of @table is missing the "primary key" property.', array('@table' => $table)), 'error');
  896. }
  897. // Notes:
  898. // The following callbacks may be defined to override default behavior
  899. // when using CRUD functions:
  900. //
  901. // create callback
  902. // load callback
  903. // load multiple callback
  904. // load all callback
  905. // save callback
  906. // delete callback
  907. // export callback
  908. // import callback
  909. //
  910. // See the appropriate ctools_export_crud function for details on what
  911. // arguments these callbacks should accept. Please do not call these
  912. // directly, always use the ctools_export_crud_* wrappers to ensure
  913. // that default implementations are honored.
  914. $cache[$table] = $schema;
  915. }
  916. return $cache[$table];
  917. }
  918. /**
  919. * Gets the schemas for all tables with ctools object metadata.
  920. */
  921. function ctools_export_get_schemas($for_export = FALSE) {
  922. $export_tables = &drupal_static(__FUNCTION__);
  923. if (is_null($export_tables)) {
  924. $export_tables = array();
  925. $schemas = drupal_get_schema();
  926. foreach ($schemas as $table => $schema) {
  927. if (!isset($schema['export'])) {
  928. unset($schemas[$table]);
  929. continue;
  930. }
  931. $export_tables[$table] = ctools_export_get_schema($table);
  932. }
  933. }
  934. return $for_export ? array_filter($export_tables, '_ctools_export_filter_export_tables') : $export_tables;
  935. }
  936. function _ctools_export_filter_export_tables($schema) {
  937. return !empty($schema['export']['bulk export']);
  938. }
  939. function ctools_export_get_schemas_by_module($modules = array(), $for_export = FALSE) {
  940. $export_tables = array();
  941. $list = ctools_export_get_schemas($for_export);
  942. foreach ($list as $table => $schema) {
  943. $export_tables[$schema['module']][$table] = $schema;
  944. }
  945. return empty($modules) ? $export_tables : array_keys($export_tables, $modules);
  946. }
  947. /**
  948. * Set the status of a default $object as a variable.
  949. *
  950. * The status, in this case, is whether or not it is 'disabled'.
  951. * This function does not check to make sure $object actually
  952. * exists.
  953. */
  954. function ctools_export_set_status($table, $name, $new_status = TRUE) {
  955. $schema = ctools_export_get_schema($table);
  956. $status = variable_get($schema['export']['status'], array());
  957. $status[$name] = $new_status;
  958. variable_set($schema['export']['status'], $status);
  959. }
  960. /**
  961. * Set the status of a default $object as a variable.
  962. *
  963. * This is more efficient than ctools_export_set_status because it
  964. * will actually unset the variable entirely if it's not necessary,
  965. * this saving a bit of space.
  966. */
  967. function ctools_export_set_object_status($object, $new_status = TRUE) {
  968. $table = $object->table;
  969. $schema = ctools_export_get_schema($table);
  970. $export = $schema['export'];
  971. $status = variable_get($export['status'], array());
  972. // Compare
  973. if (!$new_status && $object->export_type & EXPORT_IN_DATABASE) {
  974. unset($status[$object->{$export['key']}]);
  975. }
  976. else {
  977. $status[$object->{$export['key']}] = $new_status;
  978. }
  979. variable_set($export['status'], $status);
  980. }
  981. /**
  982. * Provide a form for displaying an export.
  983. *
  984. * This is a simple form that should be invoked like this:
  985. * @code
  986. * $output = drupal_get_form('ctools_export_form', $code, $object_title);
  987. * @endcode
  988. */
  989. function ctools_export_form($form, &$form_state, $code, $title = '') {
  990. $lines = substr_count($code, "\n");
  991. $form['code'] = array(
  992. '#type' => 'textarea',
  993. '#title' => $title,
  994. '#default_value' => $code,
  995. '#rows' => $lines,
  996. );
  997. return $form;
  998. }
  999. /**
  1000. * Create a new object based upon schema values.
  1001. *
  1002. * Because 'default' has ambiguous meaning on some fields, we will actually
  1003. * use 'object default' to fill in default values if default is not set
  1004. * That's a little safer to use as it won't cause weird database default
  1005. * situations.
  1006. */
  1007. function ctools_export_new_object($table, $set_defaults = TRUE) {
  1008. $schema = ctools_export_get_schema($table);
  1009. $export = $schema['export'];
  1010. $object = new $export['object'];
  1011. foreach ($schema['fields'] as $field => $info) {
  1012. if (isset($info['object default'])) {
  1013. $object->$field = $info['object default'];
  1014. }
  1015. else if (isset($info['default'])) {
  1016. $object->$field = $info['default'];
  1017. }
  1018. else {
  1019. $object->$field = NULL;
  1020. }
  1021. }
  1022. if ($set_defaults) {
  1023. // Set some defaults so this data always exists.
  1024. // We don't set the export_type property here, as this object is not saved
  1025. // yet. We do give it NULL so we don't generate notices trying to read it.
  1026. $object->export_type = NULL;
  1027. $object->{$export['export type string']} = t('Local');
  1028. }
  1029. return $object;
  1030. }
  1031. /**
  1032. * Convert a group of objects to code based upon input and return this as a larger
  1033. * export.
  1034. */
  1035. function ctools_export_to_hook_code(&$code, $table, $names = array(), $name = 'foo') {
  1036. $schema = ctools_export_get_schema($table);
  1037. $export = $schema['export'];
  1038. // Use the schema-specified function for generating hook code, if one exists
  1039. if (function_exists($export['to hook code callback'])) {
  1040. $output = $export['to hook code callback']($names, $name);
  1041. }
  1042. // Otherwise, the following code generates basic hook code
  1043. else {
  1044. $output = ctools_export_default_to_hook_code($schema, $table, $names, $name);
  1045. }
  1046. if (!empty($output)) {
  1047. if (isset($export['api'])) {
  1048. if (isset($code[$export['api']['owner']][$export['api']['api']]['version'])) {
  1049. $code[$export['api']['owner']][$export['api']['api']]['version'] = max($code[$export['api']['owner']][$export['api']['api']]['version'], $export['api']['minimum_version']);
  1050. }
  1051. else {
  1052. $code[$export['api']['owner']][$export['api']['api']]['version'] = $export['api']['minimum_version'];
  1053. $code[$export['api']['owner']][$export['api']['api']]['code'] = '';
  1054. }
  1055. $code[$export['api']['owner']][$export['api']['api']]['code'] .= $output;
  1056. }
  1057. else {
  1058. if (empty($code['general'])) {
  1059. $code['general'] = '';
  1060. }
  1061. $code['general'] .= $output;
  1062. }
  1063. }
  1064. }
  1065. /**
  1066. * Default function to export objects to code.
  1067. *
  1068. * Note that if your module provides a 'to hook code callback' then it will
  1069. * receive only $names and $name as arguments. Your module is presumed to
  1070. * already know the rest.
  1071. */
  1072. function ctools_export_default_to_hook_code($schema, $table, $names, $name) {
  1073. $export = $schema['export'];
  1074. $output = '';
  1075. $objects = ctools_export_crud_load_multiple($table, $names);
  1076. if ($objects) {
  1077. $output = "/**\n";
  1078. $output .= " * Implements hook_{$export['default hook']}().\n";
  1079. $output .= " */\n";
  1080. $output .= "function " . $name . "_{$export['default hook']}() {\n";
  1081. $output .= " \${$export['identifier']}s = array();\n\n";
  1082. foreach ($objects as $object) {
  1083. $output .= ctools_export_crud_export($table, $object, ' ');
  1084. $output .= " \${$export['identifier']}s['" . check_plain($object->$export['key']) . "'] = \${$export['identifier']};\n\n";
  1085. }
  1086. $output .= " return \${$export['identifier']}s;\n";
  1087. $output .= "}\n";
  1088. }
  1089. return $output;
  1090. }
  1091. /**
  1092. * Default function for listing bulk exportable objects.
  1093. */
  1094. function ctools_export_default_list($table, $schema) {
  1095. $list = array();
  1096. $items = ctools_export_crud_load_all($table);
  1097. $export_key = $schema['export']['key'];
  1098. foreach ($items as $item) {
  1099. // Try a couple of possible obvious title keys:
  1100. $keys = array('admin_title', 'title');
  1101. if (isset($schema['export']['admin_title'])) {
  1102. array_unshift($keys, $schema['export']['admin_title']);
  1103. }
  1104. $string = '';
  1105. foreach ($keys as $key) {
  1106. if (!empty($item->$key)) {
  1107. $string = $item->$key . " (" . $item->$export_key . ")";
  1108. break;
  1109. }
  1110. }
  1111. if (empty($string)) {
  1112. $string = $item->$export_key;
  1113. }
  1114. $list[$item->$export_key] = check_plain($string);
  1115. }
  1116. return $list;
  1117. }