advanced_forum.module 42.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
<?php

/**
 * @file
 * Enables the look and feel of other popular forum software.
 */
// DRUPAL HOOKS **************************************************************/

/**
 * Implementation of hook_perm().
 */
function advanced_forum_permission() {
  return array(
    'administer advanced forum' => array(
      'title' => t('Administer Advanced Forum')
    ),
    'view forum statistics' => array(
      'title' => t('View Advanced Forum statistics')
    ),
    'view last edited notice' => array(
      'title' => t('View last edited notice')
    )
  );
}

/**
 * Implementation of hook_menu().
 */
function advanced_forum_menu() {
  $items['admin/config/content/advanced-forum'] = array(
    'access arguments' => array('administer advanced forum'),
    'description' => 'Configure Advanced Forum with these settings.',
    'page arguments' => array('advanced_forum_settings_page'),
    'page callback' => 'drupal_get_form',
    'title' => 'Advanced Forum',
    'file' => 'includes/settings.inc'
  );

  $items['forum/markasread'] = array(
    'access callback' => 'advanced_forum_markasread_access',
    'page callback' => 'advanced_forum_markasread',
    'type' => MENU_CALLBACK,
  );

  if (variable_get('advanced_forum_add_local_task', TRUE)) {
    $items['forum/view'] = array(
      'title' => 'View Forums',
      'page callback' => 'advanced_forum_page',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => -100,
    );
  }

  return $items;
}

/**
 * Implementation of hook_cron().
 */
function advanced_forum_cron() {
  // ensure the reply stats are up-to-date
  advanced_forum_statistics_replies(NULL, TRUE);
}

/**
 * Implementation of hook_menu_alter().
 */
function advanced_forum_menu_alter(&$items) {
  // Take over the forum page creation so we can add more information.
  $items['forum']['page callback'] = 'advanced_forum_page';
  $items['forum']['module'] = 'advanced_forum';
  unset($items['forum']['file']);


  // Take over forum/%forum_forum page because we want advanced_forum_forum_load
  // is called instead of core forum_forum_load
  $items['forum/%advanced_forum_forum'] = $items['forum/%forum_forum'];
  $items['forum/%advanced_forum_forum']['page callback'] = 'advanced_forum_page';
  $items['forum/%advanced_forum_forum']['module'] = 'advanced_forum';
  unset($items['forum/%advanced_forum_forum']['file']);
  unset($items['forum/%forum_forum']);
}

/**
 * Implements hook_menu_local_tasks_alter().
 *
 * Unset all items set in core forum_menu_local_tasks_alter
 */
function advanced_forum_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'forum' || $root_path == 'forum/%') {
    $data['actions']['output'] = array();
  }
}

/**
 * Implementation of hook_module_implements_alter().
 *
 * We don't want forum_menu_local_tasks_alter() to be called and mess with our links.
 *
 */
function advanced_forum_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_local_tasks_alter') {
    unset($implementations['forum']);
  }
}

/**
 * Implementation of hook_theme().
 */
function advanced_forum_theme() {
  advanced_forum_load_style_includes();

  // Bulk read all available (active) style templates
  $existing_items = advanced_forum_find_style_templates();

  $items['advanced_forum_l'] = array(
    'variables' => array(
      'text' => NULL,
      'path' => NULL,
      'options' => array(),
      'button_class' => NULL,
    )
  );

  $items['advanced_forum_topic_header'] = array(
    'variables' => array(
      'node' => NULL,
      'comment_count' => NULL,
    )
  );

  $items['advanced_forum_active_poster'] = array(
    'variables' => array(
      'forum' => NULL,
      'account' => NULL,
      'posts' => NULL,
      'topics' => NULL,
      'last_post' => NULL,
    )
  );

  $items['advanced_forum_user_picture'] = array(
    'variables' => array(
      'account' => NULL,
    )
  );

  $items['advanced_forum_reply_link'] = array(
    'variables' => array(
      'node' => NULL,
    )
  );

  $items['advanced_forum_topic_pager'] = array(
    'variables' => array(
      'pagecount' => NULL,
      'topic' => NULL,
    )
  );

  $items['advanced_forum_shadow_topic'] = array(
    'variables' => array(
      'title' => NULL,
      'nid' => NULL,
      'new_forum' => NULL,
    )
  );

  $items['advanced_forum_subforum_list'] = array(
    'variables' => array(
      'subforum_list' => NULL,
    )
  );

  $items['advanced_forum_subcontainer_list'] = array(
    'variables' => array(
      'subcontainer_list' => NULL,
    )
  );

  $items['advanced_forum_simple_author_pane'] = array(
    'variables' => array(
      'context' => NULL,
    )
  );

  $items['advanced_forum_post_edited'] = array(
    'variables' => array(
      'who' => NULL,
      'when' => NULL,
      'why' => NULL,
    )
  );

  $items['advanced_forum_node_type_create_list'] = array(
    'variables' => array(
      'forum_id' => NULL,
    )
  );
  /*
    // Templates for features added by Views

    // style
    $items['views_view_forum_topic_list__advanced_forum_topic_list'] = array(
    'variables' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
    'template' => 'advanced-forum-topic-list-view',
    //'base hook' => 'views_view_forum_topic_list',
    );
   */
  //display
  $items['views_view__advanced_forum_topic_list'] = array(
    'variables' => array('view' => NULL),
    'template' => 'advanced-forum-topic-list-outer-view',
      //'base hook' => 'views_view',
  );

  //display group
  $items['views_view__advanced_forum_group_topic_list'] = array(
    'variables' => array('view' => NULL),
    'template' => 'advanced-forum-group-topic-list-outer-view',
      //'base hook' => 'views_view',
  );

  // Return merged items found in style folder with new ones
  // array_merge_recursive doesn't work as desired
  foreach ($items as $key => $item) {
    if (array_key_exists($key, $existing_items)) {
      $existing_items[$key] += $item;
    }
    else {
      $existing_items[$key] = $item;
    }
  }

  return $existing_items;
}

