<?php
// $Id: fbconnect_stream_publish.module,v 1.1.2.6 2010/10/12 15:07:18 vectoroc Exp $

define('FBCONNECT_STREAM_PUBLISH_NONE', 0);
define('FBCONNECT_STREAM_PUBLISH_ALL', 1);
define('FBCONNECT_STREAM_PUBLISH_NODES', 2);
define('FBCONNECT_STREAM_PUBLISH_COMMENTS', 3);

/**
 * Impletementation of hook_init().
 */
function fbconnect_stream_publish_init() {
  if (isset($_SESSION['fbconnect_feed'])) {
    fbconnect_stream_publish_render_js($_SESSION['fbconnect_feed']);
    unset($_SESSION['fbconnect_feed']);
  }
}

/**
 * Impletementation of hook_theme(). 
 */
function fbconnect_stream_publish_theme() {
  return array(
    'stream_publish_favicon' => array(
      'arguments' => array(),
    ),
  );
}

/**
 * Implementation of hook_nodeapi()
 */
function fbconnect_stream_publish_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate' && isset($a3['form_id']['#post']['fbconnect_feed'])) {
    $_SESSION['fbconnect_feed']['submit'] = TRUE;
  }
  if ($op == 'insert' && $_SESSION['fbconnect_feed']['submit'] === TRUE) {
    $_SESSION['fbconnect_feed'] = array(
      'type'    => 'node',
      'title'   => $node->title,
      'nodeurl' => url('node/' . $node->nid, array('absolute' => TRUE)),
    );
  }
}

/**
 * Impletementation of hook_form_alter().
 */
