summaryrefslogtreecommitdiffstats
path: root/quote_plus_fqb/quote_plus_fqb.module
blob: fffd50fbee6f377c96084d541a4bd6cfa9b56d28 (plain)
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
<?php

/**
 * @file
 * "Full quote buster" feature extension for Quote plus module.
 *
 * Checks if given quotes need to be considered full quotes
 * depending on defined criteria and, if necessary, shortens them
 * and adds a link to retrieve the entire quote length.
 */

/**
 * Default configuration values.
 */
define('QUOTE_PLUS_FQB_THRESHOLD', 750);
define('QUOTE_PLUS_FQB_MAXLENGTH', 500);

define('QUOTE_PLUS_FQB_TOGGLE_LINK_NONE', 0);
define('QUOTE_PLUS_FQB_TOGGLE_LINK_ADD', 1);
define('QUOTE_PLUS_FQB_TOGGLE_LINK_PLACEHOLDER', 2);

/**
 * Implements hook_comment().
 */
function quote_plus_fqb_comment(&$a1, $op) {
  // Initialize js flags.
  static $js_added = FALSE;
  $add_js = FALSE;
  // Prepare static request path and query details cache.
  static $is_node_view, $is_preview, $fq;
  if (!isset($fq)) {
    $fq = is_array($_GET['fq']) ? array_flip($_GET['fq']) : array();
  }
  if ($op == 'view') {
    // We will only work on node views.
    if (!isset($is_node_view)) {
      $is_node_view = preg_match('#^node/[0-9]+(/view)?$#', $_GET['q']) != 0;
      $is_preview = !$is_node_view && preg_match('#^comment/(quote|reply)/[0-9]+(/[0-9]+)?$#', $_GET['q']) != 0;
    }
    if ($is_node_view || $is_preview) {
      while (preg_match('/<!--fqb-start=([0-9]+)\.([0-9]+)-->(.*?)<!--fqb-end-->/s', $a1->comment, $found)) {
        if (isset($fq[$found[1]])) {
          // Replace short quotes, if requested.
          // 1. Retrieve pre-filtered long quote.
          if ($is_node_view) {
            $longquote = _quote_plus_fqb_load($found[1], $found[2], $a1->cid, TRUE, TRUE, FALSE, QUOTE_PLUS_FQB_TOGGLE_LINK_ADD);
            // 2. Add toggle link.
            $longquote .= ' ' . _quote_plus_fqb_toggle_link($found[1], $a1->cid, FALSE);
            $add_js = TRUE;
            $a1->comment = str_replace($found[0], $longquote, $a1->comment);
          }
        }
        else {
          // Otherwise, remove comment tags.
          $a1->comment = str_replace($found[0], $found[3], $a1->comment);
        }
      }
      if ($is_node_view) {
        // Replace any <!--fql-toggle--> link placeholder with a toggle link.
        while (preg_match('/<!--fql-toggle=([0-9]+)-->/', $a1->comment, $found)) {
          $a1->comment = str_replace(
            $found[0],
            ' ' . _quote_plus_fqb_toggle_link($found[1], $a1->cid, TRUE),
            $a1->comment
          );
          $add_js = TRUE;
        }
      }
    }
  }
  if ($add_js && !$js_added) {
    drupal_add_js(drupal_get_path('module', 'quote_plus_fqb') . '/quote_plus_fqb.js');
    drupal_add_js(array('quotePlusFqb' => array('callbackPath' => 'js/quote_plus_fqb/ajax')), 'setting');
    $js_added = TRUE;
  }
}

/**
 * Implements hook_cron().
 */
function quote_plus_fqb_cron() {
  // Remove shortened quotes after one week.
  // That should be long enough to cover looooong browser sessions.
  // (Otherwise the Ajax retrieval of a quote could fail just in case
  // a user falls asleep while reading a comment page...

  db_query("DELETE FROM {quote_plus_fqb} where created < %d", time() - 7 * 24 * 60 * 60);
}

/**
 * Implements hook_disable().
 */
function quote_plus_fqb_disable() {
  // If fqb submodule is being disabled, there may still be
  // shortened quotes in the filter format cache. They would
  // still be displayed without a chance to switch to full quotes.
  cache_clear_all('*', 'cache_filter', TRUE);
}

/**
 * Implements hook_enable().
 */
