Bump loofah from 2.2.3 to 2.3.1 in /apps/workbench
[arvados.git] / apps / workbench / app / helpers / application_helper.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 module ApplicationHelper
6   def current_user
7     controller.current_user
8   end
9
10   def self.match_uuid(uuid)
11     /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
12   end
13
14   def current_api_host
15     "#{Rails.configuration.Services.Controller.ExternalURL.hostname}:#{Rails.configuration.Services.Controller.ExternalURL.port}"
16   end
17
18   def current_uuid_prefix
19     Rails.configuration.ClusterID
20   end
21
22   def render_markup(markup)
23     allowed_tags = Rails::Html::Sanitizer.white_list_sanitizer.allowed_tags + %w(table tbody th tr td col colgroup caption thead tfoot)
24     sanitize(raw(RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile)), tags: allowed_tags) if markup
25   end
26
27   def human_readable_bytes_html(n)
28     return h(n) unless n.is_a? Integer
29     return "0 bytes" if (n == 0)
30
31     orders = {
32       1 => "bytes",
33       1024 => "KiB",
34       (1024*1024) => "MiB",
35       (1024*1024*1024) => "GiB",
36       (1024*1024*1024*1024) => "TiB"
37     }
38
39     orders.each do |k, v|
40       sig = (n.to_f/k)
41       if sig >=1 and sig < 1024
42         if v == 'bytes'
43           return "%i #{v}" % sig
44         else
45           return "%0.1f #{v}" % sig
46         end
47       end
48     end
49
50     return h(n)
51   end
52
53   def resource_class_for_uuid(attrvalue, opts={})
54     ArvadosBase::resource_class_for_uuid(attrvalue, opts)
55   end
56
57   # When using {remote:true}, or using {method:...} to use an HTTP
58   # method other than GET, move the target URI from href to
59   # data-remote-href. Otherwise, browsers offer features like "open in
60   # new window" and "copy link address" which bypass Rails' click
61   # handler and therefore end up at incorrect/nonexistent routes (by
62   # ignoring data-method) and expect to receive pages rather than
63   # javascript responses.
64   #
65   # See assets/javascripts/link_to_remote.js for supporting code.
66   def link_to *args, &block
67     if (args.last and args.last.is_a? Hash and
68         (args.last[:remote] or
69          (args.last[:method] and
70           args.last[:method].to_s.upcase != 'GET')))
71       if Rails.env.test?
72         # Capybara/phantomjs can't click_link without an href, even if
73         # the click handler means it never gets used.
74         raw super.gsub(' href="', ' href="#" data-remote-href="')
75       else
76         # Regular browsers work as desired: users can click A elements
77         # without hrefs, and click handlers fire; but there's no "copy
78         # link address" option in the right-click menu.
79         raw super.gsub(' href="', ' data-remote-href="')
80       end
81     else
82       super
83     end
84   end
85
86   ##
87   # Returns HTML that links to the Arvados object specified in +attrvalue+
88   # Provides various output control and styling options.
89   #
90   # +attrvalue+ an Arvados model object or uuid
91   #
92   # +opts+ a set of flags to control output:
93   #
94   # [:link_text] the link text to use (may include HTML), overrides everything else
95   #
96   # [:friendly_name] whether to use the "friendly" name in the link text (by
97   # calling #friendly_link_name on the object), otherwise use the uuid
98   #
99   # [:with_class_name] prefix the link text with the class name of the model
100   #
101   # [:no_tags] disable tags in the link text (default is to show tags).
102   # Currently tags are only shown for Collections.
103   #
104   # [:thumbnail] if the object is a collection, show an image thumbnail if the
105   # collection consists of a single image file.
106   #
107   # [:no_link] don't create a link, just return the link text
108   #
109   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
110   #
111   def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
112     if (resource_class = resource_class_for_uuid(attrvalue, opts))
113       if attrvalue.is_a? ArvadosBase
114         object = attrvalue
115         link_uuid = attrvalue.uuid
116       else
117         object = nil
118         link_uuid = attrvalue
119       end
120       link_name = opts[:link_text]
121       tags = ""
122       if !link_name
123         link_name = object.andand.default_name || resource_class.default_name
124
125         if opts[:friendly_name]
126           if attrvalue.respond_to? :friendly_link_name
127             link_name = attrvalue.friendly_link_name opts[:lookup]
128           else
129             begin
130               if resource_class.name == 'Collection'
131                 if CollectionsHelper.match(link_uuid)
132                   link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
133                 else
134                   link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
135                 end
136               else
137                 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
138               end
139             rescue ArvadosApiClient::NotFoundException
140               # If that lookup failed, the link will too. So don't make one.
141               return attrvalue
142             end
143           end
144         end
145         if link_name.nil? or link_name.empty?
146           link_name = attrvalue
147         end
148         if opts[:with_class_name]
149           link_name = "#{resource_class.to_s}: #{link_name}"
150         end
151         if !opts[:no_tags] and resource_class == Collection
152           links_for_object(link_uuid).each do |tag|
153             if tag.link_class.in? ["tag", "identifier"]
154               tags += ' <span class="label label-info">'
155               tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
156               tags += '</span>'
157             end
158           end
159         end
160         if opts[:thumbnail] and resource_class == Collection
161           # add an image thumbnail if the collection consists of a single image file.
162           collections_for_object(link_uuid).each do |c|
163             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
164               link_name += " "
165               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
166             end
167           end
168         end
169       end
170       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
171       if opts[:no_link] or (resource_class == User && !current_user)
172         raw(link_name)
173       else
174         controller_class = resource_class.to_s.tableize
175         if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
176           controller_class = 'projects'
177         end
178         (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
179       end
180     else
181       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
182       if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
183         "(none)"
184       else
185         attrvalue
186       end
187     end
188   end
189
190   def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
191     resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
192     if !resource_class
193       return link_to_if_arvados_object attrvalue, opts
194     end
195
196     readable = object_readable attrvalue, resource_class
197     if readable
198       link_to_if_arvados_object attrvalue, opts
199     elsif opts[:required] and current_user # no need to show this for anonymous user
200       raw('<div><input type="text" style="border:none;width:100%;background:#ffdddd" disabled=true class="required unreadable-input" value="') + link_text_if_not_readable + raw('" ></input></div>')
201     else
202       link_text_if_not_readable
203     end
204   end
205
206   # This method takes advantage of preloaded collections and objects.
207   # Hence you can improve performance by first preloading objects
208   # related to the page context before using this method.
209   def object_readable attrvalue, resource_class=nil
210     # if it is a collection filename, check readable for the locator
211     attrvalue = attrvalue.split('/')[0] if attrvalue
212
213     resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
214     return if resource_class.nil?
215
216     return_value = nil
217     if resource_class.to_s == 'Collection'
218       if CollectionsHelper.match(attrvalue)
219         found = collection_for_pdh(attrvalue)
220         return_value = found.first if found.any?
221       else
222         found = collections_for_object(attrvalue)
223         return_value = found.first if found.any?
224       end
225     else
226       return_value = object_for_dataclass(resource_class, attrvalue)
227     end
228     return_value
229   end
230
231   # Render an editable attribute with the attrvalue of the attr.
232   # The htmloptions are added to the editable element's list of attributes.
233   # The nonhtml_options are only used to customize the display of the element.
234   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
235     attrvalue = object.send(attr) if attrvalue.nil?
236     if not object.attribute_editable?(attr)
237       if attrvalue && attrvalue.length > 0
238         return render_attribute_as_textile( object, attr, attrvalue, false )
239       else
240         return (attr == 'name' and object.andand.default_name) ||
241                 '(none)'
242       end
243     end
244
245     input_type = 'text'
246     attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
247     if attrtype == 'text' or attr == 'description'
248       input_type = 'textarea'
249     elsif attrtype == 'datetime'
250       input_type = 'date'
251     else
252       input_type = 'text'
253     end
254
255     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
256     rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
257
258     ajax_options = {
259       "data-pk" => {
260         id: object.uuid,
261         key: object.class.to_s.underscore
262       }
263     }
264     if object.uuid
265       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
266     else
267       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
268       ajax_options['data-pk'][:defaults] = object.attributes
269     end
270     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
271     @unique_id ||= (Time.now.to_f*1000000).to_i
272     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
273
274     span_tag = content_tag 'span', rendervalue, {
275       "data-emptytext" => '(none)',
276       "data-placement" => "bottom",
277       "data-type" => input_type,
278       "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
279       "data-name" => htmloptions['selection_name'] || attr,
280       "data-object-uuid" => object.uuid,
281       "data-toggle" => "manual",
282       "data-value" => htmloptions['data-value'] || attrvalue,
283       "id" => span_id,
284       :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
285     }.merge(htmloptions).merge(ajax_options)
286
287     edit_tiptitle = 'edit'
288     edit_tiptitle = 'Warning: do not use hyphens in the repository name as they will be stripped' if (object.class.to_s == 'Repository' and attr == 'name')
289
290     edit_button = raw('<a href="#" class="btn btn-xs btn-' + (nonhtml_options[:btnclass] || 'default') + ' btn-nodecorate" data-toggle="x-editable tooltip" data-toggle-selector="#' + span_id + '" data-placement="top" title="' + (nonhtml_options[:tiptitle] || edit_tiptitle) + '"><i class="fa fa-fw fa-pencil"></i>' + (nonhtml_options[:btntext] || '') + '</a>')
291
292     if nonhtml_options[:btnplacement] == :left
293       edit_button + ' ' + span_tag
294     elsif nonhtml_options[:btnplacement] == :top
295       edit_button + raw('<br/>') + span_tag
296     else
297       span_tag + ' ' + edit_button
298     end
299   end
300
301   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
302     datatype = nil
303     required = true
304     attrvalue = value_info
305
306     if value_info.is_a? Hash
307       if value_info[:output_of]
308         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
309       end
310       if value_info[:dataclass]
311         dataclass = value_info[:dataclass]
312       end
313       if value_info[:optional] != nil
314         required = (value_info[:optional] != "true")
315       end
316       if value_info[:required] != nil
317         required = value_info[:required]
318       end
319
320       # Pick a suitable attrvalue to show as the current value (i.e.,
321       # the one that would be used if we ran the pipeline right now).
322       if value_info[:value]
323         attrvalue = value_info[:value]
324       elsif value_info[:default]
325         attrvalue = value_info[:default]
326       else
327         attrvalue = ''
328       end
329       preconfigured_search_str = value_info[:search_for]
330     end
331
332     if not object.andand.attribute_editable?(attr)
333       return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
334     end
335
336     if dataclass
337       begin
338         dataclass = dataclass.constantize
339       rescue NameError
340       end
341     else
342       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
343     end
344
345     id = "#{object.uuid}-#{subattr.join('-')}"
346     dn = "[#{attr}]"
347     subattr.each do |a|
348       dn += "[#{a}]"
349     end
350     if value_info.is_a? Hash
351       dn += '[value]'
352     end
353
354     if (dataclass == Collection) or (dataclass == File)
355       selection_param = object.class.to_s.underscore + dn
356       display_value = attrvalue
357       if value_info.is_a?(Hash)
358         if (link = Link.find? value_info[:link_uuid])
359           display_value = link.name
360         elsif value_info[:link_name]
361           display_value = value_info[:link_name]
362         elsif (sn = value_info[:selection_name]) && sn != ""
363           display_value = sn
364         end
365       end
366       if (attr == :components) and (subattr.size > 2)
367         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
368       else
369         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
370       end
371       modal_path = choose_collections_path \
372       ({ title: chooser_title,
373          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
374          action_name: 'OK',
375          action_href: pipeline_instance_path(id: object.uuid),
376          action_method: 'patch',
377          preconfigured_search_str: (preconfigured_search_str || ""),
378          action_data: {
379            merge: true,
380            use_preview_selection: dataclass == File ? true : nil,
381            selection_param: selection_param,
382            success: 'page-refresh'
383          }.to_json,
384         })
385
386       return content_tag('div', :class => 'input-group') do
387         html = text_field_tag(dn, display_value,
388                               :class =>
389                               "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
390         html + content_tag('span', :class => 'input-group-btn') do
391           link_to('Choose',
392                   modal_path,
393                   { :class => "btn btn-primary",
394                     :remote => true,
395                     :method => 'get',
396                   })
397         end
398       end
399     end
400
401     if attrvalue.is_a? String
402       datatype = 'text'
403     elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
404       # TODO: find a way to edit with x-editable
405       return attrvalue
406     end
407
408     # When datatype is a String or Fixnum, link_to the attrvalue
409     lt = link_to attrvalue, '#', {
410       "data-emptytext" => "none",
411       "data-placement" => "bottom",
412       "data-type" => datatype,
413       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
414       "data-title" => "Set value for #{subattr[-1].to_s}",
415       "data-name" => dn,
416       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
417       "data-value" => attrvalue,
418       # "clear" button interferes with form-control's up/down arrows
419       "data-clear" => false,
420       :class => "editable #{'required' if required} form-control",
421       :id => id
422     }.merge(htmloptions)
423
424     lt
425   end
426
427   def get_cwl_main(workflow)
428     if workflow[:"$graph"].nil?
429       return workflow
430     else
431       workflow[:"$graph"].each do |tool|
432         if tool[:id] == "#main"
433           return tool
434         end
435       end
436     end
437   end
438
439   def get_cwl_inputs(workflow)
440     get_cwl_main(workflow)[:inputs]
441   end
442
443
444   def cwl_shortname(id)
445     if id[0] == "#"
446       id = id[1..-1]
447     end
448     return id.split("/")[-1]
449   end
450
451   def cwl_input_info(input_schema)
452     required = !(input_schema[:type].include? "null")
453     if input_schema[:type].is_a? Array
454       primary_type = input_schema[:type].select { |n| n != "null" }[0]
455     elsif input_schema[:type].is_a? String
456       primary_type = input_schema[:type]
457     elsif input_schema[:type].is_a? Hash
458       primary_type = input_schema[:type]
459     end
460     param_id = cwl_shortname(input_schema[:id])
461     return required, primary_type, param_id
462   end
463
464   def cwl_input_value(object, input_schema, set_attr_path)
465     dn = ""
466     attrvalue = object
467     set_attr_path.each do |a|
468       dn += "[#{a}]"
469       attrvalue = attrvalue[a.to_sym]
470     end
471     return dn, attrvalue
472   end
473
474   def cwl_inputs_required(object, inputs_schema, set_attr_path)
475     r = 0
476     inputs_schema.each do |input|
477       required, _, param_id = cwl_input_info(input)
478       _, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
479       r += 1 if required and attrvalue.nil?
480     end
481     r
482   end
483
484   def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
485     required, primary_type, param_id = cwl_input_info(input_schema)
486
487     dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
488     attrvalue = if attrvalue.nil? then "" else attrvalue end
489
490     id = "#{object.uuid}-#{param_id}"
491
492     opt_empty_selection = if required then [] else [{value: "", text: ""}] end
493
494     if ["Directory", "File"].include? primary_type
495       chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
496       selection_param = object.class.to_s.underscore + dn
497       if attrvalue.is_a? Hash
498         display_value = attrvalue[:"http://arvados.org/cwl#collectionUUID"] || attrvalue[:"arv:collection"] || attrvalue[:location]
499         re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
500         locationre = CollectionsHelper.match(attrvalue[:location][5..-1])
501         if re
502           if locationre and locationre[4]
503             display_value = "#{Collection.find(re[1]).name} / #{locationre[4][1..-1]}"
504           else
505             display_value = Collection.find(re[1]).name
506           end
507         end
508       end
509       modal_path = choose_collections_path \
510       ({ title: chooser_title,
511          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
512          action_name: 'OK',
513          action_href: container_request_path(id: object.uuid),
514          action_method: 'patch',
515          preconfigured_search_str: "",
516          action_data: {
517            merge: true,
518            use_preview_selection: primary_type == 'File' ? true : nil,
519            selection_param: selection_param,
520            success: 'page-refresh'
521          }.to_json,
522         })
523
524       return content_tag('div', :class => 'input-group') do
525         html = text_field_tag(dn, display_value,
526                               :class =>
527                               "form-control #{'required' if required}")
528         html + content_tag('span', :class => 'input-group-btn') do
529           link_to('Choose',
530                   modal_path,
531                   { :class => "btn btn-primary",
532                     :remote => true,
533                     :method => 'get',
534                   })
535         end
536       end
537     elsif "boolean" == primary_type
538       return link_to attrvalue.to_s, '#', {
539                      "data-emptytext" => "none",
540                      "data-placement" => "bottom",
541                      "data-type" => "select",
542                      "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
543                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
544                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
545                      "data-name" => dn,
546                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
547                      "data-value" => attrvalue.to_s,
548                      # "clear" button interferes with form-control's up/down arrows
549                      "data-clear" => false,
550                      :class => "editable #{'required' if required} form-control",
551                      :id => id
552                    }.merge(htmloptions)
553     elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
554       return link_to attrvalue, '#', {
555                      "data-emptytext" => "none",
556                      "data-placement" => "bottom",
557                      "data-type" => "select",
558                      "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
559                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
560                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
561                      "data-name" => dn,
562                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
563                      "data-value" => attrvalue,
564                      # "clear" button interferes with form-control's up/down arrows
565                      "data-clear" => false,
566                      :class => "editable #{'required' if required} form-control",
567                      :id => id
568                    }.merge(htmloptions)
569     elsif primary_type.is_a? String
570       if ["int", "long"].include? primary_type
571         datatype = "number"
572       else
573         datatype = "text"
574       end
575
576       return link_to attrvalue, '#', {
577                      "data-emptytext" => "none",
578                      "data-placement" => "bottom",
579                      "data-type" => datatype,
580                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
581                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
582                      "data-name" => dn,
583                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
584                      "data-value" => attrvalue,
585                      # "clear" button interferes with form-control's up/down arrows
586                      "data-clear" => false,
587                      :class => "editable #{'required' if required} form-control",
588                      :id => id
589                      }.merge(htmloptions)
590     else
591       return "Unable to render editing control for parameter type #{primary_type}"
592     end
593   end
594
595   def render_arvados_object_list_start(list, button_text, button_href,
596                                        params={}, *rest, &block)
597     show_max = params.delete(:show_max) || 3
598     params[:class] ||= 'btn btn-xs btn-default'
599     list[0...show_max].each { |item| yield item }
600     unless list[show_max].nil?
601       link_to(h(button_text) +
602               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
603               button_href, params, *rest)
604     end
605   end
606
607   def render_controller_partial partial, opts
608     cname = opts.delete :controller_name
609     begin
610       render opts.merge(partial: "#{cname}/#{partial}")
611     rescue ActionView::MissingTemplate
612       render opts.merge(partial: "application/#{partial}")
613     end
614   end
615
616   RESOURCE_CLASS_ICONS = {
617     "Collection" => "fa-archive",
618     "ContainerRequest" => "fa-gears",
619     "Group" => "fa-users",
620     "Human" => "fa-male",  # FIXME: Use a more inclusive icon.
621     "Job" => "fa-gears",
622     "KeepDisk" => "fa-hdd-o",
623     "KeepService" => "fa-exchange",
624     "Link" => "fa-arrows-h",
625     "Node" => "fa-cloud",
626     "PipelineInstance" => "fa-gears",
627     "PipelineTemplate" => "fa-gears",
628     "Repository" => "fa-code-fork",
629     "Specimen" => "fa-flask",
630     "Trait" => "fa-clipboard",
631     "User" => "fa-user",
632     "VirtualMachine" => "fa-terminal",
633     "Workflow" => "fa-gears",
634   }
635   DEFAULT_ICON_CLASS = "fa-cube"
636
637   def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
638     RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
639   end
640
641   def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
642     fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
643   end
644
645   def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
646     case class_name = object.class.to_s
647     when "Group"
648       object.group_class ? 'fa-folder' : 'fa-users'
649     else
650       RESOURCE_CLASS_ICONS.fetch(class_name, default)
651     end
652   end
653
654   def chooser_preview_url_for object, use_preview_selection=false
655     case object.class.to_s
656     when 'Collection'
657       polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
658     else
659       nil
660     end
661   end
662
663   def render_attribute_as_textile( object, attr, attrvalue, truncate )
664     if attrvalue && (is_textile? object, attr)
665       markup = render_markup attrvalue
666       markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
667       return markup
668     else
669       return attrvalue
670     end
671   end
672
673   def render_localized_date(date, opts="")
674     raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
675   end
676
677   def render_time duration, use_words, round_to_min=true
678     render_runtime duration, use_words, round_to_min
679   end
680
681   # Keep locators are expected to be of the form \"...<pdh/file_path>\" or \"...<uuid/file_path>\"
682   JSON_KEEP_LOCATOR_REGEXP = /([0-9a-f]{32}\+\d+[^'"]*|[a-z0-9]{5}-4zz18-[a-z0-9]{15}[^'"]*)(?=['"]|\z|$)/
683   def keep_locator_in_json str
684     # Return a list of all matches
685     str.scan(JSON_KEEP_LOCATOR_REGEXP).flatten
686   end
687
688 private
689   def is_textile?( object, attr )
690     object.textile_attributes.andand.include?(attr)
691   end
692 end