/**
 * Implementation of hook_theme_registry_alter().
 */
function advanced_forum_theme_registry_alter(&$theme_registry) {
  advanced_forum_load_style_includes();

  // Don't let core do its basic preprocess for forums, as we want to do
  // other stuff now.
  if (isset($theme_registry['forums']['preprocess functions'])) {
    foreach ($theme_registry['forums']['preprocess functions'] as $key => $value) {
      if ($value == 'template_preprocess_forums') {
        unset($theme_registry['forums']['preprocess functions'][$key]);
      }
    }
  }

  // We duplicate all of core's forum list preprocessing so no need to run
  // it twice. Running twice also causes problems with & in forum name.
  if (isset($theme_registry['forum_list']['preprocess functions'])) {
    foreach ($theme_registry['forum_list']['preprocess functions'] as $key => $value) {
      if ($value == 'template_preprocess_forum_list') {
        unset($theme_registry['forum_list']['preprocess functions'][$key]);
      }
    }
  }

  // Views handles the topic list pages so remove the core template preprocess.
  if (isset($theme_registry['forum_topic_list']['preprocess functions'])) {
    foreach ($theme_registry['forum_topic_list']['preprocess functions'] as $key => $value) {
      if ($value == 'template_preprocess_forum_topic_list') {
        unset($theme_registry['forum_topic_list']['preprocess functions'][$key]);
      }
    }
  }

  // --- The following section manipulates the theme registry so the .tpl files
  // --- for the given templates can be found first in the (sub)theme directory
  // --- then in ancestor themes, if any, then in the active style directory
  // --- for advanced forum or any ancestor styles.
  // Affected templates
  $templates = array(
    'node',
    'comment',
    'comment_wrapper',
    'forums',
    'forum_list',
    'forum_topic_list',
    'forum_icon',
    'forum_submitted',
    'author_pane',
      /*
        'advanced_forum_statistics',
        'advanced_forum_topic_list_view',
        'advanced_forum_topic_legend',
        'advanced_forum_forum_legend',
        'advanced_forum_topic_header',
        'advanced_forum_active_poster', */
  );

  // Get the sequence of styles to look in for templates
  $lineage = advanced_forum_style_lineage();

  if (!array_key_exists('naked', $lineage)) {
    // Add naked in at the end of the line to prevent problems if a style
    // doesn't include all needed templates.
    $lineage['naked'] = drupal_get_path('module', 'advanced_forum') . '/styles/naked';
  }

  // Get theme engine extension
  global $theme_engine;
  $extension = '.tpl.php';
  if (isset($theme_engine)) {
    $extension_function = $theme_engine . '_extension';
    if (function_exists($extension_function)) {
      $extension = $extension_function();
    }
  }

  foreach ($templates as $template) {
    // Sanity check in case the template is not being used.
    if (!empty($theme_registry[$template])) {
      // There are preprocess functions to add, so figure out where we want to add
      // them.
      if (!empty($preprocess)) {
        $position = 0;
        foreach ($theme_registry[$template]['preprocess functions'] as $function) {
          $position++;
          // If we see either of these items, that means we can place our
          // preprocess functions after this.
          if (substr($function, 0, 25) == 'advanced_forum_preprocess' || substr($function, 0, 34) == 'template_preprocess_advanced_forum') {
            break;
          }
        }
        // Add in our new preprocess functions:
        if (isset($theme_registry[$template]['preprocess functions'])) {
          array_splice($theme_registry[$template]['preprocess functions'], $position, 0, $preprocess);
        }
      }
    }
  }


  // temp workaround
  if (isset($theme_registry['views_view__advanced_forum_topic_list']['preprocess functions'])) {
    array_splice($theme_registry['views_view__advanced_forum_topic_list']['preprocess functions'], 1, 0, 'template_preprocess_views_view');
  }
  if (isset($theme_registry['views_view__advanced_forum_group_topic_list']['preprocess functions'])) {
    array_splice($theme_registry['views_view__advanced_forum_group_topic_list']['preprocess functions'], 1, 0, 'template_preprocess_views_view');
  }
  //array_splice($theme_registry['views_view_forum_topic_list__advanced_forum_topic_list']['preprocess functions'], 1, 0, 'template_preprocess_views_view_forum_topic_list');
}

/**
 * Own link alteration implementaion because there are no
 * hook_link nor hook_link_alter in D7
 *
 * Name changed intentionally to avoid confusion with hook_link_alter!
 */
