boinc_solr_comments_apachesolr_index_documents_alter()   F
last analyzed

Complexity

Conditions 29
Paths > 20000

Size

Total Lines 153
Code Lines 77

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 29
eloc 77
nc 55310
nop 4
dl 0
loc 153
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// $Id$
3
4
/**
5
 * @file
6
 * Module indexes comments in nodes for apache solr.
7
 */
8
9
/*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
10
 * Hooks into drupal
11
 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  */
12
13
/**
14
 * Implementation of hook_menu()
15
 */
16
function boinc_solr_comments_menu() {
17
  $items = array();
18
  $base_path = 'admin/settings/apachesolr/indexcomments';
19
  $items[$base_path] = array(
20
      'title' => 'Index Comments',
21
      'description' => 'Administer Indexing of Comments',
22
      'page callback' => 'drupal_get_form',
23
      'page arguments' => array('boinc_solr_comments_form'),
24
      'access arguments' => array('administer search'),
25
      'file' => 'boinc_solr_comments.admin.inc',
26
      'weight' => '10',
27
  );
28
29
  return $items;
30
}
31
32
33
/*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
34
 * Hooks into apache solr
35
 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  */
36
37
/**
38
 * Implementation of hook_apachesolr_index_documents_alter()
39
 *
40
 * This function separates the comments from a parent node and indexes
41
 * the individual comments as separate ApacheSolrDocuments.
42
 *
43
 * The function loads each node’s Solr document, and removes the
44
 * ts_comments field. Then it loops over all the node's comments found
45
 * with a db_query and creates separate ApacheSolrDocument objects for
46
 * each one.
47
 *
48
 * At the end, the new documents representing the comments are merged
49
 * with the input $documents array.
50
 *
51
 * @param array $documents
52
 *   Array of ApacheSolrDocument which are to be indexed
53
 * @param string $entity
54
 *   The entity object, typically a node object.
55
 * @param string $entity_type
56
 *   The entity's type, typically 'node'.
57
 * @param $env_id
58
 *   Environment ID for apache solr.
59
 */
