node_export.module 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. <?php
  2. /**
  3. * @file
  4. * The Node export module.
  5. *
  6. * Allows users to export nodes and then import them into another Drupal installation.
  7. */
  8. /**
  9. * Implements hook_permission().
  10. */
  11. function node_export_permission() {
  12. return array(
  13. 'export nodes' => array(
  14. 'title' => t('Export nodes'),
  15. ),
  16. 'export own nodes' => array(
  17. 'title' => t('Export own nodes'),
  18. ),
  19. 'use PHP to import nodes' => array(
  20. 'title' => t('Use PHP to import nodes'),
  21. 'description' => t('Required for importing, but can allow execution of PHP.'),
  22. 'restrict access' => TRUE,
  23. ),
  24. );
  25. }
  26. /**
  27. * Implements hook_menu().
  28. */
  29. function node_export_menu() {
  30. $items['admin/config/content/node_export'] = array(
  31. 'access arguments' => array('administer site configuration'),
  32. 'page callback' => 'drupal_get_form',
  33. 'page arguments' => array('node_export_settings'),
  34. 'title' => 'Node export',
  35. 'description' => 'Configure the settings for Node export.',
  36. 'file' => 'node_export.pages.inc',
  37. );
  38. $selected_formats = variable_get('node_export_format', array('drupal'));
  39. if (count(array_filter($selected_formats)) > 1) {
  40. $format_handlers = node_export_format_handlers();
  41. foreach ($format_handlers as $format_handler => $format) {
  42. if (!empty($selected_formats[$format_handler])) {
  43. $items['node/%node/node_export/' . $format_handler] = array(
  44. 'access callback' => 'node_export_access_export',
  45. 'access arguments' => array(1),
  46. 'page callback' => 'node_export_gui',
  47. 'page arguments' => array(1, $format_handler),
  48. 'title' => 'Node export (' . $format['#title'] . ')',
  49. 'weight' => 5,
  50. 'type' => MENU_LOCAL_TASK,
  51. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  52. 'file' => 'node_export.pages.inc',
  53. );
  54. }
  55. }
  56. }
  57. else {
  58. $items['node/%node/node_export'] = array(
  59. 'access callback' => 'node_export_access_export',
  60. 'access arguments' => array(1),
  61. 'page callback' => 'node_export_gui',
  62. 'page arguments' => array(1),
  63. 'title' => 'Node export',
  64. 'weight' => 5,
  65. 'type' => MENU_LOCAL_TASK,
  66. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  67. 'file' => 'node_export.pages.inc',
  68. );
  69. }
  70. $items['admin/content/node_export'] = array(
  71. 'access arguments' => array('export nodes'),
  72. 'page callback' => 'node_export_gui',
  73. 'page arguments' => array(NULL, NULL),
  74. 'title' => 'Node export',
  75. 'type' => MENU_CALLBACK,
  76. 'file' => 'node_export.pages.inc',
  77. );
  78. $items['node/add/node_export'] = array(
  79. 'title' => 'Node export: import',
  80. 'page callback' => 'drupal_get_form',
  81. 'page arguments' => array('node_export_import_form'),
  82. 'access callback' => 'node_export_access_import',
  83. 'description' => 'Import content using <em>Node export</em>.',
  84. 'file' => 'node_export.pages.inc',
  85. );
  86. return $items;
  87. }
  88. /**
  89. * Check access to export a node.
  90. */
  91. function node_export_access_export($node) {
  92. global $user;
  93. if (is_int($node)) {
  94. $node = node_load($node);
  95. }
  96. if (function_exists('drush_main')) {
  97. // Always allow drush to export nodes.
  98. $access = TRUE;
  99. }
  100. else {
  101. // Check basic role permissions first.
  102. $access = (user_access('export nodes') || ($user->uid && ($node->uid == $user->uid) && user_access('export own nodes')));
  103. // Make sure the user can view the original node content.
  104. $access = $access && node_access('view', $node);
  105. }
  106. // Let other modules alter this - for example to only allow some users
  107. // to export specific nodes or types.
  108. drupal_alter("node_export_access_export", $access, $node);
  109. return $access;
  110. }
  111. /**
  112. * Check access to import a node.
  113. */
  114. function node_export_access_import($node = NULL) {
  115. global $user;
  116. if (function_exists('drush_main')) {
  117. // Always allow drush to import nodes.
  118. $access = TRUE;
  119. }
  120. elseif (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install') {
  121. // During the install phase $user is the Anonymous user; however, in
  122. // practice $user is performing tasks only granted to the admin user
  123. // (eg: installing modules, changing site settings). For this reason
  124. // it seems sensible to allow this "Anonymous admin" user to import
  125. // any nodes they wish.
  126. $access = TRUE;
  127. }
  128. else {
  129. // Check basic role permissions first.
  130. $access = user_access('use PHP to import nodes');
  131. if (!is_null($node) && $access) {
  132. // Check node conditions.
  133. $access = node_access('create', $node->type);
  134. }
  135. }
  136. // Let other modules alter this - for example to only allow some users
  137. // to import specific nodes or types.
  138. drupal_alter("node_export_access_import", $access, $node);
  139. return $access;
  140. }
  141. /**
  142. * Check access to export an array of nodes.
  143. */
  144. function node_export_access_export_nodes($nodes) {
  145. // Convert to array if it isn't already.
  146. if (is_object($nodes)) {
  147. $nodes = array($nodes);
  148. }
  149. foreach ($nodes as &$node) {
  150. if (!node_export_access_export($node)) {
  151. return FALSE;
  152. }
  153. }
  154. return TRUE;
  155. }
  156. /**
  157. * Check access to import an array of nodes.
  158. */
  159. function node_export_access_import_nodes($nodes) {
  160. // Convert to array if it isn't already.
  161. if (is_object($nodes)) {
  162. $nodes = array($nodes);
  163. }
  164. foreach ($nodes as &$node) {
  165. if (!node_export_access_import($node)) {
  166. return FALSE;
  167. }
  168. }
  169. return TRUE;
  170. }
  171. /**
  172. * Implements hook_node_type_update().
  173. */
  174. function node_export_node_type_update($info) {
  175. if (!empty($info->old_type) && $info->old_type != $info->type) {
  176. if (variable_get('node_export_reset_' . $info->old_type, FALSE)) {
  177. variable_del('node_export_reset_' . $info->old_type);
  178. variable_set('node_export_reset_' . $info->type, TRUE);
  179. }
  180. }
  181. }
  182. /**
  183. * Implements hook_node_type_delete().
  184. */
  185. function node_export_node_type_delete($info) {
  186. variable_del('node_export_reset_' . $info->type);
  187. }
  188. /**
  189. * Implements hook_views_api().
  190. */
  191. function node_export_views_api() {
  192. return array(
  193. 'api' => 3,
  194. 'path' => drupal_get_path('module', 'node_export') . '/views',
  195. );
  196. }
  197. /**
  198. * Implements hook_node_operations().
  199. */
  200. function node_export_node_operations() {
  201. $operations = array();
  202. if (user_access('export nodes')) {
  203. $selected_formats = variable_get('node_export_format', array('drupal'));
  204. if (count(array_filter($selected_formats)) > 1) {
  205. $format_handlers = node_export_format_handlers();
  206. foreach ($format_handlers as $format_handler => $format) {
  207. if ($selected_formats[$format_handler]) {
  208. $operations['node_export_' . $format_handler] = array(
  209. 'label' => t('Node export') . " (" . $format['#title'] . ")",
  210. 'callback' => 'node_export_bulk_operation',
  211. 'callback arguments' => array('format' => $format_handler),
  212. );
  213. }
  214. }
  215. }
  216. else {
  217. $operations = array(
  218. 'node_export' => array(
  219. 'label' => t('Node export'),
  220. 'callback' => 'node_export_bulk_operation',
  221. ),
  222. );
  223. }
  224. }
  225. return $operations;
  226. }
  227. /**
  228. * Callback for use with hook_node_operations().
  229. */
  230. function node_export_bulk_operation($nodes = NULL, $format = NULL, $delivery = NULL) {
  231. module_load_include('inc', 'node_export', 'node_export.pages');
  232. return node_export_gui($nodes, $format, $delivery);
  233. }
  234. /**
  235. * Implements hook_action_info()
  236. */
  237. function node_export_action_info() {
  238. $actions = array();
  239. if (user_access('export nodes')) {
  240. $selected_formats = variable_get('node_export_format', array('drupal'));
  241. $format_handlers = node_export_format_handlers();
  242. foreach ($format_handlers as $format_handler => $format) {
  243. if (!empty($selected_formats[$format_handler])) {
  244. // @todo: should formats be able to define their own actions?
  245. if (!empty($format['#file']) && is_file($format['#file'])) {
  246. require_once $format['#file'];
  247. }
  248. $format_action = 'node_export_' . $format_handler . '_action';
  249. if (function_exists($format_action . '_form')) {
  250. $actions[$format_action] = array(
  251. 'type' => 'node',
  252. 'label' => t('Node export') . " (" . $format['#title'] . ")",
  253. 'behavior' => array('changes_property'),
  254. // This action only works when invoked through VBO. That's why it's
  255. // declared as non-configurable to prevent it from being shown in the
  256. // "Create an advanced action" dropdown on admin/config/system/actions.
  257. 'configurable' => FALSE,
  258. 'vbo_configurable' => TRUE,
  259. );
  260. }
  261. }
  262. }
  263. }
  264. return $actions;
  265. }
  266. /**
  267. * Export Nodes Action "Configuration" Form
  268. *
  269. * Technically for a normal action this is where you would provide config
  270. * for the actual execution of the action. However, we're hijacking it to
  271. * present the completed node_export_gui page.
  272. */
  273. function node_export_action_form($context, &$form_state, $format = NULL) {
  274. // Get the name of the vbo views field
  275. $vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
  276. // Adjust the selection in case the user chose 'select all'
  277. _views_bulk_operations_adjust_selection($form_state['selection'], $form_state['select_all_pages'], $vbo);
  278. $nodes = array_combine($form_state['selection'], $form_state['selection']);
  279. return node_export_bulk_operation($nodes);
  280. }
  281. /**
  282. * Export nodes.
  283. *
  284. * @param $nids
  285. * A node ID or array of node IDs to export.
  286. * @param $format
  287. * The format to use for export.
  288. * @param $msg_t
  289. * Function used to translate.
  290. * @return
  291. * An array with keys 'success' which is a boolean value representing whether
  292. * the export was successful and 'output' which contains the code string or an
  293. * array of translated error messages to be shown to the user.
  294. */
  295. function node_export($nids, $format = NULL, $msg_t = 't') {
  296. global $user;
  297. // Make $nids an array if it isn't.
  298. if (is_int($nids)) {
  299. $nids = array($nids);
  300. }
  301. elseif (is_object($nids)) {
  302. $nids = array($nids->nid);
  303. }
  304. $nodes = array();
  305. foreach ($nids as $nid) {
  306. $original_node = node_load($nid);
  307. if (!node_export_access_export($original_node)) {
  308. // Halt exporting.
  309. $error = $msg_t("You do not have permission to perform a Node export on one or more of these nodes. No nodes exported.");
  310. return array(
  311. 'success' => FALSE,
  312. 'output' => array($error),
  313. );
  314. }
  315. $node = node_export_prepare_node($original_node);
  316. $nodes[] = $node;
  317. }
  318. // Get the node code from the format handler
  319. $format_handlers = node_export_format_handlers();
  320. $node_export_format = variable_get('node_export_format', array('drupal'));
  321. $format_handler = $format ? $format : reset($node_export_format);
  322. if (!isset($format_handlers[$format_handler])) {
  323. $format_handler = 'drupal';
  324. }
  325. // Let other modules do special fixing up.
  326. drupal_alter('node_export', $nodes, $format_handler);
  327. // If any nodes are set to FALSE, then an error was triggered in another module.
  328. // Currently modules doing this should also leave a watchdog warning.
  329. if (in_array(FALSE, $nodes)) {
  330. // Halt exporting.
  331. $error = $msg_t('An error occurred when processing nodes, please check your logs. No nodes exported.');
  332. return array(
  333. 'success' => FALSE,
  334. 'output' => array($error),
  335. );
  336. }
  337. if (!empty($format_handlers[$format_handler]['#file']) && is_file($format_handlers[$format_handler]['#file'])) {
  338. require_once $format_handlers[$format_handler]['#file'];
  339. }
  340. $code_string = call_user_func(
  341. $format_handlers[$format_handler]['#export_callback'],
  342. $nodes,
  343. $format_handler
  344. );
  345. // Let modules modify the node code.
  346. drupal_alter('node_export_encode', $code_string, $nodes, $format_handler);
  347. return array(
  348. 'success' => TRUE,
  349. 'output' => $code_string,
  350. 'format' => $format_handler,
  351. );
  352. }
  353. /**
  354. * Prepare a single node during export.
  355. */
  356. function node_export_prepare_node(&$original_node) {
  357. // Create UUID if it's not there.
  358. if (!uuid_get_uuid('node', 'nid', $original_node->nid)) {
  359. $original_node->uuid = uuid_set_uuid('node', 'nid', $original_node->nid);
  360. // Save it so future node exports are consistent.
  361. node_save($original_node);
  362. }
  363. $node = clone($original_node);
  364. // Fix taxonomy array
  365. if (isset($node->taxonomy) && count($node->taxonomy)) {
  366. $vocabularies = taxonomy_get_vocabularies();
  367. $new_taxonomy = array();
  368. foreach ($node->taxonomy as $term) {
  369. // Free-tagging vocabularies need a different format
  370. if ($vocabularies[$term->vid]->tags) {
  371. $new_taxonomy['tags'][$term->vid][] = $term->name;
  372. }
  373. else {
  374. $new_taxonomy[$term->vid][$term->tid] = $term->tid;
  375. }
  376. }
  377. if (isset($new_taxonomy['tags']) && count($new_taxonomy['tags'])) {
  378. // Comma seperate the tags
  379. foreach ($new_taxonomy['tags'] as $vid => $tags) {
  380. $new_taxonomy['tags'][$vid] = implode(', ', $tags);
  381. }
  382. }
  383. $node->taxonomy = $new_taxonomy;
  384. }
  385. // Attach path to the node. Drupal doesn't attach this anymore for
  386. // performance reasons http://drupal.org/node/332333#comment-2163634.
  387. $node->path = path_load(array('source' => 'node/' . $node->nid));
  388. // Fix menu array
  389. $node->menu = node_export_get_menu($original_node);
  390. // Remove recursion from the object.
  391. $node = node_export_remove_recursion($node);
  392. // Add a parameter to identify this node as coming from D7, might be useful some day.
  393. $node->node_export_drupal_version = '7';
  394. // Export file fields.
  395. node_export_file_field_export($node, $original_node);
  396. // Let other modules do special fixing up.
  397. drupal_alter('node_export_node', $node, $original_node);
  398. return $node;
  399. }
  400. /**
  401. * Check if all types in the import exist.
  402. *
  403. * @return
  404. * TRUE if all types exist, otherwise an array of missing type names.
  405. */
  406. function node_export_import_types_check($nodes) {
  407. $missing_types = array();
  408. foreach ($nodes as $node) {
  409. if (node_type_get_name($node) == FALSE) {
  410. $missing_types[$node->type] = $node->type;
  411. }
  412. }
  413. return (!empty($missing_types) ? $missing_types : TRUE);
  414. }
  415. /**
  416. * Import Function
  417. *
  418. * @param $code_string
  419. * The string of export code.
  420. * @param $msg_t
  421. * Function used to translate.
  422. * @param $save
  423. * When TRUE will save the nodes that are imported.
  424. * @return
  425. * An array with keys 'success' which is a boolean value representing whether
  426. * the import was successful and 'output' which contains an array of
  427. * translated strings to be shown to the user as messages.
  428. */
  429. function node_export_import($code_string, $msg_t = 't', $save = TRUE) {
  430. // Early check to avoid letting hooligans and the elderly pass data to the
  431. // eval() function call.
  432. if (!node_export_access_import()) {
  433. $error = $msg_t(
  434. 'You do not have permission to import any nodes.'
  435. );
  436. return array(
  437. 'success' => FALSE,
  438. 'output' => array($error),
  439. );
  440. }
  441. // Allow modules to manipulate the $code_string.
  442. drupal_alter('node_export_decode', $code_string);
  443. // Pass the string to each format handler until one returns something useful.
  444. $format_handlers = node_export_format_handlers();
  445. $nodes = array();
  446. $used_format = "";
  447. foreach ($format_handlers as $format_handler => $format) {
  448. if (!empty($format['#file']) && is_file($format['#file'])) {
  449. require_once $format['#file'];
  450. }
  451. $nodes = call_user_func(
  452. $format['#import_callback'],
  453. $code_string
  454. );
  455. if (!empty($nodes)) {
  456. $used_format = $format_handler;
  457. break;
  458. }
  459. }
  460. if (isset($nodes['success']) && !$nodes['success']) {
  461. // Instead of returning nodes, the format handler returned an error array.
  462. // Translate the errors and return them.
  463. foreach ($nodes['output'] as $key => $output) {
  464. $nodes['output'][$key] = $msg_t($output);
  465. }
  466. return array(
  467. 'success' => FALSE,
  468. 'output' => $nodes['output'],
  469. );
  470. }
  471. if ($used_format == "") {
  472. $error = $msg_t(
  473. 'Node export was unable to recognize the format of the supplied code. No nodes imported.'
  474. );
  475. return array(
  476. 'success' => FALSE,
  477. 'output' => array($error),
  478. );
  479. }
  480. $nodes = node_export_restore_recursion($nodes);
  481. $types_exist = node_export_import_types_check($nodes);
  482. if ($types_exist !== TRUE) {
  483. // There was a problem with the content types check.
  484. $error = $msg_t(
  485. 'Error encountered during import. Node types unknown on this site: %t. No nodes imported.',
  486. array('%t' => implode(", ", $types_exist))
  487. );
  488. return array(
  489. 'success' => FALSE,
  490. 'output' => array($error),
  491. );
  492. }
  493. if (!node_export_access_import_nodes($nodes)) {
  494. // There was a problem with permissions.
  495. $error = $msg_t(
  496. 'You do not have permission to perform a Node export: import on one or more of these nodes. No nodes imported.'
  497. );
  498. return array(
  499. 'success' => FALSE,
  500. 'output' => array($error),
  501. );
  502. }
  503. $count = 0;
  504. $total = count($nodes);
  505. // Let other modules do special fixing up.
  506. drupal_alter('node_export_import', $nodes, $used_format, $save);
  507. $new_nodes = array();
  508. $messages = array();
  509. foreach ($nodes as $original_node) {
  510. $node = node_export_node_clone($original_node);
  511. // Import file fields.
  512. node_export_file_field_import($node, $original_node);
  513. // Handle existing nodes.
  514. $nids = entity_get_id_by_uuid('node', array($node->uuid));
  515. if (!empty($nids[$node->uuid])) {
  516. $existing = variable_get('node_export_existing', 'new');
  517. switch ($existing) {
  518. case 'new':
  519. $node->is_new = TRUE;
  520. unset($node->uuid);
  521. break;
  522. case 'revision':
  523. $node->nid = $nids[$node->uuid];
  524. $node->is_new = FALSE;
  525. $node->revision = 1;
  526. break;
  527. case 'skip':
  528. $save = FALSE;
  529. break;
  530. }
  531. }
  532. // Let other modules do special fixing up.
  533. drupal_alter('node_export_node_import', $node, $original_node, $save);
  534. if ($save) {
  535. node_export_save($node);
  536. $new_nodes[$node->nid] = $node;
  537. $messages[] = $msg_t("Imported node !nid: !node", array('!nid' => $node->nid, '!node' => l($node->title, 'node/' . $node->nid)));
  538. $count++;
  539. }
  540. else {
  541. $new_nodes[] = $node;
  542. }
  543. }
  544. if ($save) {
  545. drupal_alter('node_export_after_import', $new_nodes, $used_format, $save);
  546. $messages[] = $msg_t("!count of !total nodes were imported. Some values may have been reset depending on Node export's configuration.", array('!total' => $total, '!count' => $count));
  547. // Clear the page and block caches.
  548. cache_clear_all();
  549. // Nodes were saved, so return the nids.
  550. return array(
  551. 'success' => TRUE,
  552. 'output' => $messages,
  553. 'nids' => array_keys($new_nodes),
  554. 'format' => $used_format,
  555. );
  556. }
  557. else {
  558. // We didn't save, so return full nodes.
  559. return array(
  560. 'success' => TRUE,
  561. 'output' => $messages,
  562. 'nodes' => $new_nodes,
  563. 'format' => $used_format,
  564. );
  565. }
  566. }
  567. /**
  568. * Save a node object into the database.
  569. *
  570. * $node->changed is not forced like in node_save().
  571. *
  572. * A modified version of node_save().
  573. */
  574. function node_export_save(&$node) {
  575. $transaction = db_transaction();
  576. try {
  577. // Load the stored entity, if any.
  578. if (!empty($node->nid) && !isset($node->original)) {
  579. $node->original = entity_load_unchanged('node', $node->nid);
  580. }
  581. field_attach_presave('node', $node);
  582. global $user;
  583. // Determine if we will be inserting a new node.
  584. if (!isset($node->is_new)) {
  585. $node->is_new = empty($node->nid);
  586. }
  587. // Set the timestamp fields.
  588. if (empty($node->created)) {
  589. $node->created = REQUEST_TIME;
  590. }
  591. // The update of the changed value is forced in the original node_save().
  592. if (empty($node->changed)) {
  593. $node->changed = REQUEST_TIME;
  594. }
  595. $node->timestamp = REQUEST_TIME;
  596. $update_node = TRUE;
  597. // Let modules modify the node before it is saved to the database.
  598. module_invoke_all('node_presave', $node);
  599. if ($node->is_new || !empty($node->revision)) {
  600. // When inserting either a new node or a new node revision, $node->log
  601. // must be set because {node_revision}.log is a text column and therefore
  602. // cannot have a default value. However, it might not be set at this
  603. // point (for example, if the user submitting a node form does not have
  604. // permission to create revisions), so we ensure that it is at least an
  605. // empty string in that case.
  606. // @todo: Make the {node_revision}.log column nullable so that we can
  607. // remove this check.
  608. if (!isset($node->log)) {
  609. $node->log = '';
  610. }
  611. }
  612. elseif (empty($node->log)) {
  613. // If we are updating an existing node without adding a new revision, we
  614. // need to make sure $node->log is unset whenever it is empty. As long as
  615. // $node->log is unset, drupal_write_record() will not attempt to update
  616. // the existing database column when re-saving the revision; therefore,
  617. // this code allows us to avoid clobbering an existing log entry with an
  618. // empty one.
  619. unset($node->log);
  620. }
  621. // When saving a new node revision, unset any existing $node->vid so as to
  622. // ensure that a new revision will actually be created, then store the old
  623. // revision ID in a separate property for use by node hook implementations.
  624. if (!$node->is_new && !empty($node->revision) && $node->vid) {
  625. $node->old_vid = $node->vid;
  626. unset($node->vid);
  627. }
  628. // Save the node and node revision.
  629. if ($node->is_new) {
  630. // For new nodes, save new records for both the node itself and the node
  631. // revision.
  632. drupal_write_record('node', $node);
  633. _node_save_revision($node, $user->uid);
  634. $op = 'insert';
  635. }
  636. else {
  637. // For existing nodes, update the node record which matches the value of
  638. // $node->nid.
  639. drupal_write_record('node', $node, 'nid');
  640. // Then, if a new node revision was requested, save a new record for
  641. // that; otherwise, update the node revision record which matches the
  642. // value of $node->vid.
  643. if (!empty($node->revision)) {
  644. _node_save_revision($node, $user->uid);
  645. }
  646. else {
  647. _node_save_revision($node, $user->uid, 'vid');
  648. $update_node = FALSE;
  649. }
  650. $op = 'update';
  651. }
  652. if ($update_node) {
  653. db_update('node')
  654. ->fields(array('vid' => $node->vid))
  655. ->condition('nid', $node->nid)
  656. ->execute();
  657. }
  658. // Call the node specific callback (if any). This can be
  659. // node_invoke($node, 'insert') or
  660. // node_invoke($node, 'update').
  661. node_invoke($node, $op);
  662. // Save fields.
  663. $function = "field_attach_$op";
  664. $function('node', $node);
  665. module_invoke_all('node_' . $op, $node);
  666. module_invoke_all('entity_' . $op, $node, 'node');
  667. // Update the node access table for this node. There's no need to delete
  668. // existing records if the node is new.
  669. $delete = $op == 'update';
  670. node_access_acquire_grants($node, $delete);
  671. // Clear internal properties.
  672. unset($node->is_new);
  673. unset($node->original);
  674. // Clear the static loading cache.
  675. entity_get_controller('node')->resetCache(array($node->nid));
  676. // Ignore slave server temporarily to give time for the
  677. // saved node to be propagated to the slave.
  678. db_ignore_slave();
  679. }
  680. catch (Exception $e) {
  681. $transaction->rollback();
  682. watchdog_exception('node', $e);
  683. throw $e;
  684. }
  685. }
  686. /**
  687. * Prepare a clone of the node during import.
  688. */
  689. function node_export_node_clone($original_node) {
  690. global $user;
  691. $node = clone($original_node);
  692. $node->nid = NULL;
  693. $node->vid = NULL;
  694. if (variable_get('node_export_reset_author_' . $node->type, TRUE)) {
  695. $node->name = !empty($user->name) ? $user->name : (!empty($user->uid) ? NULL : variable_get('anonymous', t('Anonymous')));
  696. $node->uid = $user->uid;
  697. }
  698. if (variable_get('node_export_reset_created_' . $node->type, TRUE)) {
  699. $node->created = NULL;
  700. }
  701. if (variable_get('node_export_reset_changed_' . $node->type, TRUE)) {
  702. $node->changed = NULL;
  703. }
  704. if (variable_get('node_export_reset_revision_timestamp_'. $node->type, TRUE)) {
  705. $node->revision_timestamp = NULL;
  706. }
  707. if (variable_get('node_export_reset_last_comment_timestamp_'. $node->type, TRUE)) {
  708. $node->last_comment_timestamp = NULL;
  709. }
  710. if (variable_get('node_export_reset_menu_' . $node->type, TRUE)) {
  711. $node->menu = NULL;
  712. }
  713. if (variable_get('node_export_reset_path_' . $node->type, TRUE)) {
  714. $node->path = NULL;
  715. }
  716. else {
  717. if (is_array($node->path) && isset($node->path['pid'])) {
  718. unset($node->path['pid']);
  719. }
  720. if (module_exists('pathauto')) {
  721. // Prevent pathauto from creating a new path alias.
  722. $node->path['pathauto'] = FALSE;
  723. }
  724. }
  725. if (variable_get('node_export_reset_book_mlid_' . $node->type, TRUE) && isset($node->book['mlid'])) {
  726. $node->book['mlid'] = NULL;
  727. }
  728. // @todo - is this still needed?
  729. $node->files = array();
  730. if (variable_get('node_export_reset_status_' . $node->type, FALSE)) {
  731. $node->status = FALSE;
  732. }
  733. if (variable_get('node_export_reset_promote_' . $node->type, FALSE)) {
  734. $node->promote = FALSE;
  735. }
  736. if (variable_get('node_export_reset_sticky_' . $node->type, FALSE)) {
  737. $node->sticky = FALSE;
  738. }
  739. return $node;
  740. }
  741. /**
  742. * Create a new menu entry with title, parent and weight exported from
  743. * another nodes menu. Returns NULL if the node has no menu title.
  744. */
  745. function node_export_get_menu($node) {
  746. // This will fetch the existing menu item if the node had one.
  747. module_invoke_all('node_prepare', $node);
  748. $type = $node->type;
  749. // Only keep the values we care about.
  750. if (!empty($node->menu['mlid'])) {
  751. // Store a copy of the old menu
  752. $old_menu = $node->menu;
  753. // Now fetch the defaults for a new menu entry.
  754. $node = new stdClass;
  755. $node->type = $type;
  756. //module_invoke_all('node_prepare', $node);
  757. node_object_prepare($node);
  758. // Make a list of values to attempt to copy.
  759. $menu_fields = array(
  760. 'link_title',
  761. 'plid',
  762. 'menu_name',
  763. 'weight',
  764. 'hidden',
  765. 'expanded',
  766. 'has_children',
  767. );
  768. // Copy those fields from the old menu over the new menu defaults.
  769. foreach ($menu_fields as $menu_field) {
  770. $node->menu[$menu_field] = $old_menu[$menu_field];
  771. }
  772. // Copy the menu description from the old menu.
  773. // Issue #1287300.
  774. if (isset($old_menu['options']['attributes']['title'])) {
  775. $node->menu['description'] = $old_menu['options']['attributes']['title'];
  776. }
  777. else {
  778. $node->menu['description'] = '';
  779. }
  780. // Ensure menu will be created during node import.
  781. // Issue #1139120.
  782. $node->menu['enabled'] = 1;
  783. // Return the menu.
  784. return $node->menu;
  785. }
  786. }
  787. /**
  788. * Remove recursion problem from an object or array.
  789. */
  790. function node_export_remove_recursion($o) {
  791. static $replace;
  792. if (!isset($replace)) {
  793. $replace = create_function(
  794. '$m',
  795. '$r="\x00{$m[1]}ecursion_export_node_";return \'s:\'.strlen($r.$m[2]).\':"\'.$r.$m[2].\'";\';'
  796. );
  797. }
  798. if (is_array($o) || is_object($o)) {
  799. $re = '#(r|R):([0-9]+);#';
  800. $serialize = serialize($o);
  801. if (preg_match($re, $serialize)) {
  802. $last = $pos = 0;
  803. while (false !== ($pos = strpos($serialize, 's:', $pos))) {
  804. $chunk = substr($serialize, $last, $pos - $last);
  805. if (preg_match($re, $chunk)) {
  806. $length = strlen($chunk);
  807. $chunk = preg_replace_callback($re, $replace, $chunk);
  808. $serialize = substr($serialize, 0, $last) . $chunk . substr($serialize, $last + ($pos - $last));
  809. $pos += strlen($chunk) - $length;
  810. }
  811. $pos += 2;
  812. $last = strpos($serialize, ':', $pos);
  813. $length = substr($serialize, $pos, $last - $pos);
  814. $last += 4 + $length;
  815. $pos = $last;
  816. }
  817. $serialize = substr($serialize, 0, $last) . preg_replace_callback($re, $replace, substr($serialize, $last));
  818. $o = unserialize($serialize);
  819. }
  820. }
  821. return $o;
  822. }
  823. /**
  824. * Restore recursion to an object or array.
  825. */
  826. function node_export_restore_recursion($o) {
  827. return unserialize(
  828. preg_replace(
  829. '#s:[0-9]+:"\x00(r|R)ecursion_export_node_([0-9]+)";#',
  830. '\1:\2;',
  831. serialize($o)
  832. )
  833. );
  834. }
  835. /**
  836. * Get a list of possible format handlers (other than the default).
  837. *
  838. * @return
  839. * An array of format handlers from hook implementations.
  840. * @see hook_node_export_format_handlers()
  841. */
  842. function node_export_format_handlers() {
  843. module_load_include('inc', 'node_export', 'node_export.formats');
  844. $format_handlers = &drupal_static(__FUNCTION__);
  845. if (empty($format_handlers)) {
  846. $format_handlers = module_invoke_all('node_export_format_handlers');
  847. }
  848. return $format_handlers;
  849. }
  850. /**
  851. * Handle exporting file fields.
  852. */
  853. function node_export_file_field_export(&$node, $original_node) {
  854. $types = array_filter(variable_get('node_export_file_types', array()));
  855. if (in_array($node->type, $types)) {
  856. $assets_path = variable_get('node_export_file_assets_path', '');
  857. $export_mode = variable_get('node_export_file_mode', 'inline');
  858. switch ($export_mode) {
  859. case 'local':
  860. $export_var = 'node_export_file_path';
  861. break;
  862. case 'remote':
  863. $export_var = 'node_export_file_url';
  864. break;
  865. default:
  866. case 'inline':
  867. $export_var = 'node_export_file_data';
  868. break;
  869. }
  870. // If files are supposed to be copied to the assets path.
  871. if ($export_mode == 'local' && $assets_path) {
  872. // Ensure the assets path is created
  873. if (!is_dir($assets_path) && mkdir($assets_path, 0777, TRUE) == FALSE) {
  874. drupal_set_message(t("Could not create assets path! '!path'", array('!path' => $assets_path)), 'error');
  875. // Don't continue if the assets path is not ready
  876. return;
  877. }
  878. // Ensure it is writable
  879. if (!is_writable($assets_path)) {
  880. drupal_set_message(t("Assets path is not writable! '!path'", array('!path' => $assets_path)), 'error');
  881. // Don't continue if the assets path is not ready
  882. return;
  883. }
  884. }
  885. // get all fields from this node type
  886. $fields = field_info_instances('node', $node->type);
  887. foreach($fields as $field_instance) {
  888. // load field infos to check the type
  889. $field = &$node->{$field_instance['field_name']};
  890. $info = field_info_field($field_instance['field_name']);
  891. $supported_fields = array_map('trim', explode(',', variable_get('node_export_file_supported_fields', 'file, image')));
  892. // check if this field should implement file import/export system
  893. if (in_array($info['type'], $supported_fields)) {
  894. // we need to loop into each language because i18n translation can build
  895. // fields with different language than the node one.
  896. foreach($field as $language => $files) {
  897. if (is_array($files)) {
  898. foreach($files as $i => $file) {
  899. // convert file to array to stay into the default node_export_file format
  900. $file = (object) $file;
  901. // Check the file
  902. if (!isset($file->uri) || !is_file($file->uri)) {
  903. drupal_set_message(t("File field found on node, but file doesn't exist on disk? '!path'", array('!path' => $file->uri)), 'error');
  904. continue;
  905. }
  906. if ($export_mode == 'local') {
  907. if ($assets_path) {
  908. $export_data = $assets_path . '/' . basename($file->uri);
  909. if (!copy($file->uri, $export_data)) {
  910. drupal_set_message(t("Export file error, could not copy '%filepath' to '%exportpath'.", array('%filepath' => $file->uri, '%exportpath' => $export_data)), 'error');
  911. return FALSE;
  912. }
  913. }
  914. else {
  915. $export_data = $file->uri;
  916. }
  917. }
  918. // Remote export mode
  919. elseif ($export_mode == 'remote') {
  920. $export_data = url($file->uri, array('absolute' => TRUE));
  921. }
  922. // Default is 'inline' export mode
  923. else {
  924. $export_data = base64_encode(file_get_contents($file->uri));
  925. }
  926. // build the field again, and remove fid to be sure that imported node
  927. // will rebuild the file again, or keep an existing one with a different fid
  928. $field[$language][$i]['fid'] = NULL;
  929. $field[$language][$i][$export_var] = $export_data;
  930. }
  931. }
  932. }
  933. }
  934. }
  935. }
  936. }
  937. /**
  938. * Handle importing file fields.
  939. */
  940. function node_export_file_field_import(&$node, $original_node) {
  941. // Get all fields from this node type.
  942. $fields = field_info_instances('node', $node->type);
  943. foreach($fields as $field_instance) {
  944. // Load field info to check the type.
  945. $field = &$node->{$field_instance['field_name']};
  946. $info = field_info_field($field_instance['field_name']);
  947. $supported_fields = array_map('trim', explode(',', variable_get('node_export_file_supported_fields', 'file, image')));
  948. // Check if this field should implement file import/export system.
  949. if (in_array($info['type'], $supported_fields)) {
  950. // We need to loop into each language because i18n translation can build
  951. // fields with different language than the node one.
  952. foreach($field as $language => $files) {
  953. if (is_array($files)) {
  954. foreach($files as $i => $file) {
  955. // Convert file to array to stay into the default node_export_file format.
  956. $file = (object)$file;
  957. $result = _node_export_file_field_import_file($file);
  958. // The file was saved successfully, update the file field (by reference).
  959. if ($result == TRUE && isset($file->fid)) {
  960. $field[$language][$i] = (array)$file;
  961. }
  962. }
  963. }
  964. }
  965. }
  966. }
  967. }
  968. /**
  969. * Detects remote and local file exports and imports accordingly.
  970. *
  971. * @param &$file
  972. * The file, passed by reference.
  973. * @return TRUE or FALSE
  974. * Depending on success or failure. On success the $file object will
  975. * have a valid $file->fid attribute.
  976. */
  977. function _node_export_file_field_import_file(&$file) {
  978. // This is here for historical reasons to support older exports. It can be
  979. // removed in the next major version.
  980. $file->uri = strtr($file->uri, array('#FILES_DIRECTORY_PATH#' => 'public:/'));
  981. // The file is already in the right location AND either the
  982. // node_export_file_path is not set or the node_export_file_path and filepath
  983. // contain the same file
  984. if (is_file($file->uri) &&
  985. (
  986. (!isset($file->node_export_file_path) || !is_file($file->node_export_file_path)) ||
  987. (
  988. is_file($file->node_export_file_path) &&
  989. filesize($file->uri) == filesize($file->node_export_file_path) &&
  990. strtoupper(dechex(crc32(file_get_contents($file->uri)))) ==
  991. strtoupper(dechex(crc32(file_get_contents($file->node_export_file_path))))
  992. )
  993. )
  994. ) {
  995. // Keep existing file if it exists already at this uri (see also #1023254)
  996. // Issue #1058750.
  997. $query = db_select('file_managed', 'f')
  998. ->fields('f', array('fid'))
  999. ->condition('uri', $file->uri)
  1000. ->execute()
  1001. ->fetchCol();
  1002. if (!empty($query)) {
  1003. watchdog('node_export', 'kept existing managed file at uri "%uri"', array('%uri' => $file->uri), WATCHDOG_NOTICE);
  1004. $file = file_load(array_shift($query));
  1005. }
  1006. $file = file_save($file);
  1007. }
  1008. elseif (isset($file->node_export_file_data)) {
  1009. $directory = drupal_dirname($file->uri);
  1010. if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
  1011. if (file_put_contents($file->uri, base64_decode($file->node_export_file_data))) {
  1012. $file = file_save($file);
  1013. }
  1014. }
  1015. }
  1016. // The file is in a local location, move it to the
  1017. // destination then finish the save
  1018. elseif (isset($file->node_export_file_path) && is_file($file->node_export_file_path)) {
  1019. $directory = drupal_dirname($file->uri);
  1020. if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
  1021. // The $file->node_export_file_path is passed to reference, and modified
  1022. // by file_unmanaged_copy(). Making a copy to avoid tainting the original.
  1023. $node_export_file_path = $file->node_export_file_path;
  1024. file_unmanaged_copy($node_export_file_path, $directory, FILE_EXISTS_REPLACE);
  1025. // At this point the $file->node_export_file_path will contain the
  1026. // destination of the copied file
  1027. //$file->uri = $node_export_file_path;
  1028. $file = file_save($file);
  1029. }
  1030. }
  1031. // The file is in a remote location, attempt to download it
  1032. elseif (isset($file->node_export_file_url)) {
  1033. // Need time to do the download
  1034. ini_set('max_execution_time', 900);
  1035. $temp_path = file_directory_temp() . '/' . md5(mt_rand()) . '.txt';
  1036. if (($source = fopen($file->node_export_file_url, 'r')) == FALSE) {
  1037. drupal_set_message(t("Could not open '@file' for reading.", array('@file' => $file->node_export_file_url)));
  1038. return FALSE;
  1039. }
  1040. elseif (($dest = fopen($temp_path, 'w')) == FALSE) {
  1041. drupal_set_message(t("Could not open '@file' for writing.", array('@file' => $file->uri)));
  1042. return FALSE;
  1043. }
  1044. else {
  1045. // PHP5 specific, downloads the file and does buffering
  1046. // automatically.
  1047. $bytes_read = @stream_copy_to_stream($source, $dest);
  1048. // Flush all buffers and wipe the file statistics cache
  1049. @fflush($source);
  1050. @fflush($dest);
  1051. clearstatcache();
  1052. if ($bytes_read != filesize($temp_path)) {
  1053. drupal_set_message(t("Remote export '!url' could not be fully downloaded, '@file' to temporary location '!temp'.", array('!url' => $file->node_export_file_url, '@file' => $file->uri, '!temp' => $temp_path)));
  1054. return FALSE;
  1055. }
  1056. // File was downloaded successfully!
  1057. else {
  1058. if (!@copy($temp_path, $file->uri)) {
  1059. unlink($temp_path);
  1060. drupal_set_message(t("Could not move temporary file '@temp' to '@file'.", array('@temp' => $temp_path, '@file' => $file->uri)));
  1061. return FALSE;
  1062. }
  1063. unlink($temp_path);
  1064. $file->filesize = filesize($file->uri);
  1065. $file->filemime = file_get_mimetype($file->uri);
  1066. }
  1067. }
  1068. fclose($source);
  1069. fclose($dest);
  1070. $file = file_save($file);
  1071. }
  1072. // Unknown error
  1073. else {
  1074. drupal_set_message(t("Unknown error occurred attempting to import file: @filepath", array('@filepath' => $file->uri)), 'error');
  1075. return FALSE;
  1076. }
  1077. return TRUE;
  1078. }
  1079. // Remove once http://drupal.org/node/858274 is resolved.
  1080. if (!function_exists('uuid_set_uuid')) {
  1081. /**
  1082. * API function to set the UUID of an object based on its serial ID.
  1083. *
  1084. * @param $table
  1085. * Base table of the object. Currently, one of node, revision_revisions,
  1086. * users, vocabulary or term_data.
  1087. * @param $key
  1088. * The name of the serial ID column.
  1089. * @param $serial_id
  1090. * The serial ID of the object.
  1091. * @param $uuid
  1092. * Optional UUID. If omitted, a UUID will be generated.
  1093. * @return
  1094. * The UUID on success, FALSE if the uuid provided is not valid.
  1095. */
  1096. function uuid_set_uuid($table, $key, $serial_id, $uuid = FALSE) {
  1097. if (empty($uuid)) {
  1098. $uuid = uuid_generate();
  1099. }
  1100. if (!uuid_is_valid($uuid)) {
  1101. return FALSE;
  1102. }
  1103. $query = db_query("UPDATE {" . $table . "} SET uuid = :uuid WHERE " . $key . " = :id", array(':uuid' => $uuid, ':id' => $serial_id));
  1104. /*
  1105. if (!$query->rowCount()) {
  1106. @db_query("INSERT INTO {" . $table . "} (" . $key . ", uuid) VALUES (:id, :uuid)", array(':uuid' => $uuid, ':id' => $serial_id));
  1107. }
  1108. */
  1109. return $uuid;
  1110. }
  1111. }
  1112. // Remove once http://drupal.org/node/858274 is resolved.
  1113. if (!function_exists('uuid_get_uuid')) {
  1114. /**
  1115. * API function to get the UUID of an object based on its serial ID.
  1116. *
  1117. * @param $entity_type
  1118. * The entity type.
  1119. * @param $key
  1120. * The name of the serial ID column.
  1121. * @param $id
  1122. * The serial ID of the object.
  1123. * @return
  1124. * The UUID of the object, or FALSE if not found.
  1125. */
  1126. function uuid_get_uuid($entity_type, $key, $id) {
  1127. $supported = uuid_get_core_entity_info();
  1128. if (!isset($supported[$entity_type])) {
  1129. return FALSE;
  1130. }
  1131. $entity_info = entity_get_info($entity_type);
  1132. $table = $entity_info['base table'];
  1133. return db_query("SELECT uuid FROM {" . $table . "} WHERE " . $key . " = :id", array(':id' => $id))->fetchField();
  1134. }
  1135. }