function advanced_forum_links_alter(&$object, $view_mode, $object_type = 'node') {
  // Don't alter anything if in preview mode
  if (!empty($object->in_preview)) {
    return;
  }

  if (!advanced_forum_is_styled($object, ($view_mode == 'teaser'), $object_type)) {
    return;
  }

  if (!empty($object->content['links']['comment'])) {
    $comment_links = $object->content['links']['comment'];
    $links = empty($comment_links['#links']) ? array() : $comment_links['#links'];
  }
  else {
    $comment_links = array();
    $links = array();
  }

  if ($object_type == 'node') {

    $node = $object;
    // Add edit / delete links to the node links to match replies.
    if (node_access('update', $node)) {
      $links['post-edit'] = array(
        'title' => t('edit'),
        'href' => 'node/' . $node->nid . '/edit',
        'query' => drupal_get_destination(),
      );
    }

    if (node_access('delete', $node)) {
      $links['post-delete'] = array(
        'title' => t('delete'),
        'href' => 'node/' . $node->nid . '/delete',
      );
    }
  }

  // Change first post from "add comment" to "reply" if it isn't already.
  if (!empty($links['comment-add'])) {
    $links['comment-add']['title'] = t('reply');
    $links['comment-add']['href'] = "comment/reply/$node->nid";
  }


  // List the keys we are interested in.
  $affected_keys = array('post-edit', 'comment-edit', 'post-delete', 'comment-delete', 'quote', 'comment-add', 'comment-reply');

  // Add extra span tags for image replacement.
  foreach ($links AS $key => $link) {
    if (in_array($key, $affected_keys)) {
      $links[$key]['attributes']['class'][] = "af-button-small";
      $links[$key]['title'] = '<span>' . $links[$key]['title'] . '</span>';
      $links[$key]['html'] = TRUE;
    }
  }

  // Put the links in a consistent order.
  foreach ($affected_keys as $key) {
    if (isset($links[$key])) {
      $temp = $links[$key];
      unset($links[$key]);
      $links[$key] = $temp;
    }
  }

  // we want to put comment links last
  unset($object->content['links']['comment']);
  $object->content['links']['comment'] = $comment_links;

  // put links back
  $object->content['links']['comment']['#links'] = $links;
}

/**
 * Implementation of hook_node_view().
 *
 * hook_link() and hook_link_alter() functionalty implemented here
 */
function advanced_forum_node_view($node, $view_mode, $langcode) {
  advanced_forum_links_alter($node, $view_mode, 'node');
}

/**
 * Implementation of hook_comment_view().
 */
function advanced_forum_comment_view($comment, $view_mode, $langcode) {
  advanced_forum_links_alter($comment, $view_mode, 'comment');
}

/**
 * Implementation of hook_comment_delete().
 */
function advanced_forum_comment_delete($comment) {
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
    advanced_forum_statistics_replies(-1);
  }
}

/**
 * Implementation of hook_comment_update().
 */
function advanced_forum_comment_update($comment) {
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
    // comment unpublished?
    if (!$comment->status) {
      advanced_forum_statistics_replies(-1);
    }
  }
}

/**
 * Implementation of hook_comment_publish().
 */
function advanced_forum_comment_publish($comment) {
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
    advanced_forum_statistics_replies(1);
  }
}

/**
 * Implementation of hook_form_alter().
 */
function advanced_forum_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['#node']->type) && advanced_forum_type_is_in_forum($form['#node']) && isset($form['body_field']) && isset($form['body_field']['#after_build'])) {
    // Remove the teaser splitter.
    $teaser_js_build = array_search('node_teaser_js', $form['body_field']['#after_build']);
    unset($form['body_field']['#after_build'][$teaser_js_build]);
    $form['body_field']['teaser_js']['#access'] = FALSE;
    $form['body_field']['teaser_include']['#access'] = FALSE;
  }

  // Add our OG view as a potential RON for organic groups.
  if (!empty($form['og_settings']['group_details']['og_home_page_view'])) {
    $form['og_settings']['group_details']['og_home_page_view']['#options']['advanced_forum_group_topic_list'] = 'advanced_forum_group_topic_list';
  }
}

// MAKE VIEWS BITS WORK *****************************************************/
function advanced_forum_views_api() {
  return array(
    'api' => '3.0-alpha1',
    'path' => drupal_get_path('module', 'advanced_forum') . '/includes/views',
  );
}

// MAKE CTOOLS BITS WORK *****************************************************/
/**
 * Tell CTools about what plugins we support.
 */
function advanced_forum_ctools_plugin_directory($module, $plugin) {
  if ($module == 'advanced_forum') {
    return 'styles';
  }

  if ($module == 'page_manager' || $module == 'ctools') {
    return 'plugins/' . $plugin;
  }
}

function advanced_forum_ctools_plugin_api($module, $api) {
  if ($module == 'page_manager' && $api = 'pages_default') {
    return array(
      'version' => 1,
      'path' => drupal_get_path('module', 'advanced_forum') . '/includes/panels',
    );
  }
}

// THEME FUNCTIONS AND TEMPLATE PREPROCESSES **********************************/
module_load_include('inc', 'advanced_forum', 'includes/theme');

// STYLE RELATED FUNCTIONS ****************************************************/
module_load_include('inc', 'advanced_forum', 'includes/style');

// CORE FORUM PAGE OVERRIDES **************************************************/
module_load_include('inc', 'advanced_forum', 'includes/core-overrides');

