<?php

/**
 * @file
 * Enables keeping an easily and regularly updated web page or a blog.
 */

/**
 * Implementation of hook_node_info().
 */
function blog_node_info() {
  return array(
    'blog' => array(
      'name' => t('Blog entry'),
      'module' => 'blog',
      'description' => t('A <em>blog entry</em> is a single post to an online journal, or <em>blog</em>.'),
    )
  );
}

/**
 * Implementation of hook_perm().
 */
function blog_perm() {
  return array('create blog entries', 'delete own blog entries', 'delete any blog entry', 'edit own blog entries', 'edit any blog entry');
}

/**
 * Implementation of hook_access().
 */
function blog_access($op, $node, $account) {
  switch ($op) {
    case 'create':
      // Anonymous users cannot post even if they have the permission. 
      return user_access('create blog entries', $account) && $account->uid ? TRUE : NULL;
    case 'update':
      return user_access('edit any blog entry', $account) || (user_access('edit own blog entries', $account) && ($node->uid == $account->uid)) ? TRUE : NULL;
    case 'delete':
      return user_access('delete any blog entry', $account) || (user_access('delete own blog entries', $account) && ($node->uid == $account->uid)) ? TRUE : NULL;
  }
}

/**
 * Implementation of hook_user().
 */
function blog_user($type, &$edit, &$user) {
  if ($type == 'view' && user_access('create blog entries', $user)) {
    $user->content['summary']['blog'] =  array(
      '#type' => 'user_profile_item',
      '#title' => t('Blog'),
      // l() escapes the attributes, so we should not escape !username here.
      '#value' => l(t('View recent blog entries'), "blog/$user->uid", array('attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => $user->name))))),
      '#attributes' => array('class' => 'blog'),
    );
  }
}

/**
 * Implementation of hook_help().
 */
function blog_help($path, $arg) {
  switch ($path) {
    case 'admin/help#blog':
      $output = '<p>'. t('The blog module allows registered users to maintain an online journal, or <em>blog</em>. Blogs are made up of individual <em>blog entries</em>, and the blog entries are most often displayed in descending order by creation time.') .'</p>';
      $output .= '<p>'. t('There is an (optional) <em>Blogs</em> menu item added to the Navigation menu, which displays all blogs available on your site, and a <em>My blog</em> item displaying the current user\'s blog entries. The <em>Blog entry</em> menu item under <em>Create content</em> allows new blog entries to be created.') .'</p>';
      $output .= '<p>'. t('Each blog entry is displayed with an automatic link to other blogs created by the same user. By default, blog entries have comments enabled and are automatically promoted to the site front page. The blog module also creates a <em>Recent blog posts</em> block that may be enabled at the <a href="@blocks">blocks administration page</a>.', array('@blocks' => url('admin/build/block'))) .'</p>';
      $output .= '<p>'. t('When using the aggregator module an automatic <em>blog it</em> icon is displayed next to the items in a feed\'s <em>latest items</em> block. Clicking this icon populates a <em>blog entry</em> with a title (the title of the feed item) and body (a link to the source item on its original site and illustrative content suitable for use in a block quote). Blog authors can use this feature to easily comment on items of interest that appear in aggregator feeds from other sites. To use this feature, be sure to <a href="@modules">enable</a> the aggregator module, <a href="@feeds">add and configure</a> a feed from another site, and <a href="@blocks">position</a> the feed\'s <em>latest items</em> block.', array('@modules' => url('admin/build/modules'), '@feeds' => url('admin/content/aggregator'), '@blocks' => url('admin/build/block'))) .'</p>';
      $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@blog">Blog module</a>.', array('@blog' => 'http://drupal.org/handbook/modules/blog/')) .'</p>';
      return $output;
  }
}

/**
 * Implementation of hook_form().
 */
function blog_form(&$node) {
  global $nid;
  $iid = isset($_GET['iid']) ? (int)$_GET['iid'] : 0;
  $type = node_get_types('type', $node);


  if (empty($node->body)) {
    // If the user clicked a "blog it" link, we load the data from the
    // database and quote it in the blog.
    if ($nid && $blog = node_load($nid)) {
      $node->body = '<em>'. $blog->body .'</em> ['. l($blog->name, "node/$nid") .']';
    }

    if ($iid && $item = db_fetch_object(db_query('SELECT i.*, f.title as ftitle, f.link as flink FROM {aggregator_item} i, {aggregator_feed} f WHERE i.iid = %d AND i.fid = f.fid', $iid))) {
      $node->title = $item->title;
      // Note: $item->description has been validated on aggregation.
      $node->body = '<a href="'. check_url($item->link) .'">'. check_plain($item->title) .'</a> - <em>'. $item->description .'</em> [<a href="'. check_url($item->flink) .'">'. check_plain($item->ftitle) ."</a>]\n";
    }

  }

  $form['title'] = array('#type' => 'textfield', '#title' => check_plain($type->title_label), '#required' => TRUE, '#default_value' => !empty($node->title) ? $node->title : NULL, '#weight' => -5);
  $form['body_field'] = node_body_field($node, $type->body_label, $type->min_word_count);
  return $form;
}

/**
 * Implementation of hook_view().
 */
function blog_view($node, $teaser = FALSE, $page = FALSE) {
  if ($page) {
    // Breadcrumb navigation. l() escapes the title, so we should not escape !name. 
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => $node->name)), 'blog/'. $node->uid)));
  }
  return node_prepare($node, $teaser);
}

