-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathflagfilter.js
More file actions
1905 lines (1646 loc) · 72 KB
/
flagfilter.js
File metadata and controls
1905 lines (1646 loc) · 72 KB
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
//
// A bunch of quick'n'dirty patches to test faster flag handling UIs on Stack Overflow
// Some or all of these may eventually be "baked in" - IF they prove useful
// Don't expect any of the actual CODE to be used in production though.
// Remember: the goal here is to be QUICK even - especially - if that means DIRTY
// --Josh "Shog9" Heyer, March 2014
//
// WARNING: May break in potentially catestrophic fashion at any time.
// DO NOT release publicly
// DO NOT USE LOCAL COPIES
// If you use a local copy and something breaks, you're responsible for the consequences.
//
$(function()
{
initTools();
initRoute();
function initRoute()
{
if (/^\/admin/.test(window.location.pathname))
{
// add tab so we can find this thing
$("#tabs a[href='/admin/dashboard']")
.after('<a href="/admin/flags" title="a simple list of all pending flags with fast filtering">filtered flags</a>');
}
if (/^\/admin\/flags\/?$/.test(window.location.pathname) )
{
initFlagFilter();
}
if (/^\/questions\//.test(window.location.pathname))
{
initQuestionPage();
initKeyboard();
}
if (/^\/review\/\w+/.test(window.location.pathname))
{
// for direct links to a review task
initReview();
// for ajax-loaded review tasks
$(document).ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions)
{
if ( ajaxOptions.url.indexOf("/review/next-task")==0 || ajaxOptions.url.indexOf("/review/task-reviewed")==0 )
{
setTimeout(function()
{
initReview();
}, 1);
}
})
}
// this is mostly just to gather information on who can see what, since that's gotten a bit... confusing
if (/^\/users\/\d+\/[^\/]+$/.test(window.location.pathname))
{
$("<a href='#'>Dashboard</a>")
.wrap("<div style='text-align:center;margin-top:1em;'></div>")
.parent().appendTo("#large-user-info .gravatar").end()
.click(function(ev)
{
ev.preventDefault();
renderUserDashboard();
$(this).parent().remove();
});
function renderUserDashboard()
{
var userId = window.location.pathname.match(/^\/users\/(\d+)/)[1];
var accountId = $(".sub-header-links a:contains('network profile')").attr('href').match(/\/users\/(\d+)/)[1];
var container = $("#user-panel-reputation").parent()
.empty();
var loading = $("<h3>TODO: load user info<img src='//sstatic.net/img/progress-dots.gif'></h3>")
.appendTo(container);
// load all PII first, so we can access this later on
var pii = $(".pii:contains('(click to show)')");
if ( pii.length )
{
pii.click();
}
// do the other loadings
var infos = [
{url:"/accounts/<accountId>", method: "GET", render: function(html) { return $(html).find("#content");}},
{url:"/users/history/<uid>", method: "GET", render: function(html) { return $(html).find("#content");}},
{url:"/admin/users/<uid>/moderator-menu",method: "GET", render: function(html) { return $(html);}},
{url:"/users/popup/logins/<accountId>", method: "POST", render: function(html) { return $(html);}}
];
loadInfo(infos);
function loadInfo(list)
{
if (!list.length)
{
loading.remove();
return;
}
var info = list.pop();
$.ajax(info.url.replace('<uid>', userId).replace('<accountId>', accountId),
{
type: info.method,
data: {fkey:StackExchange.options.user.fkey}
})
.done(function(html)
{
$("<div></div>").append(info.render(html)).appendTo(container)
.find(".popup").css({display:'block', position:'inherit'});
loadInfo(list);
});
}
}
}
}
//
// Misc utils
//
function getQSVal(name)
{
var val = [];
window.location.search.substr(1).split('&').forEach(function(p)
{
var kv = p.split('=');
if ( kv[0] === name && kv.length > 1 )
val.push(decodeURIComponent(kv[1]));
});
return val;
}
function goToFilteredFlag(delta)
{
var filtered = localStorage.flaaaaags.split(',');
var index = filtered.indexOf(location.pathname.match(/\/questions\/(\d+)/)[1]);
if ( index+delta >= 0 && index+delta < filtered.length )
window.location.pathname = "/questions/" + filtered[index+delta];
}
function predictMigrationDest(flagText)
{
return loadMigrationSites()
.then(function(sites)
{
var ret = {baseHostAddress: '', name: ''};
sites.forEach(function(site)
{
var baseHost = site.site_url.replace(/^https?:\/\//, '');
if ( (RegExp(baseHost.replace('.stackexchange.com', ''), 'i').test(flagText)
|| RegExp(site.name.replace(' ', '\\s?'), 'i').test(flagText))
&& ret.baseHostAddress.length < baseHost.length )
ret = { baseHostAddress: baseHost, name: site.name };
});
return ret;
});
function loadMigrationSites()
{
var ret = $.Deferred();
var cachekey = "flaaaaags.site-cache";
var cacheExpiration = new Date();
cacheExpiration = cacheExpiration.setHours(cacheExpiration.getHours()-24);
var siteCache = localStorage.getItem(cachekey);
if (siteCache) siteCache = JSON.parse(siteCache);
if (siteCache && siteCache.age > cacheExpiration)
{
ret.resolve(siteCache.sites);
return ret;
}
return $.get('https://api.stackexchange.com/2.2/sites?pagesize=500')
.then(function(data)
{
var sites = [];
var siteArray = data.items;
if ( siteArray && siteArray.length && siteArray[0].name )
{
sites = siteArray;
localStorage.setItem(cachekey, JSON.stringify({age: Date.now(), sites: sites}));
}
return sites;
});
}
}
//
// Generally-useful moderation routines
//
function initTools()
{
FlagFilter.tools = {
CloseReasons: { Duplicate: 'Duplicate', OffTopic: 'OffTopic', Unclear: 'Unclear', TooBroad: 'TooBroad', OpinionBased: 'OpinionBased' },
UniversalOTReasons: { Default: 1, BelongsOnSite: 2, Other: 3 },
// format for close options:
// { closeReasonId string - one of the close reasons above
// duplicateOfQuestionId number - question id for duplicate, otherwise not set
// closeAsOffTopicReasonId number - site-specific reason ID for OT, otherwise not set
// belongsOnBaseHostAddress string - host domain for destination site for OT, otherwise not set
// offTopicOtherText string - custom OT text for when the OT reason is "other"
// and offTopicOtherCommentId is not set
// offTopicOtherCommentId string - reference to an existing comment on the post describing
// why the question is off-topic for when the OT reason is "other"
// and offTopicOtherText is not specified.
// originalOffTopicOtherText string - the placeholder / prefix text used to prompt for the OT other reason,
// used when offTopicOtherText is specified, otherwise not set
// }
closeQuestion: function(postId, closeOptions)
{
closeOptions.fkey = StackExchange.options.user.fkey;
return $.post('/flags/questions/' + postId + '/close/add', closeOptions)
},
migrateTo: function(postId, destinationHost)
{
return FlagFilter.tools.closeQuestion(postId,
{
closeReasonId: FlagFilter.tools.CloseReasons.OffTopic,
closeAsOffTopicReasonId: FlagFilter.tools.UniversalOTReasons.BelongsOnSite,
belongsOnBaseHostAddress: destinationHost
});
},
annotateUser: function(userId, annotation)
{
return $.post('/admin/users/' + userId + '/annotate',
{
"mod-actions": "annotate",
annotation: annotation,
fkey: StackExchange.options.user.fkey
});
},
reviewBanUser: function(userId, days, explanation)
{
var params = {
userId: userId,
reviewBanDays: days,
fkey: StackExchange.options.user.fkey
};
if ( explanation )
params.explanation = explanation;
return $.post('/admin/review/ban-user', params);
},
formatDate: function(isoDate)
{
return (new Date(isoDate.replace(/\s/,'T')))
.toLocaleDateString(undefined, {year: "numeric", month: "short", day: "numeric", timeZone: "UTC"});
},
dismissAllCommentFlags: function(commentId, flagId)
{
// although the UI implies it's possible, we can't currently dismiss individual comment flags
return $.post('/admin/comment/' + commentId+ '/clear-flags', {fkey:StackExchange.options.user.fkey});
},
dismissFlag: function(postId, flagId, helpful, declineId, comment)
{
var ticks = window.renderTimeTicks||(Date.now()*10000+621355968000000000);
return $.post('/messages/delete-moderator-messages/' + postId + '/'
+ ticks + '?valid=' + helpful + '&flagIdsSemiColonDelimited=' + flagId,
{comment: comment||declineId||'', fkey:StackExchange.options.user.fkey});
},
dismissAllFlags: function(postId, helpful, declineId, comment)
{
var ticks = window.renderTimeTicks||(Date.now()*10000+621355968000000000);
return $.post('/messages/delete-moderator-messages/' + postId + '/'
+ ticks+ '?valid=' + helpful,
{comment: comment||declineId||'', fkey:StackExchange.options.user.fkey});
},
moveCommentsToChat: function(postId)
{
return $.post('/admin/posts/' + postId + '/move-comments-to-chat', {fkey:StackExchange.options.user.fkey});
},
makeWait(msecs)
{
return function()
{
var args = arguments;
var result = $.Deferred();
setTimeout(function() { result.resolve.apply(result, args) }, msecs);
return result.promise();
}
}
};
}
//
// coopt a 404 to provide an easily-filterable list of flags
//
function initFlagFilter()
{
var flaggedPosts = [];
var initializing = true;
document.title = "Flaaaaaags!";
$('#content').html(FlagFilter.templates.flagsLayout());
$("<div id='filterbox' style='position:fixed;bottom:0;left:0;width:100%;z-index:10000;background:white;'><hr><span style='float:right;padding-right:10em;' id='flagCount'></span> Filter: <input id='flagfilter' style='width:50%'></div>")
.appendTo('body')
$.get('/admin/all-flags')
.done(function(fp)
{
FlagFilter.flaggedPosts = flaggedPosts = fp.sort(function(a,b){return b.flags.length-a.flags.length;});
initializing = false;
renderFilters(flaggedPosts, $('#flagFilters'));
restoreFilter();
var filterDelay;
$("#flagfilter").keyup(function()
{
var filter = $(this).val();
if ( filterDelay)
clearTimeout(filterDelay);
filterDelay = setTimeout(function()
{
filterDelay=null;
setFilter(filter);
}, 600);
});
});
$("#flagFilters").on("click", ".flagFilter a", function(ev)
{
ev.preventDefault();
history.pushState(this.href, '', this.href);
restoreFilter();
});
$(window).on('popstate', restoreFilter);
$("#flagSort input[name=sort]").click(restoreFilter);
function restoreFilter()
{
var filter = getQSVal("filter")[0] || '';
$("#flagfilter").val(filter);
filterFlags(filter);
}
function setFilter(filter)
{
if ( filter === getQSVal("filter")[0] || '' )
return;
history.pushState(filter, '', filter ? '?filter=' + encodeURIComponent(filter) : location.pathname);
filterFlags(filter);
}
function filterFlags(filter)
{
if ( initializing ) return;
var filterFn = buildFilterFunction(filter);
var sortFn = getSortFunction();
var filteredFlaggedPosts = flaggedPosts.filter(filterFn);
var collaspedFilteredFlaggedPosts = collapseFlags(filteredFlaggedPosts);
var sortedCollapsedFilteredFlaggedPosts = collaspedFilteredFlaggedPosts.sort(sortFn);
localStorage.setItem("flaaaaags",
unique(sortedCollapsedFilteredFlaggedPosts.map(function(p) { return p.questionId; })).join(','));
localStorage.setItem("flaaaaags.lastFilter", location.toString());
$('#flaggedPosts').empty();
renderFlags(sortedCollapsedFilteredFlaggedPosts).then(function()
{
$("<a>Dismiss all of these flags</a>")
.appendTo('#flaggedPosts')
.click(function() { dismissAllFilteredFlags($('#flaggedPosts'), unique(sortedCollapsedFilteredFlaggedPosts.map(function(p) { return p.postId; })), filter) });
});
$("#flagCount").text(filteredFlaggedPosts.length + " flagged posts");
function getSortFunction()
{
var sortFuncs = {
postDesc: function(a,b)
{
return new Date(a.created.replace(/\s/,'T'))-new Date(b.created.replace(/\s/,'T'));
},
postAsc: function(b,a)
{
return new Date(a.created.replace(/\s/,'T'))-new Date(b.created.replace(/\s/,'T'));
},
flagDesc: function(a,b)
{
return new Date(a.flags[0].created.replace(/\s/,'T'))-new Date(b.flags[0].created.replace(/\s/,'T'));
},
flagAsc: function(b,a)
{
return new Date(a.flags[0].created.replace(/\s/,'T'))-new Date(b.flags[0].created.replace(/\s/,'T'));
},
netHelpfulDesc: function(b,a)
{
var aHelpful = Math.max.apply(null,a.flags.map(function(f){return f.flagger.helpfulFlags-f.flagger.declinedFlags;}));
var bHelpful = Math.max.apply(null,b.flags.map(function(f){return f.flagger.helpfulFlags-f.flagger.declinedFlags;}));
return aHelpful-bHelpful;
},
netHelpfulAsc: function(a,b)
{
var aHelpful = Math.max.apply(null,a.flags.map(function(f){return f.flagger.helpfulFlags-f.flagger.declinedFlags;}));
var bHelpful = Math.max.apply(null,b.flags.map(function(f){return f.flagger.helpfulFlags-f.flagger.declinedFlags;}));
return aHelpful-bHelpful;
}
};
return sortFuncs[$("#flagSort input[name=sort]:checked").val()] || sortFuncs.flagDesc;
}
function collapseFlags(flaggedPosts)
{
return flaggedPosts.map(function(fp)
{
var collapsedFlags = fp.flags
.sort(function(a,b) { return new Date(a.created.replace(/\s/,'T'))-new Date(b.created.replace(/\s/,'T')); }) // oldest flag in a group wins
.reduce(function(cf, flag)
{
if ( !cf[flag.description] )
{
cf[flag.description] = flag;
flag.flaggers = [];
}
cf[flag.description].flaggers.push(flag.flagger);
return cf;
}, {});
collapsedFlags = $.map(collapsedFlags, function(flag) { return flag; });
return $.extend({}, fp, {flags:collapsedFlags});
});
}
function renderFlags(flaggedPosts, startAt)
{
var result = $.Deferred();
// don't let these overlap
clearTimeout(window.renderTimer);
window.renderTimer = null; // debugging
startAt = startAt||0;
var startTime = Date.now();
var maxRunTime = 150;
var container = $('#flaggedPosts');
for (; startAt<flaggedPosts.length && Date.now()-startTime < maxRunTime; ++startAt)
{
$("<div class='FlaggedPost'>")
.html(FlagFilter.templates.flag(flaggedPosts[startAt]))
.appendTo(container);
}
StackExchange.realtime.updateRelativeDates(); // render dates in the standard fashion
// finish rendering after letting the display update
if ( startAt<flaggedPosts.length )
window.renderTimer = setTimeout(function() { renderFlags(flaggedPosts, startAt).then(function(){result.resolve()}); }, 100);
else
result.resolve();
return result.promise();
}
}
function buildFilterFunction(filter)
{
var filters = [];
var filterOperators = {
user: function(userId)
{
return this.author
&& (this.author.url == userId || this.author.url.indexOf("/users/"+userId+"/") == 0);
},
tag: function(tag)
{
return this.tags.some(function(t)
{
return t == tag;
});
},
flagger: function(userId)
{
return this.flags.some(function(f)
{
return f.flagger
&& (f.flagger.url == userId || f.flagger.url.indexOf("/users/"+userId+"/") == 0);
});
},
type: function(type)
{
return this.flags.some(function(f)
{
return f.flagType + (f.flagReason||'')==type;
});
},
selfflagged: function()
{
var author = this.author;
return this.flags.some(function(f)
{
return f.flagger && author && f.flagger.url==author.url;
});
},
not: function(filter)
{
var fn = buildFilterFunction(filter);
return !fn(this);
},
isquestion: function() { return this.questionId==this.postId; },
isanswer: function() { return this.questionId!=this.postId; },
isdeleted: function() { return this.deleted; },
isclosed: function() { return this.closed; },
isanswered: function() { return this.hasAcceptedAnswer; },
isaccepted: function() { return this.isAcceptedAnswer; }
};
$.each(filterOperators, function(name, fn)
{
filter = filter.replace(new RegExp("(?:fn)?\\:" + name + "(?:\\(("
+ "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" // stolen from sizzle 'cause my eyes hurt to look at it
+ "[^\\)]*"
+ ")\\))", "g"),
function()
{
var arg, i;
for (i=4; !arg && i>0; --i)
arg = arguments[i];
filters.push(function(fp)
{
return fn.call(fp, arg);
});
return '';
});
return filter !== '';
});
if ( $.trim(filter).length || !filters.length )
{
filters.push(function(fp)
{
return fp.flags.some(function (f)
{
return new RegExp(filter||'', 'i').test(f.description);
});
});
}
return function(fp) { return filters.every(function(f) { return f(fp); }); }
}
function buildFilters(flaggedPosts)
{
var filters = {};
function addFilter(category, name, search, cssClass)
{
var cat = filters[category] = filters[category]||{};
var filter = cat[search] = cat[search]
||{name:name,search:encodeURIComponent(search), cssClass: cssClass, count:0};
filter.count++;
}
function addSearchFilter(category, name, search, cssClass)
{
var count = flaggedPosts.filter(buildFilterFunction(search)).length;
if ( !count ) return;
var cat = filters[category] = filters[category]||{};
var filter = cat[search] = cat[search]
||{name:name,search:encodeURIComponent(search), cssClass: cssClass, count:0};
filter.count = count;
}
flaggedPosts.forEach(function(p)
{
// flaggers
p.flags.forEach(function(f)
{
if ( f.flagger )
addFilter("Users with flags", f.flagger.name, "fn:flagger("+f.flagger.url.match(/-?\d+/)[0]+")");
});
// flaggees
if ( p.author )
addFilter("Users with flagged posts", p.author.name, "fn:user("+p.author.url.match(/-?\d+/)[0]+")");
// tags
p.tags.forEach(function(tag)
{
addFilter("Tags", tag, "fn:tag("+tag+")", "post-tag");
});
// flag types
p.flags.forEach(function(f)
{
// TEMP: exclude comment flags from the filter list
if ( /^Comment/.test(f.flagType) ) return;
addFilter("Flag types",
f.flagType=="PostOther" || f.flagType=="CommentOther"
? "Other"
: f.description + (f.flagReason ? ' (' + f.flagReason + ')' : ''),
"fn:type("+f.flagType + (f.flagReason||'') +")");
});
});
// heh...
addSearchFilter("Shog, look at this", "History purge", "history|password|credential|login");
// ad-hoc
addSearchFilter("Low-hanging fruit", "Plagiarism", "plagia|copied.{1,16}from");
addSearchFilter("Low-hanging fruit", "Dead links", "dead");
addSearchFilter("Low-hanging fruit", "Owner requests post deletion", "fn:selfflagged()delet");
addSearchFilter("Low-hanging fruit", "Migration requests", "belongs|moved? to|migrat|better fit|stackexchange");
addSearchFilter("Low-hanging fruit", "Reopen requests", "fn:isclosed()reopen|not.{1,4}duplicate");
addSearchFilter("Low-hanging fruit", "Link-only answer", "fn:isanswer()link.?only");
addSearchFilter("Low-hanging fruit", "Closed", "fn:isclosed()");
addSearchFilter("Low-hanging fruit", "Deleted", "fn:isdeleted()");
addSearchFilter("Low-hanging fruit", "Merge requests", "merge");
addSearchFilter("Low-hanging fruit", "Duplicates", "duplicate:not(':isclosed()'):isquestion()");
// convert objects to arrays, sort
return $.map(filters, function(f, cat)
{
return {
category: cat,
filters: $.map(f, function(filter)
{
return filter;
})
.sort(function(a,b) { return b.count-a.count; })
};
})
.sort(function(a,b) { return a.filters.length-b.filters.length; });
}
function renderFilters(flaggedPosts, container)
{
container.html(FlagFilter.templates.flagFilter(buildFilters(flaggedPosts)));
}
function unique(arr)
{
var check = {};
return arr.slice()
.filter(function(el)
{
var dup = check[el];
check[el] = true;
return !dup;
});
}
function dismissAllFilteredFlags(parentContainer, postIdsToDismiss, filter)
{
if ( !filter.length || postIdsToDismiss.length > 200 )
{
alert("Too many flags - filter it.")
return;
}
var DoDismiss = function(helpful, declineId, comment)
{
if (!postIdsToDismiss.length)
return;
var flaggedPostId = postIdsToDismiss.pop();
FlagFilter.tools.dismissAllFlags(flaggedPostId, helpful, declineId, comment)
.then(FlagFilter.tools.makeWait(1000))
.then(function()
{
FlagFilter.flaggedPosts = flaggedPosts = FlagFilter.flaggedPosts.filter(f => f.postId != flaggedPostId);
filterFlags(filter);
DoDismiss(helpful, declineId, comment)
});
};
flagDismissUI(parentContainer).then(function(dismissal)
{
if (!confirm("ARE YOU SURE you want to dismiss ALL FLAGS on these " + postIdsToDismiss.length + " posts all at once??"))
return;
DoDismiss(dismissal.helpful, dismissal.declineId, dismissal.comment);
});
}
function flagDismissUI(uiParent)
{
var result = $.Deferred();
var dismissTools = $('<div class="dismiss-flags-popup"><input type="text" maxlength="200" style="width:98%" placeholder="optional feedback (visible to the user)"><br><br><input type="button" value="helpful" title="the flags have merit but no further action is required"> <input type="button" value="decline: technical" title="errors are not mod biz"> <input type="button" value="decline: no evidence" title="to support these flags"> <input type="button" value="decline: no mods needed" title="to handle these flags"></div>');
dismissTools
.appendTo(uiParent)
.slideDown();
dismissTools.find("input[value='helpful']").click(function()
{
// dismiss as helpful
dismissTools.remove();
result.resolve({helpful: true, declineId: 0, comment: dismissTools.find("input[type=text]").val()});
});
dismissTools.find("input[value='decline: technical']").click(function()
{
dismissTools.remove();
result.resolve({helpful: false, declineId: 1, comment: dismissTools.find("input[type=text]").val()});
});
dismissTools.find("input[value='decline: no evidence']").click(function()
{
dismissTools.remove();
result.resolve({helpful: false, declineId: 2, comment: dismissTools.find("input[type=text]").val()});
});
dismissTools.find("input[value='decline: no mods needed']").click(function()
{
dismissTools.remove();
result.resolve({helpful: false, declineId: 3, comment: dismissTools.find("input[type=text]").val()});
});
return result.promise();
}
}
function initReview()
{
var reviews = $(".review-bar .review-instructions .review-results");
var actions = reviews.find("b")
.map(function() { return this.innerText; }).toArray()
.filter(function(p) { if ( !this[p] ) { this[p]=true; return true;}}, {}); // de-dup
$(".review-ban-all").remove();
$(".review-ban").remove();
var explanation = "Your review on " + location.toString() + " wasn't helpful; please review the history of the post and consider how choosing a different action could've helped achieve that outcome more quickly.\n";
actions.forEach(function(act)
{
var actionBan = $("<br><a href='/admin/review/bans' class='review-ban-all'>Ban all " + act + " reviewers</a>")
.click(function(ev)
{
ev.preventDefault();
var days = prompt("How many days do you want to ban " + act + " reviewers from review?")
if (days)
{
reviews.has("b:contains('" + act + "')").each(function()
{
var banLink = $(this).find("a[href='/admin/review/bans']");
var userId = $(this).find("a[href*='/users/']").attr('href').match(/\/users\/(\d+)/)[1];
FlagFilter.tools.reviewBanUser(userId, days, explanation)
.fail(function() { banLink.replaceWith("<b>Ban failed.</b>") })
.done(function()
{
banLink.replaceWith("<i>Banned.</i>")
});
});
}
});
$(".review-bar .review-actions-container").append(actionBan);
});
reviews.append(function()
{
var banLink = $("<a href='/admin/review/bans' class='review-ban'>Ban</a>")
.click(function(ev)
{
ev.preventDefault();
var days = prompt("How many days do you want to ban "
+ $(this).parent().find("a[href*='/users/']").text()
+ " from review?");
if (days)
{
var userId = $(this).parent().find("a[href*='/users/']").attr('href').match(/\/users\/(\d+)/)[1];
FlagFilter.tools.reviewBanUser(userId, days, explanation)
.fail(function() { alert("Failed!") })
.done(function()
{
banLink.replaceWith("<i>Banned.</i>")
});
}
});
return banLink;
});
}
function initQuestionPage()
{
if ( localStorage.flaaaaags )
{
$(".nav-button.next")
.addClass("filtered-nav")
.attr("title", "go to the next filtered flag")
.off("click")
.click(function(e) { goToFilteredFlag(1) });
$(".nav-button.prev")
.addClass("filtered-nav")
.attr("title", "go to the previous filtered flag")
.off("click")
.click(function(e) { goToFilteredFlag(-1) });
// show progress
var filtered = localStorage.flaaaaags.split(',');
var index = filtered.indexOf(location.pathname.match(/\/questions\/(\d+)/)[1]);
$("#postflag-bar>div").append("<a href='" + localStorage.getItem("flaaaaags.lastFilter") + "' style='position:absolute;left: 40px;top:5px;'>" + (index+1) + " of " + filtered.length + "</div>");
}
// add a migrate options, if appropriate
$(".mod-message .active-flag")
.each(function()
{
var el = this;
predictMigrationDest(this.innerText)
.done(function(site)
{
if (!site.name) return;
$("<a>")
.attr("href", "#")
.addClass("migration-link")
.html("belongs on " + site.name + "?")
.click(function()
{
var questionId = location.pathname.match(/\/questions\/(\d+)/)[1];
if ( confirm("Really migrate this question to " + site.name + "?") )
FlagFilter.tools.migrateTo(questionId, site.baseHostAddress)
.done(function() { location.reload() })
.fail(function() { alert("something went wrong") });
})
.insertBefore(el)
})
});
}
//
// Adapted slightly from balpha's Keyboard shortcuts for StackExchange userscript
// http://stackapps.com/questions/2567/official-keyboard-shortcuts
//
function initKeyboard()
{
var updateMessage;
if (!(window.StackExchange && StackExchange.helpers && StackExchange.helpers.DelayedReaction))
return;
var TOP_BAR = $("body > .topbar");
if (!TOP_BAR.length)
TOP_BAR = false;
function setting(name, val) {
var prefix = "flaaaaags-keyboard-shortcuts.settings.";
if (arguments.length < 2) {
try {
val = localStorage.getItem(prefix + name) ;
return val === "true" ? true : val === "false" ? false : val;
} catch (e) {
return;
}
} else {
try {
return localStorage.setItem(prefix + name, val);
} catch (e) {
return;
}
}
}
var style = ".keyboard-console { background-color: black; background-color: rgba(0, 0, 0, .8); position: fixed; left: 100px; bottom: 100px;" +
"padding: 10px; text-align: left; border-radius: 6px; z-index: 1000 }" + // the global inbox has z-index 999
".keyboard-console pre { background-color: transparent; color: #ccc; width: auto; height: auto; padding: 0; margin: 0; overflow: visible; line-height:1.5; }" +
".keyboard-console pre b, .keyboard-console pre a { color: white !important; }" +
".keyboard-console pre kbd { display: inline-block; font-family: monospace; }" +
".keyboard-selected { box-shadow: 15px 15px 50px rgba(0, 0, 0, .2) inset; }"
$("<style type='text/css' />").text(style).appendTo("head");
function showConsole(text) {
var cons = $(".keyboard-console pre");
if (!text.length) {
cons.parent().hide();
return;
}
if (!cons.length) {
cons = $("<div class='keyboard-console'><pre /></div>").appendTo("body").find("pre");
}
text = text.replace(/^!(.*)$/mg, "<b>$1</b>");
cons.html(text).parent().show();
}
function Shortcuts() {
this.order = []
this.actions = {}
}
Shortcuts.prototype.add = function (key, name, action) {
if (this.actions[key])
StackExchange.debug.log("duplicate shortcut " + key);
this.order.push(key);
this.actions[key] = action;
action.name = $("<span />").text(name).html();
}
function truncate(s) {
s = $.trim(s.replace(/[\r\n ]+/g, " "));
if (s.length > 40)
s = s.substr(0, 37) + "...";
return s;
}
var popupMode = {
name: "Popup...",
isApplicable: function () { return $(".popup").length },
getShortcuts: function () {
var pane = $(".popup-active-pane"),
result = new Shortcuts(),
i = 1, j = 65,
animated = [];
if (!pane.length)
pane = $(".popup");
// hack: make sure enter submits the form
if ( !pane.find("button[type=submit], input[type=submit]").length && pane.find("button, input[type=button]").length==1)
{
pane.keyup(function(ev)
{
if (ev.which!=13) return;
pane.find("button, input[type=button]").click();
});
}
pane.find(".action-list > li input[type='radio']:visible").each(function () {
var radio = $(this),
li = radio.closest("li"),
label = li.find("label span:not(action-desc):first"),
subform = li.find(".action-subform");
result.add("" + i, $.trim(label.text()) || "unknown action", { func: function () { radio.focus().attr('checked', 'checked').click(); } }); // make sure it's checked before firing the handler!
if (subform.length) {
subform.find("input[type='radio']:visible").each(function () {
var jThis = $(this),
sublabel = jThis.closest("li").find("label span:first");
result.add(String.fromCharCode(j), truncate(sublabel.text() || "other"), { func: function () { jThis.focus().click(); } });
j++;
});
animated.push(subform);
}
i++;
});
if (animated.length) {
result.animated = $(animated);
}
return result;
}
}
var dismissMode = {
name: "Dismiss flags...",
isApplicable: function () { return $(".no-further-action-popup").length },
getShortcuts: function () {
var pane = $(".no-further-action-popup"),
result = new Shortcuts();
result.add("H", "helpful", { clickOrLink: ".no-further-action-popup .mark-as-helpful" });