Projet

Général

Profil

Paste
Télécharger (42,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / advanced_forum / advanced_forum.module @ 503b3f7b

1
<?php
2

    
3
/**
4
 * @file
5
 * Enables the look and feel of other popular forum software.
6
 */
7
// DRUPAL HOOKS **************************************************************/
8

    
9
/**
10
 * Implementation of hook_perm().
11
 */
12
function advanced_forum_permission() {
13
  return array(
14
    'administer advanced forum' => array(
15
      'title' => t('Administer Advanced Forum')
16
    ),
17
    'view forum statistics' => array(
18
      'title' => t('View Advanced Forum statistics')
19
    ),
20
    'view last edited notice' => array(
21
      'title' => t('View last edited notice')
22
    )
23
  );
24
}
25

    
26
/**
27
 * Implementation of hook_menu().
28
 */
29
function advanced_forum_menu() {
30
  $items['admin/config/content/advanced-forum'] = array(
31
    'access arguments' => array('administer advanced forum'),
32
    'description' => 'Configure Advanced Forum with these settings.',
33
    'page arguments' => array('advanced_forum_settings_page'),
34
    'page callback' => 'drupal_get_form',
35
    'title' => 'Advanced Forum',
36
    'file' => 'includes/settings.inc'
37
  );
38

    
39
  $items['forum/markasread'] = array(
40
    'access callback' => 'advanced_forum_markasread_access',
41
    'page callback' => 'advanced_forum_markasread',
42
    'type' => MENU_CALLBACK,
43
  );
44

    
45
  if (variable_get('advanced_forum_add_local_task', TRUE)) {
46
    $items['forum/view'] = array(
47
      'title' => 'View Forums',
48
      'page callback' => 'advanced_forum_page',
49
      'type' => MENU_DEFAULT_LOCAL_TASK,
50
      'weight' => -100,
51
    );
52
  }
53

    
54
  return $items;
55
}
56

    
57
/**
58
 * Implementation of hook_cron().
59
 */
60
function advanced_forum_cron() {
61
  // ensure the reply stats are up-to-date
62
  advanced_forum_statistics_replies(NULL, TRUE);
63
}
64

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

    
74

    
75
  // Take over forum/%forum_forum page because we want advanced_forum_forum_load
76
  // is called instead of core forum_forum_load
77
  $items['forum/%advanced_forum_forum'] = $items['forum/%forum_forum'];
78
  $items['forum/%advanced_forum_forum']['page callback'] = 'advanced_forum_page';
79
  $items['forum/%advanced_forum_forum']['module'] = 'advanced_forum';
80
  unset($items['forum/%advanced_forum_forum']['file']);
81
  unset($items['forum/%forum_forum']);
82
}
83

    
84
/**
85
 * Implements hook_menu_local_tasks_alter().
86
 *
87
 * Unset all items set in core forum_menu_local_tasks_alter
88
 */
89
function advanced_forum_menu_local_tasks_alter(&$data, $router_item, $root_path) {
90
  if ($root_path == 'forum' || $root_path == 'forum/%') {
91
    $data['actions']['output'] = array();
92
  }
93
}
94

    
95
/**
96
 * Implementation of hook_module_implements_alter().
97
 *
98
 * We don't want forum_menu_local_tasks_alter() to be called and mess with our links.
99
 *
100
 */
101
function advanced_forum_module_implements_alter(&$implementations, $hook) {
102
  if ($hook == 'menu_local_tasks_alter') {
103
    unset($implementations['forum']);
104
  }
105
}
106

    
107
/**
108
 * Implementation of hook_theme().
109
 */
