export.inc 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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. *
  118. * @return
  119. * An array of all loaded objects, keyed by the unique IDs of the export key.
  120. */
  121. function ctools_export_crud_load_all($table, $reset = FALSE) {
  122. $schema = ctools_export_get_schema($table);
  123. if (empty($schema['export'])) {
  124. return array();
  125. }
  126. $export = $schema['export'];
  127. if ($reset) {
  128. ctools_export_load_object_reset($table);
  129. }
  130. if (!empty($export['load all callback']) && function_exists($export['load all callback'])) {
  131. return $export['load all callback']($reset);
  132. }
  133. else {
  134. return ctools_export_load_object($table, 'all');
  135. }
  136. }
  137. /**
  138. * Save a single exportable object.
  139. *
  140. * @param $table
  141. * The name of the table to use to retrieve $schema values. This table
  142. * must have an 'export' section containing data or this function
  143. * will fail.
  144. * @param $object
  145. * The fully populated object to save.
  146. *
  147. * @return
  148. * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
  149. * SAVED_UPDATED is returned depending on the operation performed. The
  150. * $object parameter contains values for any serial fields defined by the $table
  151. */
  152. function ctools_export_crud_save($table, &$object) {
  153. $schema = ctools_export_get_schema($table);
  154. $export = $schema['export'];
  155. if (!empty($export['save callback']) && function_exists($export['save callback'])) {
  156. return $export['save callback']($object);
  157. }
  158. else {
  159. // Objects should have a serial primary key. If not, simply fail to write.
  160. if (empty($export['primary key'])) {
  161. return FALSE;
  162. }
  163. $key = $export['primary key'];
  164. if ($object->export_type & EXPORT_IN_DATABASE) {
  165. // Existing record.
  166. $update = array($key);
  167. }
  168. else {
  169. // New record.
  170. $update = array();
  171. $object->export_type = EXPORT_IN_DATABASE;
  172. }
  173. return drupal_write_record($table, $object, $update);
  174. }
  175. }
  176. /**
  177. * Delete a single exportable object.
  178. *
  179. * This only deletes from the database, which means that if an item is in
  180. * code, then this is actually a revert.
  181. *
  182. * @param $table
  183. * The name of the table to use to retrieve $schema values. This table
  184. * must have an 'export' section containing data or this function
  185. * will fail.
  186. * @param $object
  187. * The fully populated object to delete, or the export key.
  188. */
  189. function ctools_export_crud_delete($table, $object) {
  190. $schema = ctools_export_get_schema($table);
  191. $export = $schema['export'];
  192. if (!empty($export['delete callback']) && function_exists($export['delete callback'])) {
  193. return $export['delete callback']($object);
  194. }
  195. else {
  196. // If we were sent an object, get the export key from it. Otherwise
  197. // assume we were sent the export key.
  198. $value = is_object($object) ? $object->{$export['key']} : $object;
  199. db_delete($table)
  200. ->condition($export['key'], $value)
  201. ->execute();
  202. }
  203. }
  204. /**
  205. * Get the exported code of a single exportable object.
  206. *
  207. * @param $table
  208. * The name of the table to use to retrieve $schema values. This table
  209. * must have an 'export' section containing data or this function
  210. * will fail.
  211. * @param $object
  212. * The fully populated object to delete, or the export key.
  213. * @param $indent
  214. * Any indentation to apply to the code, in case this object is embedded
  215. * into another, for example.
  216. *
  217. * @return
  218. * A string containing the executable export of the object.
  219. */
  220. function ctools_export_crud_export($table, $object, $indent = '') {
  221. $schema = ctools_export_get_schema($table);
  222. $export = $schema['export'];
  223. if (!empty($export['export callback']) && function_exists($export['export callback'])) {
  224. return $export['export callback']($object, $indent);
  225. }
  226. else {
  227. return ctools_export_object($table, $object, $indent);
  228. }
  229. }
  230. /**
  231. * Turn exported code into an object.
  232. *
  233. * Note: If the code is poorly formed, this could crash and there is no
  234. * way to prevent this.
  235. *
  236. * @param $table
  237. * The name of the table to use to retrieve $schema values. This table
  238. * must have an 'export' section containing data or this function
  239. * will fail.
  240. * @param $code
  241. * The code to eval to create the object.
  242. *
  243. * @return
  244. * An object created from the export. This object will NOT have been saved
  245. * to the database. In the case of failure, a string containing all errors
  246. * that the system was able to determine.
  247. */
  248. function ctools_export_crud_import($table, $code) {
  249. $schema = ctools_export_get_schema($table);
  250. $export = $schema['export'];
  251. if (!empty($export['import callback']) && function_exists($export['import callback'])) {
  252. return $export['import callback']($code);
  253. }
  254. else {
  255. ob_start();
  256. eval($code);
  257. ob_end_clean();
  258. if (empty(${$export['identifier']})) {
  259. $errors = ob_get_contents();
  260. if (empty($errors)) {
  261. $errors = t('No item found.');
  262. }
  263. return $errors;
  264. }
  265. $item = ${$export['identifier']};
  266. // Set these defaults just the same way that ctools_export_new_object sets
  267. // them.
  268. $item->export_type = NULL;
  269. $item->{$export['export type string']} = t('Local');
  270. return $item;
  271. }
  272. }
  273. /**
  274. * Change the status of a certain object.
  275. *
  276. * @param $table
  277. * The name of the table to use to enable a certain object. This table
  278. * must have an 'export' section containing data or this function
  279. * will fail.
  280. * @param $object
  281. * The fully populated object to enable, or the machine readable name.
  282. * @param $status
  283. * The status, in this case, is whether or not it is 'disabled'.
  284. */
  285. function ctools_export_crud_set_status($table, $object, $status) {
  286. $schema = ctools_export_get_schema($table);
  287. $export = $schema['export'];
  288. if (!empty($export['status callback']) && function_exists($export['status callback'])) {
  289. $export['status callback']($object, $status);
  290. }
  291. else {
  292. if (is_object($object)) {
  293. ctools_export_set_object_status($object, $status);
  294. }
  295. else {
  296. ctools_export_set_status($table, $object, $status);
  297. }
  298. }
  299. }
  300. /**
  301. * Enable a certain object.
  302. *
  303. * @param $table
  304. * The name of the table to use to enable a certain object. This table
  305. * must have an 'export' section containing data or this function
  306. * will fail.
  307. * @param $object
  308. * The fully populated object to enable, or the machine readable name.
  309. */
  310. function ctools_export_crud_enable($table, $object) {
  311. return ctools_export_crud_set_status($table, $object, FALSE);
  312. }
  313. /**
  314. * Disable a certain object.
  315. *
  316. * @param $table
  317. * The name of the table to use to disable a certain object. This table
  318. * must have an 'export' section containing data or this function
  319. * will fail.
  320. * @param $object
  321. * The fully populated object to disable, or the machine readable name.
  322. */
  323. function ctools_export_crud_disable($table, $object) {
  324. return ctools_export_crud_set_status($table, $object, TRUE);
  325. }
  326. /**
  327. * @}
  328. */
  329. /**
  330. * Load some number of exportable objects.
  331. *
  332. * This function will cache the objects, load subsidiary objects if necessary,
  333. * check default objects in code and properly set them up. It will cache
  334. * the results so that multiple calls to load the same objects
  335. * will not cause problems.
  336. *
  337. * It attempts to reduce, as much as possible, the number of queries
  338. * involved.
  339. *
  340. * @param $table
  341. * The name of the table to be loaded from. Data is expected to be in the
  342. * schema to make all this work.
  343. * @param $type
  344. * A string to notify the loader what the argument is
  345. * - all: load all items. This is the default. $args is unused.
  346. * - names: $args will be an array of specific named objects to load.
  347. * - conditions: $args will be a keyed array of conditions. The conditions
  348. * must be in the schema for this table or errors will result.
  349. * @param $args
  350. * An array of arguments whose actual use is defined by the $type argument.
  351. */
  352. function ctools_export_load_object($table, $type = 'all', $args = array()) {
  353. $cache = &drupal_static(__FUNCTION__);
  354. $cache_table_exists = &drupal_static(__FUNCTION__ . '_table_exists', array());
  355. $cached_database = &drupal_static('ctools_export_load_object_all');
  356. if (!array_key_exists($table, $cache_table_exists)) {
  357. $cache_table_exists[$table] = db_table_exists($table);
  358. }
  359. $schema = ctools_export_get_schema($table);
  360. if (empty($schema) || !$cache_table_exists[$table]) {
  361. return array();
  362. }
  363. $export = $schema['export'];
  364. if (!isset($cache[$table])) {
  365. $cache[$table] = array();
  366. }
  367. // If fetching all and cached all, we've done so and we are finished.
  368. if ($type == 'all' && !empty($cached_database[$table])) {
  369. return $cache[$table];
  370. }
  371. $return = array();
  372. // Don't load anything we've already cached.
  373. if ($type == 'names' && !empty($args)) {
  374. foreach ($args as $id => $name) {
  375. if (isset($cache[$table][$name])) {
  376. $return[$name] = $cache[$table][$name];
  377. unset($args[$id]);
  378. }
  379. }
  380. // If nothing left to load, return the result.
  381. if (empty($args)) {
  382. return $return;
  383. }
  384. }
  385. // Build the query.
  386. $query = db_select($table, 't__0')->fields('t__0');
  387. $alias_count = 1;
  388. if (!empty($schema['join'])) {
  389. foreach ($schema['join'] as $join_key => $join) {
  390. if ($join_schema = drupal_get_schema($join['table'])) {
  391. $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
  392. $query->fields('t__' . $alias_count);
  393. $alias_count++;
  394. // Allow joining tables to alter the query through a callback.
  395. if (isset($join['callback']) && function_exists($join['callback'])) {
  396. $join['callback']($query, $schema, $join_schema);
  397. }
  398. }
  399. }
  400. }
  401. $conditions = array();
  402. $query_args = array();
  403. // If they passed in names, add them to the query.
  404. if ($type == 'names') {
  405. $query->condition($export['key'], $args, 'IN');
  406. }
  407. elseif ($type == 'conditions') {
  408. foreach ($args as $key => $value) {
  409. if (isset($schema['fields'][$key])) {
  410. $query->condition($key, $value);
  411. }
  412. }
  413. }
  414. $result = $query->execute();
  415. $status = variable_get($export['status'], array());
  416. // Unpack the results of the query onto objects and cache them.
  417. foreach ($result as $data) {
  418. if (isset($schema['export']['object factory']) && function_exists($schema['export']['object factory'])) {
  419. $object = $schema['export']['object factory']($schema, $data);
  420. }
  421. else {
  422. $object = _ctools_export_unpack_object($schema, $data, $export['object']);
  423. }
  424. $object->table = $table;
  425. $object->{$export['export type string']} = t('Normal');
  426. $object->export_type = EXPORT_IN_DATABASE;
  427. // Determine if default object is enabled or disabled.
  428. if (isset($status[$object->{$export['key']}])) {
  429. $object->disabled = $status[$object->{$export['key']}];
  430. }
  431. $cache[$table][$object->{$export['key']}] = $object;
  432. if ($type == 'conditions') {
  433. $return[$object->{$export['key']}] = $object;
  434. }
  435. }
  436. // Load subrecords.
  437. if (isset($export['subrecords callback']) && function_exists($export['subrecords callback'])) {
  438. $export['subrecords callback']($cache[$table]);
  439. }
  440. if ($type == 'names' && !empty($args) && !empty($export['cache defaults'])) {
  441. $defaults = _ctools_export_get_some_defaults($table, $export, $args);
  442. }
  443. else {
  444. $defaults = _ctools_export_get_defaults($table, $export);
  445. }
  446. if ($defaults) {
  447. foreach ($defaults as $object) {
  448. if ($type == 'conditions') {
  449. // If this does not match all of our conditions, skip it.
  450. foreach ($args as $key => $value) {
  451. if (!isset($object->$key)) {
  452. continue 2;
  453. }
  454. if (is_array($value)) {
  455. if (!in_array($object->$key, $value)) {
  456. continue 2;
  457. }
  458. }
  459. elseif ($object->$key != $value) {
  460. continue 2;
  461. }
  462. }
  463. }
  464. elseif ($type == 'names') {
  465. if (!in_array($object->{$export['key']}, $args)) {
  466. continue;
  467. }
  468. }
  469. // Determine if default object is enabled or disabled.
  470. if (isset($status[$object->{$export['key']}])) {
  471. $object->disabled = $status[$object->{$export['key']}];
  472. }
  473. if (!empty($cache[$table][$object->{$export['key']}])) {
  474. $cache[$table][$object->{$export['key']}]->{$export['export type string']} = t('Overridden');
  475. $cache[$table][$object->{$export['key']}]->export_type |= EXPORT_IN_CODE;
  476. $cache[$table][$object->{$export['key']}]->export_module = isset($object->export_module) ? $object->export_module : NULL;
  477. if ($type == 'conditions') {
  478. $return[$object->{$export['key']}] = $cache[$table][$object->{$export['key']}];
  479. }
  480. }
  481. else {
  482. $object->{$export['export type string']} = t('Default');
  483. $object->export_type = EXPORT_IN_CODE;
  484. $object->in_code_only = TRUE;
  485. $object->table = $table;
  486. $cache[$table][$object->{$export['key']}] = $object;
  487. if ($type == 'conditions') {
  488. $return[$object->{$export['key']}] = $object;
  489. }
  490. }
  491. }
  492. }
  493. // If fetching all, we've done so and we are finished.
  494. if ($type == 'all') {
  495. $cached_database[$table] = TRUE;
  496. return $cache[$table];
  497. }
  498. if ($type == 'names') {
  499. foreach ($args as $name) {
  500. if (isset($cache[$table][$name])) {
  501. $return[$name] = $cache[$table][$name];
  502. }
  503. }
  504. }
  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. elseif (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. elseif (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. $disabled = !isset($object->disabled) || $object->disabled != TRUE ? 'FALSE' : 'TRUE';
  803. $output .= $indent . '$' . $identifier . '->disabled = ' . $disabled . '; /* Edit this to true to make a default ' . $identifier . ' disabled initially */' . "\n";
  804. }
  805. if (!empty($schema['export']['api']['current_version'])) {
  806. $output .= $indent . '$' . $identifier . '->api_version = ' . $schema['export']['api']['current_version'] . ";\n";
  807. }
  808. // Put top additions here:
  809. foreach ($additions as $field => $value) {
  810. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  811. }
  812. $fields = $schema['fields'];
  813. if (!empty($schema['join'])) {
  814. foreach ($schema['join'] as $join) {
  815. if (!empty($join['load'])) {
  816. foreach ($join['load'] as $join_field) {
  817. $fields[$join_field] = $join['fields'][$join_field];
  818. }
  819. }
  820. }
  821. }
  822. // Go through our schema and joined tables and build correlations.
  823. foreach ($fields as $field => $info) {
  824. if (!empty($info['no export'])) {
  825. continue;
  826. }
  827. if (!isset($object->$field)) {
  828. if (isset($info['default'])) {
  829. $object->$field = $info['default'];
  830. }
  831. else {
  832. $object->$field = '';
  833. }
  834. }
  835. // Note: This is the *field* export callback, not the table one!
  836. if (!empty($info['export callback']) && function_exists($info['export callback'])) {
  837. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . $info['export callback']($object, $field, $object->$field, $indent) . ";\n";
  838. }
  839. else {
  840. $value = $object->$field;
  841. if ($info['type'] == 'int') {
  842. if (isset($info['size']) && $info['size'] == 'tiny') {
  843. $info['boolean'] = (!isset($info['boolean'])) ? $schema['export']['boolean'] : $info['boolean'];
  844. $value = ($info['boolean']) ? (bool) $value : (int) $value;
  845. }
  846. else {
  847. $value = (int) $value;
  848. }
  849. }
  850. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  851. }
  852. }
  853. // And bottom additions here.
  854. foreach ($additions2 as $field => $value) {
  855. $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
  856. }
  857. return $output;
  858. }
  859. /**
  860. * Get the schema for a given table.
  861. *
  862. * This looks for data the export subsystem needs and applies defaults so
  863. * that it's easily available.
  864. */
  865. function ctools_export_get_schema($table) {
  866. static $drupal_static_fast;
  867. if (!isset($drupal_static_fast)) {
  868. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
  869. }
  870. $cache = &$drupal_static_fast['cache'];
  871. if (empty($cache[$table])) {
  872. $schema = drupal_get_schema($table);
  873. // If our schema isn't loaded, it's possible we're in a state where it
  874. // simply hasn't been cached. If we've been asked, let's force the
  875. // issue.
  876. if (!$schema || empty($schema['export'])) {
  877. // Force a schema reset:
  878. $schema = drupal_get_schema($table, TRUE);
  879. }
  880. if (!isset($schema['export'])) {
  881. return array();
  882. }
  883. if (empty($schema['module'])) {
  884. return array();
  885. }
  886. // Add some defaults.
  887. $schema['export'] += array(
  888. 'key' => 'name',
  889. 'key name' => 'Name',
  890. 'object' => 'stdClass',
  891. 'status' => 'default_' . $table,
  892. 'default hook' => 'default_' . $table,
  893. 'can disable' => TRUE,
  894. 'identifier' => $table,
  895. 'primary key' => !empty($schema['primary key']) ? $schema['primary key'][0] : '',
  896. 'bulk export' => TRUE,
  897. 'list callback' => "$schema[module]_{$table}_list",
  898. 'to hook code callback' => "$schema[module]_{$table}_to_hook_code",
  899. 'cache defaults' => FALSE,
  900. 'default cache bin' => 'cache',
  901. 'export type string' => 'type',
  902. 'boolean' => TRUE,
  903. );
  904. // If the export definition doesn't have the "primary key" then the CRUD
  905. // save callback won't work.
  906. if (empty($schema['export']['primary key']) && user_access('administer site configuration')) {
  907. drupal_set_message(t('The export definition of @table is missing the "primary key" property.', array('@table' => $table)), 'error');
  908. }
  909. // Notes:
  910. // The following callbacks may be defined to override default behavior
  911. // when using CRUD functions:
  912. //
  913. // create callback
  914. // load callback
  915. // load multiple callback
  916. // load all callback
  917. // save callback
  918. // delete callback
  919. // export callback
  920. // import callback
  921. //
  922. // See the appropriate ctools_export_crud function for details on what
  923. // arguments these callbacks should accept. Please do not call these
  924. // directly, always use the ctools_export_crud_* wrappers to ensure
  925. // that default implementations are honored.
  926. $cache[$table] = $schema;
  927. }
  928. return $cache[$table];
  929. }
  930. /**
  931. * Gets the schemas for all tables with ctools object metadata.
  932. */
  933. function ctools_export_get_schemas($for_export = FALSE) {
  934. $export_tables = &drupal_static(__FUNCTION__);
  935. if (is_null($export_tables)) {
  936. $export_tables = array();
  937. $schemas = drupal_get_schema();
  938. foreach ($schemas as $table => $schema) {
  939. if (!isset($schema['export'])) {
  940. unset($schemas[$table]);
  941. continue;
  942. }
  943. $export_tables[$table] = ctools_export_get_schema($table);
  944. }
  945. }
  946. return $for_export ? array_filter($export_tables, '_ctools_export_filter_export_tables') : $export_tables;
  947. }
  948. function _ctools_export_filter_export_tables($schema) {
  949. return !empty($schema['export']['bulk export']);
  950. }
  951. function ctools_export_get_schemas_by_module($modules = array(), $for_export = FALSE) {
  952. $export_tables = array();
  953. $list = ctools_export_get_schemas($for_export);
  954. foreach ($list as $table => $schema) {
  955. $export_tables[$schema['module']][$table] = $schema;
  956. }
  957. return empty($modules) ? $export_tables : array_keys($export_tables, $modules);
  958. }
  959. /**
  960. * Set the status of a default $object as a variable.
  961. *
  962. * The status, in this case, is whether or not it is 'disabled'.
  963. * This function does not check to make sure $object actually
  964. * exists.
  965. */
  966. function ctools_export_set_status($table, $name, $new_status = TRUE) {
  967. $schema = ctools_export_get_schema($table);
  968. $status = variable_get($schema['export']['status'], array());
  969. $status[$name] = $new_status;
  970. variable_set($schema['export']['status'], $status);
  971. }
  972. /**
  973. * Set the status of a default $object as a variable.
  974. *
  975. * This is more efficient than ctools_export_set_status because it
  976. * will actually unset the variable entirely if it's not necessary,
  977. * this saving a bit of space.
  978. */
  979. function ctools_export_set_object_status($object, $new_status = TRUE) {
  980. $table = $object->table;
  981. $schema = ctools_export_get_schema($table);
  982. $export = $schema['export'];
  983. $status = variable_get($export['status'], array());
  984. // Compare.
  985. if (!$new_status && $object->export_type & EXPORT_IN_DATABASE) {
  986. unset($status[$object->{$export['key']}]);
  987. }
  988. else {
  989. $status[$object->{$export['key']}] = $new_status;
  990. }
  991. variable_set($export['status'], $status);
  992. }
  993. /**
  994. * Provide a form for displaying an export.
  995. *
  996. * This is a simple form that should be invoked like this:
  997. * @code
  998. * $output = drupal_get_form('ctools_export_form', $code, $object_title);
  999. * @endcode
  1000. */
  1001. function ctools_export_form($form, &$form_state, $code, $title = '') {
  1002. $lines = substr_count($code, "\n");
  1003. $form['code'] = array(
  1004. '#type' => 'textarea',
  1005. '#title' => $title,
  1006. '#default_value' => $code,
  1007. '#rows' => $lines,
  1008. );
  1009. return $form;
  1010. }
  1011. /**
  1012. * Create a new object based upon schema values.
  1013. *
  1014. * Because 'default' has ambiguous meaning on some fields, we will actually
  1015. * use 'object default' to fill in default values if default is not set
  1016. * That's a little safer to use as it won't cause weird database default
  1017. * situations.
  1018. */
  1019. function ctools_export_new_object($table, $set_defaults = TRUE) {
  1020. $schema = ctools_export_get_schema($table);
  1021. $export = $schema['export'];
  1022. $object = new $export['object']();
  1023. foreach ($schema['fields'] as $field => $info) {
  1024. if (isset($info['object default'])) {
  1025. $object->$field = $info['object default'];
  1026. }
  1027. elseif (isset($info['default'])) {
  1028. $object->$field = $info['default'];
  1029. }
  1030. else {
  1031. $object->$field = NULL;
  1032. }
  1033. }
  1034. if ($set_defaults) {
  1035. // Set some defaults so this data always exists.
  1036. // We don't set the export_type property here, as this object is not saved
  1037. // yet. We do give it NULL so we don't generate notices trying to read it.
  1038. $object->export_type = NULL;
  1039. $object->{$export['export type string']} = t('Local');
  1040. }
  1041. return $object;
  1042. }
  1043. /**
  1044. * Convert a group of objects to code based upon input and return this as a larger
  1045. * export.
  1046. */
  1047. function ctools_export_to_hook_code(&$code, $table, $names = array(), $name = 'foo') {
  1048. $schema = ctools_export_get_schema($table);
  1049. $export = $schema['export'];
  1050. // Use the schema-specified function for generating hook code, if one exists.
  1051. if (function_exists($export['to hook code callback'])) {
  1052. $output = $export['to hook code callback']($names, $name);
  1053. }
  1054. // Otherwise, the following code generates basic hook code.
  1055. else {
  1056. $output = ctools_export_default_to_hook_code($schema, $table, $names, $name);
  1057. }
  1058. if (!empty($output)) {
  1059. if (isset($export['api'])) {
  1060. if (isset($code[$export['api']['owner']][$export['api']['api']]['version'])) {
  1061. $code[$export['api']['owner']][$export['api']['api']]['version'] = max($code[$export['api']['owner']][$export['api']['api']]['version'], $export['api']['minimum_version']);
  1062. }
  1063. else {
  1064. $code[$export['api']['owner']][$export['api']['api']]['version'] = $export['api']['minimum_version'];
  1065. $code[$export['api']['owner']][$export['api']['api']]['code'] = '';
  1066. }
  1067. $code[$export['api']['owner']][$export['api']['api']]['code'] .= $output;
  1068. }
  1069. else {
  1070. if (empty($code['general'])) {
  1071. $code['general'] = '';
  1072. }
  1073. $code['general'] .= $output;
  1074. }
  1075. }
  1076. }
  1077. /**
  1078. * Default function to export objects to code.
  1079. *
  1080. * Note that if your module provides a 'to hook code callback' then it will
  1081. * receive only $names and $name as arguments. Your module is presumed to
  1082. * already know the rest.
  1083. */
  1084. function ctools_export_default_to_hook_code($schema, $table, $names, $name) {
  1085. $export = $schema['export'];
  1086. $output = '';
  1087. $objects = ctools_export_crud_load_multiple($table, $names);
  1088. if ($objects) {
  1089. $output = "/**\n";
  1090. $output .= " * Implements hook_{$export['default hook']}().\n";
  1091. $output .= " */\n";
  1092. $output .= "function " . $name . "_{$export['default hook']}() {\n";
  1093. $output .= " \${$export['identifier']}s = array();\n\n";
  1094. foreach ($objects as $object) {
  1095. $output .= ctools_export_crud_export($table, $object, ' ');
  1096. $output .= " \${$export['identifier']}s['" . check_plain($object->{$export['key']}) . "'] = \${$export['identifier']};\n\n";
  1097. }
  1098. $output .= " return \${$export['identifier']}s;\n";
  1099. $output .= "}\n";
  1100. }
  1101. return $output;
  1102. }
  1103. /**
  1104. * Default function for listing bulk exportable objects.
  1105. */
  1106. function ctools_export_default_list($table, $schema) {
  1107. $list = array();
  1108. $items = ctools_export_crud_load_all($table);
  1109. $export_key = $schema['export']['key'];
  1110. foreach ($items as $item) {
  1111. // Try a couple of possible obvious title keys:
  1112. $keys = array('admin_title', 'title');
  1113. if (isset($schema['export']['admin_title'])) {
  1114. array_unshift($keys, $schema['export']['admin_title']);
  1115. }
  1116. $string = '';
  1117. foreach ($keys as $key) {
  1118. if (!empty($item->$key)) {
  1119. $string = $item->$key . " (" . $item->$export_key . ")";
  1120. break;
  1121. }
  1122. }
  1123. if (empty($string)) {
  1124. $string = $item->$export_key;
  1125. }
  1126. $list[$item->$export_key] = check_plain($string);
  1127. }
  1128. return $list;
  1129. }