// MARK AS READ ***************************************************************/
module_load_include('inc', 'advanced_forum', 'includes/mark-read');

// VIEWS RELATED GOODIES ******************************************************/

/**
 * Post render a view and replace any advanced forum tokens.
 */
function advanced_forum_views_post_render(&$view, &$output) {
  if (empty($view->style_plugin) || !$view->style_plugin->uses_row_plugin()) {
    return;
  }

  $plugin = $view->display_handler->get_option('row_plugin');
  if ($plugin == 'node') {
    // Look for token matches in the output:
    $matches = array();
    $tokens = array();

    // We want to change the look of the 'new' marker from the default, slightly:
    $tokens['<span class="new">' . t('new') . '</span>'] = '<span class="new">(' . t('new') . ')</span>';

    // Replace the Author Pane token with the actual Author Pane.
    if (preg_match_all('/<!--post:author-pane-([\d]+)-->/us', $output, $matches)) {
      foreach ($matches[1] as $match => $uid) {
        $token = $matches[0][$match]; // This is the exact string that matched.
        if (!isset($tokens[$token])) {
          $account = user_load($uid);
          $tokens[$token] = theme('author_pane', array(
            'account' => $account,
            'caller' => 'advanced_forum',
            'picture_preset' => variable_get('advanced_forum_user_picture_preset', ''),
            'context' => NULL,
            'disable_css' => TRUE,
            'join_date_type' => variable_get('advanced_forum_author_pane_join_date_type', 'short'),
          ));
        }
      }
    }

    // Replace the Post edited token.
    if (preg_match_all('/<!--post:post-edited-([\d]+)-->/us', $output, $matches)) {
      foreach ($matches[1] as $match => $nid) {
        $token = $matches[0][$match]; // This is the exact string that matched.
        if (!isset($tokens[$token])) {
          if (user_access('view last edited notice')) {
            $sql = 'SELECT uid, log, timestamp FROM {node_revision} WHERE nid = %d ORDER BY timestamp DESC';
            $row = db_fetch_object(db_query($sql, $nid));
            $tokens[$token] = theme('advanced_forum_post_edited', array(
              'who' => $row->uid,
              'when' => $row->timestamp,
              'why' => $row->log
            ));
          }
          else {
            // No access; remove token.
            $tokens[$token] = '';
          }
        }
      }
    }

    // Replace the core Signature token.
    if (preg_match_all('/<!--post:signature-core-([\d]+)-->/us', $output, $matches)) {
      foreach ($matches[1] as $match => $uid) {
        $token = $matches[0][$match]; // This is the exact string that matched.
        if (!isset($tokens[$token])) {
          $account = user_load($uid);
          if ($account->signature) {
            $tokens[$token] = check_markup($account->signature, $account->signature_format, FALSE);
          }
        }
      }
    }

    // Perform replacements.
    $output = strtr($output, $tokens);
  }
}

/**
 * Display the "sort" widget. This is a specially hacked widget that only
 * works with tablesorting. Tablesorting MUST be on for these widgets
 * to appear.
 */
function advanced_forum_forum_topic_list_sort() {
  $form_state = array(
    'method' => 'get',
    'no_redirect' => TRUE,
    'rerender' => TRUE,
    'input' => $_GET,
    'drop tokens' => TRUE,
  );

  $form = drupal_build_form('advanced_forum_forum_topic_list_sort_form', $form_state);
  return drupal_render($form);
}

