summaryrefslogtreecommitdiffstats
path: root/authcache.module
blob: 32e4a9209172cce074b25bbe4a1cbd51c7831899 (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
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
<?php

/**
 * @file
 * Authenticated User Page Caching (and anonymous users, too!)
 *
 * @see authcache.admin.inc for admin page functionality
 */

// Default caching rules (Never cache these pages)
define('AUTHCACHE_NOCACHE_DEFAULT', '
user*
node/add/*
node/*/edit
node/*/track
tracker*
comment/edit*
civicrm*
cart*
system/files/*
system/temporary*
');

// Default non-HTML cachable content-types
define('AUTHCACHE_MIMETYPE_DEFAULT', '
text/html
text/javascript
text/plain
application/xml
application/atom+xml
');

// Flags for authcache_fix_cookies:
define('AUTHCACHE_FLAGS_NONE', 0x0);
define('AUTHCACHE_FLAGS_ACCOUNT_ENABLED', 0x1);
define('AUTHCACHE_FLAGS_LOGIN_ACTION', 0x2);
define('AUTHCACHE_FLAGS_LOGOUT_ACTION', 0x4);

/**
 * Implements hook_menu().
 */
function authcache_menu() {

  $items['admin/config/system/authcache'] = array(
    'title' => 'Authcache',
    'description' => 'Configure authenticated user page caching.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('authcache_admin_config'),
    'access arguments' => array('administer site configuration'),
    'file' => 'authcache.admin.inc',
    'weight' => 10,
  );
  
  $items['admin/config/system/authcache/config'] = array(
    'title' => 'Configuration',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  
  $items['admin/config/system/authcache/pagecaching'] = array(
    'title' => 'Page caching settings',
    'description' => "Configure page cache settings.",
    'page callback' => 'drupal_get_form',
    'page arguments' => array('authcache_admin_pagecaching'),
    'access arguments' => array('administer site configuration'),
    'file' => 'authcache.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 20,
  );
  $items['authcache/ajax'] = array(
    'title' => 'Javascript ajax Callback',
    'page callback' => 'authcache_ajax',
    'access arguments' => array('administer site configuration'),
    'file' => 'authcache.admin.inc',
    'type' => MENU_CALLBACK,
  );


  return $items;
}

/**
 * Implements hook_module_implements_alter().
 *
 * Make sure that hook_init of this module is called before all other modules
 * and vice versa for hook_exit.
 */
function authcache_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'init') {
    $me = $implementations['authcache'];
    unset($implementations['authcache']);
    $implementations = array_merge(array('authcache' => $me), $implementations);
  }

  if ($hook == 'exit') {
    $me = $implementations['authcache'];
    unset($implementations['authcache']);
    $implementations['authcache'] = $me;
  }
}

/**
 * Implements hook_init().
 */

function authcache_init() {
  global $conf, $user;

  $reasons = module_invoke_all('authcache_request_exclude');
  if (!empty($reasons)) {
    _authcache_exclude(reset($reasons));
  }

  $reasons = module_invoke_all('authcache_account_exclude', $user);
  if (!empty($reasons)) {
    _authcache_exclude(reset($reasons));
  }

  if (!authcache_excluded()) {
    // Don't allow format_date() to use the user's local timezone
    $conf['configurable_timezones'] = FALSE;

    // Start output buffering
    ob_start();
  } 

  // Attach required JavaScript
  drupal_add_library('system', 'jquery.cookie');
  drupal_add_js(drupal_get_path('module', 'authcache') . '/authcache.js');

  // Inject authcache cookie settings.
  $lifetime = ini_get('session.cookie_lifetime');
  $lifetime = (!empty($lifetime) && is_numeric($lifetime) ? (int)$lifetime : 0);
  drupal_add_js(array('authcache' => array(
    'q' => $_GET['q'],
    'cp' => array(
      'path' => ini_get('session.cookie_path'),
      'domain' => ini_get('session.cookie_domain'),
      'secure' => ini_get('session.cookie_secure') == '1',
    ),
    'cl' => $lifetime/86400,
  )), 'setting');

  // Fix cookies if necessary.
  $flags = (authcache_account_allows_caching()) ?
    AUTHCACHE_FLAGS_ACCOUNT_ENABLED : AUTHCACHE_FLAGS_NONE;
  authcache_fix_cookies($flags);
}


/**
 * Implements hook_user_login().
 */
function authcache_user_login(&$edit, $account) {
  $flags = AUTHCACHE_FLAGS_LOGIN_ACTION;

  if (authcache_account_allows_caching($account)) {
    $flags |= AUTHCACHE_FLAGS_ACCOUNT_ENABLED;
  }

  authcache_fix_cookies($flags, $account);
}


/**
 * Implements hook_user_logout().
 */
function authcache_user_logout($account) {
  // Note: include same cookie deletion in ajax/authcache.module
  authcache_fix_cookies(AUTHCACHE_FLAGS_LOGOUT_ACTION, $account);
}


/**
 * Implements hook_form_alter(),
 */
function authcache_form_alter(&$form, &$form_state, $form_id) {
  if (authcache_page_is_cacheable()) {
      // Need to postpone the decision whether the form and the page is cacheable
      // to an after-build callback.
      $form['#after_build'][] = '_authcache_form_after_build';
  }

  // Alter all forms
  switch ($form_id) {
    // Alter Drupal's "Performance" admin form
    case 'system_performance_settings':
      $form['caching']['cache']['#description'] = ' <strong>' . t('If Authcache is enabled for the "anonymous user" role, Drupal\'s built-in page caching will be automatically disabled since all page caching is done through Authcache API instead of Drupal core.') . '</strong>';
      if (authcache_account_allows_caching(drupal_anonymous_user())) {
        $form['caching']['cache']['#disabled'] = TRUE; //array(0 => t('Disabled') . ' ' . t('by') . ' Authcache');
        $form['caching']['cache']['#value'] = TRUE;
      }
      
      break;
    case 'user_profile_form':
      // Don't allow user local timezone
      if (authcache_account_allows_caching()) {
        unset($form['timezone']);
      }
      break;
  }
}

/**
 * Form after_build callback for all forms on cacheable pages
 *
 * Disable storing the form to form-cache if possible. However some forms (especially
 * Ajax-enabled ones) require the form cache. In this case page-caching must be
 * cancelled.
 *
 * @see drupal_build_form().
 */
function _authcache_form_after_build($form, $form_state) {
  $form_id = $form['#form_id'];

  if (isset($form['form_token']) && !authcache_get_request_property('ajax')) {
    authcache_cancel(t('Form with CSRF protected on page but cannot use AJAX to defer token-retrieval.'));
  }
  else {
    if (empty($form_state['rebuild']) && empty($form_state['cache'])) {
      // Disable form cache and remove build_id if caching is not explicitely requested
      $form_state['no_cache'] = TRUE;
      unset($form['form_build_id']);
      unset($form['#build_id']);
    }

    if (isset($form['form_token']) && authcache_get_request_property('ajax')) {
      // Remove CSRF-token from built form and make sure it can be retrieved
      // later using AJAX.
      unset($form['form_token']);

      drupal_add_js(drupal_get_path('module', 'authcache') . '/authcache.formtokenids.js');
      drupal_add_js(array('aceformtokenids' => array(
        $form_id => (isset($form['#token'])) ? $form['#token'] : $form_id,
      )), 'setting');
    }
  }

  return $form;
}

/**
 * Process page template variables.
 */
function authcache_preprocess_page(&$variables) {
  if (user_is_logged_in() && authcache_page_is_cacheable()) {
    if (authcache_get_request_property('ajax')) {
      drupal_add_js(drupal_get_path('module', 'authcache') . '/authcache.tabs.js');
    }
    $variables['tabs']['#post_render'][] = 'authcache_wrap_tabs';
    $variables['action_links']['#post_render'][] = 'authcache_wrap_local_actions';
  }
}

/**
 * Post-render callback for page-tabs. Wrap them into an authcache span, so we
 * can find it again in JavaScript.
 */
function authcache_wrap_tabs($markup) {
  if (!empty($markup)) {
    if (authcache_get_request_property('ajax')) {
      $markup = '<span id="authcache-tabs">' . $markup . '</span>';
    }
    else {
      authcache_cancel(t('Tabs on page but Authcache AJAX not enabled.'));
    }
  }

  return $markup;
}

/**
 * Post-render callback for local actions. Wrap them into an authcache span, so
 * we can find it again in JavaScript.
 */
function authcache_wrap_local_actions($markup) {
  if (!empty($markup)) {
    if (authcache_get_request_property('ajax')) {
      $markup = '<span id="authcache-local-actions">' . $markup . '</span>';
    }
    else {
      authcache_cancel(t('Local actions on page but Authcache AJAX not enabled.'));
    }
  }

  return $markup;
}

/**
 * Implements hook_exit().
 *
 * Called on drupal_goto() redirect.
 * Make sure status messages show up, if applicable.
 */
function authcache_exit($destination = NULL) {
  // Cancel caching when hook_exit was called from drupal_goto.
  if ($destination !== NULL) {
    authcache_cancel(t('Redirecting to @destination', array('@destination' => $destination)));
  }

  // Disable authcache on next page request if there are messages pending which
  // did not manage it onto the current page.
  if (drupal_set_message()) {
    authcache_fix_cookies(AUTHCACHE_FLAGS_NONE);
  }

  // If this page was excluded in hook_init, we're done here.
  if (authcache_excluded()) {
    return;
  }

  // Forcibly disable drupal built-in page caching for anonymous users.
  // Prevent drupal_page_set_cache() called from drupal_page_footer() to
  // store the page a second time after we did.
  drupal_page_is_cacheable(FALSE);

  // Cache and output
  if ($cache = authcache_page_set_cache()) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_end_flush();
  }
}

