<?php
// $Id: image_annotate.module,v 1.6 2009/03/06 16:46:22 hunvreus Exp $
/**
 * Implementation of hook_comment
 */
function image_annotate_comment(&$comment, $op) {
  if (user_access('create image annotations') || user_access('administer image annotations')) {
    if ($op == 'insert' || $op == 'update') {
      if (is_numeric($_POST['image-annotate']) && $_POST['image-annotate']) {
        global $user;
        $field = preg_replace("/[^a-zA-Z0-9_s]/", "", $_POST['image-annotate-field']);
        // TODO: check position.size is inside the picture
        $top = (int)$_POST['image-annotate-top'];
        $left = (int)$_POST['image-annotate-left'];
        $width = (int)$_POST['image-annotate-width'];
        $height = (int)$_POST['image-annotate-height'];
        if (arg(1) == 'reply') {
          db_query('INSERT INTO {image_annotate} (cid, field_name, size_width, size_height, position_top, position_left) VALUES (%d, \'%s\', %d, %d, %d, %d)', $comment['cid'], $field, $width, $height, $top, $left);
        }
        else if (arg(1) == 'edit' && (user_access('administer image annotations') || (user_access('create image annotations')  && $comment['uid'] == $user->uid))) {
          db_query('UPDATE {image_annotate} SET size_width = %d, size_height = %d, position_top = %d, position_left = %d WHERE cid = %d', $width, $height, $top, $left, arg(2));
        }
      }
    }
  }
}

/**
 * Implementation of CCK's hook_field_formatter_info().
 */
function image_annotate_field_formatter_info() {
  $formatters = array(
    'image_annotate' => array(
      'label' => t('Image with annotations'),
      'field types' => array('image', 'filefield'),
      'suitability callback' => 'image_annotate_handles_file',
      'css' => array(drupal_get_path('module','image_annotate') .'/tag.css'),
      'description' => t('Display a picture and its annotations.'),
    ),
  );

  return $formatters;
}

/**
 * Implementation of hook_link().
 */
function image_annotate_link($type, $object, $teaser = FALSE) {
  if ($type == 'comment') {
    if (user_access('view image annotations') || user_access('create image annotations') || user_access('administer image annotations')) {
      $note = db_fetch_object(db_query('SELECT aid, field_name FROM {image_annotate} WHERE cid = %d', $object->cid));
      if ($note->aid) {
        $links = array(
	      'image_annotate_link' => array(
            'title' => t('View image note'),
            'href' => $_GET['q'],
            'fragment' => 'image-annotate-add-'. $note->field_name,
            'attributes' => array(
	          'title' => t('go to the picture'),
              'class' => 'image-annotate-link',
              'rel' => 'image-annotate-'. $note->aid,
            ),
          ),
        );
        return $links;
      }
    }
  }
}

/**
 * Implementation of hook_menu()
 */
function image_annotate_menu() {
  $items = array();

  $items['content/image-annotate/create'] = array(
    'title' => 'Save note',
    'page callback' => '_image_annotate_note_create',
    'access callback' => 'image_annotate_user_access',
    'type' => MENU_CALLBACK,
  );

  $items['content/image-annotate/edit'] = array(
    'title' => 'Note edit form',
    'page callback' => '_image_annotate_note_edit',
    'access callback' => 'image_annotate_user_access',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implementation of hook_nodeapi().
 */
function image_annotate_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'delete':
      db_query("DELETE FROM {image_annotate} WHERE nid = %d", $node->nid);
      break;
  }
}

/**
 * Implementation of hook_perm().
 */
function image_annotate_perm() {
  return array('administer image annotations', 'create image annotations', 'view image annotations');
}

/**
 * Implementation of hook_theme
 */
function image_annotate_theme() {
  return array(
    'image_annotate_formatter_image_annotate' => array(
      'arguments' => array('element' => null),
    ),
  );
}

/**
 * Return permissions for editing/creating annotations for the current user.
 */
function image_annotate_user_access() {
  return user_access('administer image annotations') || user_access('create image annotations');
}

/**
 * Theme function for the image annotate formatter
 */
function theme_image_annotate_formatter_image_annotate($element) {
  drupal_add_js('misc/collapse.js');
  if (empty($element['#item'])) return '';
  $item = $element['#item'];
  $field = content_fields($element['#field_name']);
  if (empty($item['fid']) && $field['use_default_image']) $item = $field['default_image'];
  if (empty($item['filepath']))  $item = array_merge($item, field_file_load($item['fid']));

  if (user_access('view image annotations') || user_access('create image annotations') || user_access('administer image annotations')) {
    // Retrieve all the annotations for that image field
    // We sort by area (height*width) to make sure small annotations are always on the top and avoid having some unhoverable ones
    $result = db_query('SELECT i.*, c.uid, c.comment, u.name FROM {image_annotate} i JOIN {comments} c ON i.cid = c.cid JOIN {users} u ON c.uid = u.uid WHERE i.field_name = \'%s\' AND c.nid = %d ORDER BY (i.size_height*i.size_width) ASC', $field['field_name'], $element['#node']->vid);

    // Build the array of notes settings
    global $user;
    $notes = array();
    while ($note = db_fetch_object($result)) {
      $editable = user_access('administer image annotations') || (user_access('create image annotations') && $note->uid && $note->uid == $user->uid);
      $author = theme('username', $note);
      $text = '"'. check_plain($note->comment) . '"<span class="author"> '. t('by') .' '. $author . '</span>';
      if (user_access('access comments')) $text .= '<span class="actions">» '. l(t('View comment'), $_GET['q'], array('fragment'=>'comment-'. $note->cid)) .'</span>';
      $notes[] = array(
        'aid' => $note->aid,
        'cid' => $note->cid,
        'uid' => $note->uid,
        'height' => $note->size_height,
        'width' => $note->size_width,
        'top' => $note->position_top,
        'left' => $note->position_left,
        'text' => $text,
        'editable' => $editable,
      );
    }
    
    // Build the field settings
    $settings = array(array(
      'nid' => $element['#node']->nid,
      'field' => $field['field_name'],
      'notes' => $notes,
      'editable' => user_access('administer image annotations') || user_access('create image annotations'),
    ));
    
    module_load_include('module', 'jquery_ui');
    // Load all the JS and CSS magic
    drupal_add_js(array('imageAnnotate' => $settings), 'setting');
    jquery_ui_add(array('ui.resizable', 'ui.draggable'));
    drupal_add_js(drupal_get_path('module', 'image_annotate') .'/tag.js');
    drupal_add_css(drupal_get_path('module', 'image_annotate') .'/tag.css');
    
    $class = 'imagefield imagefield-'. $field['field_name'] .' image-annotate-'. $field['field_name'];
    return theme('imagefield_image', $item, $item['alt'], $item['title'], array('class' => $class));
  }
  else {
    return theme('imagefield_image', $item, $item['alt'], $item['title']);
  }
}

/**
 * Display the create form of a comment/note
 */
function _image_annotate_note_create($nid) {
  if (user_access('post comments') && user_access('access comments')) {
    print drupal_get_form('comment_form', array('nid' => $nid));
  }
}

/**
 * Display the edit form of a comment/note
 */
function _image_annotate_note_edit($aid) {
  $cid = db_result(db_query('SELECT cid FROM {image_annotate} WHERE aid = %d', $aid));
  include_once(drupal_get_path('module','comment') .'/comment.pages.inc');
  print comment_edit($cid);
}