function advanced_forum_forum_topic_list_sort_form($form_state) {
  $view = views_get_view('advanced_forum_topic_list');
  $view->set_display('default');
  $view->init_handlers();
  $view->init_style();

  // Work up a list of possible fields.
  $handler = &$view->style_plugin;
  $fields = &$view->field;
  $columns = $handler->sanitize_columns($handler->options['columns'], $fields);

  $options = array();
  foreach ($columns as $field => $column) {
    if ($field == $column && empty($fields[$field]->options['exclude'])) {
      if (empty($handler->options['info'][$field]['sortable']) || !$fields[$field]->click_sortable()) {
        continue;
      }
      $label = check_plain(!empty($fields[$field]) ? $fields[$field]->label() : '');
      $options[$field] = $label;
    }
  }

  $form['inline'] = array(
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $form['inline']['order'] = array(
    '#type' => 'select',
    '#title' => t('Order by'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => $handler->options['default'],
  );

  $form['inline']['sort'] = array(
    '#type' => 'select',
    '#title' => t('Sort'),
    '#title_display' => 'invisible',
    '#options' => array(
      'asc' => t('Up'),
      'desc' => t('Down'),
    ),
    '#default_value' => 'desc',
  );

  $form['inline']['submit'] = array(
    '#id' => 'sort-topic-submit',
    '#name' => '',
    '#type' => 'submit',
    '#value' => t('Sort'),
  );

  if (isset($_GET['page'])) {
    $form['page'] = array(
      '#type' => 'hidden',
      '#default_value' => $_GET['page'],
    );
  }

  if (!variable_get('clean_url', FALSE)) {
    $form['q'] = array(
      '#type' => 'hidden',
      '#value' => $_GET['q'],
    );
  }

  $view->destroy();
  return $form;
}

// STATISTICS *****************************************************************/

/**
 * Count total amount of forum threads.
 */
function advanced_forum_statistics_topics() {
  return db_query('SELECT COUNT(DISTINCT(nid)) FROM {forum}')->fetchField();
}

/**
 * Counts total amount of replies. Initial posts are added to this total
 * in the calling function.
 *
 * @param $delta
 *   if not NULL, a numerical delta which should be applied to the count
 * @param $refresh
 * @param $refresh
 *   TRUE if the stored count should be updated.
 * @return
 *   Total number of replies in the forum.
 */
function advanced_forum_statistics_replies($delta = NULL, $refresh = FALSE) {

  if ($refresh || !($cache = cache_get('advanced_forum_stats_replies'))) {
    $total_replies = db_query('SELECT SUM(comment_count) FROM {forum_index}')->fetchField();
    cache_set('advanced_forum_stats_replies', $total_replies);
  }
  else {
    $total_replies = $cache->data;
  }


  if (!empty($delta) && is_numeric($delta)) {
    $total_replies += $delta;
    cache_set('advanced_forum_stats_replies', $total_replies);
  }

  return $total_replies;
}

/**
 * Count total amount of active users.
 */
function advanced_forum_statistics_users() {
  return db_query('SELECT COUNT(uid) FROM {users} WHERE status = 1')->fetchField();
}

/**
 * Return the newest X active (not blocked) users, linked to their profiles.
 */
function advanced_forum_statistics_latest_users() {
  $number_to_fetch = 5; // @TODO: Make this a setting.

  $query = db_select("users", "u")
      ->fields("u", array("uid", "name"))
      ->condition("status", 0, "<>")
      ->condition("access", 0, "<>")
      ->orderBy("created", "DESC");

  $latest_users = $query->range(NULL, $number_to_fetch)->execute();
  while ($account = $latest_users->fetchObject()) {
    $list[] = theme('username', array('account' => $account));
  }

  return $list;
}

function advanced_forum_session_count($anonymous = TRUE) {

  $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);

  $query = db_select("sessions", "s")
      ->fields("s", array("uid"))
      ->distinct()
      ->condition('s.timestamp', $interval, '>=')
      ->condition('s.uid', 0, $anonymous ? '=' : '>')
      ->countQuery();

  return $query->execute()->fetchField();
}

/**
 * Return an array of online usernames, linked to their profiles.
 */
function advanced_forum_statistics_online_users() {
  $list = array();

  $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);

  $query = db_select("users", "u")->distinct()->fields("u", array("uid", "name"));
  $s_alias = $query->join("sessions", "s", "u.uid = s.uid");

  $query->addExpression("MAX({$s_alias}.timestamp)", "maxtime");
  $query
      ->condition("{$s_alias}.timestamp", $interval, ">=")
      ->condition("{$s_alias}.uid", "0", ">")
      ->groupBy("u.uid, u.name")
      ->orderBy("maxtime", "DESC");

  $authenticated_users = $query->execute();

  while ($account = $authenticated_users->fetchObject()) {
    $list[] = theme('username', array('account' => $account));
  }

  return $list;
}

// CALCULATING LINKS - New, Last, Etc *****************************************/

function advanced_forum_get_reply_link($node) {
  $reply_link = array();

  $comment_setting = $node->comment;
  $fragment = 'comment-form';

  if ($comment_setting == COMMENT_NODE_OPEN) {

    $allowed = FALSE;
    if (module_exists('forum_access')) {
      // get tid
      if (!empty($node->taxonomy_forums)) {
        reset($node->taxonomy_forums);
        $langcode = key($node->taxonomy_forums);
        if (!empty($node->taxonomy_forums[$langcode])) {
          $tid = $node->taxonomy_forums[$langcode][0]['tid'];
          if (forum_access_access('create', $tid)) {
            $allowed = TRUE;
          }
        }
      }
    }
    else {
      $allowed = user_access('post comments');
    }

    if ($allowed) {
      if (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
        // Reply form is on separate page. Grab the href from the node links
        // so it's automatically corrected for Node Comments if needed.
        $reply_link['href'] = "comment/reply/$node->nid";
        $reply_link['options']['fragment'] = $fragment;

        $reply_link['class'] = 'reply-allowed';
        $reply_link['title'] = t('Post reply');

        return $reply_link;
      }
      else {
        // Reply form is on same page. The reply button should jump down to it
        // rather than going to a new page.
        $reply_link['href'] = $_GET['q'];
        $reply_link['options']['fragment'] = $fragment;
        $current_page = isset($_GET['page']) ? $_GET['page'] : 0;
        if ($current_page)
          $reply_link['options']['query'] = array('page' => $current_page);

        $reply_link['class'] = 'reply-allowed';
        $reply_link['title'] = t('Quick reply');

        return $reply_link;
      }
    }
    else {
      // User does not have access to post replies on this node.
      return 'reply-forbidden';
    }
  }
  else {
    // Topic is locked.
    return 'reply-locked';
  }
}

/**
 * Get a link to the last post in a topic.
 *
 * @param $node
 *   Node object
 * @return
 *   Text linking to the last post in a topic.
 */