//
// Preprocess functions
//

/**
 * Implements hook_preprocess().
 *
 * Inject authcache variables into every template.
 */
function authcache_preprocess(&$variables, $hook) {
  // Define variables for templates files
  $variables['authcache_is_cacheable'] = authcache_page_is_cacheable();
}

/**
 * Implements hook_process_HOOK().
 *
 * Prevent caching pages with status messages on them. Note that due to the
 * fact the messages are only added in template_process_page, we also need to
 * use the process-hook.
 */
function authcache_process_page(&$variables) {
  if (!empty($variables['messages']) && authcache_page_is_cacheable()) {
    authcache_cancel(t('Status message on page'));
  }
}

//
// API for other modules.
//

/**
 * Private function called from authcache_init. Authcache should not alter any
 * aspect of this page.
 */
function _authcache_exclude($reason = NULL) {
  // No need for drupal_static here, flag may not be reset anyway.
  static $excluded = FALSE;

  if (!$excluded && !empty($reason)) {
    $excluded = TRUE;
    module_invoke_all('authcache_excluded', $reason);
  }

  return $excluded;
}

/**
 * Return true if this page is excluded from page caching.
 */
function authcache_excluded() {
  return _authcache_exclude();
}

/**
 * Prevent this page of beeing stored in the cache after it is built up.
 */