60
function boinc_solr_comments_apachesolr_index_documents_alter(array &$documents, $entity, $entity_type, $env_id) {
61
  $comdocs = array();
62
63
  // Array of node types that will have comments indexed.
64
  $node_types = variable_get('boinc_solr_comments_nodetypes', '');
65
  if (empty($node_types)) {
66
    // If the variable has not been set, then by default index
67
    // comments for all known node types.
68
    $node_types = array(
69
        'forum'      => 'forum',
70
        'news'       => 'news',
71
        'page'       => 'page',
72
        'story'      => 'story',
73
        'team_forum' => 'team_forum',
74
    );
75
  }
76
77
  // Loop over all documents and alter:
78
  foreach ($documents as $document) {
79
    //dd($document, "index documents alter - document");
80
81
    $to_process = ( array_key_exists($document->bundle, $node_types) AND $node_types[$document->bundle] );
82
    if ( $document->entity_type=='node' AND $to_process) {
83
84
      // Remove ts_comments if present.
85
      if (isset($document->ts_comments)) {
86
        unset($document->ts_comments);
87
      }
88
      // Node information.
89
      $nid = $document->entity_id;
90
      $node = node_load($nid);
91
92
      // Query database for comments of node. Only return comments
93
      // with status 0 (0 is published for comments).
94
      $sql = 'SELECT cid from {comments} WHERE nid = %d AND status = 0 ORDER by timestamp DESC';
95
      $resource = db_query($sql, $nid);
96
      while ($row = db_fetch_array($resource)) {
97
        // Load the comment from cid.
98
        $comment = _comment_load($row['cid']);
99
100
        // Code derived from _apachesolr_index_process_entity_get_document
101
        $url_options = array('absolute' => TRUE);
102
        $comment_document = new ApacheSolrdocument();
103
104
        $comment_document->id = apachesolr_document_id($comment->cid, 'comment');
105
        $comment_document->site = $document->site;
106
        $comment_document->hash = apachesolr_site_hash();
107
108
        $comment_document->entity_id = $comment->cid;
109
        $comment_document->entity_type = 'comment';
110
        $comment_document->bundle = 'Comment';
111
        $comment_document->bundle_name = 'Comment';
112
113
        $comment_document->path = 'goto/comment/' . $comment->cid;
114
        $comment_document->url = url($comment_document->path, $url_options);
115
116
        // Comment object has no language
117
        $comment_document->ss_language = 'und';
118
        if (function_exists('drupal_get_path_alias')) {
119
          $output = drupal_get_path_alias($comment_document->path, NULL);
120
          if ($output && $output != $document->path) {
121
            $comment_document->path_alias = $output;
122
          }
123
        }
124
125
        // Code derived from apachesolr_index_node_solr_document
126
        $comment_document->label = truncate_utf8(apachesolr_clean_text($comment->comment), 32, TRUE);
127
        $comment_document->content = apachesolr_clean_text($comment->comment);
128
        $comment_document->teaser = truncate_utf8($document->content, 300, TRUE);
129
130
        // Author information
131
        if ($comment->uid == 0 || strlen($comment->name) == 0) {
132
          // @see user_validate_name(). !'0' === TRUE.
133
          $comment_document->ss_name = '0';
134
        }
135
        else {
136
          $comment_document->ss_name = $comment->name;
137
          // We want the name to be searchable for keywords.
138
          $comment_document->tos_name = $comment->name;
139
        }
140
141
        // Index formatted username so it can be searched and sorted
142
        // on.
143
        $account = (object) array('uid' => $comment->uid, 'name' => $comment->name);
144
        $username = check_plain($account->name);
145
        $comment_document->ss_name_formatted = $username;
146
        $comment_document->tos_name_formatted = $username;
147
        $comment_document->is_uid = $comment->uid;
148
        $comment_document->bs_status = $comment->status;
149
150
        // Timestamp of the comment
151
        $comment_document->ds_created = apachesolr_date_iso($comment->timestamp);
152
        $comment_document->ds_changed = apachesolr_date_iso($comment->timestamp);
153
154
        // Add field for comment parent node id.
155
        $comment_document->tos_content_extra = $nid;
156
157
        // Unset the following fields (if set) that don't make sense
158
        // for a comment.
159
        if (isset($comment_document->bs_sticky)) {
160
          unset($comment_document->bs_sticky);
161
        }
162
        if (isset($comment_document->bs_promote)) {
163
          unset($comment_document->bs_promote);
164
        }
165
        if (isset($comment_document->is_tnid)) {
166
          unset($comment_document->is_tnid);
167
        }
168
        if (isset($comment_document->bs_translate)) {
169
          unset($comment_document->bs_translate);
170
        }
171
        if (isset($comment_document->ts_last_comment_timestamp)) {
172
          unset($comment_document->ts_last_comment_timestamp);
173
        }
174
        if (isset($comment_document->ds_last_comment_or_change)) {
175
          unset($comment_document->ds_last_comment_or_change);
176
        }
177
        if (isset($comment_document->is_comment_count)) {
178
          unset($comment_document->is_comment_count);
179
        }
180
181
        // Loop over fields in document and copy relevant values into
182
        // comment_document.
183
        foreach ($document as $fieldName => $fieldValue) {
184
185
          // Copy over fields [im_taxonomy_vid_1], [tid], [im_vid_1],
186
          // [im_vid_Forums], [tm_vid_1_names]
187
          if ( ( preg_match('/tid/', $fieldName) OR preg_match('/vid/', $fieldName) ) AND is_array($fieldValue) ) {
188
            foreach ($fieldValue as $subkey => $subvalue) {
189
              $comment_document->addField($fieldName, $subvalue);
190
            }
191
          }// if preg_match
192
193
          // Set the access keys so this module will work with
194
          // apachesolr_access.
195
          if (module_exists('apachesolr_access')) {
196
            if (preg_match('/^access/', $fieldName) AND is_array($fieldValue)) {
197
              foreach ($fieldValue as $subkey => $subvalue) {
198
                $comment_document->addField($fieldName, $subvalue);
199
              }
200
            }// if preg_match
201
          }// if module_exist
202
203
        }// foreach document
204
205
        $comdocs[] = $comment_document;
206
      }// while
207
    }// if entity_type=node
208
  }// documents
209
210
  // Merge the comment documents with the input documents array. These
211
  // documents will now be added to the Solr search index.
212
  $documents = array_merge($documents, $comdocs);
213
}
214
215
/**
216
 * Implementation of hook_apachesolr_process_results()
217
 *
218
 * After a query, the search results for comments are filled by this
219
 * function. The search results are used by the serach results
220
 * template.
221
 *
222
 * @param array $results
223
 *   Array of result from the Solr search.
224
 * @param $query
225
 *   The Solr query used for the search.
226
 */
