-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathtag_controller.rb
571 lines (502 loc) · 21.2 KB
/
tag_controller.rb
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
class TagController < ApplicationController
respond_to :html, :xml, :json, :ics
before_action :require_user, only: %i(create delete)
include Pagy::Backend
def index
@toggle = params[:sort] || "uses"
@title = I18n.t('tag_controller.tags')
@paginated = true
@order_type = params[:order].blank? || (params[:order] == "desc") ? "desc" : "asc"
@order_type_for_name = params[:order].blank? || (params[:order] == "asc") ? "asc" : "desc"
powertag_clause = params[:powertags] == 'true' ? '' : ['name NOT LIKE ?', '%:%']
if params[:search]
keyword = params[:search]
@tags = Tag.joins(:node_tag, :node)
.select('MAX(term_data.count) count, MAX(term_data.name) name, MAX(term_data.tid) tid, MAX(node.nid) nid, node.status, MAX(community_tags.tid), MAX(community_tags.date)')
.where('node.status = ?', 1)
.where('community_tags.date > ?', (DateTime.now - 1.month).to_i)
.where("name LIKE :keyword", keyword: "%#{keyword}%")
.where(powertag_clause)
.group('term_data.name')
.order(order_string.gsub('count', "MAX(term_data.count)"))
.paginate(page: params[:page], per_page: 24)
elsif @toggle == "uses"
@tags = Tag.joins(:node_tag, :node)
.select('MAX(term_data.count) count, MAX(term_data.name) name, MAX(term_data.tid) tid, MAX(node.nid) nid, node.status, MAX(community_tags.tid), MAX(community_tags.date)')
.where('node.status = ?', 1)
.where('community_tags.date > ?', (DateTime.now - 1.month).to_i)
.where(powertag_clause)
.group(:name)
.order(order_string.gsub('count', "MAX(term_data.count)"))
.paginate(page: params[:page], per_page: 24)
elsif @toggle == "name"
@tags = Tag.joins(:node_tag, :node)
.select('MAX(term_data.count) count, MAX(term_data.name) name, MAX(term_data.tid) tid, MAX(node.nid) nid, node.status, MAX(community_tags.tid), MAX(community_tags.date)')
.where('node.status = ?', 1)
.where('community_tags.date > ?', (DateTime.now - 1.month).to_i)
.where(powertag_clause)
.group(:name)
.order(order_string.gsub('count', "MAX(term_data.count)"))
.paginate(page: params[:page], per_page: 24)
elsif @toggle == "followers"
raw_tags = Tag.joins(:node_tag, :node)
.select('MAX(term_data.count) count, MAX(term_data.name) name, MAX(term_data.tid) tid, MAX(node.nid) nid, node.status, MAX(community_tags.tid), MAX(community_tags.date)')
.where('node.status = ?', 1)
.where('community_tags.date > ?', (DateTime.now - 1.month).to_i)
.where(powertag_clause)
.group(:name)
raw_tags = Tag.sort_according_to_followers(raw_tags, params[:order])
@tags = raw_tags.paginate(page: params[:page], per_page: 24)
else
tags = Tag.joins(:node_tag, :node)
.select('MAX(node.nid), node.status, term_data.*, community_tags.*')
.where('node.status = ?', 1)
.where('community_tags.date > ?', (DateTime.now - 1.month).to_i)
.where(powertag_clause)
.group(:name)
.order(order_string)
followed = []
not_followed = []
tags.each do |tag|
if current_user.following(tag.name) == true
followed.append(tag.tid)
else
not_followed.append(tag.tid)
end
end
ids = followed + not_followed
@tags = Tag.where(tid: ids).sort_by { |p| ids.index(p.tid) }.paginate(page: params[:page], per_page: 24)
end
end
def show
get_wiki
@node = @wiki # expose the wiki node in the @node variable so we get open graph meta tags in the layout
default_type = params[:id]&.match?('question:') ? 'questions' : 'note'
@node_type = params[:node_type] || default_type
@start = Time.parse(params[:start]) if params[:start]
@end = Time.parse(params[:end]) if params[:end]
node_type = if %w(questions note).include?(@node_type)
'note'
elsif @node_type == 'wiki'
'page'
elsif @node_type == 'maps'
'map'
elsif @node_type == 'contributors'
'contributor'
elsif @node_type == 'comments'
'comments'
end
if params[:id][-1..-1] == '*' # wildcard tags
@wildcard = true
@tags = Tag.where('name LIKE (?)', params[:id][0..-2] + '%')
nodes = Node.for_tagname_and_type(params[:id], node_type, wildcard: true)
else
@tags = Tag.where(name: params[:id])
nodes = Node.for_tagname_and_type(params[:id], node_type, question: (@node_type == 'questions'))
end
if @start && @end
nodes = nodes.where(created: @[email protected]_i)
else
@pinned_nodes = NodeShared.pinned_nodes(params[:id])
if @pinned_nodes.size.positive? && params[:page].nil? # i.e. first page
nodes = nodes.where.not(nid: @pinned_nodes.collect(&:id))
end
end
order_by = if params[:order] == 'views'
'node.views DESC'
elsif params[:order] == 'likes'
'node.cached_likes DESC'
elsif @node_type == 'wiki' # wiki sorting by timestamp isn't working; https://github.com/publiclab/plots2/issues/7334#issuecomment-696938352
'node.nid DESC'
else # params[:order] == 'last_updated'
'node_revisions.timestamp DESC'
end
@qids = Node.questions.where(status: 1)
.collect(&:nid)
if @qids.empty?
@questions = []
else
nodes = nodes.where('node.nid NOT IN (?)', @qids) if @node_type == 'note'
if @node_type == 'questions'
@questions = nodes.where('node.nid IN (?)', @qids)
@pagy, nodes = pagy(@questions, items: 24)
else
@pagy, nodes = pagy(nodes, items: 24)
end
end
nodes = nodes.order(order_by)
@notes = nodes
@paginated = true
@wikis = nodes if @node_type == 'wiki'
@wikis ||= []
@nodes = nodes if @node_type == 'maps'
@title = params[:id]
@contributor_count = Tag.contributor_count(params[:id]) || 0
@tagnames = [params[:id]]
@tag = Tag.find_by(name: params[:id])
@note_count = Tag.tagged_node_count(params[:id]) || 0
@users = Tag.contributors(@tagnames[0])
@related_tags = Tag.related(@tagnames[0])
fetch_counts
respond_with(nodes) do |format|
format.html { render 'tag/show' }
format.xml { render xml: nodes }
format.json do
json = []
nodes.each do |node|
json << node.as_json(except: %i(path tags))
json.last['path'] = 'https://' + request.host.to_s + node.path
json.last['preview'] = node.body_preview(500)
json.last['image'] = node.main_image.path(:large) if node.main_image
json.last['tags'] = Node.find(node.id).tags.collect(&:name) if node.tags
end
render json: json
end
end
end
def show_for_author
# try for a matching /wiki/_TAGNAME_ or /_TAGNAME_
@wiki = Node.where(path: "/wiki/#{params[:id]}").try(:first) || Node.where(path: "/#{params[:id]}").try(:first)
@wiki = Node.find(@wiki.power_tag('redirect')) if @wiki&.has_power_tag('redirect')
default_type = if params[:id].match?('question:')
'questions'
else
'note'
end
# params[:node_type] - this is an optional param
# if params[:node_type] is nil - use @default_type
@node_type = params[:node_type] || default_type
node_type = 'note' if @node_type == 'questions' || @node_type == 'note'
node_type = 'page' if @node_type == 'wiki'
node_type = 'map' if @node_type == 'maps'
qids = Node.questions.where(status: 1).collect(&:nid)
if params[:id][-1..-1] == '*' # wildcard tags
@wildcard = true
@tags = Tag.where('name LIKE (?)', params[:id][0..-2] + '%')
else
@tags = Tag.where(name: params[:id])
end
@tagname = params[:id]
@user = User.find_by(name: params[:author])
nodes = Tag.tagged_nodes_by_author(@tagname, @user)
.where(status: 1, type: node_type)
@total_posts = nodes.size
nodes = nodes.paginate(page: params[:page], per_page: 24)
@notes ||= []
@notes = nodes.where('node.nid NOT IN (?)', qids) if @node_type == 'note'
@questions = nodes.where('node.nid IN (?)', qids) if @node_type == 'questions'
@wikis = nodes if @node_type == 'wiki'
@nodes = nodes if @node_type == 'maps'
@title = "'" + @tagname.to_s + "' by " + params[:author]
@contributor_count = Tag.contributor_count(params[:id]) || 0
respond_with(nodes) do |format|
format.html { render 'tag/show' }
format.xml { render xml: nodes }
format.json do
json = []
nodes.each do |node|
json << node.as_json(except: %i(path tags))
json.last['path'] = 'https://' + request.host
.to_s + node.path
json.last['preview'] = node.body_preview(500)
json.last['image'] = node.main_image.path(:large) if node.main_image
json.last['tags'] = Node.find(node.id).tags.collect(&:name) if node.tags
end
render json: json
end
end
end
def related
@tags = Tag.related(params[:id])
render partial: 'tag/related', layout: false, locals: { tags: @tags }
end
def widget
num = params[:n] || 4
nids = Tag.find_nodes_by_type(params[:id], 'note', num).collect(&:nid)
@notes = Node.paginate(page: params[:page], per_page: 24)
.where('status = 1 AND nid in (?)', nids)
.order('nid DESC')
render layout: false
end
def blog2
nids = Tag.find_nodes_by_type(params[:id], 'note', nil).collect(&:nid)
@pagy, @notes = pagy(Node.includes(:node_tag).where('node.status = 1 AND node.nid in (?)', nids).order('community_tags.updated_at DESC'), items: 6)
@tags = Tag.where(name: params[:id])
@tagnames = @tags.collect(&:name).uniq! || []
@title = @tagnames.join(',') + ' Blog' if @tagnames
end
def blog
nids = Tag.find_nodes_by_type(params[:id], 'note', nil).collect(&:nid)
@pagy, @notes = pagy(Node.where('status = 1 AND nid in (?)', nids).order('created DESC'), items: 6)
@tags = Tag.where(name: params[:id])
@tagnames = @tags.collect(&:name).uniq! || []
@title = @tagnames.join(',') + ' Blog' if @tagnames
end
def author
render json: User.find_by(name: params[:id]).tag_counts
end
def barnstar
node = Node.find params[:nid]
tagname = 'barnstar:' + params[:star]
if Tag.exists?(tagname, params[:nid])
flash[:error] = I18n.t('tag_controller.tag_already_exists')
elsif !node.add_barnstar(tagname.strip, current_user)
flash[:error] = I18n.t('tag_controller.barnstar_not_created')
else
flash[:notice] = I18n.t('tag_controller.barnstar_awarded', url1: '/wiki/barnstars#' + params[:star].split('-').each(&:capitalize!).join('+') + '+Barnstar', star: params[:star], url2: '/profile/' + node.author.name, awardee: node.author.name).html_safe
# on success add comment
barnstar_info_link = '<a href="//' + request.host.to_s + '/wiki/barnstars">barnstar</a>'
node.add_comment(subject: 'barnstar',
uid: current_user.uid,
body: "@#{current_user.username} awards a #{barnstar_info_link} to #{node.user.name} for their awesome contribution!")
end
redirect_to node.path + '?_=' + Time.now.to_i.to_s
end
def create
params[:name] ||= ''
tagnames = params[:name].split(',')
@output = {
errors: [],
saved: []
}
@tags = [] # not used except in tests for now
nid = params[:nid] || params[:id]
node = Node.find nid
tagnames.each do |tagname|
# this should all be done in the model:
tagname = tagname.strip
if Tag.exists?(tagname, nid)
@output[:errors] << I18n.t('tag_controller.tag_already_exists')
elsif tagname.include?(":") && tagname.split(':').size < 2
if tagname.split(':')[0] == "barnstar" || tagname.split(':')[0] == "with"
@output[:errors] << I18n.t('tag_controller.cant_be_empty')
end
elsif node.can_tag(tagname, current_user) === true || logged_in_as(['admin'])
saved, tag = node.add_tag(tagname.strip, current_user)
if tagname.include?(":") && tagname.split(':').size == 2
if tagname.split(':')[0] == "barnstar"
CommentMailer.notify_barnstar(current_user, node)
barnstar_info_link = '<a href="//' + request.host.to_s + '/wiki/barnstars">barnstar</a>'
node.add_comment(subject: 'barnstar',
uid: current_user.uid,
body: "@#{current_user.username} awards a #{barnstar_info_link} to #{node.user.name} for their awesome contribution!")
elsif tagname.split(':')[0] == "with"
user = User.find_by_username_case_insensitive(tagname.split(':')[1])
CommentMailer.notify_coauthor(user, node)
node.add_comment(subject: 'co-author',
uid: current_user.uid,
body: " @#{current_user.username} has marked @#{tagname.split(':')[1]} as a co-author. ")
end
end
if saved
@tags << tag
@output[:saved] << [tag.name, tag.id, nid]
else
@output[:errors] << I18n.t('tag_controller.error_tags') + tag.errors[:name].first
end
else
@output[:errors] << node.can_tag(tagname, current_user, true)
end
end
respond_with do |format|
format.html do
if request.xhr?
render json: @output
else
flash[:notice] = I18n.t('tag_controller.tags_created_error',
tag_count: @output[:saved].size,
error_count: @output[:errors].size).html_safe
redirect_to node.path
end
end
end
end
# should delete only the term_node/node_tag (instance), not the term_data (class)
def delete
node_tag = NodeTag.where(nid: params[:nid], tid: params[:tid]).first
node = Node.where(nid: params[:nid]).first
# only admins, mods can delete other peoples' tags if the note/wiki contains the locked tag
if (node_tag.uid == current_user.uid && !node.has_tag('locked')) || logged_in_as(['admin', 'moderator']) || (node.uid == current_user.uid && !node.has_tag('locked'))
tag = Tag.joins(:node_tag)
.select('term_data.name')
.where(tid: params[:tid])
.first
if (tag.name.split(':')[0] == "lat") || (tag.name.split(':')[0] == "lon")
node.delete_coord_attribute(tag.name)
end
node_tag.delete
output = {
status: true,
tid: node_tag.tid
}
respond_with do |format|
format.html do
if request.xhr?
render json: output
else
flash[:notice] = I18n.t('tag_controller.tag_deleted')
redirect_to node_tag.node.path
end
end
end
elsif node.has_tag('locked')
flash[:error] = "Only admins can delete tags on locked pages."
redirect_to Node.find_by(nid: params[:nid]).path
else
flash[:error] = I18n.t('tag_controller.must_own_tag_to_delete')
redirect_to Node.find_by(nid: params[:nid]).path
end
end
def suggested
if !params[:id].empty? && params[:id].size > 2
@suggestions = SearchService.new.search_tags(params[:id])
render json: @suggestions.collect { |tag| tag.name }.uniq
else
render json: []
end
end
def rss
@notes = if params[:tagname][-1..-1] == '*'
Node.where(status: 1, type: 'note')
.includes(:revision, :tag)
.references(:term_data, :node_revisions)
.where('term_data.name LIKE (?)', params[:tagname][0..-2] + '%')
.limit(20)
.order('node_revisions.timestamp DESC')
else
Tag.find_nodes_by_type([params[:tagname]], 'note', 20)
end
respond_to do |format|
format.rss do
response.headers['Content-Type'] = 'application/xml; charset=utf-8'
response.headers['Access-Control-Allow-Origin'] = '*'
render layout: false
end
format.ics do
response.headers['Content-Disposition'] = "attachment; filename='public-lab-events.ics'"
response.headers['Content-Type'] = 'text/calendar; charset=utf-8'
render layout: false, template: 'tag/icalendar.ics', filename: 'public-lab-events.ics'
end
end
end
def rss_for_tagged_with_author
@user = User.find_by(name: params[:authorname])
@notes = Tag.tagged_nodes_by_author(params[:tagname], @user)
.where(status: 1)
.limit(20)
respond_to do |format|
format.rss do
response.headers['Content-Type'] = 'application/xml; charset=utf-8'
response.headers['Access-Control-Allow-Origin'] = '*'
render layout: false
end
format.ics do
response.headers['Content-Disposition'] = "attachment; filename='public-lab-events.ics'"
response.headers['Content-Type'] = 'text/calendar; charset=utf-8'
render layout: false, template: 'tag/icalendar.ics', filename: 'public-lab-events.ics'
end
end
end
def location
render template: 'locations/_form'
end
def location_modal
render template: 'locations/_modal', layout: false
end
def gridsEmbed
if %w(nodes wikis activities questions upgrades notes).include?(params[:tagname].split(':').first)
params[:t] = params[:tagname]
params[:tagname] = ""
end
render layout: false
end
def graph
render layout: false
end
def graph_data
render json: params.key?(:limit) ? Tag.graph_data(params[:limit].to_i, params[:type].to_s, params[:weight].to_i) : Tag.graph_data
end
def stats
@start = params[:start] ? Time.parse(params[:start].to_s) : Time.now - 1.year
@end = params[:end] ? Time.parse(params[:end].to_s) : Time.now
tagname = params[:id]
@tag_name = params[:id]
@tags = Tag.where(name: params[:id])
return if @tags.empty?
@tag_notes = @tags.first.contribution_graph_making('note', @start, @end)
@tag_wikis = @tags.first.contribution_graph_making('page', @start, @end)
@tag_questions = @tags.first.quiz_graph(@start, @end)
@tag_comments = @tags.first.comment_graph(@start, @end)
@subscriptions = @tags.first.subscription_graph(@start, @end)
@first_time_poster_content_tally = Rails.cache.fetch("#{params[:id][email protected][email protected]_s}/first-time-posters-in-period", expires_in: 1.day) do
# count nodes tagged "first-time-poster" in addition to this tag:
ftp_tid = Tag.where(name: 'first-time-poster')&.first&.tid
ftp_nids = NodeTag
.where(tid: ftp_tid)
.joins(:node)
.where('node.created': @[email protected]_i)
.collect(&:nid)
tag_nids = NodeTag.where(tid: @tags&.first&.tid)
.collect(&:nid)
(ftp_nids & tag_nids).count # intersection of 2 collections
end
@overall_contributor_tally = Tag.contributors(@tag_name, start: @start, finish: @end).size
@all_subscriptions = TagSelection.graph(@start, @end)
total_questions = Node.published.questions
.where(created: @[email protected]_i)
.where(nid: Node.find_by_tag(tagname))
@answers = total_questions.joins(:comments).size.size
@questions = total_questions.size.size
end
def comments
@qids = Node.questions.where(status: 1).collect(&:nid)
@wildcard = true if params[:id][-1..-1] == '*' # wildcard tags
fetch_counts
get_wiki
@title = params[:id]
@contributor_count = Tag.contributor_count(params[:id]) || 0
tids = Tag.where(name: params[:id]).collect(&:tid)
nids = NodeTag.where('tid IN (?)', tids).collect(&:nid)
@pagy, @comments = pagy(Comment.where(nid: nids).order('timestamp DESC'), items: 24)
@node_type = "comments"
render 'show'
end
private
def order_string
if params[:search] || @toggle == "uses"
params[:order].blank? || (params[:order] == "desc") ? "count DESC" : "count ASC"
else
params[:order].blank? || (params[:order] == "desc") ? "name DESC" : "name ASC"
end
end
def get_wiki
if params[:id].is_a? Integer
@wiki = Node.find(params[:id])&.first
elsif params[:id].to_s.match?(":")
@wiki = Node.where(slug: params[:id].match('[^:]*$').to_s).try(:first)
else
@wiki = Node.where(path: "/wiki/#{params[:id]}").try(:first) || Node.where(path: "/#{params[:id]}").try(:first)
@wiki = Node.where(slug: @wiki.power_tag('redirect'))&.first if @wiki&.has_power_tag('redirect') # use a redirected wiki page if it exists
end
end
def fetch_counts
# Enhancement #6306 - Add counts to `by type` dropdown on tag pages
@counts = {}
@counts[:posts] = Node.for_tagname_and_type(params[:id], 'note', wildcard: @wildcard).where('node.nid NOT IN (?)', @qids).size
@counts[:questions] = Node.for_tagname_and_type(params[:id], 'note', question: true, wildcard: @wildcard).where('node.nid IN (?)', @qids).size
@counts[:wiki] = Node.for_tagname_and_type(params[:id], 'page', wildcard: @wildcard).size
params[:counts] = @counts
# end Enhancement #6306 ============================================
@total_posts = case @node_type
when 'note'
@notes.size
when 'questions'
@questions.size
when 'wiki'
@wikis.size
when 'maps'
@nodes.size
end
end
def topic_tree; end
end