<?php

/**
 * @file
 * The FAQ module allows users to create a FAQ page, with questions and answers
 * displayed in different styles, according to the settings.
 */

/**
 * Implements hook_help().
 */
function faq_help($path, $arg) {
  $output = '';
  switch ($path) {
    case 'admin/help#faq':
      $output .= '<p>' . t("This module allows users with the 'administer faq' permission to create question and answer pairs which will be displayed on the faq page.  The faq page is automatically generated from the FAQ nodes configured and the layout of this page can be modified on the settings page.  Users will need the 'view faq page' permission in order to view the faq page.") . '</p>' .
        '<p>' . t("To create a question and answer, the user must create a 'FAQ' node (Create content >> FAQ).  This screen allows the user to edit the question and answer text.  If the 'Taxonomy' module is enabled and there are some terms configured for the FAQ node type, it will also be possible to put the questions into different categories when editing.") . '</p>' .
        '<p>' . t("The 'Frequently Asked Questions' settings configuration screen will allow users with 'administer faq' permissions to specify different layouts of the questions and answers.") . '</p>' .
        '<p>' . t("All users with 'view faq page' permissions will be able to view the generated FAQ page.") . '</p>';
      return $output;

    case 'admin/modules#description':
      return t('Allows the user to configure the layout of questions and answers on a FAQ page.');
  }
}

/**
 * Implements hook_permission().
 */
function faq_permission() {
  return array(
    'administer faq' => array(
      'title' => t('Administer FAQ module'),
    ),
    'administer faq order' => array(
      'title' => t('Administer FAQ order'),
    ),
    'view faq page' => array(
      'title' => t('View FAQ pages'),
    ),
  );
}


/**
 * Implements hook_node_access().
 */
function faq_node_access($node, $op, $account = NULL) {
  global $user;
  if (empty($account)) {
    $account = $user;
  }
  // Ignore non-FAQ node.
  if ((is_object($node) ? $node->type : $node) !== 'faq') {
    return NODE_ACCESS_IGNORE;
  }

  if ($op != 'create') {
    $node = (object) $node;
  }
  if ($op == 'view') {
    return NODE_ACCESS_IGNORE;
  }
  elseif ($op == 'create' || $op == 'update' || $op == 'delete') {
    if (user_access('administer faq')) {
      return NODE_ACCESS_ALLOW;
    }
  }
  return NODE_ACCESS_IGNORE;
}

/**
 * Implements hook_menu().
 */