function advanced_forum_last_post_link($node) {
  $last_comment_id = advanced_forum_last_post_in_topic($node->nid);
  // Return empty link if post doesn't have comments.
  if (empty($last_comment_id))
    return '';

  $last_page = advanced_forum_get_last_page($node);

  if ($last_page > 0)
    $query = array('page' => $last_page);

  $options = array(
    'html' => TRUE,
    'query' => empty($query) ? array() : $query,
    'fragment' => "comment-$last_comment_id",
  );

  return theme('advanced_forum_l', array(
    'text' => t('Last post'),
    'path' => "node/$node->nid",
    'options' => $options,
    'button_class' => 'large'
  ));
}

/**
 * Returns a link directly to the first new post in a topic.
 *
 * @param $node
 *   Node object
 * @param $comment_count
 *   Number of comments on passed node.
 * @return
 *   Link to the first unread post.
 */
function advanced_forum_first_new_post_link($node, $comment_count) {
  $nid = $node->nid;

  $current_page = isset($_GET['page']) ? $_GET['page'] : 0;
  $number_new_comments = advanced_forum_reply_num_new($nid);

  if ($number_new_comments > 0) {
    $page_of_first_new = advanced_forum_page_first_new($comment_count, $number_new_comments, $node);

    // Note that we are linking to the cid anchor rather than "new" because
    // the new links will be gone if we go to another page.
    $cid_of_first_new = advanced_forum_first_new_comment($nid);

    $number_new = t("(!new new)", array('!new' => $number_new_comments));

    $options = array(
      'html' => TRUE,
      'query' => $page_of_first_new,
      'fragment' => "comment-$cid_of_first_new"
    );

    return theme('advanced_forum_l', array(
      'text' => t('First unread'),
      'path' => "node/$nid",
      'options' => $options,
      'button_class' => 'large'
    ));
  }
}

/**
 * Get the page number with the first new post.
 */
function advanced_forum_page_first_new($comment_count, $new_replies, $node) {
  return comment_new_page_count($comment_count, $new_replies, $node);
}

/**
 * Get the number of new posts on a topic.
 */
function advanced_forum_reply_num_new($nid, $timestamp = 0) {
  // Make a static cache because this function is called twice from the topic
  // header. Once to display the number and once to make the link to first new.
  static $number_new_for_node = array();

  // $nid is empty if new topic in preview.
  if (empty($nid))
    return 0;

  if (empty($number_new_for_node[$nid])) {
    global $user;

    $node = node_load($nid);

    // We must also check the forum post itself to see if we have viewed it
    $viewed = 0; // If not told otherwise, it has been viewed before
    if ($user->uid) {
      $viewed = node_last_viewed($nid);
      // Set it to 1 if it has not been viewed before.
      $viewed = ($viewed == 0 ? 1 : 0);
    }

    $number_new_for_node[$nid] = comment_num_new($nid, $timestamp) + $viewed;
  }

  return $number_new_for_node[$nid];
}

/**
 * Get the comment id of the last post in a topic.
 *
 * @param $node
 *   Node object
 * @return
 *   cid of last post.
 */
function advanced_forum_last_post_in_topic($nid) {
  // $nid is empty if new topic in preview.
  if (empty($nid))
    return NULL;

  $node = node_load($nid);

  // Comment module version
  $query = 'SELECT c.cid
            FROM {comment} c
            WHERE c.nid = :nid AND c.status = :status
            ORDER BY c.cid DESC';
  $result = db_query_range($query, 0, 1, array(':nid' => $nid, ':status' => COMMENT_PUBLISHED))->fetchField();

  return $result;
}

/**
 * Returns the page number of the last page starting at 0 like the pager does.
 */
function advanced_forum_get_last_page($node) {
  $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  $comment_count = isset($node->comment_count) ? $node->comment_count : 0;
  $last_page = ceil($comment_count / $comments_per_page) - 1;
  return $last_page;
}

/**
 * Returns the ID of the first unread comment.
 *
 * @param $nid
 *   Node ID
 * @param $timestamp
 *   Date/time used to override when the user last viewed the node.
 * @return
 *   Comment ID
 */
function advanced_forum_first_new_comment($nid, $timestamp = 0) {
  global $user;

  if ($user->uid) {
    // Retrieve the timestamp at which the current user last viewed the
    // specified node.
    if (!$timestamp) {
      $timestamp = node_last_viewed($nid);
    }

    // Set the timestamp to the limit if the node was last read past the cutoff
    $timestamp = ($timestamp > NODE_NEW_LIMIT ? $timestamp : NODE_NEW_LIMIT);

    // Use the timestamp to retrieve the oldest new comment.
    $query = db_select('comment', 'c')
        ->fields('c', array('cid'))
        ->condition('nid', $nid)
        ->condition('changed', $timestamp, '>')
        ->condition('status', COMMENT_PUBLISHED)
        ->range(0, 1)
        ->execute();
    return $query->fetchField();
  }
  else {
    return 0;
  }
}

// GENERAL UTILITY FUNCTIONS *************************************************/

/**
 * Return an array of node types allowed in a given vocabulary or term ID.
 */
function advanced_forum_allowed_node_types($tid = 0) {
  if (module_exists('forum_access')) {
    // Check with forum access to see if this forum allows node creation.
    // If it doesn't, send back an empty list.
    if (!forum_access_access('create', $tid)) {
      return array();
    }
  }

  $field = field_info_field('taxonomy_forums');
  if (!empty($field['bundles']['node'])) {
    return $field['bundles']['node'];
  }
  else {
    return array();
  }
}

