Repository navigation
Expand file tree
/
Copy pathplugin.rb
More file actions
1002 lines (877 loc) · 38.3 KB
/
Copy pathplugin.rb
File metadata and controls
1002 lines (877 loc) · 38.3 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
# frozen_string_literal: true
# ============================================================================
# Discourse Maps
# Plugin that allows inserting geographic information in topics and
# displaying it on an interactive map (LocationIQ or Google Maps).
# NOTE: this file is the plugin's entry point. In this first step it only
# contains the basic structure (metadata, enabling, settings).
# The features (composer, /mappa page, filters) will be added in later
# steps.
# ============================================================================
# name: discourse-maps
# about: Associate geographic information in topics and display on an interactive map.
# version: 1.0.0
# authors: Stefano Sisti
# url: https://github.com/sisti86dinova/discourse-maps
# required_version: 2.7.0
# Enables/disables the whole plugin via the admin panel setting.
enabled_site_setting :discourse_maps_enabled
# Registers the common stylesheet (maps, /mappa page layout, etc.).
register_asset "stylesheets/common/discourse-maps.scss"
# Ensures the "Map" sidebar link icon is always available, regardless of
# the default icon set configured on the site.
register_svg_icon "globe"
# Icons for the button that opens/closes filters on mobile (/mappa page).
register_svg_icon "angle-up"
register_svg_icon "angle-down"
# Allows the composer to send the "discourse_maps_location" parameter when
# creating a topic. We declare it as :hash because it's an object with
# multiple fields (address + lat/lng coordinates).
# ----------------------------------------------------------------------------
# Server-side initialization block.
# ----------------------------------------------------------------------------
after_initialize do
add_permitted_post_create_param("discourse_maps_location", :hash)
# Without this the flag set by the /mappa page's "New topic" button would be
# dropped by PostsController before reaching on(:post_created).
add_permitted_post_create_param("discourse_maps_from_map")
# Lets the location be set, corrected or removed by editing the topic's
# first post, instead of only at creation time (see
# DiscourseMaps.update_map_metadata below): without this, fixing a wrong
# address meant deleting the post and recreating it.
add_permitted_post_update_param("discourse_maps_location") do |post, location|
::DiscourseMaps.update_map_metadata(post, location)
end
# Makes these parameters survive in the ReviewableQueuedPost payload, so
# they can be retrieved in on(:approved_post) when a post from a
# not-yet-approved user is put in the moderation queue and the actual
# post is only created after staff approval (see apply_map_metadata
# below).
NewPostManager.add_plugin_payload_attribute("discourse_maps_location")
NewPostManager.add_plugin_payload_attribute("discourse_maps_from_map")
# Plugin module namespace.
module ::DiscourseMaps
PLUGIN_NAME = "discourse-maps"
# URL of the map page and, with ".json", of its data. Not "/map": the
# widely used Locations plugin registers "map" as a core topic list
# filter, whose route is drawn before any plugin route and would take
# over both. Must match MAP_PATH in lib/discourse-maps-paths.js.
MAP_PATH = "/mappa"
# Name of the topic custom field where we store the geographic data.
# Contains: { address, lat, lng, display_name, country_code, country,
# start_date, end_date }. "address" is the address typed by the user,
# the other geocoding fields are the provider's result. The country is
# identified by "country_code" (ISO 3166-1 alpha-2): "country" is only
# the name as the provider returned it when the topic was saved, which
# depends on the locale in force at that moment, so it is never used as
# an identity (the client renders the name from the code instead).
# start_date/end_date ("YYYY-MM-DD") are the topic's reference period,
# also typed by the user in the modal.
LOCATION_FIELD = "discourse_maps_location"
# Practical stand-in for "no upper bound", used by the "upcoming"
# period filter (see date_filter_range below): a real event starting
# this far out would be a data entry mistake, not a legitimate
# open-ended range to support.
FAR_FUTURE_DATE = Date.new(9999, 12, 31)
# Returns the "map" tag configured in the admin panel (setting
# `discourse_maps_map_tag_id`), or nil if it doesn't exist.
def self.map_tag
Tag.find_by(id: SiteSetting.discourse_maps_map_tag_id)
end
# Whether the given user is allowed to use the "New topic" button on
# the /mappa page (setting `discourse_maps_new_topic_groups`: empty =
# admins only). This is the server-side counterpart of the check done
# in map-page.gjs to show/hide the button: without it, any user could
# get the staff-only "map" tag applied by sending
# "discourse_maps_from_map" directly, bypassing the admin's intended
# restriction on who may publish to the public map.
def self.user_allowed_from_map?(user)
return false unless user
return true if user.admin?
group_ids = SiteSetting.discourse_maps_new_topic_groups_map
group_ids.present? &&
GroupUser.where(user_id: user.id, group_id: group_ids).exists?
end
# Whether the topic list of the given type (TopicQuery filter name),
# built with the given TopicQuery options, must leave out the topics
# with the "map" tag (see the topic_query_create_list_topics modifier
# below).
def self.hide_from_list?(list_type, query_options)
return false if list_type.blank?
if SiteSetting.discourse_maps_hide_from_lists_map.exclude?(list_type.to_s)
return false
end
if query_options[:category].present?
return SiteSetting.discourse_maps_hide_on_category_pages
end
if query_options[:tags].present?
return SiteSetting.discourse_maps_hide_on_tag_pages
end
true
end
# Drops the topics with the "map" tag from a topic list. Most lists
# are still a relation at this point (filtering it in SQL keeps the
# page full), but suggested topics arrive as an already loaded Array.
def self.without_map_topics(topics)
map_topic_ids =
TopicTag.where(tag_id: SiteSetting.discourse_maps_map_tag_id).select(
:topic_id
)
if topics.is_a?(ActiveRecord::Relation)
topics.where.not(id: map_topic_ids)
else
hidden_ids =
map_topic_ids
.where(topic_id: topics.map(&:id))
.pluck(:topic_id)
.to_set
topics.reject { |topic| hidden_ids.include?(topic.id) }
end
end
# Applies the geographic data and the "map" tag to the topic, based on
# the "discourse_maps_location" / "discourse_maps_from_map"
# parameters. Used both on direct post creation (on :post_created) and
# on approval of a post that was in the moderation queue (on
# :approved_post), because in that second case the post is recreated
# by ReviewableQueuedPost and :post_created is not emitted.
#
# Only users allowed to publish to the map (see user_allowed_from_map?)
# may put a topic on it; once a topic is on the map, its location can
# be corrected by whoever can edit its first post. Without this, any
# user could send "discourse_maps_location" directly (API, or a
# modified client) and publish to the public map, even though the
# composer only offers the location button to allowed users.
def self.apply_map_metadata(topic, location, from_map, user)
return unless user_allowed_from_map?(user) || on_map?(topic)
location = sanitize_location(location)
from_map = ActiveModel::Type::Boolean.new.cast(from_map)
return if location.blank? && !from_map
if location.present?
topic.custom_fields[LOCATION_FIELD] = location
topic.save_custom_fields(true)
end
tag = map_tag
if tag && topic.tags.exclude?(tag)
topic.tags << tag
topic.save!
end
end
# Whether the topic is already published to the map. Only the saved
# location counts: unlike the "map" tag, which any user may be able to
# add by hand when the tag isn't in a restricted tag group, it can only
# be written by this plugin after the permission check above. A topic
# created from /mappa without a location belongs to an allowed author,
# who passes that check anyway.
def self.on_map?(topic)
topic.custom_fields[LOCATION_FIELD].present?
end
# Value the client sends to remove a topic's location while editing
# (the modal's "Remove location"). It must differ from a missing
# param: PostsController passes every permitted update param to the
# revisor, as nil when the request doesn't carry it, so nil has to
# mean "unchanged" or any edit made without the composer's location
# (API, mobile app, an edit that never opened the modal) would wipe it.
REMOVE_LOCATION = ""
# Applies a location change made while editing the topic's first post
# (see add_permitted_post_update_param above):
# - nil: nothing to do (see REMOVE_LOCATION);
# - REMOVE_LOCATION: removes the location and the "map" tag;
# - a hash: overwrites the location, after sanitizing it like on
# creation (see apply_map_metadata/sanitize_location).
# Anything else (another string, an array, a number) or a malformed
# hash is ignored: the modal never sends those.
#
# Known limitation: core runs this handler before validating the rest
# of the edit, so a location change is applied even if the text edit
# is then refused, and it isn't recorded in the post's revisions.
# Only users allowed to edit the post can trigger it.
def self.update_map_metadata(post, location)
return unless post.is_first_post?
return if location.nil?
topic = post.topic
if location == REMOVE_LOCATION
remove_map_metadata(topic)
elsif location.is_a?(Hash) || location.respond_to?(:to_unsafe_h)
apply_map_metadata(topic, location, nil, post.user)
end
end
# Removes the location and the "map" tag from a topic: the reverse of
# apply_map_metadata, used when a location is unset while editing.
def self.remove_map_metadata(topic)
topic.custom_fields.delete(LOCATION_FIELD)
topic.save_custom_fields(true)
tag = map_tag
if tag && topic.tags.include?(tag)
topic.tags = topic.tags - [tag]
topic.save!
end
end
# Base scope: topics with the "map" tag, a saved location, and visible
# to the user (guardian). Doesn't apply the category/tag filters: it's
# the base for both the topic list and the filter options calculation.
def self.base_map_scope(guardian)
tag = map_tag
return nil unless tag
topic_ids = TopicCustomField.where(name: LOCATION_FIELD).select(:topic_id)
scope =
Topic
.listable_topics
.secured(guardian)
.where(id: topic_ids)
.joins(:topic_tags)
.where(topic_tags: { tag_id: tag.id }) # "map" tag constraint
# Unlisted topics stay hidden from those who can't see them in the
# regular topic lists either (same rule as TopicQuery).
scope = scope.visible unless guardian.can_see_unlisted_topics?
{ scope: scope, tag: tag }
end
# Filters a scope by tag: the topic must have ALL the given tags. A
# tag that doesn't exist, or that the user isn't allowed to see,
# matches nothing: ignoring it instead would let a hidden tag's name be
# used to probe which topics carry it.
def self.filter_by_tags(scope, tag_names, guardian)
names = tag_names.uniq
visible_names = names - DiscourseTagging.hidden_tag_names(guardian)
tag_ids = Tag.where(name: visible_names).pluck(:id)
return scope.none if tag_ids.size < names.size
tag_ids.each do |tid|
scope = scope.where(id: TopicTag.where(tag_id: tid).select(:topic_id))
end
scope
end
# Filters a scope by country. The country is only stored inside the
# JSON custom field (LOCATION_FIELD), it's not a column: the
# comparison must be done by reading and parsing the JSON, not with a
# SQL where.
def self.filter_by_countries(scope, country_keys)
scope.where(id: topic_ids_matching_countries(scope, country_keys))
end
def self.topic_ids_matching_countries(scope, country_keys)
TopicCustomField
.where(
topic_id: scope.distinct.pluck("topics.id"),
name: LOCATION_FIELD
)
.pluck(:topic_id, :value)
.select { |_, value| country_keys.include?(parse_country_key(value)) }
.map(&:first)
end
# (De-duplicated) list of the countries present among the topics of the
# given scope, as { id, name } pairs whose id is the ISO 3166-1 alpha-2
# code. The name is the one stored at save time and is only a fallback:
# the client renders the code in the site's language, so the same
# country is a single entry even across topics saved under different
# locales.
def self.countries_for_scope(scope)
TopicCustomField
.where(
topic_id: scope.distinct.pluck("topics.id"),
name: LOCATION_FIELD
)
.pluck(:value)
.filter_map { |value| country_entry(value) }
.uniq { |entry| entry[:id] }
.sort_by { |entry| entry[:name] }
end
# Country of a stored location, as the { id, name } pair the filter
# expects. Topics saved before country_code was introduced fall back to
# the stored name as their id, so they stay filterable until the
# backfill task (lib/tasks/discourse_maps.rake) gives them a code.
def self.country_entry(raw_value)
data = parse_location(raw_value)
return nil unless data
code = data["country_code"].presence&.upcase
name = data["country"].presence
return nil if code.blank? && name.blank?
{ id: code || name, name: name || code }
end
# Identity of the country for a stored location: the ISO code, or the
# stored name for topics that don't have one yet.
def self.parse_country_key(raw_value)
country_entry(raw_value)&.fetch(:id)
end
# The custom field is stored as JSON: safely parses it (nil if the
# value is missing or not valid JSON).
def self.parse_location(raw_value)
return nil if raw_value.blank?
data = JSON.parse(raw_value)
data.is_a?(Hash) ? data : nil
rescue JSON::ParserError
nil
end
# Extracts the period (start/end date) from the JSON custom field.
# Returns nil if the value is missing/invalid or if one of the two
# dates is missing: both are required at creation time, but topics
# saved before this feature was introduced don't have them, and will
# simply never show up in the date filters (they remain visible
# without a filter).
def self.parse_date_range(raw_value)
data = parse_location(raw_value)
return nil unless data
start_date = data["start_date"]
end_date = data["end_date"]
return nil if start_date.blank? || end_date.blank?
[Date.parse(start_date), Date.parse(end_date)]
rescue ArgumentError, TypeError
nil
end
# Max length kept for the free-text fields of a location: generous
# enough for any real address/display name, but short enough to keep
# a malicious or buggy client from stuffing the custom field (and the
# page that renders it) with an unbounded string.
MAX_TEXT_LENGTH = 500
# ISO 3166-1 alpha-2: exactly two letters.
COUNTRY_CODE_REGEXP = /\A[a-zA-Z]{2}\z/
# Validates and normalizes a location as it arrives from the composer
# (hash with symbol or string keys, possibly an ActionController::Parameters,
# not yet serialized to JSON) into the plain Hash we actually persist.
# Returns nil if it isn't acceptable: lat/lng missing or out of range,
# or start/end date missing, unparseable or in the wrong order.
#
# This is the only place allowed to decide what ends up in the
# LOCATION_FIELD custom field: it whitelists the known keys (instead
# of storing whatever hash the client sent) and coerces every value
# to the expected type, so a non-compliant client (bug, direct API
# call) can at most store a well-formed location, never arbitrary
# keys/types riding along with it.
def self.sanitize_location(raw_location)
return nil if raw_location.blank?
unless raw_location.is_a?(Hash) || raw_location.respond_to?(:to_unsafe_h)
return nil
end
location =
(
if raw_location.respond_to?(:to_unsafe_h)
raw_location.to_unsafe_h
else
raw_location
end
).stringify_keys
lat = Float(location["lat"], exception: false)
lng = Float(location["lng"], exception: false)
return nil if lat.nil? || lng.nil?
return nil unless lat.between?(-90, 90) && lng.between?(-180, 180)
start_date = Date.parse(location["start_date"].to_s)
end_date = Date.parse(location["end_date"].to_s)
return nil if end_date < start_date
country_code = location["country_code"].to_s.strip.upcase
country_code = nil unless country_code.match?(COUNTRY_CODE_REGEXP)
{
"address" => location["address"].to_s.strip.truncate(MAX_TEXT_LENGTH),
"lat" => lat,
"lng" => lng,
"display_name" =>
location["display_name"].to_s.strip.truncate(MAX_TEXT_LENGTH),
"country_code" => country_code,
"country" => location["country"].to_s.strip.truncate(MAX_TEXT_LENGTH),
"start_date" => start_date.to_s,
"end_date" => end_date.to_s
}
rescue ArgumentError, TypeError
nil
end
# Converts the (possibly partial) year/month/day filter parameters
# into the corresponding date range, used for the "overlap" comparison
# with each topic's period. nil if neither a year nor `upcoming` is
# given (no date filter) or if the year/month/day combination isn't a
# valid date. `upcoming` (today onward, no upper bound) only applies
# when no year is given: an explicit year/month/day always wins, same
# as a user picking a date overriding the page's default on open (see
# routes/map.js).
def self.date_filter_range(year, month, day, upcoming: false)
return Date.current, FAR_FUTURE_DATE if year.blank? && upcoming
return nil if year.blank?
year = year.to_i
if month.present?
month = month.to_i
if day.present?
date = Date.new(year, month, day.to_i)
[date, date]
else
start = Date.new(year, month, 1)
[start, start.end_of_month]
end
else
[Date.new(year, 1, 1), Date.new(year, 12, 31)]
end
rescue ArgumentError
nil
end
# Periods ([start, end] pairs) of the topics of the given scope, with
# a valid period. Common base for calculating the year/month/day
# options.
def self.date_ranges_for_scope(scope)
TopicCustomField
.where(
topic_id: scope.distinct.pluck("topics.id"),
name: LOCATION_FIELD
)
.pluck(:value)
.map { |value| parse_date_range(value) }
.compact
end
# Filters a scope by period: the topic must have a period that
# overlaps the given [filter_start, filter_end] interval.
def self.filter_by_date_range(scope, filter_start, filter_end)
scope.where(
id: topic_ids_matching_date_range(scope, filter_start, filter_end)
)
end
def self.topic_ids_matching_date_range(scope, filter_start, filter_end)
TopicCustomField
.where(
topic_id: scope.distinct.pluck("topics.id"),
name: LOCATION_FIELD
)
.pluck(:topic_id, :value)
.select do |_, value|
range = parse_date_range(value)
range && range[0] <= filter_end && range[1] >= filter_start
end
.map(&:first)
end
# Years available in the given scope: a topic whose period spans
# multiple years shows up in each of them (consistent with the
# "overlap" logic).
def self.years_for_scope(scope)
years =
date_ranges_for_scope(scope)
.flat_map do |start_date, end_date|
(start_date.year..end_date.year).to_a
end
.uniq
.sort
years.map { |year| { id: year, name: year.to_s } }
end
# Months available in the given scope for the selected year: each
# period is "clipped" to the year's boundaries before extracting its
# months, so a topic spanning multiple years only contributes the
# months that actually fall within that year.
def self.months_for_scope(scope, year)
year_start = Date.new(year, 1, 1)
year_end = Date.new(year, 12, 31)
months =
date_ranges_for_scope(scope)
.flat_map do |start_date, end_date|
clipped_start = [start_date, year_start].max
clipped_end = [end_date, year_end].min
next [] if clipped_start > clipped_end
(clipped_start.month..clipped_end.month).to_a
end
.uniq
.sort
months.map { |month| { id: month, name: month.to_s } }
end
# Days available in the given scope for the selected year/month: same
# clipping logic as months, applied to the month's boundaries.
def self.days_for_scope(scope, year, month)
month_start = Date.new(year, month, 1)
month_end = month_start.end_of_month
days =
date_ranges_for_scope(scope)
.flat_map do |start_date, end_date|
clipped_start = [start_date, month_start].max
clipped_end = [end_date, month_end].min
next [] if clipped_start > clipped_end
(clipped_start.day..clipped_end.day).to_a
end
.uniq
.sort
days.map { |day| { id: day, name: day.to_s } }
end
# Collects the topics to show on the /mappa page, ordered by descending
# creation date. Respects the user's permissions (guardian) and
# returns only the data needed by the map and the list.
#
# Optional filters:
# - category_id : shows only topics in the given category;
# - tag_names : shows only topics that have ALL the given tags
# (the "map" tag constraint is always applied);
# - country_keys : shows only topics whose address is in one of the
# given countries (ISO 3166-1 alpha-2 codes);
# - year/month/day: shows only topics whose period (start/end)
# overlaps the given period (year, year+month or
# exact date depending on which are present);
# - upcoming : with no year given, shows only topics whose
# period hasn't ended yet (today onward); the
# default view on /mappa, "today" or "upcoming",
# is controlled by the discourse_maps_default_date_filter
# site setting (applied client-side, see routes/map.js).
# - limit : max number of topics returned (most recent first).
def self.map_topics(
guardian,
category_id: nil,
tag_names: [],
country_keys: [],
year: nil,
month: nil,
day: nil,
upcoming: false,
limit: nil
)
base = base_map_scope(guardian)
return [] unless base
scope = base[:scope]
# Category filter.
scope = scope.where(category_id: category_id) if category_id.present?
# Tag filter: the topic must have all the selected tags.
scope = filter_by_tags(scope, tag_names, guardian) if tag_names.present?
# Country filter.
scope = filter_by_countries(scope, country_keys) if country_keys.present?
# Period filter.
date_range = date_filter_range(year, month, day, upcoming: upcoming)
scope = filter_by_date_range(scope, *date_range) if date_range
topics =
scope
.includes(:tags)
.distinct
.order(created_at: :desc)
.limit(limit)
.to_a
# Preload custom fields to avoid N+1 queries.
Topic.preload_custom_fields(topics, [LOCATION_FIELD])
# Tags in staff-only (or otherwise restricted) tag groups stay out of
# the response, as in core's topic lists.
hidden_tag_names = DiscourseTagging.hidden_tag_names(guardian)
# Topics already read (at least one post) by the current user, for
# the "visited" class in the list (like in the native topic list).
visited_topic_ids =
if guardian.user
TopicUser
.where(user_id: guardian.user.id, topic_id: topics.map(&:id))
.where("last_read_post_number > 0")
.pluck(:topic_id)
.to_set
else
Set.new
end
topics.map do |topic|
{
id: topic.id,
title: topic.title,
fancy_title: topic.fancy_title,
url: "/t/#{topic.slug}/#{topic.id}",
category_id: topic.category_id,
tags: topic.tags.map(&:name) - hidden_tag_names,
location: topic.custom_fields[LOCATION_FIELD],
image_url: topic.image_url,
views: topic.views,
like_count: topic.like_count,
posts_count: topic.posts_count,
last_posted_at: topic.last_posted_at,
created_at: topic.created_at,
visited: visited_topic_ids.include?(topic.id)
}
end
end
# Available options for the category/tag/country/period filters:
# cross-referenced with each other (AND), so that choosing one filter
# updates the other filters' options, showing only the ones that
# wouldn't lead to zero results with the filters already set.
# Year/month/day additionally have a hierarchy among them (month
# depends on the chosen year, day on year+month): the options for a
# more specific level are only calculated if the higher level is
# already selected.
def self.map_filter_options(
guardian,
category_id: nil,
tag_names: [],
country_keys: [],
year: nil,
month: nil,
day: nil,
upcoming: false
)
base = base_map_scope(guardian)
unless base
return(
{
category_ids: [],
tags: [],
countries: [],
years: [],
months: [],
days: []
}
)
end
scope = base[:scope]
tag = base[:tag]
date_range = date_filter_range(year, month, day, upcoming: upcoming)
# Available categories: respect the tag, country and period filters already set.
scope_for_categories = scope
scope_for_categories =
filter_by_tags(
scope_for_categories,
tag_names,
guardian
) if tag_names.present?
scope_for_categories =
filter_by_countries(
scope_for_categories,
country_keys
) if country_keys.present?
scope_for_categories =
filter_by_date_range(scope_for_categories, *date_range) if date_range
category_ids = scope_for_categories.distinct.pluck(:category_id).compact
# Available tags: respect the category, country and period filters already set.
scope_for_tags = scope
scope_for_tags =
scope_for_tags.where(category_id: category_id) if category_id.present?
scope_for_tags =
filter_by_countries(
scope_for_tags,
country_keys
) if country_keys.present?
scope_for_tags =
filter_by_date_range(scope_for_tags, *date_range) if date_range
tag_ids =
TopicTag
.where(topic_id: scope_for_tags.distinct.pluck("topics.id"))
.where.not(tag_id: tag.id)
.distinct
.pluck(:tag_id)
tags =
Tag
.where(id: tag_ids)
.where.not(name: DiscourseTagging.hidden_tag_names(guardian))
.order(:name)
.pluck(:id, :name)
.map { |id, name| { id: id, name: name } }
# Available countries: respect the category, tag and period filters already set.
scope_for_countries = scope
scope_for_countries =
scope_for_countries.where(
category_id: category_id
) if category_id.present?
scope_for_countries =
filter_by_tags(
scope_for_countries,
tag_names,
guardian
) if tag_names.present?
scope_for_countries =
filter_by_date_range(scope_for_countries, *date_range) if date_range
countries = countries_for_scope(scope_for_countries)
# Available years/months/days: respect the category/tag/country
# filters already set (not the period itself, which is hierarchical
# among the three).
scope_for_dates = scope
scope_for_dates =
scope_for_dates.where(category_id: category_id) if category_id.present?
scope_for_dates =
filter_by_tags(
scope_for_dates,
tag_names,
guardian
) if tag_names.present?
scope_for_dates =
filter_by_countries(
scope_for_dates,
country_keys
) if country_keys.present?
years = years_for_scope(scope_for_dates)
months = year.present? ? months_for_scope(scope_for_dates, year.to_i) : []
days =
(
if year.present? && month.present?
days_for_scope(scope_for_dates, year.to_i, month.to_i)
else
[]
end
)
{
category_ids: category_ids,
tags: tags,
countries: countries,
years: years,
months: months,
days: days
}
end
end
# Registers the custom field type as JSON: reading returns a Hash,
# writing automatically serializes it to JSON.
Topic.register_custom_field_type(::DiscourseMaps::LOCATION_FIELD, :json)
# --------------------------------------------------------------------------
# Server-side check, on post creation: a geolocated topic must have a
# valid location (lat/lng in range, start/end date present and
# ordered; see DiscourseMaps.sanitize_location). The composer modal
# already validates this client-side, but without a check here a
# different client (bug, direct API call) could still create a topic
# with a malformed location, which would silently never show up on
# the map or in its filters (see apply_map_metadata). This only
# applies to the creation of a new topic (manager.args[:topic_id]
# absent): the location/period concern only the first post, just like
# the location itself.
# --------------------------------------------------------------------------
NewPostManager.add_handler do |manager|
location =
manager.args[:discourse_maps_location] ||
manager.args["discourse_maps_location"]
if manager.args[:topic_id].blank? && location.present? &&
!::DiscourseMaps.sanitize_location(location)
result = NewPostResult.new(:discourse_maps, false)
result.add_error(I18n.t("discourse_maps.errors.invalid_location"))
next result
end
nil
end
# --------------------------------------------------------------------------
# On creation of a topic's first post:
# 1. we save the geographic data (if present) in the topic's custom field;
# 2. we automatically assign the "map" tag configured in admin.
# --------------------------------------------------------------------------
on(:post_created) do |post, opts, user|
# We only care about the first post (the actual topic).
next unless post.is_first_post?
# The parameter can arrive with a symbol or string key: we handle both.
location = opts[:discourse_maps_location] || opts["discourse_maps_location"]
from_map = opts[:discourse_maps_from_map] || opts["discourse_maps_from_map"]
# Automatic assignment of the "map" tag (id read from the setting) and
# saving of the location. The tag is assigned even without a location
# when the topic was created via the "New topic" button on the /mappa
# page: the tag group is staff-only, so a normal user can't assign it
# themselves through the composer (the selector hides it and the
# server would filter it out anyway), and without this bypass it
# would never show up in the /mappa list. apply_map_metadata re-checks
# `user` against discourse_maps_new_topic_groups: without it, any
# user could send discourse_maps_from_map directly and bypass the
# setting, which only gates the button client-side.
::DiscourseMaps.apply_map_metadata(post.topic, location, from_map, user)
end
# --------------------------------------------------------------------------
# Case of not-yet-approved users (or otherwise subject to new topic
# moderation): the actual post is NOT created immediately, but is
# queued (ReviewableQueuedPost) and recreated only when staff approves
# it. At that point :post_created is not emitted (skip_events is
# passed) and the custom opts don't arrive anyway, because
# ReviewableQueuedPost rebuilds the opts from its own "payload", which
# by default only contains raw/title/tags/category. This is why we
# register our parameters as "plugin payload attribute" (they survive
# in the payload) and apply them here, once approval has happened.
# --------------------------------------------------------------------------
on(:approved_post) do |reviewable, post|
next unless post&.is_first_post?
payload = reviewable.payload || {}
location = payload["discourse_maps_location"]
from_map = payload["discourse_maps_from_map"]
::DiscourseMaps.apply_map_metadata(
post.topic,
location,
from_map,
post.user
)
end
# --------------------------------------------------------------------------
# Keeps geolocated topics (the ones with the "map" tag) out of the topic
# lists picked in discourse_maps_hide_from_lists. The list type is the
# TopicQuery filter name (:latest also covers the homepage, its
# "categories + latest" layout and the RSS feed). Category and tag pages
# are the same lists scoped by options[:category] / options[:tags], and
# are only filtered when their own setting says so. /mappa is unaffected:
# it has its own query (see base_map_scope).
# --------------------------------------------------------------------------
register_modifier(
:topic_query_create_list_topics
) do |topics, options, topic_query|
if ::DiscourseMaps.hide_from_list?(options[:filter], topic_query.options)
::DiscourseMaps.without_map_topics(topics)
else
topics
end
end
# --------------------------------------------------------------------------
# Exposes the topic's geographic data to the client (topic page), so
# the map can be drawn. The attribute is only included if present.
# --------------------------------------------------------------------------
add_to_serializer(
:topic_view,
:discourse_maps_location,
include_condition: -> do
object.topic.custom_fields[::DiscourseMaps::LOCATION_FIELD].present?
end
) { object.topic.custom_fields[::DiscourseMaps::LOCATION_FIELD] }
# --------------------------------------------------------------------------
# /mappa page controller.
# - HTML request: boots the Ember app (which then renders the page);
# - JSON request: returns the topics with the map tag + location.
# --------------------------------------------------------------------------
class ::DiscourseMaps::MapController < ::ApplicationController
requires_plugin ::DiscourseMaps::PLUGIN_NAME
# For the direct (HTML) page load this isn't an XHR request.
skip_before_action :check_xhr, only: [:index]
# /mappa.json is public and rebuilds the whole result and filter options
# on every request: a per user (or per IP, for anonymous visitors)
# limit keeps it from being used to load the server. Staff is exempt.
before_action :rate_limit_map_json,
only: [:index],
if: -> { request.format.json? }
def index
respond_to do |format|
# Boots the Ember application: the client route will then request the JSON.
format.html { render "default/empty" }
# Data for the map and the list, filtered by user permissions and
# by any category/tag filters passed as query parameters.
format.json do
filter_params = {
category_id: integer_param(:category_id, 1..),
tag_names: list_param(:tags),
country_keys: list_param(:countries),
year: integer_param(:year, 1..9999),
month: integer_param(:month, 1..12),
day: integer_param(:day, 1..31),
upcoming: ActiveModel::Type::Boolean.new.cast(params[:upcoming])
}
# One extra topic tells whether the result was cut at the limit.
max_topics = SiteSetting.discourse_maps_max_topics
topics =
::DiscourseMaps.map_topics(
guardian,
**filter_params,
limit: max_topics + 1
)
truncated = topics.size > max_topics
topics = topics.first(max_topics)
filters =
::DiscourseMaps.map_filter_options(guardian, **filter_params)
render json: {
topics: topics,
filters: filters,
truncated: truncated,
max_topics: max_topics
}
end
end
end
private
def rate_limit_map_json
RateLimiter.new(
current_user,
"discourse-maps-json-#{current_user&.id || request.remote_ip}",
SiteSetting.discourse_maps_requests_per_minute,
1.minute
).performed!
end
# Max values accepted in a comma-separated filter (tags, countries):
# the UI only ever sends one, this just bounds the work per request.
MAX_LIST_VALUES = 10
# Query params are user-controlled: anything other than a plain string
# (e.g. ?tags[]=x or ?month=13) is ignored instead of raising a 500.
def integer_param(key, range)
value = params[key]
return nil unless value.is_a?(String) && value.match?(/\A\d{1,10}\z/)
number = value.to_i
range.cover?(number) ? number : nil
end
def list_param(key)
value = params[key]
return [] unless value.is_a?(String)
value.split(",").map(&:strip).reject(&:blank?).first(MAX_LIST_VALUES)
end
end
# Registers the map page route (serves both the HTML and the JSON data).
Discourse::Application.routes.append do
get ::DiscourseMaps::MAP_PATH => "discourse_maps/map#index"