You are here

function node_clone_action_clone in Node clone 8

Action callback.

File

./node_clone.module, line 157
Allow users to make a copy of an item of content (a node) and then edit that copy.

Code

function node_clone_action_clone($original_node, $context) {
  module_load_include('inc', 'clone', 'clone.pages');
  if (node_clone_is_permitted($original_node->type)) {
    $val = !empty($context['clone_context']) ? $context['clone_context'] : array();
    $node = _node_clone_node_prepare($original_node, !empty($val['prefix_title']));
    if (isset($val['substitute_from']) && strlen($val['substitute_from']) && isset($val['substitute_to'])) {
      $i = !empty($val['substitute_case_insensitive']) ? 'i' : '';
      $pattern = '#' . strtr($val['substitute_from'], array(
        '#' => '\\#',
      )) . '#' . $i;
      foreach (array(
        'title',
      ) as $property) {
        $new = preg_replace($pattern, $val['substitute_to'], $node->{$property});
        if ($new) {
          $node->{$property} = $new;
        }
      }
      foreach (array(
        'body',
      ) as $property) {
        foreach ($node->{$property} as $lang => $row) {
          foreach ($row as $delta => $data) {
            foreach (array(
              'value',
              'summary',
            ) as $key) {
              if (isset($node->{$property}[$lang][$delta][$key])) {
                $new = preg_replace($pattern, $val['substitute_to'], $node->{$property}[$lang][$delta][$key]);
                if ($new) {
                  $node->{$property}[$lang][$delta][$key] = $new;
                }
              }
            }
          }
        }
      }
    }

    // Let other modules do special fixing up.
    $context = array(
      'method' => 'action',
      'original_node' => $original_node,
      'clone_context' => $val,
    );
    \Drupal::moduleHandler()
      ->alter('node_clone_node', $node, $context);
    $node
      ->save();
    if (\Drupal::moduleHandler()
      ->moduleExists('rules')) {
      rules_invoke_event('node_clone_node', $node, $original_node);
    }
  }
  else {
    drupal_set_message(t('Clone failed for %title : not permitted for nodes of type %type', array(
      '%title' => $original_node->title,
      '%type' => $original_node->type,
    )), 'warning');
  }
}