/**
 * Return whether a given node type is allowed in the whole forum or given forum.
 */
function advanced_forum_type_is_in_forum($node, $tid = 0) {
  $vid = (empty($vid)) ? variable_get('forum_nav_vocabulary', 0) : $vid;
  if (!empty($node->taxonomy_forums)) {
    // Check for language used
    if (!isset($node->taxonomy_forums[$node->language])) {
      $langcode = LANGUAGE_NONE;
    }
    else {
      $langcode = $node->language;
    }

    foreach ($node->taxonomy_forums[$langcode] as $tforum) {
      if (!isset($tforum['taxonomy_term'])) {
        continue;
      }
      if (($tforum['taxonomy_term']->vid == $vid) || ($tforum['taxonomy_term']->tid == $tid))
        return TRUE;
    }
  }
  return FALSE;
}

/**
 * Generate a list of node creation links for a forum.
 *
 * This is used on the forum list, allowing us to have direct
 * links to create new nodes in the forum.
 */
function advanced_forum_node_type_create_list($tid) {
  $allowed_types = advanced_forum_allowed_node_types($tid);

  // Ensure "new topic" is first.
  if (isset($allowed_types['forum'])) {
    unset($allowed_types['forum']);
    array_unshift($allowed_types, 'forum');
  }
  // Loop through all node types allowed in this forum.
  foreach ($allowed_types as $type) {
    // Check if this node type can be created by current user.
    if (node_access('create', $type)) {
      // Fetch the "General" name of the content type.
      $node_type = t(node_type_get_name($type));

      // Remove the word "Forum" out of "Forum topic" to shorten it.
      // @TODO: this is a little dodgy and may not work right with
      // translations. Should be replaced if there's a better way.
      $node_type = str_replace('Forum', '', $node_type);

      // Push the link with title and url to the array.
      $forum_types[$type] = array(
        'name' => $node_type,
        'href' => 'node/add/' . str_replace('_', '-', $type) . '/' . $tid,
      );
    }
  }

  if (empty($forum_types)) {
    // The user is logged-in; but denied access to create any new forum content type.
    global $user;
    if ($user->uid) {
      return t('You are not allowed to post new content in the forum.');
    }
    // The user is not logged-in; and denied access to create any new forum content type.
    else {
      return t('<a href="@login">Log in</a> to post new content in the forum.', array(
        '@login' => url('user/login', array('query' => drupal_get_destination())),
      ));
    }
  }
  else {
    return $forum_types;
  }
}

/**
 * Create a drop down list of forum actions.
 */
function advanced_forum_forum_tools($tid = 0) {
  global $user;
  $options = array();

  ctools_include('jump-menu');
  if ($tid > 0) {
    $select[url("forum/active", array('query' => array('forum[]' => $tid)))] = t("View active posts in this forum");
    $select[url("forum/unanswered", array('query' => array('forum[]' => $tid)))] = t("View unanswered posts in this forum");

    if ($user->uid) {
      $select[url("forum/new", array('query' => array('forum[]' => $tid)))] = t("View new posts in this forum");
    }
  }
  else {
    $select[url("forum/active")] = t("View active forum posts");
    $select[url("forum/unanswered")] = t("View unanswered forum posts");

    if ($user->uid) {
      $select[url("forum/new")] = t("View new forum posts");
    }
  }

  // Add mark as read to the jump list.
  // This code is a little odd and needs explaining. The return value of
  // the mark_as_read function is already formed HTML and so is unsuitable
  // for the jump list. The function already has built in the ability
  // to add to an existing $links array, which has the URL and title text
  // separated. Rather than add a third method just for the jump menu, I
  // reused that functionality here.
  $mark_as_read = array();
  advanced_forum_get_mark_read_link($tid, $mark_as_read);
  if (!empty($mark_as_read['mark-read']['href'])) {
    $select[url($mark_as_read['mark-read']['href'])] = $mark_as_read['mark-read']['title'];
  }

  $options['choose'] = t("- Forum Tools -");

  // Create and return the jump menu.
  $form = drupal_get_form('ctools_jump_menu', $select, $options);
  return drupal_render($form);
}

/**
 * Creates a pager to place on each multi-page topic of the topic listing page.
 *
 * @param $max_pages_to_display
 *   Number of pages to include on the pager.
 * @param $topic
 *   Topic object to create a pager for.
 * @return
 *   Object containing the linked pages ready assembly by the theme function.
 */
