<?php

function cobaltnodes_init() {
  if (user_access('use cobalt')) {
    drupal_add_js(drupal_get_path('module', 'cobalt') . '/js/cobalt.nodes.js');

    // Add the current node nid as a javascript setting
    if (arg(0)=='node' && is_numeric(arg(1))) {
      drupal_add_js(array('cobalt' => array('nodes_current' => arg(1))), 'setting');
    }
  }
}

function cobaltnodes_menu() {
  $items = array();
  $items['cobalt/data/nodes_update/%'] = array(
    'title' => 'Serialized nodes',
    'page callback' => 'cobaltnodes_json',
    'page arguments' => array('update', 3),
    'access arguments' => array('use cobalt'),
    'type' => MENU_CALLBACK,
  );
  $items['cobalt/data/nodes_single/%'] = array(
    'title' => 'Serialized node',
    'page callback' => 'cobaltnodes_json',
    'page arguments' => array('single', 3),
    'access arguments' => array('use cobalt'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function cobaltnodes_cron() {
  // Delete logged deletions older than two weeks
  db_query("DELETE FROM {cobalt_node_deletion} WHERE deleted<:time_ago", array(
    ':time_ago' => time() - 86400*14,
  ));
}

function cobaltnodes_node_delete($node) {
  db_query("INSERT INTO {cobalt_node_deletion}(nid, deleted) VALUES(:nid, :deleted)", array(
    ':nid' => $node->nid, 
    ':deleted' => time()+60*1, // Add a minute for margin
  ));
}

function cobaltnodes_json($op, $value) {
  $result = array();

  // We're skipping the status check on purpose. As we check with the node_access
  // function later this allows administrators to access unpublished nodes.
  if ($op=='update') {
    $res = db_query("SELECT n.nid, n.title, n.type, n.uid, n.status
      FROM {node} n
      WHERE created > :since OR changed > :since
      ORDER BY created DESC
      LIMIT 100", array(
        ':since' => $value,
      ));
  }
  else if ($op=='single') {
    $res = db_query("SELECT nid, title, type, uid, status FROM {node}
      WHERE nid = :nid", array(
        ':nid' => $value,
      ));
  }

  $nodes = array();
  $access_types = array(
    'r' => 'view',
    'w' => 'update',
    'd' => 'delete',
  );

  foreach ($res as $node) {
    $access = '';
    foreach ($access_types as $key => $permission) {
      if (node_access($permission, $node)) {
        $access .= $key;
      }
    }
    if (!empty($access)) {
      $nodes[] = array($node->nid, $node->title, $access);
    }
  }

  $result['nodes'] = $nodes;

  if ($op=='update') {
    $deleted = array();
    // Get deletions
    $res = db_query("SELECT nid FROM {cobalt_node_deletion} WHERE deleted>:since", array(
      ':since' => $value,
    ));
    foreach ($res as $node) {
      $deleted[] = $node->nid;
    }
    $result['deleted'] = $deleted;
  }

  print drupal_json_output($result);
  exit;
}