/**
 * Implementation of hook_link().
 */
function blog_link($type, $node = NULL, $teaser = FALSE) {
  $links = array();

  if ($type == 'node' && $node->type == 'blog') {
    if (arg(0) != 'blog' || arg(1) != $node->uid) {
      // This goes to l() and therefore escapes !username in both the title and attributes.
      $links['blog_usernames_blog'] = array(
        'title' => t("!username's blog", array('!username' => $node->name)),
        'href' => "blog/$node->uid",
        'attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => $node->name)))
      );
    }
  }

  return $links;
}

/**
 * Implementation of hook_menu().
 */
function blog_menu() {
  $items['blog'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_page_last',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'blog.pages.inc',
  );
  $items['blog/%user_uid_optional'] = array(
    'title' => 'My blog',
    'page callback' => 'blog_page_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'file' => 'blog.pages.inc',
  );
  $items['blog/%user/feed'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_feed_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'type' => MENU_CALLBACK,
    'file' => 'blog.pages.inc',
  );
  $items['blog/feed'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_feed_last',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'blog.pages.inc',
  );

  return $items;
}

/**
 * Access callback for user blog pages.
 */
function blog_page_user_access($account) {
  // The visitor must be able to access the site's content.
  // For a blog to 'exist' the user must either be able to
  // create new blog entries, or it must have existing posts.
  return $account->uid && user_access('access content') && (user_access('create blog entries', $account) || _blog_post_exists($account));
}

/**
 * Helper function to determine if a user has blog posts already.
 */
function _blog_post_exists($account) {
  return (bool)db_result(db_query_range(db_rewrite_sql("SELECT 1 FROM {node} n WHERE n.type = 'blog' AND n.uid = %d AND n.status = 1"), $account->uid, 0, 1));
}

/**
 * Implementation of hook_block().
 *
 * Displays the most recent 10 blog titles.
 */
function blog_block($op = 'list', $delta = 0) {
  global $user;
  if ($op == 'list') {
    $block[0]['info'] = t('Recent blog posts');
    return $block;
  }
  else if ($op == 'view') {
    if (user_access('access content')) {
      $result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = 'blog' AND n.status = 1 ORDER BY n.created DESC"), 0, 10);
      if ($node_title_list = node_title_list($result)) {
        $block['content'] = $node_title_list;
        $block['content'] .= theme('more_link', url('blog'), t('Read the latest blog entries.'));
        $block['subject'] = t('Recent blog posts');
        return $block;
      }
    }
  }
}