function advanced_forum_create_topic_pager($max_pages_to_display, $topic) {
  // Find the number of comments per page for the node type of the topic.
  $comments_per_page = variable_get('comment_default_per_page_' . $topic->type, 50);

  if ($max_pages_to_display > 0 && $topic->comment_count > $comments_per_page) {
    // Topic has more than one page and a pager is wanted. Start off the
    // first page because that doesn't have a query.
    $pager_array = array();
    $current_display_page = 1;
    $pager_array[0] = l('1', "node/$topic->nid");

    // Find the ending point. The pager URL is always 1 less than
    // the number being displayed because the first page is 0.
    $last_display_page = ceil($topic->comment_count / $comments_per_page);
    $last_pager_page = $last_display_page - 1;

    // Add pages until we run out or until we hit the max to show.
    while (($current_display_page < $last_display_page) && ($current_display_page < $max_pages_to_display)) {
      // Move to the next page
      $current_display_page++;

      // The page number we link to is 1 less than what's displayed
      $link_to_page = $current_display_page - 1;

      // Add the link to the array
      $pager_array[$link_to_page] = l($current_display_page, "node/$topic->nid", array('query' => array('page' => $link_to_page)));
    }

    // Move to the next page
    $current_display_page++;

    if ($current_display_page == $last_display_page) {
      // We are one past the max to display, but it's the last page,
      // so putting the ...last is silly. Just display it normally.
      $link_to_page = $current_display_page - 1;
      $pager_array[$link_to_page] = l($current_display_page, "node/$topic->nid", array('query' => array('page' => $link_to_page)));
    }

    if ($current_display_page < $last_display_page) {
      // We are one past the max to display and still aren't
      // on the last page, so put in ... Last Page(N)
      $text = t('Last Page');
      $pager_last_text = l($text, "node/$topic->nid", array('query' => array('page' => $last_pager_page)));
      $pager_last_number = l($last_display_page, "node/$topic->nid", array('query' => array('page' => $last_pager_page)));
      // Create last page array to enable more customization for themers.
      $pager_last = array(
        'number' => $last_display_page,
        'link' => "node/$topic->nid",
        'options' => array('query' => array('page' => $last_pager_page)),
      );
    }

    $topic_pager = new stdClass();
    $topic_pager->initial_pages = (empty($pager_array)) ? array() : $pager_array;
    $topic_pager->last_page_text = (empty($pager_last_text)) ? '' : $pager_last_text;
    $topic_pager->last_page_number = (empty($pager_last_number)) ? '' : $pager_last_number;
    $topic_pager->last_page = (empty($pager_last)) ? array() : $pager_last;

    return $topic_pager;
  }
}

/**
 * Create a drop down list of forum hierarchy
 */
function advanced_forum_forum_jump($tid = 0) {
  global $user;
  ctools_include('jump-menu');
  $select = array();
  $options = array();
  $vid = variable_get('forum_nav_vocabulary', 0);
  if ($tid > 0) {
    $forum_tree = taxonomy_get_tree($vid);
    foreach ($forum_tree as $forum) {
      $select[url("forum/" . $forum->tid)] = str_repeat("-", $forum->depth) . $forum->name;
    }
  }
  else {
    // nothing
  }

  $options['choose'] = t("- Select a forum -");

  // Create and return the jump menu.
  $form = drupal_get_form('ctools_jump_menu', $select, $options);
  return drupal_render($form);
}

/**
 * Calculates the number of unread replies for each forum and returns the
 * count for the requested forum.
 */
function advanced_forum_unread_replies_in_forum($tid, $uid) {
  static $result_cache = NULL;

  if (is_null($result_cache)) {
    $result_cache = array();

    $query = db_select("comment", "c");
    $f_alias = $query->join("forum", "f", "c.nid = f.nid");
    //$n_alias = $query->join("node", "n", "f.vid = n.vid");
    $h_alias = $query->leftJoin("history", "h", "c.nid = h.nid AND h.uid = :uid", array(":uid" => $uid));
    $query->addExpression("COUNT(DISTINCT(c.cid))", "count");
    $query->addField($f_alias, "tid");

    $query->condition("c.status", COMMENT_PUBLISHED)
        ->condition("c.changed", NODE_NEW_LIMIT, ">")
        ->condition(db_or()->where("c.changed > {$h_alias}.timestamp")->isNull("h.timestamp"))
        ->groupBy("{$f_alias}.tid")
        ->addTag("node_access");

    $result = $query->execute();
    foreach ($result as $row) {
      $result_cache[$row->tid] = $row->count;
    }
  }

  return (isset($result_cache[$tid])) ? $result_cache[$tid] : 0;
}

/**
 * Returns the display position of a given reply post ID on a given node.
 */
function advanced_forum_post_position($node, $comment) {
  static $post_order = array();

  if (empty($node) || empty($comment)) {
    return 0;
  }

  $node_id = $node->nid;
  $post_id = $comment->cid;

  if (!isset($post_order[$node_id])) {
    // Initialize the spot for this node's list.
    $post_order[$node_id] = array();

    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);

    // Get the list of CIDs from the database in order of oldest first.
    // We are going to make that assumption for now for simplicity but may
    // revisit in the future if there are requests for newest first.
    $query = db_select('comment', 'c')
        ->fields('c', array('cid'))
        ->condition('c.nid', $node_id)
        ->addTag('node_access')
        ->addTag('comment_filter');

    if ($mode === COMMENT_MODE_FLAT) {
      $query->orderBy('c.cid', 'ASC');
    }
    else {
      $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
      $query->orderBy('torder', 'ASC');
    }

    $query = $query->execute();
    // Cycle through the results and fill in the array.
    while ($post = $query->fetchAssoc()) {
      $post_order[$node_id][] = reset($post);
    }
  }

  // Find the position of the passed in post ID.
  $post_position = 0;
  if (is_array($post_order[$node_id])) {
    if (($index = array_search($post_id, $post_order[$node_id])) !== FALSE) {
      $post_position = $index;

      // We need to add 2 because the array starts at 0 and also because the topic
      // node is post #1 on display but is not included in the index.
      $post_position = $post_position + 2;
    }
  }

  return $post_position;
}