110
function advanced_forum_theme() {
111
  advanced_forum_load_style_includes();
112

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

    
116
  $items['advanced_forum_l'] = array(
117
    'variables' => array(
118
      'text' => NULL,
119
      'path' => NULL,
120
      'options' => array(),
121
      'button_class' => NULL,
122
    )
123
  );
124

    
125
  $items['advanced_forum_topic_header'] = array(
126
    'variables' => array(
127
      'node' => NULL,
128
      'comment_count' => NULL,
129
    )
130
  );
131

    
132
  $items['advanced_forum_active_poster'] = array(
133
    'variables' => array(
134
      'forum' => NULL,
135
      'account' => NULL,
136
      'posts' => NULL,
137
      'topics' => NULL,
138
      'last_post' => NULL,
139
    )
140
  );
141

    
142
  $items['advanced_forum_user_picture'] = array(
143
    'variables' => array(
144
      'account' => NULL,
145
    )
146
  );
147

    
148
  $items['advanced_forum_reply_link'] = array(
149
    'variables' => array(
150
      'node' => NULL,
151
    )
152
  );
153

    
154
  $items['advanced_forum_topic_pager'] = array(
155
    'variables' => array(
156
      'pagecount' => NULL,
157
      'topic' => NULL,
158
    )
159
  );
160

    
161
  $items['advanced_forum_shadow_topic'] = array(
162
    'variables' => array(
163
      'title' => NULL,
164
      'nid' => NULL,
165
      'new_forum' => NULL,
166
    )
167
  );
168

    
169
  $items['advanced_forum_subforum_list'] = array(
170
    'variables' => array(
171
      'subforum_list' => NULL,
172
    )
173
  );
174

    
175
  $items['advanced_forum_subcontainer_list'] = array(
176
    'variables' => array(
177
      'subcontainer_list' => NULL,
178
    )
179
  );
180

    
181
  $items['advanced_forum_simple_author_pane'] = array(
182
    'variables' => array(
183
      'context' => NULL,
184
    )
185
  );
186

    
187
  $items['advanced_forum_post_edited'] = array(
188
    'variables' => array(
189
      'who' => NULL,
190
      'when' => NULL,
191
      'why' => NULL,
192
    )
193
  );
194

    
195
  $items['advanced_forum_node_type_create_list'] = array(
196
    'variables' => array(
197
      'forum_id' => NULL,
198
    )
199
  );
200
  /*
201
    // Templates for features added by Views
202

    
203
    // style
204
    $items['views_view_forum_topic_list__advanced_forum_topic_list'] = array(
205
    'variables' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
206
    'template' => 'advanced-forum-topic-list-view',
207
    //'base hook' => 'views_view_forum_topic_list',
208
    );
209
   */
210
  //display
211
  $items['views_view__advanced_forum_topic_list'] = array(
212
    'variables' => array('view' => NULL),
213
    'template' => 'advanced-forum-topic-list-outer-view',
214
      //'base hook' => 'views_view',
215
  );
216

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

    
224
  // Return merged items found in style folder with new ones
225
  // array_merge_recursive doesn't work as desired
226
  foreach ($items as $key => $item) {
227
    if (array_key_exists($key, $existing_items)) {
228
      $existing_items[$key] += $item;
229
    }
230
    else {
231
      $existing_items[$key] = $item;
232
    }
233
  }
234

    
235
  return $existing_items;
236
}
237

    
238
/**
239
 * Implementation of hook_theme_registry_alter().
240
 */
