drg_cms 0.6.1.1.1 → 0.6.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +25 -10
  3. data/app/assets/javascripts/drg_cms/drg_cms.js +99 -29
  4. data/app/assets/stylesheets/drg_cms/drg_cms.css +89 -12
  5. data/app/controllers/dc_application_controller.rb +60 -163
  6. data/app/controllers/dc_common_controller.rb +49 -45
  7. data/app/forms/all_options.yml +4 -1
  8. data/app/forms/dc_page.yml +4 -0
  9. data/app/helpers/cms_edit_helper.rb +31 -22
  10. data/app/helpers/cms_index_helper.rb +42 -21
  11. data/app/helpers/dc_application_helper.rb +31 -44
  12. data/app/models/concerns/dc_page_concern.rb +3 -2
  13. data/app/models/concerns/dc_piece_concern.rb +1 -1
  14. data/app/models/concerns/dc_site_concern.rb +1 -1
  15. data/app/models/concerns/dc_user_concern.rb +3 -3
  16. data/app/models/dc_filter.rb +16 -10
  17. data/app/models/drgcms_form_fields/date_picker.rb +2 -0
  18. data/app/models/drgcms_form_fields/drgcms_field.rb +2 -1
  19. data/app/models/drgcms_form_fields/embedded.rb +4 -2
  20. data/app/models/drgcms_form_fields/number_field.rb +4 -3
  21. data/app/models/drgcms_form_fields/readonly.rb +13 -17
  22. data/app/models/drgcms_form_fields/select.rb +8 -9
  23. data/app/models/drgcms_form_fields/text_autocomplete.rb +17 -11
  24. data/app/renderers/dc_page_renderer.rb +7 -6
  25. data/app/views/cmsedit/_edit_stuff.html.erb +5 -2
  26. data/app/views/cmsedit/edit.html.erb +2 -1
  27. data/app/views/cmsedit/index.html.erb +1 -1
  28. data/app/views/cmsedit/new.html.erb +3 -2
  29. data/config/locales/models_en.yml +2 -0
  30. data/config/locales/models_sl.yml +4 -3
  31. data/drg_cms.gemspec +16 -16
  32. data/lib/drg_cms/version.rb +1 -1
  33. data/lib/drg_cms.rb +44 -4
  34. metadata +29 -29
@@ -26,9 +26,8 @@
26
26
  # application controllers.
27
27
  ##########################################################################
28
28
  class DcApplicationController < ActionController::Base
29
- protect_from_forgery
30
-
31
- before_action :dc_reload_patches if Rails.env.development?
29
+ protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
30
+ before_action :dc_reload_patches if Rails.env.development?
32
31
 
33
32
  ########################################################################
34
33
  # Writes anything passed as parameter to logger file.
@@ -54,9 +53,9 @@ end
54
53
  ####################################################################
55
54
  # Checks if user has required role.
56
55
  #
57
- # @param [DcPolicyRole] role can be passed as DcPolicyRole object or
58
- # @param [String] role as role name. If passed as name, dc_policy_roles is searched for appropriate role.
59
- #
56
+ # @param [DcPolicyRole or String] role can be passed as DcPolicyRole object or
57
+ # as role name. If passed as name, dc_policy_roles is searched for appropriate role.
58
+ #
60
59
  # @return [Boolean] True if user has required role added to his profile.
61
60
  #
62
61
  # @example If user has required role
@@ -153,7 +152,7 @@ end
153
152
  # Will write document to dc_visits collection unless visit comes from robot.
154
153
  # It also sets session[is_robot] variable to true if robot.
155
154
  ########################################################################
156
- def dc_log_visit()
155
+ def dc_log_visit
157
156
  if request.env["HTTP_USER_AGENT"] and request.env["HTTP_USER_AGENT"].match(/\(.*https?:\/\/.*\)/)
158
157
  logger.info "ROBOT: #{Time.now.strftime('%Y.%m.%d %H:%M:%S')} id=#{@page.id} ip=#{request.remote_ip}."
159
158
  session[:is_robot] = true
@@ -173,8 +172,8 @@ protected
173
172
  # Checks if user can perform (read, create, edit, delete) document in specified
