<?php
/**
 * @file
 * Allow users to make a copy of an item of content (a node) and then edit that copy.
 */

/**
 * Implementation of hook_help().
 */
function clone_help($path, $arg) {
  switch ($path) {
    case 'admin/help#clone':
      $output = '<p>' . t('The clone module allows users to make a copy of an existing node and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original node.') . '</p>';
      $output .= '<p>' . t('Users with the "clone node" permission can utilize this functionality. A new tab will appear on node pages with the word "Clone".') . '</p>';
      return $output;
    case 'node/%/clone':
      $method = variable_get('clone_method', 'prepopulate');
      if ($method == 'prepopulate') {
        return t('This clone will not be saved to the database until you submit.');
      }
  }
}

/**
 * Implementation of hook_permission().
 */
function clone_permission() {
  return array(
    'clone node' => array('title' => t('Clone any node')),
    'clone own nodes' => array('title' => t('Clone own nodes.')),
  );
}

/**
 * Implementation of hook_menu().
 */
function clone_menu() {
  $items['admin/config/content/clone'] = array(
    'access arguments' => array('administer site configuration'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('clone_settings'),
    'title' => 'Node clone module',
    'file' => 'clone.pages.inc',
    'description' => 'Allows users to clone (copy then edit) an existing node.',
  );
  $items['node/%node/clone/%clone_token'] = array(
    'access callback' => 'clone_access_cloning',
    'access arguments' => array(1, TRUE, 3),
    'page callback' => 'clone_node_check',
    'page arguments' => array(1),
    'title' => 'Clone content',
    'title callback' => 'clone_action_link_title',
    'title arguments' => array(1),
    'weight' => 5,
    'file' => 'clone.pages.inc',
    'type' => MENU_LOCAL_ACTION,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );
  return $items;
}

/**
 * Implements a to_arg function for the clone local action.
 *
 * @param string $arg
 *   The current argument value.
 * @param array $map
 *   The path arguments.
 *
 * @return string
 *   Either 'confirm' or a CSRF token.
 */
function clone_token_to_arg($arg, $map) {
  // Supply CSRF token if needed.
  return clone_get_token($map[1]);
}

/**
 * Get the token that needs to be added to the clone link.
 *
 * @param int $nid
 *   The node ID of the node to be cloned
 *
 * @return string
 *   Either 'confirm' or a CSRF token.
 */
function clone_get_token($nid) {
  if (variable_get('clone_nodes_without_confirm', FALSE)) {
    return drupal_get_token('clone_access_cloning-' . $nid);
  }
  return 'confirm';
}

function clone_access_cloning($node, $check_token = FALSE, $token = FALSE) {
  global $user;
  // Check CSRF token if needed.
  if ($check_token) {
    if (!$token || $token !== clone_get_token($node->nid)) {
      return FALSE;
    }
  }
  // Check basic permissions first.
  $access = clone_is_permitted($node->type) && (user_access('clone node') || ($user->uid && ($node->uid == $user->uid) && user_access('clone own nodes')));
  // Make sure the user can view the original node content, and create a new one..
  $access = $access && node_access('view', $node) && node_access('create', $node->type);
  // Let other modules alter this.
  drupal_alter("clone_access", $access, $node);
  return $access;
}

function clone_is_permitted($type) {
  $omitted = variable_get('clone_omitted', array());
  return empty($omitted[$type]);
}

/**
 * Menu title callback.
 */
function clone_action_link_title($node) {
  // A hack to present a shorter title in contextual links.
  if (current_path() != 'node/' . $node->nid) {
    return t('Clone');
  }
  if (variable_get('clone_use_node_type_name', 0)) {
    return t('Clone this !type', array('!type' => drupal_strtolower(node_type_get_name($node))));
  }
  return t('Clone content');
}

/**
 * Implementation of hook_node_type_delete().
 */
function clone_node_type_delete($info) {
  variable_del('clone_reset_' . $info->type);
}

/**
 * Implementation of hook_node_type_update().
 */
function clone_node_type_update($info) {
  if (!empty($info->old_type) && $info->old_type != $info->type) {
    if (variable_get('clone_reset_' . $info->old_type, FALSE)) {
      variable_del('clone_reset_' . $info->old_type);
      variable_set('clone_reset_' . $info->type, TRUE);
    }
  }
}

/**
  * Implements hook_views_api.
  */
function clone_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'clone') . '/views',
  );
}

/**
 * Implementation of hook_admin_paths().
 */