241
function advanced_forum_theme_registry_alter(&$theme_registry) {
242
  advanced_forum_load_style_includes();
243

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

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

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

    
267
  // --- The following section manipulates the theme registry so the .tpl files
268
  // --- for the given templates can be found first in the (sub)theme directory
269
  // --- then in ancestor themes, if any, then in the active style directory
270
  // --- for advanced forum or any ancestor styles.
271
  // Affected templates
272
  $templates = array(
273
    'node',
274
    'comment',
275
    'comment_wrapper',
276
    'forums',
277
    'forum_list',
278
    'forum_topic_list',
279
    'forum_icon',
280
    'forum_submitted',
281
    'author_pane',
282
      /*
283
        'advanced_forum_statistics',
284
        'advanced_forum_topic_list_view',
285
        'advanced_forum_topic_legend',
286
        'advanced_forum_forum_legend',
287
        'advanced_forum_topic_header',
288
        'advanced_forum_active_poster', */
289
  );
290

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

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

    
300
  // Get theme engine extension
301
  global $theme_engine;
302
  $extension = '.tpl.php';
303
  if (isset($theme_engine)) {
304
    $extension_function = $theme_engine . '_extension';
305
    if (function_exists($extension_function)) {
306
      $extension = $extension_function();
307
    }
308
  }
309

    
310
  foreach ($templates as $template) {
311
    // Sanity check in case the template is not being used.
312
    if (!empty($theme_registry[$template])) {
313
      // There are preprocess functions to add, so figure out where we want to add
314
      // them.
315
      if (!empty($preprocess)) {
316
        $position = 0;
317
        foreach ($theme_registry[$template]['preprocess functions'] as $function) {
318
          $position++;
319
          // If we see either of these items, that means we can place our
320
          // preprocess functions after this.
321
          if (substr($function, 0, 25) == 'advanced_forum_preprocess' || substr($function, 0, 34) == 'template_preprocess_advanced_forum') {
322
            break;
323
          }
324
        }
325
        // Add in our new preprocess functions:
326
        array_splice($theme_registry[$template]['preprocess functions'], $position, 0, $preprocess);
327
      }
328
    }
329
  }
330

    
331

    
332
  // temp workaround
333
  array_splice($theme_registry['views_view__advanced_forum_topic_list']['preprocess functions'], 1, 0, 'template_preprocess_views_view');
334
  array_splice($theme_registry['views_view__advanced_forum_group_topic_list']['preprocess functions'], 1, 0, 'template_preprocess_views_view');
335
  //array_splice($theme_registry['views_view_forum_topic_list__advanced_forum_topic_list']['preprocess functions'], 1, 0, 'template_preprocess_views_view_forum_topic_list');
336
}
337

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

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

    
354
  if (!empty($object->content['links']['comment'])) {
355
    $comment_links = $object->content['links']['comment'];
356
    $links = empty($comment_links['#links']) ? array() : $comment_links['#links'];
357
  }
358
  else {
359
    $comment_links = array();
360
    $links = array();
361
  }
362

    
363
  if ($object_type == 'node') {
364

    
365
    $node = $object;
366
    // Add edit / delete links to the node links to match replies.
367
    if (node_access('update', $node)) {
368
      $links['post-edit'] = array(
369
        'title' => t('edit'),
370
        'href' => 'node/' . $node->nid . '/edit',
371
        'query' => drupal_get_destination(),
372
      );
373
    }
374

    
375
    if (node_access('delete', $node)) {
376
      $links['post-delete'] = array(
377
        'title' => t('delete'),
378
        'href' => 'node/' . $node->nid . '/delete',
379
      );
380
    }
381
  }
382

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

    
389

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

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

    
402
  // Put the links in a consistent order.
403
  foreach ($affected_keys as $key) {
404
    if (isset($links[$key])) {
405
      $temp = $links[$key];
406
      unset($links[$key]);
407
      $links[$key] = $temp;
408
    }
409
  }
410

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

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

    
419
/**
420
 * Implementation of hook_node_view().
421
 *
422
 * hook_link() and hook_link_alter() functionalty implemented here
423
 */
424
function advanced_forum_node_view($node, $view_mode, $langcode) {
425
  advanced_forum_links_alter($node, $view_mode, 'node');
426
}
427

    
428
/**
429
 * Implementation of hook_comment_view().
430
 */
431
function advanced_forum_comment_view($comment, $view_mode, $langcode) {
432
  advanced_forum_links_alter($comment, $view_mode, 'comment');
433
}
434

    
435
/**
436
 * Implementation of hook_comment_delete().
437
 */