function authcache_cancel($reason = NULL) {
  // No need for drupal_static here, flag may not be reset anyway.
  static $cancelled = FALSE;

  if (!$cancelled && !empty($reason)) {
    $cancelled = TRUE;
    module_invoke_all('authcache_cancelled', $reason);
  }

  return $cancelled;
}

/**
 * Return true if the caching of the page request was cancelled during
 * page-build.
 */
function authcache_cancelled() {
  return authcache_cancel();
}

/**
 * Return true if this page possibly will be cached later.
 */
function authcache_page_is_cacheable() {
  return !(authcache_excluded() || authcache_cancelled());
}

/**
 * Return true if the given account is cacheable.
 */
function authcache_account_allows_caching($account = NULL) {
  global $user;
  $cacheable = &drupal_static(__FUNCTION__);

  if (!isset($account)) {
    $account = $user;
  }

  if (!isset($cacheable[$account->uid])) {
    $reasons = module_invoke_all('authcache_account_exclude', $account);
    $cacheable[$account->uid] = empty($reasons);
  }

  return $cacheable[$account->uid];
}

/**
 * Return characterizing key-value pairs of a browsers capabilities and the
 * HTTP request.
 */
function authcache_request_properties() {
  static $properties;

  if (!isset($properties)) {
    $properties = module_invoke_all('authcache_request_properties');
    drupal_alter('authcache_request_properties', $properties);
  }

  return $properties;
}

/**
 * Return characterizing properties of groups the given account is a member of.
 */
function authcache_account_properties($account = NULL) {
  global $user;
  static $properties;

  if (!isset($account)) {
    $account = $user;
  }

  if (!isset($properties)) {
    $properties = module_invoke_all('authcache_account_properties', $account);
    drupal_alter('authcache_account_properties', $properties, $account);
  }

  return $properties;
}

/**
 * Return the property value of the given request property or null.
 *
 * @see hook_authcache_request_properties().
 */
function authcache_get_request_property($name) {
  $properties = authcache_request_properties();
  return isset($properties[$name]) ? $properties[$name] : NULL;
}