function faq_menu() {
  $items = array();
  $faq_path = variable_get('faq_path', 'faq-page');

  $items[$faq_path] = array(
    'title' => 'Frequently Asked Questions',
    'page callback' => 'faq_page',
    'access callback' => 'user_access',
    'access arguments' => array('view faq page'),
    'weight' => 1,
    'type' => MENU_SUGGESTED_ITEM,
  );

  $items[$faq_path . '/list'] = array(
    'title' => 'List',
    'page callback' => 'faq_page',
    'access callback' => 'user_access',
    'access arguments' => array('view faq page'),
    'weight' => -10,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items[$faq_path . '/order'] = array(
    'title' => 'Order',
    'description' => 'Allows the user to configure the order of questions and answers on a FAQ page.',
    'file' => 'faq.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('faq_order_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer faq order'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -8,
  );

  $items[$faq_path . '/%'] = array(
    'title' => 'Frequently Asked Questions',
    'page callback' => 'faq_page',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('view faq page'),
    'type' => MENU_CALLBACK,
  );

  $items[$faq_path . '/%/list'] = array(
    'title' => 'List',
    'page callback' => 'faq_page',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('view faq page'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items[$faq_path . '/%/order'] = array(
    'title' => 'Order',
    'description' => 'Allows the user to configure the order of questions and answers on a FAQ page.',
    'file' => 'faq.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('faq_order_settings_form', 1),
    'access callback' => 'user_access',
    'access arguments' => array('administer faq order'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -8,
  );

  $items['admin/config/content/faq'] = array(
    'title' => 'Frequently Asked Questions',
    'description' => 'Allows the user to configure the layout of questions and answers on a FAQ page.',
    'file' => 'faq.admin.inc',
    'page callback' => 'faq_settings_page',
    'access callback' => 'user_access',
    'access arguments' => array('administer faq'),
  );
  $items['admin/config/content/faq/general'] = array(
    'title' => 'General',
    'description' => 'Allows the user to configure the header and descriptive text for the FAQ page.',
    'file' => 'faq.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('faq_general_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer faq'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/content/faq/questions'] = array(
    'title' => 'Questions',
    'description' => 'Allows the user to configure the layout of questions and answers on a FAQ page.',
    'file' => 'faq.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('faq_questions_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer faq'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
  );
  $items['admin/config/content/faq/categories'] = array(
    'title' => 'Categories',
    'description' => 'Allows the user to configure the layout of questions and answers using categories on a FAQ page.',
    'file' => 'faq.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('faq_categories_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer faq'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -8,
  );
  return $items;
}

/**
 * Implements hook_node_info().
 *
 * Defines the FAQ node/content type.
 * @return array
 *   An array, containing the title, module name and the description.
 */
function faq_node_info() {
  return array(
    'faq' => array(
      'name' => t('FAQ'),
      'base' => 'faq',
      'description' => t('A frequently asked question and its answer.'),
      'has_title' => TRUE,
      'title_label' => t('Question'),
    ),
  );
}

/**
 * Implements hook_form().
 *
 * @param object $node
 *   The node being added or edited.
 *
 * @param array $form_state
 *   The hook can set this variable to an associative array of attributes to add
 *   to the enclosing <form> tag.
 *
 * @return array
 *   The form elements in the $form array.
 */
function faq_form($node, $form_state) {
  $type = node_type_get_type($node);
  $form = node_content_form($node, $form_state);
  $form['title']['#description'] = t('Question to be answered.  This will appear in all question listings, such as the FAQ blocks.');

  return $form;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function faq_form_faq_general_settings_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'faq_general_settings_form_validate';
  $form['#submit'][] = 'faq_general_settings_form_submit';
}

/**
 * Implements hook_insert().
 *
 * Inserts the faq node question text into the 'faq_questions' table.
 *
 * @param object $node
 *   The node object.
 */
function faq_insert($node) {
  $items = field_get_items('node', $node, 'field_detailed_question');
  $detailed_question = reset($items);
  db_insert('faq_questions')
    ->fields(array(
      'nid' => $node->nid,
      'vid' => $node->vid,
      'question' => $node->title,
      'detailed_question' => $detailed_question['value'],
    ))
    ->execute();
}

/**
 * Implements hook_update().
 *
 * Updates the faq node question text in the 'faq_questions' table.
 *
 * @param object $node
 *   The node object.
 */
function faq_update($node) {
  if (isset($node->revision) && $node->revision) {
    faq_insert($node);
  }
  else {
    // Empty detailed question as default.
    $detailed_question = array('value' => '');
    if ($items = field_get_items('node', $node, 'field_detailed_question')) {
      $detailed_question = reset($items);
    }
    // Just to be safe, we do a merge query instead of an update query.
    db_merge('faq_questions')
      ->fields(array(
        'question' => $node->title,
        'detailed_question' => $detailed_question['value'],
      ))
      ->key(array(
        'nid' => $node->nid,
        'vid' => $node->vid,
      ))
      ->execute();
  }
}

/**
 * Implements hook_delete().
 *
 * Deletes an FAQ node from the database.
 */
function faq_delete($node) {
  db_delete('faq_weights')
  ->condition('nid', $node->nid)
  ->execute();
  db_delete('faq_questions')
  ->condition('nid', $node->nid)
  ->execute();
}

/**
 * Implements hook_load().
 *
 * Initialises $node->question using the value in the 'faq_questions' table.
 *
 * @param array $nodes
 *   The node objects array.
 */
function faq_load($nodes) {

  return;
  // @codingStandardsIgnoreStart
  /*
  foreach ($nodes as $nid => &$node) {
    // @todo: change logic to load faq nodes - do not rely on specific faq table
    $result = db_query('SELECT question, detailed_question FROM {faq_questions} WHERE nid = :nid AND vid = :vid', array(
      ':nid' => $node->nid,
      ':vid' => $node->vid,
    ))->fetchObject();
    if ($result && !drupal_match_path($_GET['q'], 'node/' . $node->nid . '/edit')) {
      $question_length = variable_get('faq_question_length', 'short');
      if ($question_length == 'long' && !empty($result->detailed_question)) {
        $result->title = $result->detailed_question;
      }
      else {
        $result->title = $result->question;
      }
    }
    foreach ($result as $property => &$value) {
      $node->$property = $value;
    }
  }
  */
  // @codingStandardsIgnoreEnd
}

/**
 * Implements hook_node_revision_delete().
 */
function faq_node_revision_delete($node) {
  db_delete('faq_questions')
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

/**
 * Implements hook_view().
 */
function faq_view($node, $view_mode) {
  drupal_add_css(drupal_get_path('module', 'faq') . '/faq.css');

  $detailed_question = FALSE;
  // Get the detailed question.
  if ($field_items = field_get_items('node', $node, 'field_detailed_question')) {
    $detailed_question = reset($field_items);
  }

  // Only show the detailed question if there is something to show.
  if ($detailed_question && !empty($detailed_question['value'])) {
    $show_question = FALSE;
    if ($view_mode == 'full') {
      // The detailed question is always shown on the full node.
      $show_question = TRUE;
    }
    else {
      // On other pages, consider the admin settings.
      if (variable_get('faq_question_length', 'short') == 'both' && variable_get('faq_display', 'questions_top') == 'hide_answer') {
        $show_question = TRUE;
      }
    }

    // Should be handled by theming - create field--field_detailed_question.tpl.php.
    if ($show_question) {
      // We're here if we are showing the question.
      $node->content['field_detailed_question'] = array(
        '#markup' => theme('field_detailed_question', $detailed_question),
      );
    }
    else {
      // We switch off the visibility of the detailed question.
      hide($node->content['field_detailed_question']);
    }
  }

  return $node;
}

/**
 * Implements hook_views_api().
 */
function faq_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'faq') . '/views',
  );
}

/**
 * Function to display the faq page.
 *
 * @param int $tid
 *   Default is 0, determines if the questions and answers on the page
 *   will be shown according to a category or non-categorized.
 *
 * @param string $faq_display
 *   Optional parameter to override default question layout setting.
 *
 * @param string $category_display
 *   Optional parameter to override default category layout setting.
 *
 * @return string|NULL
 *   The output variable which contains an HTML formatted page with FAQ
 *   questions and answers.
 */
function faq_page($tid = 0, $faq_display = '', $category_display = '') {
  if (module_exists('pathauto')) {
    module_load_include('inc', 'pathauto');
  }

  // Things to provide translations for.
  $default_values = array(
    t('Frequently Asked Questions'),
    t('Back to Top'),
    t('Q:'),
    t('A:'),
  );

  $output = $output_answers = '';
  drupal_add_css(drupal_get_path('module', 'faq') . '/faq.css');
  if (arg(0) == 'faq-page') {
    drupal_set_title(t(variable_get('faq_title', 'Frequently Asked Questions')));
  }
  if (!module_exists("taxonomy")) {
    $tid = 0;
  }

  // Configure the breadcrumb trail.
  if (!empty($tid) && $current_term = taxonomy_term_load($tid)) {
    if (variable_get('faq_auto_generate_alias', TRUE) && !drupal_lookup_path('alias', arg(0) . '/' . $tid) && module_exists('pathauto')) {
      $alias = pathauto_create_alias('faq', 'insert', arg(0) . '/' . arg(1), array('term' => $current_term));
      if ($alias) {
        drupal_goto($alias['alias']);
      }
    }
    if (drupal_match_path($_GET['q'], 'faq-page/*')) {
      faq_set_breadcrumb($current_term);
    }
  }

  if (empty($faq_display)) {
    $faq_display = variable_get('faq_display', 'questions_top');
  }
  $use_categories = variable_get('faq_use_categories', FALSE);
  if (!empty($category_display)) {
    $use_categories = TRUE;
  }
  else {
    $category_display = variable_get('faq_category_display', 'categories_inline');
  }
  if (!module_exists("taxonomy")) {
    $use_categories = FALSE;
  }

  $faq_path = drupal_get_path('module', 'faq') . '/includes';

  if (($use_categories && $category_display == 'hide_qa') || $faq_display == 'hide_answer') {
    drupal_add_js(array('faq' => array('faq_hide_qa_accordion' => variable_get('faq_hide_qa_accordion', FALSE))), array('type' => 'setting', 'scope' => JS_DEFAULT));
    drupal_add_js(array('faq' => array('faq_category_hide_qa_accordion' => variable_get('faq_category_hide_qa_accordion', FALSE))), array('type' => 'setting', 'scope' => JS_DEFAULT));
    drupal_add_js(drupal_get_path('module', 'faq') . '/faq.js');
  }

  // Non-categorized questions and answers.
  if (!$use_categories || ($category_display == 'none' && empty($tid))) {
    if (!empty($tid)) {
      drupal_not_found();
      return;
    }
    $default_sorting = variable_get('faq_default_sorting', 'DESC');

    $query = db_select('node', 'n');
    $weight_alias = $query->leftJoin('faq_weights', 'w', '%alias.nid=n.nid');
    $query
      ->addTag('node_access')
      ->fields('n', array('nid'))
      ->condition('n.type', 'faq')
      ->condition('n.status', 1)
      ->condition(db_or()->condition("$weight_alias.tid", 0)->isNull("$weight_alias.tid"));

    $default_weight = 0;
    if ($default_sorting == 'ASC') {
      $default_weight = 1000000;
    }

    // Works, but involves variable concatenation - safe though, since
    // $default_weight is an integer.
    $query->addExpression("COALESCE(w.weight, $default_weight)", 'effective_weight');

    // @codingStandardsIgnoreStart
    // @todo Doesn't work in Postgres.
    //$query->addExpression('COALESCE(w.weight, CAST(:default_weight as SIGNED))', 'effective_weight', array(':default_weight' => $default_weight));
    // @codingStandardsIgnoreEnd

    $query->orderBy('effective_weight', 'ASC')
          ->orderBy('n.sticky', 'DESC');
    if ($default_sorting == 'ASC') {
      $query->orderBy('n.created', 'ASC');
    }
    else {
      $query->orderBy('n.created', 'DESC');
    }
    if (module_exists('i18n_select')) {
      $query->condition('n.language', i18n_select_langcodes());
    }

    // Only need the nid column.
    $nids = $query->execute()->fetchCol();
    $data = node_load_multiple($nids);

    switch ($faq_display) {
      case 'questions_top':
        include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.questions_top.inc';
        $output = theme('faq_questions_top', array('data' => $data));
        break;

      case 'hide_answer':
        include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.hide_answer.inc';
        $output = theme('faq_hide_answer', array('data' => $data));
        break;

      case 'questions_inline':
        include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.questions_inline.inc';
        $output = theme('faq_questions_inline', array('data' => $data));
        break;

      case 'new_page':
        include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.new_page.inc';
        $output = theme('faq_new_page', array('data' => $data));
        break;
    }
  }

  // Categorize questions.
  else {
    $hide_child_terms = variable_get('faq_hide_child_terms', FALSE);

    // If we're viewing a specific category/term.
    if (!empty($tid)) {
      if ($term = taxonomy_term_load($tid)) {
        $title = t(variable_get('faq_title', 'Frequently Asked Questions'));
        if (arg(0) == 'faq-page' && is_numeric(arg(1))) {
          drupal_set_title($title . ($title ? ' - ' : '') . faq_tt("taxonomy:term:$term->tid:name", $term->name));
        }
        _display_faq_by_category($faq_display, $category_display, $term, 0, $output, $output_answers);
        return theme('faq_page', array('content' => $output, 'answers' => $output_answers));
      }
      else {
        drupal_not_found();
        return;
      }
    }

    $list_style = variable_get('faq_category_listing', 'ul');
    $vocabularies = taxonomy_get_vocabularies('faq');
    $vocab_omit = variable_get('faq_omit_vocabulary', array());
    $items = array();
    $vocab_items = array();
    $valid_vocab = FALSE;

    foreach ($vocabularies as $vid => $vobj) {
      if (isset($vocab_omit[$vid]) && $vocab_omit[$vid] != 0) {
        continue;
      }
      $valid_vocab = TRUE;

      if ($category_display == "new_page") {
        $vocab_items = _get_indented_faq_terms($vid, 0);
        $items = array_merge($items, $vocab_items);
      }

      // Not a new page.
      else {
        if ($hide_child_terms && $category_display == 'hide_qa') {
          $tree = taxonomy_get_tree($vid, 0, 1, TRUE);
        }
        else {
          $tree = taxonomy_get_tree($vid, 0, NULL, TRUE);
        }

        if (function_exists('i18n_taxonomy_localize_terms')) {
          $tree = i18n_taxonomy_localize_terms($tree);
        }

        foreach ($tree as $term) {
          switch ($category_display) {
            case 'hide_qa':
            case 'categories_inline':
              if (faq_taxonomy_term_count_nodes($term->tid)) {
                _display_faq_by_category($faq_display, $category_display, $term, 1, $output, $output_answers);
              }
              break;
          }
        }
      }
    }

    if ($category_display == "new_page") {
      $output = theme('item_list',
        array(
          'items' => $items,
          'title' => NULL,
          'type' => $list_style,
        )
      );
    }
    if (!$valid_vocab) {
      drupal_set_message(t('Categories are enabled but no vocabulary is associated with the FAQ content type. Either create a vocabulary or disable categorization in order for questions to appear.'), 'error');
    }
  }

  $faq_description = t(variable_get('faq_description', ''));
  $format = variable_get('faq_description_format', 0);
  if ($format) {
    $faq_description = check_markup($faq_description, $format);
  }
  return theme('faq_page',
    array(
      'content' => $output,
      'answers' => $output_answers,
      'description' => $faq_description,
    )
  );
}

/**
 * Display FAQ questions and answers filtered by category.
 *
 * @param string $faq_display
 *   Define the way the FAQ is being shown; can have the values:
 *   'questions top',hide answers','questions inline','new page'.
 *
 * @param string $category_display
 *   The layout of categories which should be used.
 *
 * @param object $term
 *   The category / term to display FAQs for.
 *
 * @param int $display_header
 *   Set if the header will be shown or not.
 *
 * @param string &$output
 *   Reference which holds the content of the page, HTML formatted.
 *
 * @param string &$output_answers
 *   Reference which holds the answers from the FAQ, when showing questions
 *   on top.
 */
function _display_faq_by_category($faq_display, $category_display, $term, $display_header, &$output, &$output_answers) {

  $default_sorting = variable_get('faq_default_sorting', 'DESC');

  $query = db_select('node', 'n');
  $ti_alias = $query->innerJoin('taxonomy_index', 'ti', '(n.nid = %alias.nid)');
  $td_alias = $query->innerJoin('taxonomy_term_data', 'td', "({$ti_alias}.tid = %alias.tid)");
  $w_alias = $query->leftJoin('faq_weights', 'w', "%alias.tid = {$ti_alias}.tid AND n.nid = %alias.nid");
  $query
    ->fields('n', array('nid'))
    ->condition('n.type', 'faq')
    ->condition('n.status', 1)
    ->condition("{$ti_alias}.tid", $term->tid)
    ->addTag('node_access');

  $default_weight = 0;
  if ($default_sorting == 'ASC') {
    $default_weight = 1000000;
  }
  // Works, but involves variable concatenation - safe though, since
  // $default_weight is an integer.
  $query->addExpression("COALESCE(w.weight, $default_weight)", 'effective_weight');

  // @codingStandardsIgnoreStart
  // @todo Doesn't work in Postgres.
  //$query->addExpression('COALESCE(w.weight, CAST(:default_weight as SIGNED))', 'effective_weight', array(':default_weight' => $default_weight));
  // @codingStandardsIgnoreEnd

  $query->orderBy('effective_weight', 'ASC')
        ->orderBy('n.sticky', 'DESC');
  if ($default_sorting == 'ASC') {
    $query->orderBy('n.created', 'ASC');
  }
  else {
    $query->orderBy('n.created', 'DESC');
  }
  if (module_exists('i18n_select')) {
    $query->condition('n.language', i18n_select_langcodes());
    if (module_exists('i18n_taxonomy')) {
      $query->condition("{$td_alias}.language", i18n_select_langcodes());
    }
  }

  // We only want the first column, which is nid, so that we can load all
  // related nodes.
  $nids = $query->execute()->fetchCol();
  $data = node_load_multiple($nids);

  // Handle indenting of categories.
  $depth = 0;
  if (!isset($term->depth)) {
    $term->depth = 0;
  }
  while ($depth < $term->depth) {
    $display_header = 1;
    $indent = '<div class="faq-category-indent">';
    $output .= $indent;
    $depth++;
  }

  // Set up the class name for hiding the q/a for a category if required.
  $faq_class = "faq-qa";
  if ($category_display == "hide_qa") {
    $faq_class = "faq-qa-hide";
  }

  $faq_path = drupal_get_path('module', 'faq') . '/includes';

  switch ($faq_display) {
    case 'questions_top':
      include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.questions_top.inc';
      // @todo fix workaround: have to share result.
      $output .= theme('faq_category_questions_top',
        array(
          'data' => $data,
          'display_header' => $display_header,
          'category_display' => $category_display,
          'term' => $term,
          'class' => $faq_class,
          'parent_term' => $term,
        )
      );
      $output_answers .= theme('faq_category_questions_top_answers',
        array(
          'data' => $data,
          'display_header' => $display_header,
          'category_display' => $category_display,
          'term' => $term,
          'class' => $faq_class,
          'parent_term' => $term,
        )
      );
      break;

    case 'hide_answer':
      include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.hide_answer.inc';
      $output .= theme('faq_category_hide_answer',
        array(
          'data' => $data,
          'display_header' => $display_header,
          'category_display' => $category_display,
          'term' => $term,
          'class' => $faq_class,
          'parent_term' => $term,
        )
      );
      break;

    case 'questions_inline':
      include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.questions_inline.inc';
      $output .= theme('faq_category_questions_inline',
        array(
          'data' => $data,
          'display_header' => $display_header,
          'category_display' => $category_display,
          'term' => $term,
          'class' => $faq_class,
          'parent_term' => $term,
        )
      );
      break;

    case 'new_page':
      include_once DRUPAL_ROOT . '/' . $faq_path . '/faq.new_page.inc';
      $output .= theme('faq_category_new_page',
        array(
          'data' => $data,
          'display_header' => $display_header,
          'category_display' => $category_display,
          'term' => $term,
          'class' => $faq_class,
          'parent_term' => $term,
        )
      );
      break;
  }

  // Handle indenting of categories.
  while ($depth > 0) {
    $output .= '</div>';
    $depth--;
  }
}

/**
 * Implements hook_theme().
 */
function faq_theme() {
  $path = drupal_get_path('module', 'faq') . '/includes';
  return array(
    'field_detailed_question' => array(
      'render element' => 'element',
    ),
    'faq_draggable_question_order_table' => array(
      'render element' => 'form',
    ),
    'faq_questions_top' => array(
      'path' => $path,
      'file' => 'faq.questions_top.inc',
      'template' => 'faq-questions-top',
      'variables' => array('data' => NULL),
    ),
    'faq_category_questions_top' => array(
      'path' => $path,
      'file' => 'faq.questions_top.inc',
      'template' => 'faq-category-questions-top',
      'variables' => array(
        'data' => NULL,
        'display_header' => 0,
        'category_display' => NULL,
        'term' => NULL,
        'class' => NULL,
        'parent_term' => NULL,
      ),
    ),
    'faq_category_questions_top_answers' => array(
      'path' => $path,
      'file' => 'faq.questions_top.inc',
      'template' => 'faq-category-questions-top-answers',
      'variables' => array(
        'data' => NULL,
        'display_header' => 0,
        'category_display' => NULL,
        'term' => NULL,
        'class' => NULL,
        'parent_term' => NULL,
      ),
    ),
    'faq_hide_answer' => array(
      'path' => $path,
      'file' => 'faq.hide_answer.inc',
      'template' => 'faq-hide-answer',
      'variables' => array('data' => NULL),
    ),
    'faq_category_hide_answer' => array(
      'path' => $path,
      'file' => 'faq.hide_answer.inc',
      'template' => 'faq-category-hide-answer',
      'variables' => array(
        'data' => NULL,
        'display_header' => 0,
        'category_display' => NULL,
        'term' => NULL,
        'class' => NULL,
        'parent_term' => NULL,
      ),
    ),
    'faq_questions_inline' => array(
      'path' => $path,
      'file' => 'faq.questions_inline.inc',
      'template' => 'faq-questions-inline',
      'variables' => array('data' => NULL),
    ),
    'faq_category_questions_inline' => array(
      'path' => $path,
      'file' => 'faq.questions_inline.inc',
      'template' => 'faq-category-questions-inline',
      'variables' => array(
        'data' => NULL,
        'display_header' => 0,
        'category_display' => NULL,
        'term' => NULL,
        'class' => NULL,
        'parent_term' => NULL,
      ),
    ),
    'faq_new_page' => array(
      'path' => $path,
      'file' => 'faq.new_page.inc',
      'template' => 'faq-new-page',
      'variables' => array('data' => NULL),
    ),
    'faq_category_new_page' => array(
      'path' => $path,
      'file' => 'faq.new_page.inc',
      'template' => 'faq-category-new-page',
      'variables' => array(
        'data' => NULL,
        'display_header' => 0,
        'category_display' => NULL,
        'term' => NULL,
        'class' => NULL,
        'parent_term' => NULL,
      ),
    ),
    'faq_page' => array(
      'variables' => array(
        'content' => '',
        'answers' => '',
        'description' => NULL,
      ),
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function faq_block_info() {
  $blocks['faq_categories']['info'] = t('FAQ Categories');
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function faq_block_view($delta) {
  static $vocabularies, $terms;

  $block = array();
  switch ($delta) {
    case 'faq_categories':
      if (module_exists('taxonomy')) {
        if (!isset($terms)) {
          $terms = array();
          $vocabularies = taxonomy_get_vocabularies('faq');
          $vocab_omit = array_flip(variable_get('faq_omit_vocabulary', array()));
          $vocabularies = array_diff_key($vocabularies, $vocab_omit);
          foreach ($vocabularies as $vocab) {
            foreach (taxonomy_get_tree($vocab->vid) as $term) {
              if (faq_taxonomy_term_count_nodes($term->tid)) {
                $terms[$term->name] = $term->tid;
              }
            }
          }
        }
        if (count($terms) > 0) {
          $block['subject'] = t('FAQ Categories');
          $items = array();
          foreach ($terms as $name => $tid) {
            $items[] = l(faq_tt("taxonomy:term:$tid:name", $name), 'faq-page/' . $tid);
          }
          $list_style = variable_get('faq_category_listing', 'ul');
          $block['content'] = theme('item_list',
            array(
              'items' => $items,
              'title' => NULL,
              'type' => $list_style,
            )
          );
        }
      }
      break;
  }

  return $block;
}

/**
 * Return a HTML formatted list of terms indented according to the term depth.
 *
 * @param int $vid
 *   Vocabulary id.
 *
 * @param int $tid
 *   Term id.
 *
 * @return string
 *   Return a HTML formatted list of terms indented according to the term depth.
 */
function _get_indented_faq_terms($vid, $tid) {
  if (module_exists('pathauto')) {
    module_load_include('inc', 'pathauto');
  }

  $display_faq_count = variable_get('faq_count', FALSE);
  $hide_child_terms = variable_get('faq_hide_child_terms', FALSE);

  $items = array();
  $tree = taxonomy_get_tree($vid, $tid, 1, TRUE);

  foreach ($tree as $term) {

    $tree_count = faq_taxonomy_term_count_nodes($term->tid);

    if ($tree_count) {
      // Get taxonomy image.
      $term_image = '';
      if (module_exists('taxonomy_image')) {
        $term_image = taxonomy_image_display($term->tid, array('class' => 'faq-tax-image'));
      }

      // Get term description.
      $desc = '';
      if (!empty($term->description)) {
        $desc = '<div class="faq-qa-description">';
        $desc .= check_markup(faq_tt("taxonomy:term:$term->tid:description", $term->description)) . "</div>";
      }

      // See if this term has any nodes itself, should it be a link?
      $query = db_select('node', 'n');
      $ti_alias = $query->innerJoin('taxonomy_index', 'ti', '(n.nid = %alias.nid)');
      $term_node_count = $query
        ->condition('n.status', 1)
        ->condition('n.type', 'faq')
        ->condition("{$ti_alias}.tid", $term->tid)
        ->addTag('node_access')
        ->countQuery()
        ->execute()
        ->fetchField();

      if ($term_node_count > 0) {
        $path = "faq-page/$term->tid";

        if (!drupal_lookup_path('alias', arg(0) . '/' . $term->tid) && module_exists('pathauto')) {
          $alias = pathauto_create_alias('faq', 'insert', arg(0) . '/' . $term->tid, array('term' => $term));
          if ($alias) {
            $path = $alias['alias'];
          }
        }

        if ($display_faq_count) {
          $count = $term_node_count;
          if ($hide_child_terms) {
            $count = $tree_count;
          }
          $cur_item = $term_image . l(faq_tt("taxonomy:term:$term->tid:name", $term->name), $path) . " ($count) " . $desc;
        }
        else {
          $cur_item = $term_image . l(faq_tt("taxonomy:term:$term->tid:name", $term->name), $path) . $desc;
        }
      }
      else {
        $cur_item = $term_image . check_plain(faq_tt("taxonomy:term:$term->tid:name", $term->name)) . $desc;
      }
      if (!empty($term_image)) {
        $cur_item .= '<div class="clear-block"></div>';
      }

      $term_items = array();
      if (!$hide_child_terms) {
        $term_items = _get_indented_faq_terms($vid, $term->tid);
      }
      $items[] = array(
        "data" => $cur_item,
        "children" => $term_items,
      );
    }
  }

  return $items;
}

/**
 * Get a list of terms associated with the FAQ nodes.
 *
 * @return string
 *   Return the HTML-formatted content.
 */
function faq_get_terms() {
  $items = array();
  $vocabularies = taxonomy_get_vocabularies('faq');
  $vocab_omit = array_flip(variable_get('faq_omit_vocabulary', array()));
  $vocabularies = array_diff_key($vocabularies, $vocab_omit);
  foreach ($vocabularies as $vid => $vobj) {
    $vocab_items = _get_indented_faq_terms($vid, 0);
    $items = array_merge($items, $vocab_items);
  }

  return theme('item_list', array('items' => $items));
}

/**
 * Format the output for the faq_site_map() function.
 *
 * @return array
 *   Return a list of FAQ categories if categorization is enabled, otherwise
 *   return a list of faq nodes.
 */
function faq_get_faq_list() {
  // Return list of vocab terms if categories are configured.
  $use_categories = variable_get('faq_use_categories', FALSE);
  if ($use_categories) {
    return faq_get_terms();
  }

  // Otherwise return list of weighted FAQ nodes.
  $items = array();
  $default_sorting = variable_get('faq_default_sorting', 'DESC');

  $query = db_select('node', 'n');
  $w_alias = $query->leftJoin('faq_weights', 'w', "%alias.nid = n.nid");
  $query
    ->fields('n', array('nid'))
    ->condition('n.type', 'faq')
    ->condition('n.status', 1)
    ->condition(db_or()->condition("{$w_alias}.tid", 0)->isNull("{$w_alias}.tid"))
    ->addTag('node_access');

  $default_weight = 0;
  if ($default_sorting == 'ASC') {
    $default_weight = 1000000;
  }
  // Works, but involves variable concatenation - safe though, since
  // $default_weight is an integer.
  $query->addExpression("COALESCE(w.weight, $default_weight)", 'effective_weight');

  // @codingStandardsIgnoreStart
  // @todo Doesn't work in Postgres.
  //$query->addExpression('COALESCE(w.weight, CAST(:default_weight as SIGNED))', 'effective_weight', array(':default_weight' => $default_weight));
  // @codingStandardsIgnoreEnd

  $query->orderBy('effective_weight', 'ASC')
        ->orderBy('n.sticky', 'DESC');
  if ($default_sorting == 'ASC') {
    $query->orderBy('n.created', 'ASC');
  }
  else {
    $query->orderBy('n.created', 'DESC');
  }
  if (module_exists('i18n_select')) {
    $query->condition('n.language', i18n_select_langcodes());
  }

  // We only want the first column, which is nid, so that we can load all
  // related nodes.
  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    if (node_access('view', $node)) {
      $items[] = l($node->question, "node/$node->nid");
    }
  }

  return theme('item_list', array('items' => $items));
}

if (!function_exists('array_diff_key')) {
  /**
   * Override array_diff_key function.
   */
  function array_diff_key() {
    $arrs = func_get_args();
    $result = array_shift($arrs);
    foreach ($arrs as $array) {
      foreach ($result as $key => $v) {
        if (array_key_exists($key, $array)) {
          unset($result[$key]);
        }
      }
    }
    return $result;
  }
}

/**
 * Helper function to setup the faq question.
 *
 * @param array &$data
 *   Array reference to store display data in.
 *
 * @param object $node
 *   The node object.
 *
 * @param string $path
 *   The path/url which the question should link to if links are disabled.
 *
 * @param string $anchor
 *   Link anchor to use in question links.
 */
function faq_view_question(&$data, $node, $path = NULL, $anchor = NULL) {
  $disable_node_links = variable_get('faq_disable_node_links', FALSE);
  $question = '';

  // Don't link to faq node, instead provide no link, or link to current page.
  if ($disable_node_links) {
    if (empty($path) && empty($anchor)) {
      $question = check_plain($node->title);
    }
    elseif (empty($path)) {
      // Can't seem to use l() function with empty string as screen-readers
      // don't like it, so create anchor name manually.
      $question = '<a id="' . $anchor . '"></a>' . check_plain($node->title);
    }
    else {
      $options = array();
      if ($anchor) {
        $options['attributes'] = array('id' => $anchor);
      }
      $question = l($node->title, $path, $options);
    }
  }

  // Link to faq node.
  else {
    if (empty($anchor)) {
      $question = l($node->title, "node/$node->nid");
    }
    else {
      $question = l($node->title, "node/$node->nid", array("attributes" => array("id" => "$anchor")));
    }
  }
  $question = '<span datatype="" property="dc:title">' . $question . '</span>';

  // Get the language of the body field.
  $language = 'und';
  foreach ($node->body as $lang => $values) {
    if ($values[0]['value']) {
      $language = $lang;
    }
  }

  // Get the detailed question.
  $detailed_question = '';
  if ($dq = field_get_items('node', $node, 'field_detailed_question')) {
    $detailed_question = reset($dq);
  }

  if (variable_get('faq_display', 'questions_top') != 'hide_answer'
        && !empty($detailed_question['value'])
        && variable_get('faq_question_length', 'short') == 'both') {
    $question .= '<div class="faq-detailed-question">' . $detailed_question['safe_value'] . '</div>';
  }
  $data['question'] = $question;
}

/**
 * Helper function to setup the faq answer.
 *
 * @param array &$data
 *   Array reference to store display data in.
 *
 * @param object $node
 *   The node object.
 *
 * @param array $back_to_top
 *   An array containing the "back to top" link.
 *
 * @param bool $teaser
 *   Whether or not to use teasers.
 *
 * @param array $links
 *   Whether or not to show node links.
 */
function faq_view_answer(&$data, $node, $back_to_top, $teaser, $links) {
  $view_mode = $teaser ? 'teaser' : 'full';
  $langcode = $GLOBALS['language_content']->language;

  // Build the faq node content and invoke other modules' links, etc, functions.
  $node = (object) $node;
  node_build_content($node, $view_mode, $langcode);

  // Add "edit answer" link if they have the correct permissions.
  if (node_access('update', $node)) {
    $node->content['links']['node']['#links']['faq_edit_link'] = array(
      'title' => t('Edit answer'),
      'href' => "node/$node->nid/edit",
      'query' => drupal_get_destination(),
      'attributes' => array('title' => t('Edit answer')),
    );
  }

  // Add "back to top" link.
  if (!empty($back_to_top)) {
    $node->content['links']['node']['#links']['faq_back_to_top'] = $back_to_top;
  }
  $build = $node->content;
  // We don't need duplicate rendering info in node->content.
  unset($node->content);

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Add contextual links for this node.
  if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }

  // Allow modules to modify the structured node.
  $type = 'node';
  drupal_alter(array('node_view', 'entity_view'), $build, $type);

  $node_links = ($links ? $build['links']['node']['#links'] : (!empty($back_to_top) ? array($build['links']['node']['#links']['faq_back_to_top']) : NULL));
  unset($build['links']);

  // We don't want node title displayed.
  unset($build['#theme']);

  $content = drupal_render($build);

  $data['body'] = $content;
  $data['links'] = !empty($node_links) ? theme('links', array('links' => $node_links, 'attributes' => array('class' => 'links inline'))) : '';
}

/**
 * Helper function to setup the "back to top" link.
 *
 * @param string $path
 *   The path/url where the "back to top" link should bring the user too.  This
 *   could be the 'faq-page' page or one of the categorized faq pages, e.g 'faq-page/123'
 *   where 123 is the tid.
 *
 * @return array
 *   An array containing the "back to top" link.
 */
function faq_init_back_to_top($path) {
  $back_to_top = array();
  $back_to_top_text = trim(variable_get('faq_back_to_top', 'Back to Top'));
  if (!empty($back_to_top_text)) {
    $back_to_top = array(
      'title' => check_plain($back_to_top_text),
      'href' => $path,
      'attributes' => array('title' => t('Go back to the top of the page.')),
      'fragment' => 'faq-top',
      'html' => TRUE,
    );
  }

  return $back_to_top;
}

/**
 * Helper function for retrieving the sub-categories faqs.
 *
 * @param object $term
 *   The category / term to display FAQs for.
 *
 * @param string $theme_function
 *   Theme function to use to format the Q/A layout for sub-categories.
 *
 * @param int $default_weight
 *   Is 0 for $default_sorting = DESC; is 1000000 for $default_sorting = ASC.
 *
 * @param string $default_sorting
 *   If 'DESC', nodes are sorted by creation date descending; if 'ASC', nodes
 *   are sorted by creation date ascending.
 *
 * @param string $category_display
 *   The layout of categories which should be used.
 *
 * @param string $class
 *   CSS class which the HTML div will be using. A special class name is
 *   required in order to hide and questions / answers.
 *
 * @param string $parent_term
 *   The original, top-level, term we're displaying FAQs for.
 *
 * @return string
 *   Returns markup.
 */
function faq_get_child_categories_faqs($term, $theme_function, $default_weight, $default_sorting, $category_display, $class, $parent_term = NULL) {
  $output = array();

  $list = taxonomy_get_children($term->tid);

  if (function_exists('i18n_taxonomy_localize_terms')) {
    $list = i18n_taxonomy_localize_terms($list);
  }

  if (!is_array($list)) {
    return '';
  }
  foreach ($list as $tid => $child_term) {
    $child_term->depth = $term->depth + 1;

    if (faq_taxonomy_term_count_nodes($child_term->tid)) {
      $query = db_select('node', 'n');
      $ti_alias = $query->innerJoin('taxonomy_index', 'ti', '(n.nid = %alias.nid)');
      $td_alias = $query->innerJoin('taxonomy_term_data', 'td', "({$ti_alias}.tid = %alias.tid)");
      $w_alias = $query->leftJoin('faq_weights', 'w', "%alias.tid = {$ti_alias}.tid AND n.nid = %alias.nid");
      $query
        ->fields('n', array('nid'))
        ->condition('n.type', 'faq')
        ->condition('n.status', 1)
        ->condition("{$ti_alias}.tid", $child_term->tid)
        ->addTag('node_access');

      $default_weight = 0;
      if ($default_sorting == 'ASC') {
        $default_weight = 1000000;
      }
      // Works, but involves variable concatenation - safe though, since
      // $default_weight is an integer.
      $query->addExpression("COALESCE(w.weight, $default_weight)", 'effective_weight');

      // @codingStandardsIgnoreStart
      // @todo Doesn't work in Postgres.
      //$query->addExpression('COALESCE(w.weight, CAST(:default_weight as SIGNED))', 'effective_weight', array(':default_weight' => $default_weight));
      // @codingStandardsIgnoreEnd

      $query->orderBy('effective_weight', 'ASC')
            ->orderBy('n.sticky', 'DESC');
      if ($default_sorting == 'ASC') {
        $query->orderBy('n.created', 'ASC');
      }
      else {
        $query->orderBy('n.created', 'DESC');
      }
      if (module_exists('i18n_select')) {
        $query->condition('n.language', i18n_select_langcodes());
        if (module_exists('i18n_taxonomy')) {
          $query->condition("{$td_alias}.language", i18n_select_langcodes());
        }
      }

      // We only want the first column, which is nid, so that we can load all
      // related nodes.
      $nids = $query->execute()->fetchCol();
      $data = node_load_multiple($nids);

      $output[] = theme($theme_function,
        array(
          'data' => $data,
          'display_header' => 1,
          'category_display' => $category_display,
          'term' => $child_term,
          'class' => $class,
          'parent_term' => $parent_term,
        )
      );
    }
  }

  return $output;
}

/**
 * Helper function to setup the list of sub-categories for the header.
 *
 * @param object $term
 *   The term to setup the list of child terms for.
 *
 * @return array
 *   An array of sub-categories.
 */
function faq_view_child_category_headers($term) {
  $child_categories = array();
  $list = taxonomy_get_children($term->tid);

  if (function_exists('i18n_taxonomy_localize_terms')) {
    $list = i18n_taxonomy_localize_terms($list);
  }

  foreach ($list as $tid => $child_term) {
    $term_node_count = faq_taxonomy_term_count_nodes($child_term->tid);
    if ($term_node_count) {

      // Get taxonomy image.
      $term_image = '';
      if (module_exists('taxonomy_image')) {
        $term_image = taxonomy_image_display($child_term->tid, array('class' => 'faq-tax-image'));
      }

      $term_vars['link'] = l(faq_tt("taxonomy:term:$child_term->tid:name", $child_term->name), "faq-page/$child_term->tid");
      $term_vars['description'] = check_markup(faq_tt("taxonomy:term:$child_term->tid:description", $child_term->description));
      $term_vars['count'] = $term_node_count;
      $term_vars['term_image'] = $term_image;
      $child_categories[] = $term_vars;
    }
  }

  return $child_categories;
}

/**
 * Implements hook_pathauto().
 */
function faq_pathauto($op) {
  switch ($op) {
    case 'settings':
      $settings = array();
      $settings['module'] = 'faq';
      $settings['groupheader'] = t('FAQ category page settings');
      $settings['patterndescr'] = t('Default path pattern (applies to all FAQ categories with blank patterns below)');
      $settings['patterndefault'] = t('faq-page/[term:tid]');
      $settings['batch_update_callback'] = 'faq_pathauto_bulkupdate';
      $settings['token_type'] = 'term';
      return (object) $settings;

    default:
      break;
  }
}

/**
 * Implements hook_path_alias_types().
 */
function faq_path_alias_types() {
  $objects['faq-page/'] = t('FAQ pages');
  return $objects;
}

/**
 * Batch processing callback; Generate aliases for faq pages.
 */
function faq_pathauto_bulkupdate() {
  module_load_include('inc', 'pathauto');

  if (!isset($context['sandbox']['current'])) {
    $context['sandbox']['count'] = 0;
    $context['sandbox']['current'] = 0;
  }

  // Get the allowed vocabs.
  $vocabularies = taxonomy_get_vocabularies('faq');
  $vocab_omit = variable_get('faq_omit_vocabulary', array());
  $faq_vocabs = array();
  foreach ($vocabularies as $vid => $vobj) {
    if (isset($vocab_omit[$vid]) && $vocab_omit[$vid] != 0) {
      continue;
    }
    $faq_vocabs[$vid] = $vid;
  }

  // Get tids that need aliasing.
  $query = db_select('taxonomy_term_data', 'td');
  $query->leftJoin('url_alias', 'ua', "CONCAT('faq-page/', td.tid) = ua.source");
  $query->addField('td', 'tid');
  $query->isNull('ua.source');
  $query->condition('td.tid', $context['sandbox']['current'], '>');
  $query->condition('td.vid', $faq_vocabs, 'IN');
  $query->orderBy('td.tid');
  $query->addTag('pathauto_bulk_update');
  $query->addMetaData('entity', 'taxonomy_term');

  // Get the total amount of items to process.
  if (!isset($context['sandbox']['total'])) {
    $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();

    // If there are no nodes to update, the stop immediately.
    if (!$context['sandbox']['total']) {
      $context['finished'] = 1;
      return;
    }
  }

  $query->range(0, 25);
  $tids = $query->execute()->fetchCol();

  $terms = taxonomy_term_load_multiple($tids);
  foreach ($terms as $term) {
    pathauto_create_alias('faq', 'bulkupdate', 'faq-page/' . $term->tid, array('term' => $term));
  }
  $context['sandbox']['count'] += count($tids);
  $context['sandbox']['current'] = max($tids);
  $context['message'] = t('Updated alias for faq page @tid.', array('@tid' => end($tids)));

  if ($context['sandbox']['count'] != $context['sandbox']['total']) {
    $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
  }
}

/**
 * Implements hook_taxonomy_term_insert().
 */
function faq_taxonomy_term_insert($term) {
  if (module_exists('pathauto')) {
    module_load_include('inc', 'pathauto');

    $vocabularies = taxonomy_get_vocabularies('faq');
    $vocab_omit = variable_get('faq_omit_vocabulary', array());
    foreach ($vocabularies as $vid => $vobj) {
      if ((isset($vocab_omit[$vid]) && $vocab_omit[$vid] != 0) || ($term->vid != $vid)) {
        continue;
      }
      $alias = pathauto_create_alias('faq', 'insert', 'faq-page/' . $term->tid, array('term' => $term));
    }
  }
}

/**
 * Implements hook_taxonomy_term_update().
 */
function faq_taxonomy_term_update($term) {
  if (module_exists('pathauto')) {
    module_load_include('inc', 'pathauto');

    $vocabularies = taxonomy_get_vocabularies('faq');
    $vocab_omit = variable_get('faq_omit_vocabulary', array());
    foreach ($vocabularies as $vid => $vobj) {
      if ((isset($vocab_omit[$vid]) && $vocab_omit[$vid] != 0) || ($term->vid != $vid)) {
        continue;
      }
      $alias = pathauto_create_alias('faq', 'update', 'faq-page/' . $term->tid, array('term' => $term));
    }
  }
}

/**
 * Implements hook_taxonomy_term_delete().
 */
function faq_taxonomy_term_delete($term) {
  if (module_exists('pathauto')) {
    module_load_include('inc', 'pathauto');
    pathauto_path_delete_all("faq-page/{$term->tid}");
  }
}

/**
 * Function to set up the FAQ breadcrumbs for a given taxonomy term.
 *
 * @param object $term
 *   The taxonomy term object.
 *
 * @return array|NULL
 *   Breadcrumbs.
 */
function faq_set_breadcrumb($term = NULL) {
  $breadcrumb = array();
  if (variable_get('faq_custom_breadcrumbs', TRUE)) {
    if (module_exists("taxonomy") && $term) {
      $breadcrumb[] = l(faq_tt("taxonomy:term:$term->tid:name", $term->name), 'faq-page/' . $term->tid);
      while ($parents = taxonomy_get_parents($term->tid)) {
        $term = array_shift($parents);
        $breadcrumb[] = l(faq_tt("taxonomy:term:$term->tid:name", $term->name), 'faq-page/' . $term->tid);
      }
    }
    $breadcrumb[] = l(t(variable_get('faq_title', 'Frequently Asked Questions')), 'faq-page');
    $breadcrumb[] = l(t('Home'), NULL, array('attributes' => array('title' => variable_get('site_name', ''))));
    $breadcrumb = array_reverse($breadcrumb);
    return drupal_set_breadcrumb($breadcrumb);
  }
  // This is also used to set the breadcrumbs in the faq_preprocess_page()
  // so we need to return a valid trail.
  return drupal_get_breadcrumb();
}

/**
 * Implements template_preprocess_page().
 *
 * Override the breadcrumbs for faq nodes.
 */
function faq_preprocess_page(&$variables) {
  if (!empty($variables['node']) && isset($variables['node']->type) && $variables['node']->type == 'faq' && module_exists('taxonomy')) {
    if (!empty($variables['node']->taxonomy)) {
      foreach ($variables['node']->taxonomy as $term) {
        continue;
      }
    }
    else {
      $term = NULL;
    }
    $variables['breadcrumb'] = theme('breadcrumb', array('breadcrumb' => faq_set_breadcrumb($term)));
  }
}

/**
 * Helper function for when i18ntaxonomy module is not installed.
 */
function faq_tt($string_id, $default, $language = NULL) {
  return function_exists('tt') ? tt($string_id, $default, $language) : $default;
}

/**
 * Implements hook_filter_info().
 */
function faq_filter_info() {
  $filters['faq_embed'] = array(
    'title' => t('Embed FAQ page'),
    'cache' => FALSE,
    'description' => t('Embed FAQ page using [faq] type tags.  Disables filter caching so not recommended for all input formats.'),
    'tips callback' => 'faq_filter_tips_faq_embed',
    'process callback' => '_faq_filter_process',
    'settings callback' => '_faq_filter_settings',
  );
  return $filters;
}

/**
 * Filter settings.
 */
function _faq_filter_settings($form, &$form_state, $filter, $format, $defaults, $filters) {
  return array();
}

/**
 * Filter string.
 */
function _faq_filter_process($text) {
  $text = preg_replace_callback('/\[faq:?([^\]]*)\]/', '_faq_faq_page_filter_replacer', $text);
  // Remove comments, as they're not supported by all input formats.
  $text = preg_replace('/<!--.*?-->/', '', $text);
  return $text;
}

/**
 * Filter tips callback function for $filters[0] in hook_filter_info().
 */
function faq_filter_tips_faq_embed($format, $long = FALSE) {
  return t('[faq] or [faq:123,questions_inline,categories_inline] - insert FAQ content based on the optional category, question style and category style.');
}

/**
 * Helper function for faq input filter.
 */
function _faq_faq_page_filter_replacer($matches) {
  $tid = 0;
  $faq_display = '';
  $category_display = '';
  $default_display = array(
    'questions_top',
    'hide_answer',
    'questions_inline',
    'new_page',
  );
  $default_category_display = array('hide_qa', 'new_page', 'categories_inline');
  if (drupal_strlen($matches[1])) {
    list($tid, $faq_display, $category_display) = explode(',', $matches[1] . ',,');
    $tid = (int) trim($tid);
    $faq_display = trim($faq_display);
    $category_display = trim($category_display);
    // These two checks ensure that a typo in the faq_display or
    // category_display string still results in the FAQ showing.
    if ($faq_display && !in_array($faq_display, $default_display)) {
      $faq_display = '';
    }
    if ($category_display && !in_array($category_display, $default_category_display)) {
      $category_display = '';
    }
  }

  return faq_page($tid, $faq_display, $category_display);
}

/**
 * Count number of nodes for a term and its children.
 */
function faq_taxonomy_term_count_nodes($tid) {
  static $count;

  if (!isset($count) || !isset($count[$tid])) {
    $query = db_select('node', 'n')
             ->fields('n', array('nid'))
             ->addTag('node_access');
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
    $query->condition('n.type', 'faq')
          ->condition('n.status', 1)
          ->condition('ti.tid', $tid);
    $count[$tid] = $query->countQuery()->execute()->fetchField();
  }

  $children_count = 0;
  foreach (faq_taxonomy_term_children($tid) as $child_term) {
    $children_count += faq_taxonomy_term_count_nodes($child_term);
  }

  return $count[$tid] + $children_count;
}

/**
 * Helper function to faq_taxonomy_term_count_nodes() to return list of child terms.
 */
function faq_taxonomy_term_children($tid) {
  static $children;

  if (!isset($children)) {
    $result = db_select('taxonomy_term_hierarchy', 'tth')
             ->fields('tth', array('parent', 'tid'))
             ->execute();
    while ($term = $result->fetch()) {
      $children[$term->parent][] = $term->tid;
    }
  }
  return isset($children[$tid]) ? $children[$tid] : array();
}

/**
 * Theme function for faq page wrapper divs.
 */
function theme_faq_page($variables) {
  $content = $variables['content'];
  $answers = $variables['answers'];
  $description = $variables['description'];
  $output = '<div class="faq-content"><div class="faq">';
  if (!empty($description)) {
    $output .= '<div class="faq-description">' . $description . "</div>\n";
  }
  if (variable_get('faq_show_expand_all', FALSE)) {
    $output .= '<div id="faq-expand-all">';
    $output .= '<a class="faq-expand-all-link" href="#faq-expand-all-link">[' . t('expand all') . ']</a>';
    $output .= '<a class="faq-collapse-all-link" href="#faq-collapse-all-link">[' . t('collapse all') . ']</a>';
    $output .= "</div>\n";
  }

  $output .= $content;
  $output .= $answers . "</div></div>\n";
  return $output;
}

/**
 * Theme function for the detailed questionfield.
 *
 * @param array $variables
 *   Variables array.
 *
 * @return string
 *   Markup.
 */
function theme_field_detailed_question($variables) {
  // Render the label, if it's not hidden.
  $output = '';

  if (isset($variables['label']) && !$variables['label_hidden'] && $variables['label']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ':&nbsp;</div>';
  }

  // Render the items.
  $output .= '<div class="faq-detailed-question">' . $variables['safe_value'] . '</div>';

  // Render the top-level DIV.
  if (isset($variables['classes']) && isset($variables['attributes'])) {
    $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';
  }

  return $output;
}

/**
 * Theme function for question ordering drag and drop table.
 */
function theme_faq_draggable_question_order_table($variables) {
  $form = $variables['form'];
  drupal_add_tabledrag('question-sort', 'order', 'sibling', 'sort');
  $header = array('', t('Question'), '', t('Sort'));
  $rows = array();
  foreach (element_children($form) as $key) {
    // Add class to group weight fields for drag and drop.
    $form[$key]['sort']['#attributes']['class'] = array('sort');

    $row = array('');
    $row[] = drupal_render($form[$key]['title']);
    $row[] = drupal_render($form[$key]['nid']);
    $row[] = drupal_render($form[$key]['sort']);
    $rows[] = array(
      'data' => $row,
      'class' => array('draggable'),
    );
  }
  $output = theme('table',
    array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array('id' => 'question-sort'),
    )
  );
  $output .= drupal_render_children($form);
  return $output;
}
