You are here

function cpn_node_insert in Code per Node 7

Implements hook_node_insert().

Saves in DB and file system.

1 call to cpn_node_insert()
cpn_node_update in ./cpn.module
Implements hook_node_update().

File

./cpn.module, line 284
Primary hook implementations.

Code

function cpn_node_insert($node) {
  $cpn = array();
  if (isset($node->cpn)) {
    $cpn['nid'] = $node->nid;
    $cpn['css'] = isset($node->cpn['css']) ? $node->cpn['css'] : '';
    $cpn['js'] = isset($node->cpn['js']) ? $node->cpn['js'] : '';
    $cpn['noscript'] = isset($node->cpn['noscript']) ? $node->cpn['noscript'] : '';
  }

  // If the node is being updated, account for when the user does not have
  // permission to edit them and the previous records might be deleted.
  if (isset($node->original, $node->original->cpn)) {
    if (variable_get('cpn_css_enabled_' . $node->type, FALSE)) {
      if (!user_access('administer code per node') && !user_access('edit css per node')) {
        if (!empty($node->original->cpn['css'])) {
          $cpn['css'] = $node->original->cpn['css'];
        }
      }
    }
    if (variable_get('cpn_js_enabled_' . $node->type, FALSE)) {
      if (!user_access('administer code per node') && !user_access('edit javascript per node')) {
        if (!empty($node->original->cpn['js'])) {
          $cpn['js'] = $node->original->cpn['js'];
        }
        if (!empty($node->original->cpn['noscript'])) {
          $cpn['noscript'] = $node->original->cpn['noscript'];
        }
      }
    }
  }
  if (!empty($cpn)) {
    if (drupal_strlen(trim($cpn['css'] . $cpn['js'] . $cpn['noscript']))) {
      db_merge('cpn')
        ->fields($cpn)
        ->key(array(
        'nid' => $node->nid,
      ))
        ->execute();
      foreach (array(
        'css',
        'js',
      ) as $type) {

        // Add the global wrapper code.
        $output = cpn_wrap_output($cpn[$type], 'node', $type);

        // Replace the token strings using any available global & node tokens.
        $output = token_replace($output, array(
          'node' => $node,
        ));

        // Output the file.
        if (!empty($output)) {
          cpn_save_file($output, $node->nid . '.' . $type);
        }
      }
    }
  }
}