/**
 * Return the property value of the given account property or null.
 *
 * @see hook_authcache_account_properties().
 */
function authcache_get_account_property($name, $account = NULL) {
  $properties = authcache_account_properties($account);
  return isset($properties[$name]) ? $properties[$name] : NULL;
}

/**
 * Return the properties used as a base for calculation of the authcache key.
 *
 * @see authcache_key().
 * @see hook_authcache_key_properties_alter().
 */
function authcache_key_properties($account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  $properties = array(
    'request' => authcache_request_properties(),
    'account' => authcache_account_properties($account),
  );
  drupal_alter('authcache_key_properties', $properties, $account);

  return $properties;
}

/**
 * Generate and return the authcache key for the given account.
 *
 * @see hook_authcache_key_properties().
 * @see hook_authcache_key_properties_alter().
 */
function authcache_key($account = NULL) {
  global $base_root, $user;

  if (!isset($account)) {
    $account = $user;
  }

  if ($account->uid) {
    // Calculate the key for logged in users from key-properties.
    $data = serialize(authcache_key_properties($account));
    $hmac = hash_hmac('sha1', $data, drupal_get_private_key(), FALSE);

    $abbrev = variable_get('authcache_hmac_abbrev', 7);
    $key = $abbrev ? substr($hmac, 0, $abbrev) : $hmac;
  }
  else {
    // Generate base-key for anonymous users.
    $generator = variable_get('authcache_key_generator');
    if (is_callable($generator)) {
      $key = call_user_func($generator);
    }
    else {
      $key = $base_root;
    }
  }

  return $key;
}

/**
 * Return the authcache cache-id for the given path.
 *
 * @see authcache_key().
 */
function authcache_cid($request_uri = NULL, $account = NULL) {
  if (!isset($request_uri)) {
    $request_uri = request_uri();
  }

  $key = authcache_key($account);
  return $key . $request_uri;
}

/**
 * Add and remove cookies to the browser session as required.
 *
 * @see hook_authcache_cookie().
 * @see hook_authcache_cookie_alter().
 */