227
function boinc_solr_comments_apachesolr_process_results(&$results, DrupalSolrQueryInterface $query) {
228
  //dpm($query->getSolrParams(), "process_results query getSolrParams");
229
  foreach($results as $id => $result) {
230
    if ($result['entity_type']=='comment') {
231
        $results[$id]['type'] = 'Comment';
232
        $results[$id]['date'] = $result['fields']['changed'];
233
        if (isset($result['fields']['is_uid'])) {
234
          $uid = $result['fields']['is_uid'];
235
          $results[$id]['uid']  = $uid;
236
          $results[$id]['user'] = theme('username', user_load($uid));
237
        }
238
    } //if result entity_type == comment
239
  }// foreach $result
240
  //dpm($results, "process_results array_results");
241
}
242
243
/**
244
 * Implementation of hook_apachesolr_query_alter()
245
 *
246
 * An additional field is added to the query results,
247
 * tos_content_extra. This is used for comment search results, as the
248
 * field contains the parent node id.
249
 *
250
 * @params query
251
 *   The Solr query used for the search.
252
 */
253
function boinc_solr_comments_apachesolr_query_alter($query) {
254
  // Add custom field to query results
255
  $query->addParam('fl','tos_content_extra');
256
}
257
258
/*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
259
 * Hooks into core/other modules
260
 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  */
261
262
263
/**
264
 * Implementation of hook_nodeapi()
265
 *
266
 */
267
function boinc_solr_comments_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
268
  // Array of node types that will have comments indexed.
269
  $node_types = variable_get('boinc_solr_comments_nodetypes', '');
270
  if (empty($node_types)) {
271
    // If the variable has not been set, then by default index
272
    // comments for all known node types.
273
    $node_types = array(
274
        'forum'      => 'forum',
275
        'news'       => 'news',
276
        'page'       => 'page',
277
        'story'      => 'story',
278
        'team_forum' => 'team_forum',
279
    );
280
  }
281
282
  switch ($op) {
283
    case 'delete':
284
      // Only call delete function on certain node types
285
      if (in_array( $node->type, $node_types)) {
286
        boinc_solr_comments_delete($node);
287
      }
288
      break;
289
  } //switch
290
}
291
292
293
/**
294
 * Helper function for hook_nodeapi()
295
 *
296
 * When a node is deleted, the comments with parent nid are removed
297
 * from the Solr index.
298
 *
299
 * @param node $node
300
 *  The node that is being deleted.
301
 *
302
 * @return bool
303
 *   Returns TRUE if the comment was deleted, otherwise return FALSE.
304
 */
305
function boinc_solr_comments_delete($node) {
306
  // Load the Solr environment.
307
  $env_id = apachesolr_default_environment();
308
  // Check to see if Solr is read-only.
309
  if (apachesolr_environment_variable_get($env_id, 'apachesolr_read_only', APACHESOLR_READ_WRITE) == APACHESOLR_READ_ONLY) {
310
    return FALSE;
311
  }
312
313
  // Code derived from apachesolr_index_delete_entity_from_index
314
  try {
315
    $solr = apachesolr_get_solr($env_id);
316
    // Custom query to find all comments with parent nid of the node bing deleted.
317
    $query = "entity_type:comment AND tos_content_extra:" . $node->nid;
318
    $solr->deleteByQuery($query);
319
    // Log the query used for deletion.
320
    watchdog('Apache Solr', 'Deleted documents from index with query @query', array('@query' => $query), WATCHDOG_INFO);
321
  }
322
  catch (Exception $e) {
323
      watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
324
      return FALSE;
325
  }// try
326
327
  // all deletions sucessful
328
  apachesolr_set_last_index_updated($env_id, APACHESOLR_REQUEST_TIME);
329
  return TRUE;
330
}
331
332
/**
333
 * Implementation of hook_comment()
334
 *
335
 */
