-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontent_lock.module
1199 lines (1095 loc) · 37.7 KB
/
content_lock.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Allows users to lock documents for modification.
*/
/**
* Implements hook_permission().
*/
function content_lock_permission() {
return array(
'check out documents' => array(
'title' => t('Check Out/Lock Documents'),
'description' => t('Enables users to lock documents and requires them to respect locks others have made.'),
),
'administer checked out documents' => array(
'title' => t('Administer Checked Out Documents'),
'description' => t('Enables administrators to view and break locks made by other users.'),
'restrict access' => TRUE,
),
);
}
/**
* Implements hook_help().
*/
function content_lock_help($path, $arg) {
switch ($path) {
case 'admin/help#content_lock':
$output = '<p>' . t("Backdrop's default content locking strategy is optimistic, that is, two users may start to edit the same content and the one who is hitting the save button first wins the race, while the other is displayed a message stating <em>this content has been modified by another user, changes cannot be saved</em>. Depending on the number of editors in your organization this might not be an acceptable solution.") . '</p>';
$output .= '<p>' . t('The Content locking module implements pessimistic locking, which means that content will be exclusively locked whenever a user starts editing it. The lock will be automatically released when the user submits the form or navigates away from the edit page.') . '</p>';
$output .= '<p>' . t('Users may also permanently lock content, to prevent others from editing it. Content locks that have been "forgotten" can be automatically released after a configurable time span.') . '</p>';
return $output;
case 'admin/content/content_lock':
return '<p>' . t('Below is a list of all locked documents. Click on <em>!checkin</em> to release a lock.', array('!checkin' => t('release lock'))) . '</p>';
case 'user/%/content_lock':
return '<p>' . t('Below is a list of all documents locked by you. Click on <em>!checkin</em> to release a lock.', array('!checkin' => t('release lock'))) . '</p>';
}
}
/**
* Implements hook_menu().
*/
function content_lock_menu() {
$items['admin/content/content_lock'] = array(
'title' => 'Locked documents',
'page callback' => 'content_lock_overview',
'access callback' => 'user_access',
'access arguments' => array('administer checked out documents'),
'weight' => 5,
'type' => MENU_LOCAL_TASK,
);
$items['admin/content/content_lock/release'] = array(
'page callback' => 'content_lock_release_item',
'page arguments' => array(4, NULL),
'access arguments' => array('administer checked out documents'),
'type' => MENU_CALLBACK,
);
$items['admin/content/%/content_lock/releaseown'] = array(
'page callback' => 'content_lock_release_own_item',
'page arguments' => array(2, TRUE, FALSE),
'access arguments' => array('check out documents'),
'type' => MENU_CALLBACK,
);
$items['user/%user/content_lock'] = array(
'title' => 'Locked documents',
'page callback' => 'content_lock_overview',
'page arguments' => array(1),
'access callback' => 'user_access',
'access arguments' => array('check out documents'),
'weight' => 5,
'type' => MENU_LOCAL_TASK,
);
$items['ajax/content_lock/%/canceledit'] = array(
'page callback' => 'content_lock_release_own_item',
'page arguments' => array(2, FALSE, FALSE),
'access callback' => 'user_access',
'access arguments' => array('check out documents'),
);
$items['ajax/content_lock/%node/lock/%'] = array(
'page callback' => 'content_lock_node_ajax_callback',
'page arguments' => array(2, 4),
'access callback' => 'user_access',
'access arguments' => array('check out documents'),
);
$items['admin/config/content/content_lock'] = array(
'type' => MENU_NORMAL_ITEM,
'title' => 'Content lock',
'description' => 'Configuration options for the Content lock module',
'page callback' => 'backdrop_get_form',
'page arguments' => array('content_lock_admin_settings'),
'access arguments' => array('administer site configuration'),
'file' => 'content_lock.admin.inc',
);
return $items;
}
/**
* Implements hook_admin_paths().
*
* Register ajax lock path as an admin path.
*/
function content_lock_admin_paths() {
$paths = array(
'ajax/content_lock/*/lock/*' => TRUE,
);
return $paths;
}
/**
* Implements hook_backdrop_goto_alter().
*/
function content_lock_backdrop_goto_alter(&$path, &$options, &$http_response_code) {
// Add content lock token.
if (module_exists('entity_translation') && fnmatch('node/*/edit/add/*/*', $path) && !isset($options['content_lock_token'])) {
$options = array(
'query' => array(
'content_lock_token' => backdrop_get_token($path),
),
);
}
}
/**
* Check if an internal Backdrop path should be protected with a token.
*
* Adds requirements that certain path be accessed only through tokenized URIs
* which are enforced by this module. This prevents people from being CSRFed
* into locking nodes that they can access without meaning to lock them.
*
* @return bool
* Returns TRUE if the path is protected or FALSE if not protected.
*/
function content_lock_is_path_protected($path) {
$cache = &backdrop_static(__FUNCTION__, array());
// Check cache.
if (isset($cache[$path])) {
return $cache[$path];
}
// Invoke hook and collect grants/denies for protected paths.
$protected = array();
foreach (module_implements('content_lock_path_protected') as $module) {
$protected = array_merge(
$protected,
array(
$module => module_invoke($module, 'content_lock_path_protected', $path),
)
);
}
// Allow other modules to alter the returned grants/denies.
backdrop_alter('content_lock_path_protected', $protected, $path);
// If TRUE is returned, path is protected.
$cache[$path] = in_array(TRUE, $protected);
return $cache[$path];
}
/**
* Implements hook_content_lock_path_protected().
*/
function content_lock_content_lock_path_protected($path) {
// Always protect node edit and revert paths.
if (strpos($path, 'node/') === 0) {
$paths_patterns = array(
'node/*/edit',
'node/*/edit/*',
'node/*/revisions/*/revert',
);
foreach ($paths_patterns as $protected_pattern) {
if (backdrop_match_path($path, $protected_pattern)) {
return TRUE;
}
}
}
// Allow extended tests via protection_menu_token module.
// if (function_exists('protection_menu_token_is_path_protected')) {
// return protection_menu_token_is_path_protected($path);
// }
}
/**
* Implements hook_preprocess_link().
*/
// function content_lock_preprocess_link(&$vars) {
// dpm($vars, 'vars');
// Append a CSRF token to all paths that show the node add/edit form.
// if (content_lock_is_path_protected($vars['path'])) {
// if (!isset($vars['options']['query']['content_lock_token'])) {
// $vars['options']['query']['content_lock_token'] = backdrop_get_token($vars['path']);
// }
// }
// }
/**
* apply token to menu local task
*
* @param [type] $vars
* @return void
*/
function content_lock_preprocess_menu_local_task(&$vars) {
// Append a CSRF token to all paths that show the node add/edit form.
if (isset($vars['element']['#link']['path']) && content_lock_is_path_protected($vars['element']['#link']['path'])) {
if (!isset($vars['element']['#link']['localized_options']['query']['content_lock_token'])) {
// dpm($vars['element']['#link']['href']);
$vars['element']['#link']['localized_options']['query']['content_lock_token'] = backdrop_get_token($vars['element']['#link']['href']);
}
}
}
/**
* apply token on edit links for views
*
* @param [type] $var
* @return void
*/
function content_lock_preprocess_views_view_field(&$var) {
if ($var['field']->field == 'edit_node' ||
$var['field']->field == 'dropbutton' ||
$var['field']->field == 'contextual_links') {
$output = $var['output'];
//extract the path to create the token
$pattern = '/href=".*\/(node\/\d+\/edit)/';
preg_match($pattern, $output, $matches);
if (isset($matches[1])) {
$token_path = $matches[1];
// add token to href
$pattern = '/(href=".*\/node\/\d+\/edit[^"]*)/';
$replacement = '$1&content_lock_token=' . backdrop_get_token($token_path);
$var['output'] = preg_replace($pattern, $replacement, $output);
}
}
}
/**
* Implements hook_node_validate().
*/
function content_lock_node_validate($node, $form, &$form_state) {
global $user;
if (isset($node->nid) && _content_lock_is_lockable_node($node) && user_access('check out documents')) {
// Existing node. Check if we still own the lock.
if ($lock = content_lock_fetch_lock($node->nid)) {
if ($lock->uid != $user->uid) {
// Lock is no longer ours.
form_set_error('changed', t('Your lock has been removed!') . '<br />' . content_lock_lock_owner($lock) . '<br />' . t('You can still save the content if this user aborts the edit operation without saving changes.'));
}
} else {
// Node is not locked. Try to re-lock if node is unchanged.
if (node_last_changed($node->nid) > $node->changed || !content_lock_node($node->nid, $user->uid)) {
form_set_error('alsochanged', t(
'Your lock has been removed due to inactivity or by an administrator. Failed to regain the lock since the document has been changed since. Please !discard.',
array('!discard' => l(t('discard your changes'), 'node/' . $node->nid))
));
}
}
}
}
/**
* Implements hook_node_update().
*/
function content_lock_node_update($node) {
if (user_is_logged_in() && _content_lock_is_lockable_node($node)) {
global $user;
content_lock_release($node->nid, $user->uid);
}
}
/**
* Implements hook_node_delete().
*/
function content_lock_node_delete($node) {
content_lock_release($node->nid, NULL);
}
/**
* Implements hook_node_view().
*/
function content_lock_node_view($node, $view_mode, $langcode) {
global $user;
static $messages_shown = FALSE;
if (
$view_mode != 'full'
|| !_content_lock_is_lockable_node($node)
) {
return;
}
if (!$messages_shown) {
_content_lock_show_warnings();
$messages_shown = TRUE;
}
if (empty($node->in_preview)) {
// Check if the user has pending locks and warn him.
content_lock_warn_pending_locks($user->uid);
}
}
/**
* Implements hook_config_info().
*/
function content_lock_config_info() {
$prefixes['content_lock.settings'] = array(
'label' => t('Content locking (edit lock) settings'),
'group' => t('Configuration'),
);
return $prefixes;
}
/**
* Implements hook_form_alter().
*/
function content_lock_form_alter(&$form, &$form_state, $form_id) {
$config = config('content_lock.settings');
global $user;
$node = empty($form['#node']) ? NULL : $form['#node'];
$nid = empty($form['nid']['#value']) ? NULL : $form['nid']['#value'];
$destination = 'node/' . $nid;
// Ensure user acquire a lock when reverting a node to an older revision.
if (!empty($form['#node_revision'])) {
$node = $form['#node_revision'];
$nid = $node->nid;
$destination = 'node/' . $nid . '/revisions';
}
// **************** Restore the node format ******************************
// This _content_lock_is_lockable_node() needs to know the original
// node format. We either dig up a stashed content_lock_old_format or
// initialize it here.
// Only touch node edit forms and then only if the form is `normal'
// and has a body with a format (#1183678).
if (
is_object($node) && is_numeric($nid)
&& ($form_id == $node->type . '_node_form' || $form_id == 'node_revision_revert_confirm')
&& isset($node->body)
&& is_array($node->body)
&& !empty($node->body[$node->langcode][0]['format'])
) {
$old_format = $node->body[$node->langcode][0]['format'];
if (!empty($node->content_lock_old_format)) {
$old_format = $node->content_lock_old_format;
}
if (!empty($form_state['values']['content_lock_old_format'])) {
$old_format = $form_state['values']['content_lock_old_format'];
}
// Needs to be manually set before first form submission.
// We set this in the $node-> namespace because content_lock_nodeapi()
// doesn't see $form_state['values'].
$node->content_lock_old_format = $old_format;
$form['content_lock_old_format'] = array(
'#type' => 'hidden',
'#value' => $node->content_lock_old_format,
);
}
// General preconditions for locking.
// Veto-API. Let other modules veto the locking - so force skipping out
// of any conditions they want.
// We will use || logic, so if any module denies locking then we
// deny locking.
// Be sure to notice that content_lock also implements this api
// for his own vetos.
$skip_lock = FALSE;
$result = module_invoke_all('content_lock_skip_locking', $node, $form_id, $form, $form_state);
foreach ($result as $bool) {
if (is_bool($bool)) {
$skip_lock = $skip_lock || $bool;
}
}
if ($skip_lock == FALSE) {
// Adding cancel button, if configured.
if ($config->get('content_lock_admin_cancelbutton')) {
_content_lock_add_cancelbutton($form, $form_state, $form_id);
}
// If we are handling a preview, skip locking.
if (!empty($form_state['rebuild']) && $form_state['rebuild'] == TRUE) {
// Placeholder.
}
// If the form did not get submitted we show it the first time
// so try to get the lock if possible.
else {
if ($form_state['submitted'] === FALSE) {
// Refuse to lock if a token is not present. This prevents a CSRF attack
// if a user is tricked into visiting pages that cause nodes to be
// locked.
// A CSRF token may be missing in these cases:
// - A node add/edit form is displayed on a path that is not protected
// with a CSRF token. Please add the path to the list of protected
// paths by implementing hook_content_lock_path_protected().
// - The CSRF token has not been added to the URL as a query parameter,
// for example because the user entered node/1/edit directly in the
// address bar of the browser. To avoid CSRF attacks we do not lock
// the node automatically, but still give the user the possibility to
// lock the node manually using an AJAX call with a proper CSRF token.
$menu_item = menu_get_item();
if (empty($_GET['content_lock_token']) || !backdrop_valid_token($_GET['content_lock_token'], $menu_item['href'])) {
backdrop_set_message(t('The page you are editing could not be locked automatically. Please !link to make sure other people cannot accidentally overwrite your changes.', array(
'!link' => l(t('lock the page'), 'nojs/content_lock/' . $nid . '/lock/' . backdrop_get_token($nid), array('attributes' => array('class' => array('use-ajax')))),
)), 'error');
if (!content_lock_is_path_protected($menu_item['path'])) {
watchdog('content_lock', 'Attempt to load the node_form form at menu path %path which is not protected from CSRF. Developers who want to create custom node editing pages and protect them with hook_content_lock_path_protected() or use protection_menu_token module to protect this path.', array('%path' => $menu_item['path']), WATCHDOG_WARNING);
}
} else {
// Finally set the lock if everything passed.
if (content_lock_node($nid, $user->uid) == FALSE) {
// Could not lock node, it's locked by someone else.
backdrop_goto($destination);
}
// If we should lock or already have been locked, load the unload js.
// Don't use form alter but rather after build, so it works even for
// previews.
elseif ($config->get('content_lock_unload_js')) {
$form['#after_build'][] = '_content_lock_add_unload_js';
}
}
}
}
}
}
/**
* Implements our own skip_locking api to implement our logic to skip locks.
*/
function content_lock_content_lock_skip_locking($node, $form_id, $form, $form_state) {
global $user;
$nid = empty($form['nid']['#value']) ? NULL : $form['nid']['#value'];
// Support node revision by not requiring the form to have an 'nid' key.
if (empty($nid) && $form_id == 'node_revision_revert_confirm' && !empty($form['#node_revision'])) {
$nid = $node->nid;
}
// Locked node types. Do not mix this up with the content_types you can
// chose on the admin form of content lock
// this types are forced due to disfunctionality.
// We are not allowed to lock on users form edit, as it
// always returns to the edit form.
$node_type_blacklist = array(
'user' => TRUE,
);
// Form ids listed here will not be locked.
// Do not lock on comment forms.
$form_id_blacklist = array(
'comment_form' => TRUE,
);
// Add the node-type administration.
if ($node != NULL) {
$form_id_blacklist['node_type_form'] = TRUE;
}
// Let other modules modify our blacklist.
backdrop_alter('content_lock_form_id_blacklist', $form_id_blacklist, $node);
if (
$node == NULL
|| empty($nid)
|| !empty($node_type_blacklist[$node->type])
|| !empty($form_id_blacklist[$form_id])
|| $user->uid <= 0
|| !user_access('check out documents')
|| ($form_id != $node->type . '_node_form'
&& $form_id != 'node_revision_revert_confirm')
) {
// Preconditions failed, skip the lock.
return TRUE;
}
// Check if the current node type and format type is configured to be locked
// $node->content_lock_old_format has been set in content_lock_form_alter().
if (!_content_lock_is_lockable_node($node)) {
// It should not be locked, so skip the lock.
return TRUE;
}
// We have no veto, so lock the node.
return FALSE;
}
/**
* Calculate the token required to unlock a node.
*
* Tokens are required because they prevent CSRF.
*
* @see https://security.drupal.org/node/2429
*/
function content_lock_get_release_token($nid) {
return backdrop_get_token("content_lock/release/$nid");
}
/**
* Add unload js.
*
* @param array $form
* Form.
* @param array $form_state
* Form state.
*
* @return mixed
* Form array
*/
function _content_lock_add_unload_js(&$form, $form_state) {
$config = config('content_lock.settings');
$m = backdrop_get_path('module', 'content_lock');
backdrop_add_js("$m/js/jquery.url.packed.js", array('group' => JS_LIBRARY));
backdrop_add_js("$m/js/onUserExit.js", array('group' => JS_LIBRARY));
backdrop_add_js("$m/js/content_lock_init.js");
$nid = empty($form['nid']['#value']) ? NULL : $form['nid']['#value'];
$internal_urls = array();
$internal_form_selectors = array();
// We're on a locked revision reversion page.
if (!empty($form['#node_revision']->nid)) {
$nid = $form['#node_revision']->nid;
// Don't ask the user if he wants to leave the page when
// cancelling a reversion.
$internal_urls[] = $form['actions']['cancel']['#href'];
$internal_form_selectors[] = '.confirmation';
}
$internal_urls[] = 'node/' . $nid . '/edit';
$internal_form_selectors[] = 'form.node-form';
// Check lock status.
$lock = content_lock_fetch_lock($nid);
if ($lock) {
$lock_ajax_key = $lock->ajax_key;
} else {
$lock_ajax_key = FALSE;
}
// Get tokens.
$token = content_lock_get_release_token($nid);
// Prepare settings.
$settings = array(
'nid' => $nid,
'ajax_key' => $lock_ajax_key,
'token' => $token,
'unload_js_message_enable' => $config->get('content_lock_unload_js_message_enable'),
'internal_urls' => implode('|', $internal_urls),
'internal_forms' => implode(', ', $internal_form_selectors),
);
if ($settings['unload_js_message_enable']) {
$settings['unload_js_message'] = $config->get('content_lock_unload_js_message');
}
/*
* Workaround for http://drupal.org/node/1525784 where this function
* is called multiple times when doing a file field AJAX upload and
* array_merge_recursive() is used instead of
* backdrop_array_merge_deep_array() to construct the Backdrop.settings
* value. Not calling backdrop_add_js() multiple times deprives
* file_ajax_upload() of the ability to mess up here ;-).
*/
$called = &backdrop_static(__FUNCTION__ . '__called');
if (!empty($called)) {
$called++;
return $form;
}
$called = 1;
backdrop_add_js(array('content_lock' => $settings), 'setting');
return $form;
}
/**
* Get verbose.
*/
function _content_lock_verbose() {
return config_get('content_lock.settings', 'content_lock_admin_verbose');
}
/**
* Add cancel button.
*/
function _content_lock_add_cancelbutton(&$form, $form_state, $form_id) {
// If we're on the node form.
$node = empty($form['#node']) ? NULL : $form['#node'];
$nid = empty($form['nid']['#value']) ? NULL : $form['nid']['#value'];
if (!empty($form['#node_revision'])) {
$node = $form['#node_revision'];
$nid = $node->nid;
}
if (
!empty($node) && !empty($nid)
&& ($form_id == $node->type . '_node_form' || $form_id == 'node_revision_revert_confirm')
) {
// Revert node.
if ($form_id == 'node_revision_revert_confirm') {
/* Hijack the default cancel link to become a lock-releasing link */
$destination = 'node/' . $nid . '/revisions';
if (!empty($form['actions']['cancel']['#href'])) {
$destination = $form['actions']['cancel']['#href'];
}
$form['actions']['cancel']['#href'] = 'admin/content/' . $nid . '/content_lock/releaseown';
$form['actions']['cancel'] += array('#options' => array());
$form['actions']['cancel']['#options'] += array(
'query' => array(
'token' => content_lock_get_release_token($nid),
'destination' => $destination,
),
);
}
// If we're editing a node (not adding).
else {
if ($node->nid) {
$form['actions']['cancel'] = array(
'#type' => 'button',
'#weight' => 2000,
'#value' => t('Cancel edit'),
'#validate' => array('content_lock_cancel_submit'),
);
if (isset($form['actions']['delete'])) {
$form['actions']['delete']['#weight'] = 2001;
}
}
}
}
}
/**
* Callback for a cancel request on a form.
*/
function content_lock_cancel_submit(&$form, &$form_state) {
// Release the node.
content_lock_release_own_item($form['#node']->nid, TRUE, TRUE);
}
/**
* Fetch the lock for a node.
*
* @param string $nid
* A node id.
*
* @return object
* The lock for the node. FALSE, if the document is not locked.
*/
function content_lock_fetch_lock($nid) {
$query = db_select('content_lock', 'c')
->fields('c')
->condition('c.nid', $nid);
$u = $query->leftJoin('users', 'u', '%alias.uid = c.uid');
$query->fields($u, array('name'));
return $query->execute()->fetchObject();
}
/**
* Tell who has locked node.
*
* @param object $lock
* The lock for a node.
*
* @return string
* String with the message.
*/
function content_lock_lock_owner($lock) {
$username = theme('username', array('account' => user_load($lock->uid)));
$date = format_date($lock->timestamp, 'medium');
return t('This document is locked for editing by !name since @date.', array(
'!name' => $username,
'@date' => $date,
));
}
/**
* Implements hook_user_logout().
*/
function content_lock_user_logout($account) {
// Removing all locks, as the user logs out.
_content_lock_release_all_user_locks($account->uid);
}
/**
* AJAX callback to lock a node manually.
*
* @param object $node
* The node to lock.
* @param string $token
* The CSRF token.
*/
function content_lock_node_ajax_callback($node, $token) {
global $user;
// Only lock the node if we have a valid CSRF token.
if (backdrop_valid_token($token, $node->nid)) {
content_lock_node($node->nid, $user->uid);
// Add the javascript that unlocks the node when the user navigates away
// from the page.
$form = array('nid' => array('#value' => $node->nid));
_content_lock_add_unload_js($form, array());
} else {
backdrop_set_message(t('The content could not be locked.'));
}
$commands = array();
$commands[] = ajax_command_remove('div.messages');
$commands[] = ajax_command_before('#block-system-main', theme('status_messages'));
ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));
}
/**
* Try to lock a document for editing.
*
* If the lock exists, a new AJAX unlock key is created to combat AJAX
* unlocks during page reloads. See http://drupal.org/node/1049708.
*
* @param int $nid
* A node id.
* @param int $uid
* The user id to lock the node for.
* @param bool $quiet
* Suppress any normal user messages.
*
* @return bool
* FALSE, if a document has already been locked by someone else.
*/
function content_lock_node($nid, $uid, $quiet = FALSE) {
$lock = content_lock_fetch_lock($nid);
if ($lock != FALSE && $lock->uid != $uid) {
$message = content_lock_lock_owner($lock);
if (user_access('administer checked out documents')) {
$url = "admin/content/content_lock/release/$nid";
}
if (isset($url)) {
$token = content_lock_get_release_token($nid);
$message .= '<br />';
$message .= t('Click !here to check back in now.', array(
'!here' => l(t('here'), $url, array(
'query' => array(
'token' => $token,
'destination' => $_GET['q'],
),
)),
));
}
if (!empty($message)) {
backdrop_set_message($message, 'warning', FALSE);
}
return FALSE;
} else {
// No lock yet, create one.
if ($lock == FALSE) {
// Lock node.
$data = array(
'nid' => $nid,
'uid' => $uid,
'timestamp' => time(),
'ajax_key' => rand(),
);
backdrop_write_record(
'content_lock',
$data
);
if (_content_lock_verbose() && !$quiet) {
backdrop_set_message(t('This document is now locked against simultaneous editing.'), 'status', FALSE);
}
module_invoke_all('content_lock_locked', $nid, $uid);
} else {
/* A lock already exists: update its AJAX key */
$lock->ajax_key = rand();
if (!backdrop_write_record('content_lock', $lock, array('nid'))) {
/*
* we encountered a race condition where the lock was deleted
* between when we loaded it and when we tried to update it
* with a new key. Recreate the lock then:
*/
backdrop_write_record('content_lock', $lock);
}
}
}
return TRUE;
}
/**
* Release a locked node.
*
* @param int $nid
* The node id to release the edit lock for.
* @param int $uid
* If set, verify that a lock belongs to this user prior to release.
*/
function content_lock_release($nid, $uid = NULL) {
$query = db_delete('content_lock')
->condition('nid', $nid);
if (!empty($uid)) {
$query->condition('uid', $uid);
}
$query->execute();
module_invoke_all('content_lock_release', $nid);
}
/**
* Release all locks.
*/
function _content_lock_release_all_user_locks($uid) {
db_delete('content_lock')
->condition('uid', $uid)
->execute();
}
/**
* Build an overview of locked documents.
*
* @param object $account
* User account.
*
* @return string
* Overview list.
*
* @throws \Exception
*/
function content_lock_overview($account = NULL) {
global $user;
// @TODO old checkout code, review.
$header = array(
array(
'data' => t('Title'),
'field' => 'n.title',
'sort' => 'asc',
),
);
// In the case of an admin, we do not have uid, as he sees all locks.
if (!is_object($account)) {
$header[] = array(
'data' => t('Username'),
'field' => 'u.name',
);
$uid = NULL;
}
// Otherwise we have the account of the user just being views as argument.
else {
$uid = $account->uid;
}
$header[] = array(
'data' => t('Locked since'),
'field' => 'c.timestamp',
);
if ($uid == $user->uid || user_access('administer checked out documents')) {
$header[] = t('Operations');
}
$query = db_select('content_lock', 'c')
->extend('TableSort')
->fields('c');
$n = $query->join('node', 'n', '%alias.nid = c.nid');
$query->fields($n, array('title'));
$u = $query->join('users', 'u', '%alias.uid = c.uid');
$query->fields($u, array('name'));
if ($uid) {
$query->condition('c.uid', $uid);
}
$query->orderByHeader($header);
$rows = array();
foreach ($query->execute() as $data) {
$url = $uid ? "admin/content/" . $data->nid . "/content_lock/releaseown" : 'admin/content/content_lock/release/' . $data->nid;
$row = array();
$row[] = l($data->title, "node/$data->nid");
if (!$uid) {
$row[] = theme('username', array('account' => user_load($data->uid)));
}
$row[] = format_date($data->timestamp, 'small');
if ($uid == $user->uid || user_access('administer checked out documents')) {
$row[] = l(t('release lock'), $url, array('query' => array('token' => content_lock_get_release_token($data->nid))));
}
$rows[] = $row;
}
$output = theme('table', array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => 'content_lock'),
'empty' => t('No locked documents.'),
));
$output .= theme('pager', array('quantity' => 50));
return $output;
}
/**
* Menu callback.
*
* Release a locked node for all users or a specific user.
*
* @param int $nid
* A node id.
* @param object $account
* A user object. If passed, the lock will only be released if this
* user owned it.
*
* @return int
* This function will execute a redirect and not return.
*
* @throws \Exception
*/
function content_lock_release_item($nid, $account = NULL) {
global $user;
if (empty($_GET['token']) || !backdrop_valid_token($_GET['token'], "content_lock/release/$nid")) {
return MENU_ACCESS_DENIED;
}
if (!$account && _content_lock_verbose()) {
/*
* Enable our "lock released" message to inform the user who
* likely owned the lock which is to be broken.
*/
$lock = content_lock_fetch_lock($nid);
}
content_lock_release($nid, $account ? $account->uid : NULL);
if (_content_lock_verbose()) {
if (!empty($lock) && !$account && $user->uid != $lock->uid) {
$lock_account = user_load($lock->uid);
backdrop_set_message(t('The editing lock held by !user has been released.', array('!user' => theme('username', array('account' => $lock_account)))), 'status', FALSE);
} else {
backdrop_set_message(t('The editing lock has been released.'), 'status', FALSE);
}
}
backdrop_goto($account ? "user/{$account->uid}/content_lock" : 'admin/content/content_lock');
}
/**
* Warn pending locks.
*
* For every lock a user current have on any nodes, print a warning message
* with an link to release this node.
*
* @param int $uid
* User ID.
*/
function content_lock_warn_pending_locks($uid) {
// Cache.
static $warned_nodes = array();
static $content_lock_messages_printed = FALSE;
if ($content_lock_messages_printed) {
return;
}
if (array_key_exists($uid, $warned_nodes)) {
// Placeholder.
} else {
// Load form db.
$warned_nodes[$uid] = array();
$query = db_select('content_lock', 'c')
->fields('c', array('nid'))
->condition('c.uid', $uid);
$n = $query->leftJoin('node', 'n', '%alias.nid = c.nid');
$query->fields($n, array('title'));
foreach ($query->execute() as $lock) {
$warned_nodes[$uid][] = $lock;
}
}
foreach ($warned_nodes[$uid] as $lock) {
$nodetitle_link = l($lock->title, "node/{$lock->nid}");
$token = content_lock_get_release_token($lock->nid);
$releasethelock_link = l(t('release the lock'), "admin/content/{$lock->nid}/content_lock/releaseown", array('query' => array('token' => $token)));
_content_lock_save_lock_warning(t("The node '!nodetitle_link' is locked by you. You may want to '!releasethelock_link' in order to allow others to edit.", array(
'!nodetitle_link' => $nodetitle_link,
'!releasethelock_link' => $releasethelock_link,
)), $lock->nid);
}
$content_lock_messages_printed = TRUE;
}
/**
* Save lock warning.
*
* @param string $message
* Message string.
* @param int $nid
* Node id.