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