336
function boinc_solr_comments_comment(&$a1, $op) {
337
  switch ($op) {
338
    case 'view':
339
    case 'update':
340
      break;
341
    case 'delete':
342
      // $a1 should be a comment object
343
      boinc_solr_comments_deletecomment($a1);
344
      break;
345
  }// switch
346
}
347
348
/**
349
 * Helper function for hook_comment()
350
 *
351
 * When a comment is deleted, the corresponding apache Solr document
352
 * is removed from the Solr index.
353
 *
354
 * @param comment $comment
355
 *   The comment to be deleted.
356
 *
357
 * @return bool
358
 *   Returns TRUE if the comment was deleted, otherwise return FALSE.
359
 */
360
function boinc_solr_comments_deletecomment($comment) {
361
  // Load the Solr environment.
362
  $env_id = apachesolr_default_environment();
363
  // Check to see if Solr is read-only.
364
  if (apachesolr_environment_variable_get($env_id, 'apachesolr_read_only', APACHESOLR_READ_WRITE) == APACHESOLR_READ_ONLY) {
365
    return FALSE;
366
  }
367
  //dd($comment->cid, "delete - nid begin");
368
369
  // Code derived from apachesolr_index_delete_entity_from_index.
370
  try {
371
    $solr = apachesolr_get_solr($env_id);
372
    $entity_id = $comment->cid;
373
    $entity_type = 'comment';
374
    $document_id = apachesolr_document_id($entity_id, $entity_type);
375
    $query = "id:$document_id OR sm_parent_document_id:$document_id";
376
    $solr->deleteByQuery($query);
377
    // Log the query used for deletion.
378
    watchdog('Apache Solr', 'Deleted documents from index with query @query', array('@query' => $query), WATCHDOG_INFO);
379
    }
380
  catch (Exception $e) {
381
    watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
382
    return FALSE;
383
  }// try
384
385
  // deletion sucessful
386
  apachesolr_set_last_index_updated($env_id, APACHESOLR_REQUEST_TIME);
387
  return TRUE;
388
}
389
390
391
/*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
392
 * Other Functions
393
 *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  */
394
395
/**
396
 *  Implementation of module_enable()
397
 *
398
 * Simply gives the admin a message after installing and enabling this module.
399
 */
400
401
function boinc_solr_comments_enable() {
402
  drupal_set_message( bts('Warning: Your content <a href="@url">must be re-indexed</a> before Apache Solr will search comments.', array('@url' => url('admin/settings/apachesolr/index')), NULL, 'boinc:admin-solr-index-comments-message'), 'warning');
403
}
404
405
/**
406
 * Helper function which is called when a comment is published.
407
 * Interfaces with boinccore module.
408
 *
409
 * @param comment $comment
410
 *   The comment to be published (unhidden).
411
 */
412
function boinc_solr_comments_publish($comment) {
413
  if ( ($comment->cid) AND ($comment->nid) ) {
414
    $node = node_load($comment->nid);
415
    // Tell Solr that the node has been updated, so the comment can be
416
    // indexed.
417
    apachesolr_entity_update($node, 'node');
418
  }
419
}
420
421
/**
422
 * Helper function which is called when a comment is unpublished.
423
 * Interfaces with boinccore module.
424
 *
425
 * @param comment $comment
426
 *   The comment to be unpublished (hidden).
427
 */
428
function boinc_solr_comments_unpublish($comment) {
429
  if ( ($comment->cid) ) {
430
    // Call the deletecomment function for hook comment.
431
    boinc_solr_comments_deletecomment($comment);
432
  }
433
}
434
435