438
function advanced_forum_comment_delete($comment) {
439
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
440
    advanced_forum_statistics_replies(-1);
441
  }
442
}
443

    
444
/**
445
 * Implementation of hook_comment_insert().
446
 */
447
function advanced_forum_comment_insert($comment) {
448
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
449
    advanced_forum_statistics_replies(1);
450
  }
451
}
452

    
453
/**
454
 * Implementation of hook_comment_update().
455
 */
456
function advanced_forum_comment_update($comment) {
457
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
458
    // comment unpublished?
459
    if (!$comment->status) {
460
      advanced_forum_statistics_replies(-1);
461
    }
462
  }
463
}
464

    
465
/**
466
 * Implementation of hook_comment_publish().
467
 */
468
function advanced_forum_comment_publish($comment) {
469
  if (!empty($comment->node_type) && ($comment->node_type == "comment_node_forum")) {
470
    advanced_forum_statistics_replies(1);
471
  }
472
}
473

    
474
/**
475
 * Implementation of hook_form_alter().
476
 */
477
function advanced_forum_form_alter(&$form, &$form_state, $form_id) {
478
  if (!empty($form['#node']->type) && advanced_forum_type_is_in_forum($form['#node']) && isset($form['body_field']) && isset($form['body_field']['#after_build'])) {
479
    // Remove the teaser splitter.
480
    $teaser_js_build = array_search('node_teaser_js', $form['body_field']['#after_build']);
481
    unset($form['body_field']['#after_build'][$teaser_js_build]);
482
    $form['body_field']['teaser_js']['#access'] = FALSE;
483
    $form['body_field']['teaser_include']['#access'] = FALSE;
484
  }
485

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

    
492
// MAKE VIEWS BITS WORK *****************************************************/
493
function advanced_forum_views_api() {
494
  return array(
495
    'api' => '3.0-alpha1',
496
    'path' => drupal_get_path('module', 'advanced_forum') . '/includes/views',
497
  );
498
}
499

    
500
// MAKE CTOOLS BITS WORK *****************************************************/
501
/**
502
 * Tell CTools about what plugins we support.
503
 */
504
function advanced_forum_ctools_plugin_directory($module, $plugin) {
505
  if ($module == 'advanced_forum') {
506
    return 'styles';
507
  }
508

    
509
  if ($module == 'page_manager' || $module == 'ctools') {
510
    return 'plugins/' . $plugin;
511
  }
512
}
513

    
514
function advanced_forum_ctools_plugin_api($module, $api) {
515
  if ($module == 'page_manager' && $api = 'pages_default') {
516
    return array(
517
      'version' => 1,
518
      'path' => drupal_get_path('module', 'advanced_forum') . '/includes/panels',
519
    );
520
  }
521
}
522

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

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

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

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

    
535
// VIEWS RELATED GOODIES ******************************************************/
536

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

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

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

    
554
    // Replace the Author Pane token with the actual Author Pane.
555
    if (preg_match_all('/<!--post:author-pane-([\d]+)-->/us', $output, $matches)) {
556
      foreach ($matches[1] as $match => $uid) {
557
        $token = $matches[0][$match]; // This is the exact string that matched.
558
        if (!isset($tokens[$token])) {
559
          $account = user_load($uid);
560
          $tokens[$token] = theme('author_pane', array(
561
            'account' => $account,
562
            'caller' => 'advanced_forum',
563
            'picture_preset' => variable_get('advanced_forum_user_picture_preset', ''),
564
            'context' => NULL,
565
            'disable_css' => TRUE,
566
            'join_date_type' => variable_get('advanced_forum_author_pane_join_date_type', 'short'),
567
          ));
568
        }
569
      }
570
    }
571

    
572
    // Replace the Post edited token.
573
    if (preg_match_all('/<!--post:post-edited-([\d]+)-->/us', $output, $matches)) {
574
      foreach ($matches[1] as $match => $nid) {
575
        $token = $matches[0][$match]; // This is the exact string that matched.
576
        if (!isset($tokens[$token])) {
577
          if (user_access('view last edited notice')) {
578
            $sql = 'SELECT uid, log, timestamp FROM {node_revision} WHERE nid = %d ORDER BY timestamp DESC';
579
            $row = db_fetch_object(db_query($sql, $nid));
580
            $tokens[$token] = theme('advanced_forum_post_edited', array(
581
              'who' => $row->uid,
582
              'when' => $row->timestamp,
583
              'why' => $row->log
584
            ));
585
          }
586
          else {
587
            // No access; remove token.
588
            $tokens[$token] = '';
589
          }
590
        }
591
      }
592
    }
593

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

    
607
    // Perform replacements.
608
    $output = strtr($output, $tokens);
609
  }