174
173
  # table (collection).
175
174
  #
176
- # @param [Integer] Required permission level
177
- # @param [String] Collection (table) name for which permission is queried. Defaults to params[table].
175
+ # @param [Integer] permission: Required permission level
176
+ # @param [String] table: Collection (table) name for which permission is queried. Defaults to params[table].
178
177
  #
179
178
  # @return [Boolean] true if user's role permits (is higher or equal then required) operation on a table (collection).
180
179
  #
@@ -182,19 +181,14 @@ protected
182
181
  # if dc_user_can(DcPermission::CAN_VIEW, params[:table]) then ...
183
182
  ############################################################################
184
183
  def dc_user_can(permission, table = params[:table])
185
- permissions = DcPermission.permissions_for_table(table)
186
- session[:user_roles].each {|r| return true if permissions[r] && permissions[r] >= permission }
187
- false
188
- end
189
-
190
- def dc_user_can(permission, table = params[:table])
184
+ table = table.underscore
191
185
  cache_key = ['dc_permission', table, session[:user_id], dc_get_site.id]
192
186
  permissions = dc_cache_read(cache_key)
193
187
  if permissions.nil?
194
188
  permissions = DcPermission.permissions_for_table(table)
195
189
  dc_cache_write(cache_key, permissions)
196
190
  end
197
- session[:user_roles].each {|r| return true if permissions[r] && permissions[r] >= permission }
191
+ session[:user_roles].each { |r| return true if permissions[r] && permissions[r] >= permission }
198
192
  false
199
193
  end
200
194
 
@@ -216,33 +210,22 @@ def dc_cache_read(keys)
216
210
  end
217
211
  end
218
212
 
219
- def __dc_cache_read(keys)
220
- p 'read', keys.join(''), Rails.cache.instance_variable_get(:@data).keys
221
- pp Rails.cache.read(keys.join(''))
222
- end
223
-
224
213
  ####################################################################
225
214
  # Write data to cache
226
215
  #
227
- # @param [Array] Array of keys
228
- # @param [Object] Data written to cache
216
+ # @param [Array] keys: Array of keys
217
+ # @param [Object] data: Data written to cache
229
218
  #
230
219
  # @return [Object] data so dc_cache_write can be used as last statement in method.
231
220
  ####################################################################
232
- def dc_cache_write(keys, data)
233
- if redis_cache_store?
234
- keys = keys.dup
235
- first = keys.shift
236
- redis.hset(first, keys.join(''), Marshal.dump(data))
237
- else
238
- Rails.cache.write(keys.join(''), data)
239
- end
240
- data
221
+ def dc_cache_write(keys, data)
222
+ if redis_cache_store?
223
+ keys = keys.dup
224
+ first = keys.shift
225
+ redis.hset(first, keys.join(''), Marshal.dump(data))
226
+ else
227
+ Rails.cache.write(keys.join(''), data)
241
228
  end
242
-
243
- def __dc_cache_write(keys, data)
244
- p 'write', keys.join('')
245
- pp Rails.cache.write(keys.join(''), data)
246
229
  data
247
230
  end
248
231
 