function authcache_fix_cookies($flags, $account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  $cookies = module_invoke_all('authcache_cookie', $flags, $account);
  drupal_alter('authcache_cookie', $cookies, $flags, $account);

  $default_params = array(
    'present' => FALSE,
    'value' => NULL,
    'lifetime' => ini_get('session.cookie_lifetime'),
    'path' => ini_get('session.cookie_path'),
    'domain' => ini_get('session.cookie_domain'),
    'secure' => ini_get('session.cookie_secure') == '1',
    'httponly' => FALSE,
  );

  foreach ($cookies as $name => $params) {
    $params += $default_params;

    if ($params['present']) {
      // Fix cookie if it is not present in the users browser or the value does
      // not match our expectations.
      if (!isset($_COOKIE[$name]) || $_COOKIE[$name] != $params['value']) {
        $expires = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
        setcookie($name, $params['value'], $expires, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
      }
    }
    elseif (!$params['present'] && isset($_COOKIE[$name])) {
      // Remove spare cookie
      setcookie($name, "", REQUEST_TIME - 86400, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
  }
}

/**
 * Returns an array containing all the roles from account_roles that are not
 * present in allowed_roles.
 */
function authcache_diff_roles($account_roles, $allowed_roles) {
  // Remove "authenticated user"-role from the account roles except when it is
  // the only role on the account.
  if (array_keys($account_roles) != array(DRUPAL_AUTHENTICATED_RID)) {
    unset($account_roles[DRUPAL_AUTHENTICATED_RID]);
  }

  return array_diff_key($account_roles, $allowed_roles);
}

/**
 * Determines the MIME content type of the current page response based on
 * the currently set Content-Type HTTP header.
 *
 * This should normally return the string 'text/html' unless another module
 * has overridden the content type.
 */
function _authcache_get_content_type($default = NULL) {
  $params = explode(';', drupal_get_http_header('content-type'));
  $params = array_map('trim', $params);
  $mime = array_shift($params);

  return array(
    'mimetype' => $mime,
    'params' => $params,
  );
}

/**
 * Determines the HTTP response code that the current page request will be
 * returning by examining the HTTP headers that have been output so far.
 */
function _authcache_get_http_status($status = 200) {
  $value = drupal_get_http_header('status');
  return isset($value) ? (int) $value : $status;
}

/**
 * Stores the current page in the cache.
 *
 * @see hook_authcache_presave().
 * @see hook_authcache_cache_alter().
 * @see drupal_page_set_cache().
 */
function authcache_page_set_cache() {
  // Give other modules a last chance to cancel page saving
  module_invoke_all('authcache_presave');

  if (authcache_page_is_cacheable()) {
    $cache = (object) array(
      'cid' => authcache_cid(),
      'data' => array(
        'path' => $_GET['q'],
        'body' => ob_get_clean(),
        'title' => drupal_get_title(),
        'headers' => array(),
      ),
      'expire' => CACHE_TEMPORARY,
      'created' => REQUEST_TIME,
    );

    // Restore preferred header names based on the lower-case names returned
    // by drupal_get_http_header().
    $header_names = _drupal_set_preferred_header_name();
    foreach (drupal_get_http_header() as $name_lower => $value) {
      $cache->data['headers'][$header_names[$name_lower]] = $value;
      if ($name_lower == 'expires') {
        // Use the actual timestamp from an Expires header if available.
        $cache->expire = strtotime($value);
      }
    }

    if ($cache->data['body']) {
      if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
      }

      // Let other modules act on the cacheable data.
      drupal_alter('authcache_cache', $cache);

      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
    }
    return $cache;
  }
}

//
// Authcache hooks
//

/**
 * Implements hook_authcache_request_properties().
 */
function authcache_authcache_request_properties() {
  global $base_url;

  return array(
    'js' => !empty($_COOKIE['has_js']),
    'base_url' => $base_url,
  );
}

/**
 * Implements hook_authcache_account_properties().
 */
function authcache_authcache_account_properties($account) {
  $roles = array_keys($account->roles);
  sort($roles);

  return array(
    'roles' => $roles,
  );
}

/**
 * Implements hook_authcache_request_exclude().
 */
function authcache_authcache_request_exclude() {
  global $user;

  // The following three basic exclusion rules are mirrored in
  // authcacheinc_retrieve_cache_page() in authcache.inc
  // BEGIN: basic exclusion rules
  if (drupal_is_cli()) {
    return t('Running as CLI script');
  }

  if (!($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')) {
    return t('Only GET and HEAD requests allowed. Method for this request is: @method.',
      array('@method' => $_SERVER['REQUEST_METHOD']));
  }

  if (($ar = explode('?', basename(request_uri()))) && substr(array_shift($ar), -4) == '.php') {
    return t('PHP files (cron.php, update.php, etc)');
  }
  // END: basic exclusion rules

  module_load_install('authcache');
  $requirements = module_invoke('authcache', 'requirements', 'runtime');
  if (isset($requirements['authcache']['severity']) && $requirements['authcache']['severity'] == REQUIREMENT_ERROR) {
    return $requirements['authcache']['description'];
  }

  if (variable_get('authcache_noajax', FALSE)
      && isset($_SERVER['HTTP_X_REQUESTED_WITH'])
      && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
    ) {
    return t('Ajax request');
  }

  $alias = drupal_get_path_alias($_GET['q']);

  // Now check page caching settings, defined by the site admin
  $pagecaching = variable_get('authcache_pagecaching', array(array(
    'option' => 0,
    'pages' => AUTHCACHE_NOCACHE_DEFAULT,
    'roles' => array(DRUPAL_ANONYMOUS_RID),
  )));

  foreach ($pagecaching as $i => $page_rules) {
    // Do caching page roles apply to current user?
    $extra_roles = authcache_diff_roles($user->roles, $page_rules['roles']);
    if (empty($extra_roles)) {
      switch ($page_rules['option']) {
        case '0': // Cache every page except the listed pages.
        case '1': // Cache only the listed pages.
          $page_listed = drupal_match_path($alias, $page_rules['pages']);
          if (!(!($page_rules['option'] xor $page_listed))) {
            return t('Caching disabled by path list of page ruleset #@number', array('@number' => $i));
          }
          break;

        case '2': // Cache pages for which the following PHP code returns TRUE
          $result = 0;
          if (module_exists('php')) {
            $result = php_eval($page_rules['pages']);
          }
          if (empty($result)) {
            return t('Caching disabled by PHP rule of page ruleset #@number', array('@number' => $i));
          }
          break;

        default:
          break;
      }

      if (!empty($page_rules['noadmin']) && path_is_admin(current_path())) {
       return t('Not caching admin pages (by page ruleset #@number)', array('@number' => $i));
      }
    }
  }
}


/**
 * Implements hook_authcache_account_exclude().
 */
function authcache_authcache_account_exclude($account) {
  // Bail out from requests by superuser (uid=1)
  if ($account->uid == 1 && !variable_get('authcache_su', 0)) {
    return t('Caching disabled for superuser');
  }

  // Check for non-cacheable roles of the account.
  $cache_roles = variable_get('authcache_roles', array());
  $extra_roles = authcache_diff_roles($account->roles, $cache_roles);
  if (!empty($extra_roles)) {
    return format_plural(count($extra_roles),
      'Account has non-cachable role @roles',
      'Account has non-cachable roles @roles',
      array('@roles' => implode(', ', $extra_roles)));
  }

  // If JavaScript is disabled on the users browser, check if chaching is still
  // allowed.
  if (!authcache_get_request_property('js')) {
    $nojs_roles = variable_get('authcache_nojsroles', drupal_map_assoc(array(DRUPAL_ANONYMOUS_RID)));
    $extra_roles = authcache_diff_roles($account->roles, $nojs_roles);
    if (!empty($extra_roles)) {
      return format_plural(count($extra_roles),
        'Role @roles is not cacheable if JavaScript is disabled.',
        'Roles @roles are not cacheable if JavaScript is disabled.',
        array('@roles' => implode(', ', $extra_roles)));
    }
  }
}


/**
 * Implements hook_authcache_presave().
 */
function authcache_authcache_presave() {
  // Check content-type
  $content_type = _authcache_get_content_type();
  $allowed_mimetypes = preg_split('/(\r\n?|\n)/', variable_get('authcache_mimetype', AUTHCACHE_MIMETYPE_DEFAULT), -1, PREG_SPLIT_NO_EMPTY);
  if (!in_array($content_type['mimetype'], $allowed_mimetypes)) {
    authcache_cancel(t('Only cache allowed HTTP content types (HTML, JS, etc)'));
  }

  // Check http status
  if (variable_get('authcache_http200', FALSE) && _authcache_get_http_status() != 200) {
    authcache_cancel(t('Don`t cache 404/403s/etc'));
  }

  // Check headers already were sent
  if (headers_sent()) {
    authcache_cancel(t('Don`t cache private file transfers or if headers were unexpectly sent.'));
  }

  // Make sure "Location" redirect isn't used
  foreach (headers_list() as $header) {
    if (strpos($header, 'Location:') === 0) {
      authcache_cancel(t('Location header detected'));
    }
  }

  // Don't cache pages with PHP errors (Drupal can't catch fatal errors)
  if (function_exists('error_get_last') && $error = error_get_last()) {
    switch ($error['type']) {
      // Ignore these errors:
      case E_NOTICE: // run-time notices
      case E_USER_NOTICE: // user-generated notice message
      case E_DEPRECATED: // run-time notices
      case E_USER_DEPRECATED: // user-generated notice message
        break;
      default:
        // Let user know there is PHP error and return
        authcache_cancel(t('PHP Error: @error', array('@error' => error_get_last())));
        break;
    }
  }
}


/**
 * Implements hook_authcache_cookie().
 */
function authcache_authcache_cookie($flags, $account) {
  $authenticated = $account->uid;
  $enabled = $flags & AUTHCACHE_FLAGS_ACCOUNT_ENABLED;
  $present = $authenticated && $enabled;

  $cookies['authcache']['present'] = $present;
  $cookies['authcache']['httponly'] = TRUE;
  $cookies['drupal_user']['present'] = $present;
  $cookies['drupal_uid']['present'] = $present;

  if ($present) {
    $cookies['authcache']['value'] =  authcache_key($account);
    $cookies['drupal_user']['value'] =  $account->name;
    $cookies['drupal_uid']['value'] =  $account->uid;
  }

  return $cookies;
}

/**
 * Implements hook_aceajax_request().
 */
function authcache_aceajax_request() {
  $request['tab'] = array(
    'maxage' => 86400,
  );

  return $request;
}

/**
 * Implements hook_aceajax_command().
 */
function authcache_aceajax_command() {
  return array(
    'form_token_id' => array(
      'class' => 'AuthcacheFormTokenIdCommand',
    ),
    'menu_local_tasks' => array(
      'class' => 'AuthcacheMenuLocalTasksCommand',
      'bootstrap' => DRUPAL_BOOTSTRAP_FULL,
    ),
  );
}