610
}
611

    
612
/**
613
 * Display the "sort" widget. This is a specially hacked widget that only
614
 * works with tablesorting. Tablesorting MUST be on for these widgets
615
 * to appear.
616
 */
617
function advanced_forum_forum_topic_list_sort() {
618
  $form_state = array(
619
    'method' => 'get',
620
    'no_redirect' => TRUE,
621
    'rerender' => TRUE,
622
    'input' => $_GET,
623
    'drop tokens' => TRUE,
624
  );
625

    
626
  $form = drupal_build_form('advanced_forum_forum_topic_list_sort_form', $form_state);
627
  return drupal_render($form);
628
}
629

    
630
function advanced_forum_forum_topic_list_sort_form($form_state) {
631
  $view = views_get_view('advanced_forum_topic_list');
632
  $view->set_display('default');
633
  $view->init_handlers();
634
  $view->init_style();
635

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

    
641
  $options = array();
642
  foreach ($columns as $field => $column) {
643
    if ($field == $column && empty($fields[$field]->options['exclude'])) {
644
      if (empty($handler->options['info'][$field]['sortable']) || !$fields[$field]->click_sortable()) {
645
        continue;
646
      }
647
      $label = check_plain(!empty($fields[$field]) ? $fields[$field]->label() : '');
648
      $options[$field] = $label;
649
    }
650
  }
651

    
652
  $form['inline'] = array(
653
    '#prefix' => '<div class="container-inline">',
654
    '#suffix' => '</div>',
655
  );
656
  $form['inline']['order'] = array(
657
    '#type' => 'select',
658
    '#title' => t('Order by'),
659
    '#title_display' => 'invisible',
660
    '#options' => $options,
661
    '#default_value' => $handler->options['default'],
662
  );
663

    
664
  $form['inline']['sort'] = array(
665
    '#type' => 'select',
666
    '#title' => t('Sort'),
667
    '#title_display' => 'invisible',
668
    '#options' => array(
669
      'asc' => t('Up'),
670
      'desc' => t('Down'),
671
    ),
672
    '#default_value' => 'desc',
673
  );
674

    
675
  $form['inline']['submit'] = array(
676
    '#id' => 'sort-topic-submit',
677
    '#name' => '',
678
    '#type' => 'submit',
679
    '#value' => t('Sort'),
680
  );
681

    
682
  if (isset($_GET['page'])) {
683
    $form['page'] = array(
684
      '#type' => 'hidden',
685
      '#default_value' => $_GET['page'],
686
    );
687
  }
688

    
689
  if (!variable_get('clean_url', FALSE)) {
690
    $form['q'] = array(
691
      '#type' => 'hidden',
692
      '#value' => $_GET['q'],
693
    );
694
  }
695

    
696
  $view->destroy();
697
  return $form;
698
}
699

    
700
// STATISTICS *****************************************************************/
701

    
702
/**
703
 * Count total amount of forum threads.
704
 */