function fbconnect_stream_publish_form_alter(&$form, &$form_state, $form_id) {
  // Facebook feed checkbox on node edit/create form.
  // only show this on the create new forms, not the edit forms
  if (isset($form['#node']) && $form['#node']->type . '_node_form' == $form_id && $form['nid']['#value'] == NULL) {
    // only with allowed content types
    $publishing_mode = variable_get('fbconnect_stream_publish_onoff_' . $form['#node']->type, FBCONNECT_STREAM_PUBLISH_NONE);
    if (!in_array($publishing_mode, array(FBCONNECT_STREAM_PUBLISH_ALL, FBCONNECT_STREAM_PUBLISH_NODES))) {
      return;
    }

    $favicon = theme('stream_publish_favicon');

    $form['fbconnect_stream_publish'] = array(
      '#type' => 'fieldset',
      '#title' => t('Facebook Stream Publish'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    
    $form['fbconnect_stream_publish']['fbconnect_feed'] = array(
      '#type' => 'checkbox',
      '#title' => $favicon .' '. t('Publish to Facebook'),
      '#default_value' => 1,
    );
  };
}

/**
 * Implementation of hook_form_FORM_ID_alter() for comment_form
 */
function fbconnect_stream_publish_form_comment_form_alter(&$form, &$form_state) {
  // Facebook feed checkbox on comment form.
  if ($node = node_load($form['nid']['#value'])) {
    // add only for allowed content types
    $publishing_mode = variable_get('fbconnect_stream_publish_onoff_' . $node->type, FBCONNECT_STREAM_PUBLISH_NONE);
    if (in_array($publishing_mode, array(FBCONNECT_STREAM_PUBLISH_ALL, FBCONNECT_STREAM_PUBLISH_COMMENTS))) {

      $form['fbconnect_stream_publish'] = array(
        '#type' => 'fieldset',
        '#title' => t('Facebook Stream Publish'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
      );

      $favicon = theme('stream_publish_favicon');
      $form['fbconnect_stream_publish']['fbconnect_feed'] = array(
        '#type' => 'checkbox',
        '#title' => $favicon .' '. t('Publish to Facebook'),
        '#default_value' => 1,
        '#weight' => 9,
      );
      
      if (module_exists('ajax_comments')) {
        $form['submit']['#submit'][] = 'fbconnect_stream_publish_comment_feed_submit';
        drupal_add_js(drupal_get_path('module', 'fbconnect_stream_publish') .'/fbconnect_stream_publish.js');
      }
      else {
        $form['#submit'][] = 'fbconnect_stream_publish_comment_feed_submit';
      }
    }
  }
}

/**
 * Implementation of hook_form_FORM_ID_alter() for node_type_form
 */
function fbconnect_stream_publish_form_node_type_form_alter(&$form, &$form_state) {
  // admin settings for enabling/disabling the ability to publish to Facebook, per node type
  $form['fbconnect_stream_publish_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Facebook Stream Publish'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['fbconnect_stream_publish_settings']['fbconnect_stream_publish_onoff'] = array(
    '#type' => 'select',
    '#title' => t('Allow this content type to publish to Facebook'),
    '#options' => array(
      FBCONNECT_STREAM_PUBLISH_NONE => t('Disable publishing'),
      FBCONNECT_STREAM_PUBLISH_ALL => t('Publish nodes on comments'),
      FBCONNECT_STREAM_PUBLISH_NODES => t('Publish only nodes'),
      FBCONNECT_STREAM_PUBLISH_COMMENTS => t('Publish only comments'),
    ),
    '#default_value' => variable_get('fbconnect_stream_publish_onoff_' . $form['#node_type']->type, FBCONNECT_STREAM_PUBLISH_NONE),
  );
}

/**
 *  Implement CCK's hook_content_extra_fields().
 */
function fbconnect_stream_publish_content_extra_fields($type_name) {
  $extra = array();
  if (variable_get('fbconnect_'. $type_name .'_onoff', 0)) {
    $extra['fbconnect_stream_publish'] = array(
      'label' => t('Facebook Connect'),
      'description' => t('Facebook Connect Confirmation'),
      'weight' => 100,
    );
  }
  return $extra;
}

/**
 * Stock informations used by the facebook feed javascript function.
 */
function fbconnect_stream_publish_comment_feed_submit($form, &$form_state) {
  if (isset($form_state['values']['fbconnect_feed'])) {
    $node = node_load($form_state['values']['nid']);

    $feed = array(
      'type'    => 'comment',
      'comment' => $form_state['values']['comment'],
      'title'   => $node->title,
      'nodeurl' => url('node/' . $node->nid, array('absolute' => TRUE)),
    );
    
    if (module_exists('ajax_comments')) {
      fbconnect_stream_publish_render_js($feed);
    }
    else {
      $_SESSION['fbconnect_feed'] = $feed;
    }
  }
}

/**
 * @param array $feed
 *    Properites - type, title, nodeurl[, comment]
 */
function fbconnect_stream_publish_render_js($feed) {
  global $base_url;
  
  $site = variable_get('site_name', $base_url);

  switch ($feed['type']) {
    case 'comment':
      $autopublish = 'false';
      $attachment = array(
        'name'        => $feed['title'],
        'href'        => $feed['nodeurl'],
        'caption'     => t("{*actor*} commented at !site", array("!site" => $site)),
        'description' => strip_tags($feed['comment']),
      );
      $action_links = array(
        array(
          'text'  => $site,
          'href'  => $base_url,
        ),
      );
      $message = t('I posted a comment on !site_name.', array('!site_name' => variable_get('site_name', 'Drupal')));
      break;
    case 'node':
      $autopublish = 'false';
      $attachment = array(
        'name'        => $feed['title'],
        'href'        => $feed['nodeurl'],
        'caption'     => t("{*actor*} created some content at !site", array("!site" => $site)),
      );
      $action_links = array(
        array(
          'text'  => $site,
          'href'  => $base_url,
        ),
      );
      $message = t('I posted new content on !site_name.', array('!site_name' => variable_get('site_name', 'Drupal')));
      break;
    case 'register':
      $autopublish = 'true';
      $attachment = array(
        'name'        => t('Welcome to @site', array('@site' => $site)),
        'href'        => $base_url,
        'caption'     => t("{*actor*} has registered at !site", array("!site" => $site)),
      );
      $action_links = array(
        array(
          'text'  => $site,
          'href'  => $base_url,
        ),
      );
      $message = t('I just became a member at !site_name!', array('!site_name' => variable_get('site_name', 'Drupal')));
  }

  /**
   * @see http://developers.facebook.com/docs/reference/rest/stream.publish
   * @see http://developers.facebook.com/docs/guides/attachments
   */
  $method = 'stream.publish';    
  $user_message_prompt = t('Share your thoughts');
  $streamPublishArgs = compact('method', 'message', 'attachment', 'action_links', 'user_message_prompt');
    
//  drupal_alter('fbconnect_stream_publish', $streamPublishArgs);
  drupal_add_js(array('FB.streamPublish' => $streamPublishArgs), 'setting');
  drupal_add_js(drupal_get_path('module', 'fbconnect_stream_publish') .'/fbconnect_stream_publish.js');
}

function theme_stream_publish_favicon() {
  $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';

  return '<img src="'. $protocol .'facebook.com/images/connect_favicon.png" />';
}