Class: DcCommonController

Inherits:
DcApplicationController show all
Defined in:
app/controllers/dc_common_controller.rb

Overview

This controller holds some common actions used by CMS.

Instance Method Summary collapse

Methods inherited from DcApplicationController

#dc_dump, #dc_edit_mode?, #dc_find_form_file, #dc_get_site, #dc_log_visit, #dc_render_404, #dc_user_has_role, #set_page_title

Instance Method Details

#ad_clickObject

Register and record click when ad link is clicked.



83
84
85
86
87
88
89
90
91
92
93
# File 'app/controllers/dc_common_controller.rb', line 83

def ad_click
  if params[:id] and (ad = DcAd.find(params[:id]))
    ad.clicked += 1
    ad.save
    DcAdStat.create!(dc_ad_id: params[:id], ip: request.ip, type: 2 ) 
  else
    logger.error "ERROR ADS: Invalid ad id=#{params[:id]} ip=#{request.ip}."
  end

  render body: nil
end

#add_json_ld_schemaObject

Will add new json_ld element with blank structure into dc_json_ld field on a document.



269
270
271
272
273
274
275
276
277
278
279
280
# File 'app/controllers/dc_common_controller.rb', line 269

def add_json_ld_schema
  edited_document = DcJsonLd.find_document_by_ids(CmsHelper.table_param(params), params[:ids])
  yaml = YAML.load_file( dc_find_form_file('json_ld_schema') )
  schema_data = yaml[params[:schema]]
  # Existing document
  if edited_document.dc_json_lds.find_by(type: "@#{params[:schema]}")
    return render json: {'msg_error' => t('helpers.help.dc_json_ld.add_error', schema: params[:schema] ) }
  else
    add_empty_json_ld_schema(edited_document, schema_data, params[:schema], params[:schema], yaml)
  end
  render json: {'reload_' => 1}
end

#autocompleteObject

This action is called on ajax autocomplete call. It checks if user has rights to view data.

URL parameters:

table

Table (collection) model name in lower case indicating table which will be searched.

id

Name of id key field that will be returned. Default is ‘_id’

input

Search data entered in input field.

search

when passed without dot it defines field name on which search

will be performed. When passed with dot class_method.method_name is assumed. Method name will be parsed and any class with class method name can be evaluated. Class method must accept input parameter and return array [ [_id, value],.. ] which will be used in autocomplete field.

Return: JSON array [label, value, id] of first 20 documents that confirm to query.



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
# File 'app/controllers/dc_common_controller.rb', line 46