function quote_plus_fqb_enable() {
  // If fqb submodule was not disabled, there may still be
  // unshortened quotes in the filter format cache.
  // fqb module would be useless for up to one day.
  cache_clear_all('*', 'cache_filter', TRUE);
}

/**
 * Implements hook_js().
 */
function quote_plus_fqb_js() {
  return array(
    'ajax' => array(
      'callback' => '_quote_plus_fqb_ajax',
      'includes' => array('unicode'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function quote_plus_fqb_menu() {
  return array(
    'js/quote_plus_fqb/ajax' => array(
      'title' => 'JS fullquote toggle',
      'page callback' => '_quote_plus_fqb_ajax',
      'type' => MENU_CALLBACK,
    ),
  );
}

/**
 * Retrieve quotes from the DB and serve them via JSON output.
 *
 * Checks user access, evaluates POST data and conditionally returns
 * a shortened or a full length quote.
 */
function _quote_plus_fqb_ajax() {
  if (user_access('access comments')) {
    // Evaluate POST params.
    if (is_numeric($qid = $_POST['qid']) && is_numeric($full = $_POST['full']) && is_numeric($cid = $_POST['cid']) && is_numeric($sid = $_POST['sid'])) {
      // Retrieve the short or full quote.
      $quote = _quote_plus_fqb_load($qid, $sid, $cid, $full == 1, TRUE, FALSE, QUOTE_PLUS_FQB_TOGGLE_LINK_ADD);
      drupal_json(array('content' => $quote));
    }
  }
}

/**
 * Process one text block out of one quote level.
 *
 * @param $block
 *   Text block without sub quotes. Not yet filtered,
 *   may contain HTML etc.
 * @param $format
 *   Current filter format (settings related).
 *
 * @return string
 *   The processed block content.
 */
function _quote_plus_fqb_process($block, $format) {
  // Remove the filter indicator we have set to force refiltering,
  // in case e.g. the HTML filter did not do that yet.
  // @see quote_plus_fqb_comment()
  $block = preg_replace('/<!--fqb-->$/', '', $block);

  // Configuration data.
  static $threshold = array();
  static $maxlength = array();
  if (!isset($threshold[$format])) {
    $threshold[$format] = variable_get(
      "quote_plus_fqb_threshold_$format",
      QUOTE_PLUS_FQB_THRESHOLD
    );
    $maxlength[$format]  = variable_get(
      "quote_plus_fqb_maxlength_$format",
      QUOTE_PLUS_FQB_MAXLENGTH
    );
  }

  // Shortened quotes and length determination will base on plain text.
  $plain_text = decode_entities(strip_tags($block));
  $total_length = drupal_strlen($plain_text);

  // Find out if the block is a candidate and, if so, process it.
  if ($total_length > $threshold[$format]) {

    $data = array(
      'sid' => rand(100000, 999999),
      'full' => check_markup($block, $format),
      'short' => truncate_utf8($plain_text, $maxlength[$format], TRUE, TRUE),
      'length' => $total_length,
      'created' => time(),
    );
    drupal_write_record('quote_plus_fqb', $data);

    // Only shorten if DB operation was successful.
    if ($data['qid']) {
      $block = _quote_plus_fqb_load($data['qid'], $data['sid'], NULL, FALSE, TRUE, TRUE, QUOTE_PLUS_FQB_TOGGLE_LINK_PLACEHOLDER);
    }
  }
  return $block;
}

/**
 * Load a formatted quote from the database.
 *
 * @param $qid
 *   Internal quote ID.
 * @param $sid
 *   The additional "secure" ID.
 * @param $cid
 *   ID of the comment the quote belongs to.
 * @param $full
 *   If TRUE, load the full quote. Otherwise the shortened version.
 * @param $container
 *   If TRUE, return the quote embedded in a shortquote/fullquote container
 *   consisting of a div with properly named classes and ID and comment
 *   tags indicating a quote sections start, end and a placeholder for a
 *   toggle link.
 * @param $delimiters
 *   Whether to enclose the container in <!--fqb-start--><!--fqb-end-->
 *   delimiters (needed for conditional replacement of the pre-filtered 
 *   cache data) in hook_comment.
 * @param $toggle_link
 *   Whether to add a toggle link or a placeholder or none of these.
 *   See QUOTE_PLUS_FQB_TOGGLE_LINK_ constant definitions.
 *   
 * @return string|bool
 *   The quote related to $qid or FALSE, if loading failed.
 */
function _quote_plus_fqb_load($qid, $sid, $cid, $full = TRUE, $container = FALSE, $delimiters = FALSE, $toggle_link = QUOTE_PLUS_FQB_TOGGLE_LINK_NONE) {
  if (is_numeric($qid) && is_numeric($sid)) {
    if ($res = db_query('SELECT * FROM {quote_plus_fqb} WHERE qid = %d AND sid = %d', $qid, $sid)) {
      $data = db_fetch_array($res);
      if ($container) {
        $ret = '<div class="quote-plus-fqb quote-plus-fqb-' . ($full ? 'full' : 'short')
          . 'quote" id="quote-plus-fqb-' . $data['qid']. '"'
        ;
        if (!$full) {
          $ret .= ' title="' . t(
            'This quote block has been shortened from a total length of appr. !length characters for better readability.',
            array('!length' => $data['length'])
          ) . '"';
        }
        $ret .= '><span class="quote-plus-fqb-sid" id="quote-plus-fqb-sid-' . $data['sid'] . '"></span>' . $data[$full ? 'full' : 'short'];
        if ($toggle_link == QUOTE_PLUS_FQB_TOGGLE_LINK_ADD) {
          $ret .= ' ' . _quote_plus_fqb_toggle_link($data['qid'], $cid, !$full);
        }
        elseif ($toggle_link == QUOTE_PLUS_FQB_TOGGLE_LINK_PLACEHOLDER) {
          $ret .= '<!--fql-toggle=' . $data['qid'] . '--></div>';
        }
        if ($delimiters) {
          $ret = '<!--fqb-start=' . $data['qid'] . '.' . $data['sid'] . '-->' . $ret . '<!--fqb-end-->';
        }
      }
      else {
        $ret = $data[$full ? 'full' : 'short'];
      }
      return $ret;
    }
  }
  return FALSE;
}

/**
 * Generate a toggle link.
 *
 * @param $qid
 *   Internal quote ID (for link CSS id).
 * @param $cid
 *   Comment ID (for direct redirection in non-JS calls).
 * @param $full
 *   If true, link to a full quote. Otherwise to a short quote.
 *
 * @return string
 *   An HTML link snippet.
 *
 * @todo
 *   Add theming support?
 */
function _quote_plus_fqb_toggle_link($qid, $cid, $full) {
  static $query, $fq;
  if (!isset($query)) {
    $query = is_array($_GET) ? $_GET : array();
    unset($query['fq']);
    unset($query['q']);
    $fq = is_array($_GET['fq']) ? $_GET['fq'] : array();
  }
  if ($full) {
    return l(
      '(' . t('Show full quote') . ')',
      'comment/' . $cid,
      array(
        'attributes' => array(
          'class' => 'quote-plus-fqb-toggle',
          'id' => 'quote-plus-fqb-toggle-' . $qid,
        ),
        'query' => array_merge($query, array('fq' => array_merge((array)$_GET['fq'], array($qid)))),
      )
    );
  }
  else {
    return l(
      '(' . t('Hide full quote') . ')',
      'comment/' . $cid,
      array(
        'attributes' => array(
          'class' => 'quote-plus-fqb-toggle',
          'id' => 'quote-plus-fqb-toggle-' . $qid,
        ),
        'query' => array_merge($query, array('fq' => array_diff((array)$_GET['fq'], array($qid))))
      )
    );
  }
}

/**
 * Validation callback for fqb specific filter settings.
 *
 * @see quote_plus.module
 * @see quote_plus_form_alter()
 */
function _quote_plus_fqb_settings_validate($form, &$form_state) {
  if (!is_numeric($form_state['values']['quote_plus_fqb_threshold'])) {
    form_set_error('quote_plus_fqb_threshold', t('The long quote threshold must be a positive integer.'));
  }
  if (
    !is_numeric($form_state['values']['quote_plus_fqb_maxlength'])
    ||
    $form_state['values']['quote_plus_fqb_maxlength'] >= $form_state['values']['quote_plus_fqb_threshold']
  ) {
    form_set_error('quote_plus_fqb_maxlength', t('The maximum short quote length must be a positive integer and smaller than the threshold.'));
  }
}