705
function advanced_forum_statistics_topics() {
706
  return db_query('SELECT COUNT(DISTINCT(nid)) FROM {forum}')->fetchField();
707
}
708

    
709
/**
710
 * Counts total amount of replies. Initial posts are added to this total
711
 * in the calling function.
712
 *
713
 * @param $delta
714
 *   if not NULL, a numerical delta which should be applied to the count
715
 * @param $refresh
716
 * @param $refresh
717
 *   TRUE if the stored count should be updated.
718
 * @return
719
 *   Total number of replies in the forum.
720
 */
721
function advanced_forum_statistics_replies($delta = NULL, $refresh = FALSE) {
722

    
723
  if ($refresh || !($cache = cache_get('advanced_forum_stats_replies'))) {
724
    $total_replies = db_query('SELECT SUM(comment_count) FROM {forum_index}')->fetchField();
725
    cache_set('advanced_forum_stats_replies', $total_replies);
726
  }
727
  else {
728
    $total_replies = $cache->data;
729
  }
730

    
731

    
732
  if (!empty($delta) && is_numeric($delta)) {
733
    $total_replies += $delta;
734
    cache_set('advanced_forum_stats_replies', $total_replies);
735
  }
736

    
737
  return $total_replies;
738
}
739

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

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

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

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

    
764
  return $list;
765
}
766

    
767
function advanced_forum_session_count($anonymous = TRUE) {
768

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

    
771
  $query = db_select("sessions", "s")
772
      ->fields("s", array("uid"))
773
      ->distinct()
774
      ->condition('s.timestamp', $interval, '>=')
775
      ->condition('s.uid', 0, $anonymous ? '=' : '>')
776
      ->countQuery();
777

    
778
  return $query->execute()->fetchField();
779
}
780

    
781
/**
782
 * Return an array of online usernames, linked to their profiles.
783
 */
784
function advanced_forum_statistics_online_users() {
785
  $list = array();
786

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

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

    
792
  $query->addExpression("MAX({$s_alias}.timestamp)", "maxtime");
793
  $query
794
      ->condition("{$s_alias}.timestamp", $interval, ">=")
795
      ->condition("{$s_alias}.uid", "0", ">")
796
      ->groupBy("u.uid, u.name")
797
      ->orderBy("maxtime", "DESC");
798

    
799
  $authenticated_users = $query->execute();
800

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

    
805
  return $list;
806
}
807

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

    
810
function advanced_forum_get_reply_link($node) {
811
  $reply_link = array();
812

    
813
  $comment_setting = $node->comment;
814
  $fragment = 'comment-form';
815

    
816
  if ($comment_setting == COMMENT_NODE_OPEN) {
817

    
818
    $allowed = FALSE;
819
    if (module_exists('forum_access')) {
820
      // get tid
821
      if (!empty($node->taxonomy_forums)) {
822
        reset($node->taxonomy_forums);
823
        $langcode = key($node->taxonomy_forums);
824
        if (!empty($node->taxonomy_forums[$langcode])) {
825
          $tid = $node->taxonomy_forums[$langcode][0]['tid'];
826
          if (forum_access_access('create', $tid)) {
827
            $allowed = TRUE;
828
          }
829
        }
830
      }
831
    }
832
    else {
833
      $allowed = user_access('post comments');
834
    }
835

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

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

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

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

    
860
        return $reply_link;
861
      }
862
    }
863
    else {
864
      // User does not have access to post replies on this node.
865
      return 'reply-forbidden';
866
    }
867
  }
868
  else {
869
    // Topic is locked.
870
    return 'reply-locked';
871
  }
872
}
873

    
874
/**
875
 * Get a link to the last post in a topic.
876
 *
877
 * @param $node
878
 *   Node object
879
 * @return
880
 *   Text linking to the last post in a topic.
881
 */
