node_export.module 45 KB

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