summaryrefslogtreecommitdiff
path: root/app/controllers/forums_controller.rb
blob: 16ea5b2100f3b27633ac1e7eb2548708c5d07db4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class ForumsController < ApplicationController

  before_filter :check_permission, only: [:show, :edit, :update, :destroy]

  def index
     @groups = Forumgroup.select {|g| g.can_view?(current_user) }
     @groups.sort_by!{ |g| g.position || 0 }
  end

  def show
    @threads = @forum.forumthreads.select {|f| f.can_read?(current_user) }.to_a
    @threads.sort_by! do |t|
      # sticky goes first, then sort by last activity (new replies)
      [t.sticky ? 0 : 1, -(t.replies.order(:id).last.try(:created_at) || t.created_at).to_i]
    end
    @threads = Kaminari.paginate_array(@threads).page(params[:page])
  end

  def edit
    unless admin?
      flash[:alert] = "You are not allowed to change a forum"
      redirect_to forums_path
    end
  end

  def new
    if admin?
      @forum = Forum.new(forumgroup: @group)
      @forum.forumgroup = Forumgroup.find(params[:forumgroup])
    else
      flash[:alert] = "You are not allowed to create a forum."
      redirect_to forums_path
    end
  end

  def update
    if admin?
      if @forum.update_attributes(forum_params)
        flash[:notice] = "Forum updated"
        redirect_to @forum
      else
        flash[:alert] = "Something went wrong"
      end
    else
      flash[:alert] = "You are not allowed to change a forum"
      redirect_to @forum
    end
  end

  def create
    if admin?
      @forum = Forum.new(forum_params([:forumgroup_id]))
      if @forum.save
        flash[:notice] = "Forum created."
        redirect_to @forum
      else
        flash[:alert] = "Something went wrong"
        render :new
      end
    else
      flash[:alert] = "You are not allowed to create a forum."
      redirect_to forums_path
    end
  end

  def destroy
    if admin?
      if @forum.destroy
        flash[:notice] = "Forum deleted."
      else
        flash[:alert] = "Something went wrong"
        redirect_to @forum
        return
      end
    else
      flash[:alert] = "You are not allowed to delete a forum."
    end
    redirect_to forums_path
  end

  private

  def check_permission
    @forum = Forum.find(params[:id])
    unless @forum.can_view?(current_user)
      flash[:alert] = "You are not allowed to view this forum"
      redirect_to forums_path
    end
  end

  def forum_params(add = [])
    a = [:name, :position, :role_read_id, :role_write_id, :necro_length, :disable_deletion] + add
    params.require(:forum).permit(a)
  end
end