882
function advanced_forum_last_post_link($node) {
883
  $last_comment_id = advanced_forum_last_post_in_topic($node->nid);
884
  // Return empty link if post doesn't have comments.
885
  if (empty($last_comment_id))
886
    return '';
887

    
888
  $last_page = advanced_forum_get_last_page($node);
889

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

    
893
  $options = array(
894
    'html' => TRUE,
895
    'query' => empty($query) ? array() : $query,
896
    'fragment' => "comment-$last_comment_id",
897
  );
898

    
899
  return theme('advanced_forum_l', array(
900
    'text' => t('Last post'),
901
    'path' => "node/$node->nid",
902
    'options' => $options,
903
    'button_class' => 'large'
904
  ));
905
}
906

    
907
/**
908
 * Returns a link directly to the first new post in a topic.
909
 *
910
 * @param $node
911
 *   Node object
912
 * @param $comment_count
913
 *   Number of comments on passed node.
914
 * @return
915
 *   Link to the first unread post.
916
 */
917
function advanced_forum_first_new_post_link($node, $comment_count) {
918
  $nid = $node->nid;
919

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

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

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

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

    
932
    $options = array(
933
      'html' => TRUE,
934
      'query' => $page_of_first_new,
935
      'fragment' => "comment-$cid_of_first_new"
936
    );
937

    
938
    return theme('advanced_forum_l', array(
939
      'text' => t('First unread'),
940
      'path' => "node/$nid",
941
      'options' => $options,
942
      'button_class' => 'large'
943
    ));
944
  }
945
}
946

    
947
/**
948
 * Get the page number with the first new post.
949
 */
950
function advanced_forum_page_first_new($comment_count, $new_replies, $node) {
951
  return comment_new_page_count($comment_count, $new_replies, $node);
952
}
953

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

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

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

    
969
    $node = node_load($nid);
970

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

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

    
982
  return $number_new_for_node[$nid];
983
}
984

    
985
/**
986
 * Get the comment id of the last post in a topic.
987
 *
988
 * @param $node
989
 *   Node object
990
 * @return
991
 *   cid of last post.
992
 */
993
function advanced_forum_last_post_in_topic($nid) {
994
  // $nid is empty if new topic in preview.
995
  if (empty($nid))
996
    return NULL;
997

    
998
  $node = node_load($nid);
999

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

    
1007
  return $result;
1008
}
1009

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

    
1020
/**
1021
 * Returns the ID of the first unread comment.
1022
 *
1023
 * @param $nid
1024
 *   Node ID
1025
 * @param $timestamp
1026
 *   Date/time used to override when the user last viewed the node.
1027
 * @return
1028
 *   Comment ID
1029
 */
1030
function advanced_forum_first_new_comment($nid, $timestamp = 0) {
1031
  global $user;
1032

    
1033
  if ($user->uid) {
1034
    // Retrieve the timestamp at which the current user last viewed the
1035
    // specified node.
1036
    if (!$timestamp) {
1037
      $timestamp = node_last_viewed($nid);
1038
    }
1039

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

    
1043
    // Use the timestamp to retrieve the oldest new comment.
1044
    $query = db_select('comment', 'c')
1045
        ->fields('c', array('cid'))
1046
        ->condition('nid', $nid)
1047
        ->condition('changed', $timestamp, '>')
1048
        ->condition('status', COMMENT_PUBLISHED)
1049
        ->range(0, 1)
1050
        ->execute();
1051
    return $query->fetchField();
1052
  }
1053
  else {
1054
    return 0;
1055
  }
1056
}
1057

    
1058
// GENERAL UTILITY FUNCTIONS *************************************************/
1059

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

    
1072
  $field = field_info_field('taxonomy_forums');
1073
  if (!empty($field['bundles']['node'])) {
1074
    return $field['bundles']['node'];
1075
  }
1076
  else {
1077
    return array();
1078
  }
1079
}
1080

    
1081
/**
1082
 * Return whether a given node type is allowed in the whole forum or given forum.
1083
 */
