add a method to get the current version
[shapado:shapado.git] / app / controllers / application_controller.rb
1 # Filters added to this controller apply to all controllers in the application.
2 # Likewise, all the methods added will be available for all controllers.
3
4 class ApplicationController < ActionController::Base
5   include Rack::Recaptcha::Helpers
6   include Subdomains
7   include Sweepers
8
9   include Shapado::Controllers::Access
10   include Shapado::Controllers::Routes
11   include Shapado::Controllers::Locale
12   include Shapado::Controllers::Utils
13
14   if !AppConfig.recaptcha['activate']
15     def recaptcha_valid?
16       true
17     end
18   end
19
20   protect_from_forgery
21
22   before_filter :check_cookies
23   before_filter :find_group
24   before_filter :check_group_access
25   before_filter :set_locale
26   before_filter :find_languages
27   before_filter :share_variables
28   before_filter :check_social
29   before_filter :set_custom_headers
30   before_filter :check_sidebar
31
32   layout :set_layout
33
34   helper_method :recaptcha_tag
35
36   rescue_from Error404, :with => :render_404
37   rescue_from Mongoid::Errors::DocumentNotFound, :with => :render_404
38
39   protected
40
41   def check_social
42     if logged_in? && current_group.is_social_only_signup? &&
43         !current_user.is_socially_connected?
44       redirect_to social_connect_path if params[:controller] == 'questions'
45     end
46   end
47
48   def check_cookies
49     if params[:format] == 'mobile'
50       cookies.delete(:pp)
51       session[:user_return_to] = '/mobile'
52     end
53   end
54
55   def find_group
56     @current_group ||= begin
57       subdomains = request.subdomains
58       subdomains.delete("www") if request.host == "www.#{AppConfig.domain}"
59       _current_group = Group.where({:state => "active", :domain => request.host}).first
60       unless _current_group
61         if subdomain = subdomains.first
62           _current_group = Group.where(:state => "active", :subdomain => subdomain).first
63           unless _current_group.nil?
64             redirect_to domain_url(:custom => _current_group.domain)
65             return
66           end
67         end
68         flash[:warn] = t("global.group_not_found", :url => request.host)
69         redirect_to domain_url(:custom => AppConfig.domain)
70         return
71       end
72       _current_group
73     end
74     @current_group
75   end
76
77   def find_questions(extra_conditions = {}, extra_scope = { })
78     if params[:language] || request.query_string =~ /tags=/
79       params.delete(:language)
80       head :moved_permanently, :location => url_for(params)
81       return
82     end
83
84     set_page_title(t("questions.index.title"))
85     conditions = scoped_conditions(:banned => false)
86
87     if params[:sort] == "hot"
88       conditions[:activity_at] = {"$gt" => 5.days.ago}
89     end
90
91     @active_tab = "questions"
92     if params[:unanswered]
93       conditions[:answered_with_id] = nil
94       @active_tab = "unanswered"
95     elsif params[:answers]
96       @active_tab = "answers"
97     end
98     @active_subtab ||= params[:sort] || "newest"
99
100     @questions = Question.minimal.where(conditions.merge(extra_conditions)).order_by(current_order)
101
102     extra_scope.keys.each do |key|
103       @questions = @questions.send(key, extra_scope[key])
104     end
105
106     @questions = @questions.page(params["page"])
107
108     @langs_conds = @languages
109
110     if logged_in?
111       feed_params = { :feed_token => current_user.feed_token }
112     else
113       feed_params = {  :lang => I18n.locale, :mylangs => current_languages }
114     end
115     add_feeds_url(url_for({:format => "atom"}.merge(feed_params)), t("feeds.questions"))
116     if params[:tags]
117       add_feeds_url(url_for({:format => "atom", :tags => params[:tags]}.merge(feed_params)),
118                     "#{t("feeds.tag")} #{params[:tags].inspect}")
119     end
120
121     respond_to do |format|
122       format.html { render :layout => layout_for_theme }
123       format.mobile
124       format.json  { render :json => @questions.to_json(:except => %w[_keywords watchers slugs]) }
125       format.atom
126     end
127   end
128
129   def find_activities(conds = {})
130     #add_feeds_url(url_for({:format => "atom"}.merge(feed_params)), t("feeds.questions"))
131
132     @activities = current_group.activities.where(conds).order(:created_at.desc).page(params["page"])
133
134     respond_to do |format|
135       format.html
136       format.json { render :json => @activities}
137     end
138   end
139
140   def current_group
141     @current_group
142   end
143   helper_method :current_group
144   
145   def current_version
146     @current_version ||= begin
147       current_group.shapado_version ? current_group.shapado_version : ShapadoVersion.libre
148     end
149   end
150   helper_method :current_version
151
152   def scoped_conditions(conditions = {})
153     unless current_tags.empty?
154       conditions.deep_merge!({:tags => {:$all => current_tags}})
155     end
156     conditions.deep_merge!({:group_id => current_group.id})
157     conditions.deep_merge!(language_conditions)
158     conditions
159   end
160   helper_method :scoped_conditions
161
162   def set_layout
163     if env && env['HTTP_X_PJAX'].present? && !params[:_refresh]
164       nil
165     elsif devise_controller? || (action_name == "new" && controller_name == "users")
166       'sessions'
167     elsif params["format"] == "mobile"
168       'mobile'
169     elsif current_group.current_theme.has_layout_html?
170       'theme_layout.mustache.mustache'
171     elsif current_group.layout.present?
172       current_group.layout
173     else
174       'application'
175     end
176   end
177
178   def check_sidebar
179     return if !current_group
180
181     @widget_context = widgets_context(params[:controller], params[:action])
182     @show_sidebar = !( params[:controller] == "users")
183
184     if @show_sidebar
185       @show_sidebar = current_group.send(:"#{@widget_context}_widgets").sidebar.count > 0
186     end
187   end
188
189   def widgets_context(controller, action)
190     @widgets_context ||= (controller == "questions" && action == "show" && @question.present?) ? 'question' : 'mainlist'
191   end
192
193   def layout_for_theme
194     if @template_format == 'mustache'
195       current_group.current_theme.has_layout_html?
196     else
197       true
198     end
199   end
200
201   def set_custom_headers
202     if env && env['HTTP_X_PJAX'].present?
203       response.headers['X-BODYCLASS'] = bodys_class(params).join(" ")
204     end
205   end
206
207   def render_404
208     Rails.logger.info "ROUTE NOT FOUND (404): #{request.url}"
209
210     respond_to do |format|
211       format.html { render "public_errors/not_found", :status => '404 Not Found' }
212       format.json { render :json => {:success => false, :message => "Not Found"}, :status => '404 Not Found' }
213     end
214   end
215
216   # override from devise
217   def after_sign_out_path_for(resource)
218     params[:format] == "mobile" ? "/mobile" : root_path
219   end
220
221   def after_sign_in_path_for(resource_or_scope)
222     self.current_user.logged!(self.current_group)
223     super(resource_or_scope)
224   end
225
226   def share_variables
227     Thread.current[:current_group] = current_group
228     Thread.current[:current_user] = current_user
229     Thread.current[:current_ip] = request.remote_ip
230   end
231
232   def process_payment_and_redirect(success, invoice)
233     Rails.logger.info ">> A PAYMENT WAS MADE: #{success.inspect}"
234     if success
235       flash[:notice] = "The payment was successful"
236       case invoice.action
237       when "upgrade_plan"
238         invoice.items.each do |item|
239           if item["item_class"] == "ShapadoVersion"
240             current_group.override(:shapado_version_id => item["item_id"],
241                                      :plan_expires_at => Time.now + 1.month)
242
243           end
244         end
245       end
246
247       redirect_to root_path
248     else
249       flash[:error] = "Something went wrong with the payment"
250       redirect_to root_path
251     end
252
253   end
254
255   def close
256
257   end
258 end