def autocomplete
  # table parameter must be defined. If not, get it from search parameter
  if params['table'].nil? && params['search'].match(/\./)
    name = params['search'].split('.').first
    params['table'] = name.underscore
  end
  if params['table'].match('_control')
    # it must be at least logged on
    return render json: { label: t('drgcms.not_authorized') } unless dc_user_can(DcPermission::CAN_VIEW, 'dc_memory')
  else
    return render json: { label: t('drgcms.not_authorized') } unless dc_user_can(DcPermission::CAN_VIEW)
  end

  table = params['table'].classify.constantize
  input = params['input'].gsub(/\(|\)|\[|\]|\{|\|\.|\,}/, '')
  # call method in class if search parameter contains . This is for user defined searches
  a = if params['search'].match(/\./)
        #method, additional_params = params['search'].split('.')
        #data = additional_params ? table.send(method, input, additional_params, self) : table.send(method, input)
        name, method = params['search'].split('.')
        data = table.send(method, input)
        data.map do |v|
          { label: v[0], value: v[0], id: (v[1] || v[0]).to_s }
        end
      # will search and return field_name defined in params['search']
      else
        table.where(params['search'] => /#{input}/i).limit(20).map do |v|
          { label: v[params['search']], value: v[params['search']], id: v.id.to_s }
        end
      end

  render json: a
end

#copy_clipboardObject

Copy current record to clipboard as json text. It will actually ouput an window with data formatted as json.



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'app/controllers/dc_common_controller.rb', line 211

def copy_clipboard
  # Only administrators can perform this operation
  return render(plain: t('drgcms.not_authorized') )  unless dc_user_can(DcPermission::CAN_ADMIN,'dc_site')

  respond_to do |format|
    # just open new window to same url and come back with html request
    format.json { dc_render_ajax(operation: 'window', url: request.url ) }
    
    format.html do
      table = CmsHelper.table_param(params)
      doc   = dc_find_document(table, params[:id], params[:ids])
      text  = "<br><br>[#{table},#{params[:id]},#{params[:ids]}]<br>"
      render plain: text + doc.as_document.to_json
    end
  end  
end

#helpObject

Will provide help data



285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'app/controllers/dc_common_controller.rb', line 285

def help
  form_name = CmsHelper.form_param(params) || CmsHelper.table_param(params)
  @form = form_name ? YAML.load_file(dc_find_form_file(form_name)) : {}
  return render json: {} if @form.nil?

  help_file_name = @form['help'] || @form['extend'] || form_name
  help_file_name = find_help_file(help_file_name)
  @help = YAML.load_file(help_file_name) if help_file_name
  # no auto generated help on index action
  return render json: {} if params[:type] == 'index' && @help.nil?

  render json: { popup: render_to_string(partial: 'help') }
end

#loginObject

Alternative login action with remember_me cookie. If found it will automatically login user otherwise user will be presented with regular login dialog.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'app/controllers/dc_common_controller.rb', line 154

def 
  if cookies.signed[:remember_me]
    user = DcUser.find(cookies.signed[:remember_me])
    if user and user.active
      (user, true)
      return redirect_to params[:return_to]
    else
       # on the safe side
    end
  end
  # Display login
  route = params[:route] || 'poll'
  redirect_to "/#{route}?poll_id=login&return_to=#{params[:return_to]}"
end

#logoutObject

Default user logout action.



145
146
147
148
# File 'app/controllers/dc_common_controller.rb', line 145

def logout
  
  redirect_to params[:return_to] || '/'
end

#paste_clipboardObject

Paste data from clipboard into text_area and update documents in destination database. This action is called twice. First time for displaying text_area field and second time ajax call for processing data.



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
# File 'app/controllers/dc_common_controller.rb', line 233

def paste_clipboard
  # Only administrators can perform this operation
  return render(plain: t('drgcms.not_authorized') )  unless dc_user_can(DcPermission::CAN_ADMIN,'dc_site')

  result = ''
  respond_to do |format|
    # just open new window to same url and come back with html request
    format.html { return render('paste_clipboard', layout: 'cms') }
    format.json {
      table, id, ids = nil
      params[:data].split("\n").each do |line|
        line.chomp!
        next if line.size < 5                 # empty line. Skip

        begin
          if line[0] == '['                   # id(s)
            result << "<br>#{line}"
            line = line[/\[(.*?)\]/, 1]       # just what is between []
            table, id, ids = line.split(',')
          elsif line[0] == '{'                # document data
            result << process_document(line, table, id, ids)
          end
        rescue Exception => e 
          result << " Runtime error. #{e.message}\n"
          break
        end
      end
    }
  end
  dc_render_ajax(div: 'result', value: result )
end

#process_loginObject

Default user login action.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'app/controllers/dc_common_controller.rb', line 125

def 
  # Somebody is probably playing
  return dc_render_404 unless ( params[:record] && params[:record][:username] && params[:record][:password] )

  unless params[:record][:password].blank? #password must not be empty
    user  = DcUser.find_by(username: params[:record][:username], active: true)
    if user and user.authenticate(params[:record][:password])
      (user, params[:record][:remember_me].to_i == 1)
      return redirect_to params[:return_to] ||  '/'
    else
       # on the safe side
    end
  end
  flash[:error] = t('drgcms.invalid_username')
  redirect_to params[:return_to_error] ||  '/'
end

#restore_from_journalObject

Action for restoring document data from journal document.



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
# File 'app/controllers/dc_common_controller.rb', line 172

def restore_from_journal
  # Only administrators can perform this operation
  unless dc_user_has_role('admin')
    return render plain: { 'msg_info' => (t ('drgcms.not_authorized')) }.to_json
  end
  # selected fields to hash
  restore = {} 
  params[:select].each { |key,value| restore[key] = value if value == '1' }
  result = if restore.size == 0
    { 'msg_error' => (t ('drgcms.dc_journal.zero_selected')) }
  else
    journal_doc = DcJournal.find(params[:id])
    # update hash with data to be restored
    JSON.parse(journal_doc.diff).each {|k,v| restore[k] = v.first if restore[k] }
    # determine tables and document ids
    tables = journal_doc.tables.split(';')
    ids = (journal_doc.ids.blank? ? [] : journal_doc.ids.split(';') ) << journal_doc.doc_id
    # find document
    doc = nil
    tables.each_index do |i|
      doc = if doc.nil?
        (tables[i].classify.constantize).find(ids[i])
      else
        doc.send(tables[i].pluralize).find(ids[i])
      end
    end
    # restore and save values
    restore.each { |field,value| doc.send("#{field}=",value) }
    doc.save
    # TODO Error checking
    { 'msg_info' => (t ('drgcms.dc_journal.restored')) }
  end
  render plain: result.to_json
end

#toggle_edit_modeObject

Toggle CMS edit mode.This action is called when user clicks CMS option on top of the browser.



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'app/controllers/dc_common_controller.rb', line 99

def toggle_edit_mode
  session[:edit_mode] ||= 0 
  # error when not logged in
  return dc_render_404 if session[:edit_mode] < 1

  # if return_to_ypos parameter is present it will forward it and thus scroll to
  # aproximate position it was when toggle was clicked
  session[:edit_mode] = (session[:edit_mode] == 1) ? 2 : 1
  uri = Rack::Utils.parse_nested_query(request.url)
  # it parses only on & so first (return_to) parameter also contains url
  url = uri.first.last
  if (i = url.index('return_to_ypos')).to_i > 0
    url = url[0, i-1]
  end 
  # offset CMS menu
  if (ypos = uri['return_to_ypos'].to_i) > 0
    ypos += session[:edit_mode] == 2 ? 250 : -250
  end
  url << (url.match(/\?/) ? '&' : '?')
  url << "return_to_ypos=#{ypos}"
  redirect_to url
end