1084
function advanced_forum_type_is_in_forum($node, $tid = 0) {
1085
  $vid = (empty($vid)) ? variable_get('forum_nav_vocabulary', 0) : $vid;
1086
  if (!empty($node->taxonomy_forums)) {
1087
    // Check for language used
1088
    if (!isset($node->taxonomy_forums[$node->language])) {
1089
      $langcode = LANGUAGE_NONE;
1090
    }
1091
    else {
1092
      $langcode = $node->language;
1093
    }
1094

    
1095
    foreach ($node->taxonomy_forums[$langcode] as $tforum) {
1096
      if (!isset($tforum['taxonomy_term'])) {
1097
        continue;
1098
      }
1099
      if (($tforum['taxonomy_term']->vid == $vid) || ($tforum['taxonomy_term']->tid == $tid))
1100
        return TRUE;
1101
    }
1102
  }
1103
  return FALSE;
1104
}
1105

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

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

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

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

    
1140
  if (empty($forum_types)) {
1141
    // The user is logged-in; but denied access to create any new forum content type.
1142
    global $user;
1143
    if ($user->uid) {
1144
      return t('You are not allowed to post new content in the forum.');
1145
    }
1146
    // The user is not logged-in; and denied access to create any new forum content type.
1147
    else {
1148
      return t('<a href="@login">Log in</a> to post new content in the forum.', array(
1149
        '@login' => url('user/login', array('query' => drupal_get_destination())),
1150
      ));
1151
    }
1152
  }
1153
  else {
1154
    return $forum_types;
1155
  }
1156
}
1157

    
1158
/**
1159
 * Create a drop down list of forum actions.
1160
 */
1161
function advanced_forum_forum_tools($tid = 0) {
1162
  global $user;
1163
  $options = array();
1164

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

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

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

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

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

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

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

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

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

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

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

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

    
1241
    // Move to the next page
1242
    $current_display_page++;
1243

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

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

    
1265
    $topic_pager = new stdClass();
1266
    $topic_pager->initial_pages = (empty($pager_array)) ? array() : $pager_array;
1267
    $topic_pager->last_page_text = (empty($pager_last_text)) ? '' : $pager_last_text;
1268
    $topic_pager->last_page_number = (empty($pager_last_number)) ? '' : $pager_last_number;
1269
    $topic_pager->last_page = (empty($pager_last)) ? array() : $pager_last;
1270

    
1271
    return $topic_pager;
1272
  }
1273
}
1274

    
1275
/**
1276
 * Create a drop down list of forum hierarchy
1277
 */
1278
function advanced_forum_forum_jump($tid = 0) {
1279
  global $user;
1280
  ctools_include('jump-menu');
1281
  $select = array();
1282
  $options = array();
1283
  $vid = variable_get('forum_nav_vocabulary', 0);
1284
  if ($tid > 0) {
1285
    $forum_tree = taxonomy_get_tree($vid);
1286
    foreach ($forum_tree as $forum) {
1287
      $select[url("forum/" . $forum->tid)] = str_repeat("-", $forum->depth) . $forum->name;
1288
    }
1289
  }
1290
  else {
1291
    // nothing
1292
  }
1293

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

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

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

    
1308
  if (is_null($result_cache)) {
1309
    $result_cache = array();
1310

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

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

    
1324
    $result = $query->execute();
1325
    foreach ($result as $row) {
1326
      $result_cache[$row->tid] = $row->count;
1327
    }
1328
  }
1329

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

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

    
1339
  if (empty($node) || empty($comment)) {
1340
    return 0;
1341
  }
1342

    
1343
  $node_id = $node->nid;
1344
  $post_id = $comment->pid;
1345

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

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

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

    
1361
    if ($mode === COMMENT_MODE_FLAT) {
1362
      $query->orderBy('c.cid', 'ASC');
1363
    }
1364
    else {
1365
      $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
1366
      $query->orderBy('torder', 'ASC');
1367
    }
1368

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

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

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

    
1388
  return $post_position;
1389
}