function clone_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/clone/*' => TRUE,
    );
    return $paths;
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function clone_form_node_form_alter(&$form, $form_state, $form_id) {
  // Add the clone_from_original_nid value for node forms triggered by cloning.
  // This will make sure the clone_from_original_nid property is still
  // attached to the node when passing through hook_node_insert().
  if (!empty($form['#node']->clone_from_original_nid)) {
    $form['clone_from_original_nid'] = array(
      '#type' => 'value',
      '#value' => $form['#node']->clone_from_original_nid,
    );
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function clone_form_node_admin_content_alter(&$form, $form_state, $form_id) {
  if (variable_get('clone_method', 'prepopulate') == 'prepopulate') {
    $destination = drupal_get_destination();
  }
  else {
    $destination = array();
  }
  // The property attribute changes in the $form array depending on the user role.
  $property = isset($form['admin']['nodes']['#options']) ? '#options' : '#rows';
  if (empty($form['admin']['nodes'][$property])) {
    return;
  }
  // Expose a Clone operation on each node.
  foreach ($form['admin']['nodes'][$property] as $nid => &$row) {
    $node = node_load($nid);
    if (clone_access_cloning($node)) {
      // The structure of this form is different if there is just 1 or more
      // than one operation.
      if (!isset($row['operations']['data']['#links'])) {
        $row['operations']['data']['#links'] = array();
        $row['operations']['data']['#attributes']['class'] = array('links', 'inline');
        $row['operations']['data']['#theme'] = 'links__node_operations';
        if (isset($row['operations']['data']['#title'])) {
          $title = $row['operations']['data']['#title'];
          $row['operations']['data']['#links'][$title] = array(
            'title' => $title,
            'href' => $row['operations']['data']['#href'],
            'query' => $row['operations']['data']['#options']['query'],
          );
          unset($row['operations']['data']['#type']);
        }
      }
      $row['operations']['data']['#links']['clone'] = array(
        'title' => t('clone'),
        'href' => 'node/' . $nid . '/clone/' . clone_get_token($nid),
        'query' => $destination,
      );
    }
  }
}

/**
 * Implements hook_action_info().
 */
function clone_action_info() {
  return array(
    'clone_action_clone' => array(
      'type' => 'node',
      'label' => t('Clone item'),
      'configurable' => TRUE,
      'hooks' => array('any' => TRUE),
      'triggers' => array('any'),
    ),
  );
}

/**
 * Action callback.
 */
function clone_action_clone($original_node, $context) {
  module_load_include('inc', 'clone', 'clone.pages');
  if (clone_is_permitted($original_node->type)) {
    $val = !empty($context['clone_context']) ? $context['clone_context'] : array();
    $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_alter('clone_node', $node, $context);
    node_save($node);
    if (module_exists('rules')) {
      rules_invoke_event('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');
  }
}

/**
 * Action form.
 */
function clone_action_clone_form($context) {
 $form['clone_context'] = array(
   '#tree' => TRUE,
 );
 $form['clone_context']['prefix_title'] = array(
    '#title' => t('Prefix title'),
    '#type' => 'checkbox',
    '#description' => t('Should cloned node tiles be prefixed?'),
    '#default_value' => isset($context['clone_context']['prefix_title']) ? $context['clone_context']['prefix_title'] : 1,
  );
 $form['clone_context']['substitute_from'] = array(
    '#title' => t('Substitute from string'),
    '#type' => 'textfield',
    '#description' => t('String (or regex) to substitute from in title and body.'),
    '#default_value' => isset($context['clone_context']['substitue_from']) ? $context['clone_context']['substitue_from'] : '',
  );
 $form['clone_context']['substitute_to'] = array(
    '#title' => t('Substitute to string'),
    '#type' => 'textfield',
    '#description' => t('String (or regex) to substitute to in title and body.'),
    '#default_value' => isset($context['clone_context']['substitue_to']) ?  $context['clone_context']['substitue_to'] : '',
  );
 $form['clone_context']['substitute_case_insensitive'] = array(
    '#title' => t('Case insensitive substitution'),
    '#type' => 'checkbox',
    '#description' => t('Should the substituion match be case insensitive?'),
    '#default_value' => isset($context['clone_context']['substitute_case_insensitive']) ? $context['clone_context']['substitute_case_insensitive'] : NULL,
  );
  return $form;
}

/**
 * Action form submit.
 */
function clone_action_clone_submit($form, $form_state) {
  return array('clone_context' => $form_state['values']['clone_context']);
}