@@ -256,8 +239,8 @@ def dc_set_is_mobile
256
239
  is_mobile = request.user_agent ? /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.match(request.user_agent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.match(request.user_agent[0..3])
257
240
  : false
258
241
  session[:is_mobile] = is_mobile ? 1 : 0
259
- #
260
- if request.env["HTTP_USER_AGENT "] and request.env["HTTP_USER_AGENT"].match(/\(.*https?:\/\/.*\)/)
242
+
243
+ if request.env["HTTP_USER_AGENT "] && request.env["HTTP_USER_AGENT"].match(/\(.*https?:\/\/.*\)/)
261
244
  logger.info "ROBOT: #{Time.now.strftime('%Y.%m.%d %H:%M:%S')} id=#{@page.id} ip=#{request.remote_ip}."
262
245
  session[:is_robot] = true
263
246
  end
@@ -266,23 +249,13 @@ end
266
249
  ##########################################################################
267
250
  # Merge values from parameters fields (from site, page ...) into internal @options hash.
268
251
  #
269
- # @param [String] YAML string.
252
+ # @param [String] parameters: passed as YAML string.
270
253
  ##########################################################################
271
254
  def dc_set_options(parameters)
272
255
  @options ||= {}
273
256
  return if parameters.to_s.size < 3
274
- # parameters are set az YAML. This should be default in future.
275
- parms = YAML.load(parameters) rescue nil
276
- if parms.nil? # error when loadnig yaml, try the old way parsing manually
277
- parms = {}
278
- parameters.split("\n").each do |line|
279
- line.chomp.split(',').each do |parm|
280
- key, value = parm.split(':')
281
- value = value.to_s.strip.gsub(/\'|\"/,'')
282
- parms[key.strip] = (value == '/' ? nil : value)
283
- end
284
- end
285
- end
257
+ # parameters are set as YAML. This should be default in future.
258
+ parms = YAML.load(parameters) rescue {}
286
259
  @options.merge!(parms)
287
260
  end
288
261
 
@@ -296,7 +269,6 @@ end
296
269
  # @return [Boolean] true when none of documents is changed.
297
270
  ##########################################################################
298
271
  def dc_not_modified?(*documents)
299
- # request.env.each {|k,v| p k,'*',v}
300
272
  return false unless request.env.include? 'HTTP_IF_MODIFIED_SINCE'
301
273
 
302
274
  since_date = Time.parse request.env['HTTP_IF_MODIFIED_SINCE']
@@ -305,7 +277,7 @@ def dc_not_modified?(*documents)
305
277
  next unless doc.respond_to?(:updated_at)
306
278
  last_modified = doc.updated_at if doc.updated_at > last_modified
307
279
  end
308
- # p last_modified, since_date
280
+
309
281
  if last_modified >= since_date then
310
282
  render :nothing => true, :status => 304
311
283
  return true
@@ -324,13 +296,13 @@ def get_design_and_render(design_doc)
324
296
  layout = @site.site_layout.blank? ? 'content' : @site.site_layout
325
297
  site_top = '<%= dc_page_top %>'
326
298
  site_bottom = '<%= dc_page_bottom %>'
327
- # lets try the rails way
299
+ # lets try the rails way
328
300
  if @options[:control] && @options[:action]
329
301
  controller = "#{@options[:control]}_control".classify.constantize rescue nil
330
302
  extend controller if controller
331
303
  return send @options[:action] if respond_to?(@options[:action])
332
304
  end
333
- # design doc present
305
+ # design doc present
334
306
  if design_doc
335
307
  # defined as rails view
336
308
  design = if design_doc.rails_view.blank? || design_doc.rails_view == 'site'
@@ -344,7 +316,7 @@ def get_design_and_render(design_doc)
344
316
  design = site_top + design + site_bottom
345
317
  return render(inline: design, layout: layout) unless design.blank?
346
318
  end
347
- # Design doc not defined
319
+ # Design doc not defined
348
320
  if @site.rails_view.blank?
349
321
  design = site_top + @site.design + site_bottom
350
322
  render(inline: design, layout: layout)
@@ -384,6 +356,7 @@ def dc_process_default_request
384
356
  params[:path] = @options[:path].first if @options[:path].size > 1
385
357
  # some other process request. It should fail if not defined
386
358
  return send(@site.request_processor) unless @site.request_processor.blank?
359
+
387
360
  # Search for page
388
361
  pageclass = @site.page_klass
389
362
  if params[:id]
@@ -405,6 +378,7 @@ def dc_process_default_request
405
378
  end
406
379
  # if @page is not found render 404 error
407
380
  return dc_render_404('Page!') unless @page
381
+
408
382
  dc_set_is_mobile unless session[:is_mobile] # do it only once per session
409
383
  # find design if defined. Otherwise design MUST be declared in site
410
384
  if @page.dc_design_id
@@ -427,8 +401,7 @@ def dc_process_default_request
427
401
  get_design_and_render @design
428
402
  end
429
403
 
430
- ######
431
- # ####################################################################
404
+ ###########################################################################
432
405
  # Single site document kind of request handler.
433
406
  #
434
407
  # This request handler assumes that all data for the site is saved in the site document.
@@ -444,18 +417,17 @@ def dc_single_sitedoc_request
444
417
  if @site.nil?
445
418
  session[:edit_mode] ||= 0
446
419
  @site = dc_get_site
447
- # @site is not defined. render 404 error
420
+ # @site is not defined. render 404 error
448
421
  return dc_render_404('Site!') unless @site
422
+
449
423
  dc_set_options(@site.settings)
450
424
  end
451
- # HOMEPAGE. When no parameters is set
425
+ # HOMEPAGE. When no parameters is set
452
426
  params[:path] = @site.homepage_link if params[:path].nil?
453
427
  @parts = @site.dc_parts
454
428
  @part = @parts.find_by(link: params[:path])
455
429
  return dc_render_404('Part!') unless @part
456
- # Document was not modified since last visit
457
- # return if dc_not_modified?(@site, @part)
458
- #
430
+
459
431
  @page_title = "#{@site.page_title} #{@part.name}"
460
432
  @js, @css = '', ''
461
433
  get_design_and_render nil
@@ -466,46 +438,36 @@ end
466
438
  # very good with non ascii chars. Since this method is used for converting from model
467
439
  # to collection names it is very unwise to use non ascii chars for table (collection) names.
468
440
  #
469
- # @param [String] String to be converted
470
- #
441
+ # @param [Object] model_string to be converted
442
+ #
471
443
  # @example
472
444
  # decamelize_type(ModelName) # 'ModelName' => 'model_name'
473
445
  ########################################################################
474
- def decamelize_type(string)
475
- return nil unless string
476
- r = ''
477
- string.to_s.each_char do |c|
478
- r << case
479
- when r.size == 0 then c.downcase
480
- when c.downcase != c then '_' + c.downcase
481
- else c
482
- end
483
- end
484
- r
446
+ def decamelize_type(model_string)
447
+ model_string ? model_string.underscore : nil
485
448
  end
486
449
 
487
450
  ####################################################################
488
451
  # Return's error messages for the document formated for display on edit form.
489
452
  #
490
- # @param [Document] Document object which will be examined for errors.
491
- #
453
+ # @param [Document] document object which will be examined for errors.
454
+ #
492
455
  # @return [String] HTML code for displaying error on edit form.
493
456
  ####################################################################
494
457
  def dc_error_messages_for(document)
495
458
  return '' unless document.errors.any?
459
+
496
460
  msg = ''
497
- document.errors.each do |attribute, errors_array|
498
- label = t("helpers.label.#{decamelize_type(document.class)}.#{attribute}")
499
- msg << "<li>#{label} : #{errors_array}</li>"
461
+ document.errors.each do |error|
462
+ label = t("helpers.label.#{decamelize_type(document.class)}.#{error.attribute}", error.attribute)
463
+ msg << "<li>#{label} : #{error.message}</li>"
500
464
  end
501
465
 
502
- html = <<eot
466
+ %(
503
467
  <div class="dc-form-error">
504
468
  <h2>#{t('drgcms.errors_no')} #{document.errors.size}</h2>
505
469
  <ul>#{msg}</ul>
506
- </div>
507
- eot
508
- html.html_safe
470
+ </div>).html_safe
509
471
  end
510
472
 
511
473
  ####################################################################
@@ -514,8 +476,8 @@ end
514
476
  # model errors or when saving to multiple collections and where each save must be
515
477
  # checked if succesfull.
516
478
  #
517
- # @param [Document] Document object which will be checked
518
- # @param [Boolean] If true method should end in runtime error. Default = false.
479
+ # @param [Document] document: Document object to be checked
480
+ # @param [Boolean] crash: If true method should end in runtime error. Default = false.
519
481
  #
520
482
  # @return [String] Error messages or empty string if everything is OK.
521
483
  #
@@ -527,16 +489,16 @@ end
527
489
  # end
528
490
  #
529
491
  ####################################################################
530
- def dc_check_model(document, crash=false)
492
+ def dc_check_model(document, crash = false)
531
493
  DrgCms.model_check(document, crash)
532
494
  end
533
495
 
534
496
  ######################################################################
535
497
  # Call rake task from controller.
536
498
  #
537
- # @param [String] Rake task name
538
- # @param [Hash] Options that will be send to task as environment variables
539
- #
499
+ # @param [String] task: Rake task name
500
+ # @param [Hash] options: Options that will be send to task as environment variables
501
+ #
540
502
  # @example Call rake task from application
541
503
  # dc_call_rake('clear:all', some_parm: some_id)
542
504
  ######################################################################
@@ -551,7 +513,7 @@ end
551
513
  # made from DRG CMS form return may be quite complicated. All ajax return combinations
552
514
  # can be found in drg_cms.js file.
553
515
  #
554
- # @param [Hash] Options
516
+ # @param [Hash] opts: Options
555
517
  #
556
518
  # @return [JSON Response] Formatted to be used for ajax return.
557
519
  #
@@ -643,51 +605,6 @@ def set_default_guest_user_role
643
605
  session[:user_roles] = [guest.id] if guest
644
606
  end
645
607
 
646
- ####################################################################
647
- # Fills session with data related to successful login.
648
- #
649
- # @param [DcUser] user : User's document
650
- # @param [Boolean] remember_me : false by default
651
- ####################################################################
652
- def fill_login_data(user, remember_me=false)
653
- session[:user_id] = user.id if user
654
- session[:user_name] = user.name if user
655
- session[:edit_mode] = 0
656
- session[:user_roles] = []
657
- # Every user has guest role
658
- # guest = DcPolicyRole.find_by(system_name: 'guest')
659
- # session[:user_roles] << guest.id if guest
660
- set_default_guest_user_role
661
- return unless user and user.active
662
- # special for SUPERADMIN
663
- sa = DcPolicyRole.find_by(system_name: 'superadmin')
664
- if sa and (role = user.dc_user_roles.find_by(dc_policy_role_id: sa.id))
665
- session[:user_roles] << role.dc_policy_role_id
666
- session[:edit_mode] = 2
667
- return
668
- end
669
- # read default policy from site. Policy might be inherited
670
- policy_site = dc_get_site()
671
- policy_site = DcSite.find(policy_site.inherit_policy) if policy_site.inherit_policy
672
- default_policy = policy_site.dc_policies.find_by(is_default: true)
673
- # load user roles
674
- user.dc_user_roles.each do |role|
675
- next unless role.active
676
- next if role.valid_from and role.valid_from > Time.now.end_of_day.to_date
677
- next if role.valid_to and role.valid_to < Time.now.to_date
678
- # check if role is active in this site
679
- policy_role = default_policy.dc_policy_rules.find_by(dc_policy_role_id: role.dc_policy_role_id)
680
- next unless policy_role
681
- # set edit_mode
682
- session[:edit_mode] = 1 if policy_role.permission > 1
683
- session[:user_roles] << role.dc_policy_role_id
684
- end
685
- # Save remember me cookie if not CMS user and remember me is selected
686
- if session[:edit_mode] == 0 and remember_me
687
- cookies.signed[:remember_me] = { :value => user.id, :expires => 180.days.from_now}
688
- end
689
- end
690
-
691
608
  ####################################################################
692
609
  # Fills session with data related to successful login.
693
610
  #
@@ -696,7 +613,7 @@ end
696
613
  ####################################################################
697
614
  def fill_login_data(user, remember_me = false)
698
615
  session[:user_id] = user.id if user
699
- session[:user_name] = user.name if user
616
+ session[:user_name] = user.name.squish if user
700
617
  session[:edit_mode] = 0
701
618
  set_default_guest_user_role
702
619
  return unless user&.active
@@ -771,7 +688,7 @@ end
771
688
  # Evaluates Class.method in more predictable context then just calling eval
772
689
  #
773
690
  # @param [String] class_method defined as MyClass.method_name
774
- # @param [Object] optional parameters send to class_method
691
+ # @param [Object] params: optional parameters send to class_method
775
692
  ##########################################################################
776
693
  def dc_eval_class_method(class_method, params = nil)
777
694
  klass, method = class_method.split('.')
@@ -823,28 +740,9 @@ def dc_add_meta_tag(type, name, content)
823
740
  end
824
741
 
825
742
  ########################################################################
826
- # Will prepare flash[:update] data, which will be used for updating fields
827
- # on forms parent form fields.
828
- #
829
- # Parameters:
830
- # [field_name] String: Field name
831
- # [value] String: New value
832
- # [readonly] Boolean: Field is readonly
833
- #
834
- ########################################################################
835
- def dc_update_form_field(field_name, value, readonly=false)
836
- dc_deprecate('dc_update_form_field will be deprecated. Use dc_update_form_element instead.')
837
- key_name = (readonly ? 'td_' : '') + "record_#{field_name}"
838
- flash[:update] ||= {}
839
- flash[:update][key_name] = value
840
- end
841
-
842
- ########################################################################
843
- # Will prepare flash[:update] data, which will be used for updating elements
743
+ # Will prepare flash[:update] data, which is used for updating elements
844
744
  # on parent form.
845
745
  #
846
- # dc_update_form_field will be deprecated eventually.
847
- #
848
746
  # Parameters passed as hash:
849
747
  # [field] String: Field name
850
748
  # [head] String: Filed name in head of form
@@ -858,11 +756,10 @@ def dc_update_form_element(field: nil, head: nil, value:, readonly: true)
858
756
  elsif head
859
757
  "head-#{head}"
860
758
  end
759
+ return if key.nil?
861
760
 
862
- if key
863
- flash[:update] ||= {}
864
- flash[:update][key] = value
865
- end
761
+ flash[:update] ||= {}
762
+ flash[:update][key] = value
866
763
  end
867
764
 
868
765
  ####################################################################
@@ -45,28 +45,29 @@ layout false
45
45
  ########################################################################
46
46
  def autocomplete
47
47
  # table parameter must be defined. If not, get it from search parameter
48
- if params['table'].nil? and params['search'].match(/\./)
48
+ if params['table'].nil? && params['search'].match(/\./)
49
49
  name = params['search'].split('.').first
50
50
  params['table'] = name.underscore
51
51
  end
52
-
53
52
  return render plain: t('drgcms.not_authorized') unless dc_user_can(DcPermission::CAN_VIEW)
54
- # TODO Double check if previous line works as it should.
53
+
55
54
  table = params['table'].classify.constantize
56
- id = [params['id']] || '_id'
57
- # call method in class if search parameter has . This is for user defined searches
58
- # result must be returned as array of [id, search_field_value]
55
+ input = params['input'].gsub(/\(|\)|\[|\]|\{|\|\.|\,}/, '')
56
+ # call method in class if search parameter contains . This is for user defined searches
59
57
  a = if params['search'].match(/\./)
60
- name, method = params['search'].split('.')
61
- table.send(method, params['input']).inject([]) do |r,v|
62
- r << { label: v[0], value: v[0], id: (v[1] || v[0]).to_s }
63
- end
64
- # simply search which will search and return field_name defined in params['search']
65
- else
66
- table.where(params['search'] => /#{params['input']}/i).limit(20).inject([]) do |r,v|
67
- r << { label: v[params['search']], value: v[params['search']], id: v.id.to_s }
68
- end
69
- end
58
+ #method, additional_params = params['search'].split('.')
59
+ #data = additional_params ? table.send(method, input, additional_params, self) : table.send(method, input)
60
+ name, method = params['search'].split('.')
61
+ data = table.send(method, input)
62
+ data.map do |v|
63
+ { label: v[0], value: v[0], id: (v[1] || v[0]).to_s }
64
+ end
65
+ # will search and return field_name defined in params['search']
66
+ else
67
+ table.where(params['search'] => /#{input}/i).limit(20).map do |v|
68
+ { label: v[params['search']], value: v[params['search']], id: v.id.to_s }
69
+ end
70
+ end
70
71
 
71
72
  render plain: a.to_json
72
73
  end
@@ -92,18 +93,19 @@ end
92
93
  ##########################################################################
93
94
  def toggle_edit_mode
94
95
  session[:edit_mode] ||= 0
95
- # error when not logged in
96
- return dc_render_404 if session[:edit_mode] < 1
97
- # if return_to_ypos parameter is present it will forward it and thus scroll to
98
- # aproximate position it was when toggle was clicked
96
+ # error when not logged in
97
+ return dc_render_404 if session[:edit_mode] < 1
98
+
99
+ # if return_to_ypos parameter is present it will forward it and thus scroll to
100
+ # aproximate position it was when toggle was clicked
99
101
  session[:edit_mode] = (session[:edit_mode] == 1) ? 2 : 1
100
102
  uri = Rack::Utils.parse_nested_query(request.url)
101
- # it parses only on & so first (return_to) parameter also contains url
103
+ # it parses only on & so first (return_to) parameter also contains url
102
104
  url = uri.first.last
103
105
  if (i = url.index('return_to_ypos')).to_i > 0
104
- url = url[0,i-1]
106
+ url = url[0, i-1]
105
107
  end
106
- # offset CMS menu
108
+ # offset CMS menu
107
109
  if (ypos = uri['return_to_ypos'].to_i) > 0
108
110
  ypos += session[:edit_mode] == 2 ? 250 : -250
109
111
  end
@@ -116,8 +118,8 @@ end
116
118
  # Default user login action.
117
119
  ####################################################################
118
120
  def process_login
119
- # Somebody is probably playing
120
- return dc_render_404 unless ( params[:record] and params[:record][:username] and params[:record][:password] )
121
+ # Somebody is probably playing
122
+ return dc_render_404 unless ( params[:record] && params[:record][:username] && params[:record][:password] )
121
123
 
122
124
  unless params[:record][:password].blank? #password must not be empty
123
125
  user = DcUser.find_by(username: params[:record][:username], active: true)
@@ -154,7 +156,7 @@ def login
154
156
  clear_login_data # on the safe side
155
157
  end
156
158
  end
157
- # Display login
159
+ # Display login
158
160
  route = params[:route] || 'poll'
159
161
  redirect_to "/#{route}?poll_id=login&return_to=#{params[:return_to]}"
160
162
  end
@@ -163,23 +165,23 @@ end
163
165
  # Action for restoring document data from journal document.
164
166
  ####################################################################
165
167
  def restore_from_journal
166
- # Only administrators can perform this operation
168
+ # Only administrators can perform this operation
167
169
  unless dc_user_has_role('admin')
168
170
  return render plain: { 'msg_info' => (t ('drgcms.not_authorized')) }.to_json
169
171
  end
170
- # selected fields to hash
172
+ # selected fields to hash
171
173
  restore = {}
172
- params[:select].each {|key,value| restore[key] = value if value == '1' }
174
+ params[:select].each { |key,value| restore[key] = value if value == '1' }
173
175
  result = if restore.size == 0
174
176
  { 'msg_error' => (t ('drgcms.dc_journal.zero_selected')) }
175
177
  else
176
178
  journal_doc = DcJournal.find(params[:id])
177
- # update hash with data to be restored
179
+ # update hash with data to be restored
178
180
  JSON.parse(journal_doc.diff).each {|k,v| restore[k] = v.first if restore[k] }
179
- # determine tables and document ids
181
+ # determine tables and document ids
180
182
  tables = journal_doc.tables.split(';')
181
183
  ids = (journal_doc.ids.blank? ? [] : journal_doc.ids.split(';') ) << journal_doc.doc_id
182
- # find document
184
+ # find document
183
185
  doc = nil
184
186
  tables.each_index do |i|
185
187
  doc = if doc.nil?
@@ -188,10 +190,10 @@ def restore_from_journal
188
190
  doc.send(tables[i].pluralize).find(ids[i])
189
191
  end
190
192
  end
191
- # restore and save values
193
+ # restore and save values
192
194
  restore.each { |field,value| doc.send("#{field}=",value) }
193
195
  doc.save
194
- # TODO Error checking
196
+ # TODO Error checking
195
197
  { 'msg_info' => (t ('drgcms.dc_journal.restored')) }
196
198
  end
197
199
  render plain: result.to_json
@@ -202,10 +204,11 @@ end
202
204
  # window with data formatted as json.
203
205
  ########################################################################
204
206
  def copy_clipboard
205
- # Only administrators can perform this operation
207
+ # Only administrators can perform this operation
206
208
  return render(plain: t('drgcms.not_authorized') ) unless dc_user_can(DcPermission::CAN_ADMIN,'dc_site')
209
+
207
210
  respond_to do |format|
208
- # just open new window to same url and come back with html request
211
+ # just open new window to same url and come back with html request
209
212
  format.json { dc_render_ajax(operation: 'window', url: request.url ) }
210
213
 
211
214
  format.html do
@@ -213,7 +216,6 @@ def copy_clipboard
213
216
  text = "<br><br>[#{params[:table]},#{params[:id]},#{params[:ids]}]<br>"
214
217
  render plain: text + doc.as_document.to_json
215
218
  end
216
-
217
219
  end
218
220
  end
219
221
 
@@ -223,17 +225,19 @@ end
223
225
  # ajax call for processing data.
224
226
  ########################################################################
225
227
  def paste_clipboard
226
- # Only administrators can perform this operation
228
+ # Only administrators can perform this operation
227
229
  return render(plain: t('drgcms.not_authorized') ) unless dc_user_can(DcPermission::CAN_ADMIN,'dc_site')
230
+
228
231
  result = ''
229
232
  respond_to do |format|
230
- # just open new window to same url and come back with html request
233
+ # just open new window to same url and come back with html request
231
234
  format.html { return render('paste_clipboard', layout: 'cms') }
232
235
  format.json {
233
236
  table, id, ids = nil
234
237
  params[:data].split("\n").each do |line|
235
238
  line.chomp!
236
239
  next if line.size < 5 # empty line. Skip
240
+
237
241
  begin
238
242
  if line[0] == '[' # id(s)
239
243
  result << "<br>#{line}"
@@ -260,7 +264,7 @@ def add_json_ld_schema
260
264
  edited_document = DcJsonLd.find_document_by_ids(params[:table], params[:ids])
261
265
  yaml = YAML.load_file( dc_find_form_file('json_ld_schema') )
262
266
  schema_data = yaml[params[:schema]]
263
- # Existing document
267
+ # Existing document
264
268
  if edited_document.dc_json_lds.find_by(type: "@#{params[:schema]}")
265
269
  return render json: {'msg_error' => t('helpers.help.dc_json_ld.add_error', schema: params[:schema] ) }
266
270
  else
@@ -337,7 +341,7 @@ def update_json(json, is_update=false) #:nodoc:
337
341
  json.each do |k,v|
338
342
  if v.class == Hash
339
343
  result[k] = v['$oid'] unless is_update
340
- #TODO Double check if unless works as expected
344
+ # TODO Double check if unless works as expected
341
345
  elsif v.class == Array
342
346
  result[k] = []
343
347
  v.each {|e| result[k] << update_json(e, is_update)}
@@ -354,22 +358,22 @@ end
354
358
  def process_document(line, table, id, ids)
355
359
  if params[:do_update] == '1'
356
360
  doc = dc_find_document(table, id, ids)
357
- # document found. Update it and return
361
+ # document found. Update it and return
358
362
  if doc
359
363
  doc.update( update_json(ActiveSupport::JSON.decode(line), true) )
360
364
  msg = dc_check_model(doc)
361
365
  return (msg ? " ERROR! #{msg}" : " UPDATE. OK.")
362
366
  end
363
367
  end
364
- # document will be added to collection
368
+ # document will be added to collection
365
369
  if ids.to_s.size > 5
366
- #TODO Add embedded document
370
+ #TODO Add embedded document
367
371
  " NOT SUPPORTED YET!"
368
372
  else
369
373
  doc = table.classify.constantize.new( update_json(ActiveSupport::JSON.decode(line)) )
370
374
  doc.save
371
375
  end
372
- msg = dc_check_model(doc)
376
+ msg = DrgCms.model_check(doc)
373
377
  msg ? " ERROR! #{msg}" : " NEW. OK."
374
378
  end
375
379