cewebs-aman 2.0.1

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.
@@ -0,0 +1,1042 @@
1
+ # Please see the LICENSE.GPL file for copyright and distribution information
2
+
3
+ # Usage: gui.render(:to_ui,:script)
4
+ class RelaxNGUI_1_2 < CEWebS::View
5
+
6
+ attr_reader :path, :id
7
+
8
+ def initialize(file,schema,helper_files,strings,id,urls,path="/",language=["en"])
9
+ #{{{
10
+ @strings = strings
11
+ @urls = urls
12
+ @schema = schema
13
+ @file_name = file
14
+ @helper_files = helper_files
15
+ @file = XML::Smart.open(file)
16
+ @rpath = path
17
+ if path.strip == "/" || path.strip == ""
18
+ path = @schema.find("string(/r:element/@name)")
19
+ end
20
+ @language = language
21
+ @sortables = -1
22
+ @schema_path = path_to_schema_path(path)
23
+ @schema_pos = @schema.find(@schema_path)
24
+ @path = path
25
+ @id = id
26
+ #}}}
27
+ end
28
+
29
+ def new_part(part)
30
+ #{{{
31
+ @schema_pos.each do |sp|
32
+ # because columns are on level higher at choice or zeroOrMore level
33
+ sp = sp.parent
34
+ upath = []
35
+ ui = sp.lfind("c:ui",@language)
36
+ ui.find("c:list/c:column").each do |listitem|
37
+ col = path_to_schema_path("#{@path}#{@id}/#{listitem.attributes['search'] ? listitem.attributes['search'] : listitem.text}")
38
+ pdoc = XML::Smart.string(part)
39
+ if listitem.attributes['ignoreunique'] != "true" && @schema.find(col + "/c:ui/c:unique").any?
40
+ r = @schema.find(col).first
41
+ unless r.nil?
42
+ while r.path != sp.path
43
+ if ['oneOrMore','optional','choice','zeroOrMore'].include?(kind(r))
44
+ r = nil
45
+ break
46
+ end
47
+ r = r.parent
48
+ end
49
+ end
50
+ next if r.nil?
51
+ upath << "#{listitem.text}=#{literal(pdoc.find("string(/*/" + listitem.text + ")"))}"
52
+ end
53
+ end
54
+ @id = upath.length > 0 ? "[" + upath.join(" and ") + "]" : ""
55
+ break
56
+ end
57
+ #}}}
58
+ end
59
+
60
+ def to_more(user,search,parameters)
61
+ #{{{
62
+ tpath = @path
63
+ @path = File::dirname(@path)
64
+ @schema_pos.each do |tp|
65
+ sp = tp.parent
66
+ ui = sp.lfind("c:ui",@language)
67
+ heading = ui.sfind("c:heading")
68
+ text = ui.sffind("c:text")
69
+ h1_(heading) unless heading == ""
70
+ div_(:class => 'margin-bottom-huge') { text } unless text == ""
71
+ crits = []
72
+ XML::Smart.modify(search,"<search/>") do |doc|
73
+ node = doc.find("/search/user[@id='#{user}']").first
74
+ node = doc.root.add("user",:id => user) if node.nil?
75
+ lnode = node.find("location[@path=\"#{path_to_send(tpath)}\"]").first
76
+ lnode = node.add("location",:path => path_to_send(tpath)) if lnode.nil?
77
+ if parameters.nil?
78
+ crits = lnode.find("criteria").map { |c| [c.attributes["path"].to_s,c.attributes["value"].to_s] }
79
+ else
80
+ lnode.find("criteria").delete_all!
81
+ parameters.each do |key,value|
82
+ lnode.add("criteria",:path => key, :value => value)
83
+ end
84
+ crits = parameters
85
+ end
86
+ end
87
+ columns = ui.find("c:list/c:column").map { |e| [e.attributes['search'] ? e.attributes['search'] : e.text,e.attributes['label']] }
88
+ url = "&amp;CEWebS_id=&amp;CEWebS_path=#{path_to_send(tpath)}"
89
+ i = 0
90
+ form_(:class => 'margin-bottom-huge', :method => 'post', :action => @urls[:more_list] + url) do
91
+ input_ :type => 'hidden', :name => 'CEWebS_search', :value => 'true'
92
+ div_ :id => 'CEWebS_search' do
93
+ crits.each do |key,value|
94
+ div_ do
95
+ button_ :class => 'margin-top-small', :type => 'button', :onclick => 'this.parentNode.remove(this)' do
96
+ small_img_ 'list-remove', :alt => @strings.sfind('delsearch')
97
+ end
98
+ select_ :name => "CEWebS_spath_#{i}" do
99
+ columns.each do |ckey,cvalue|
100
+ if key == ckey
101
+ option_ cvalue, :value => ckey, :selected => 'selected'
102
+ else
103
+ option_ cvalue, :value => ckey
104
+ end
105
+ end
106
+ end
107
+ input_ :type => 'text', :name => "CEWebS_svalue_#{i}", :value => h(value)
108
+ end
109
+ i += 1
110
+ end
111
+ end
112
+ div_(:class => 'margin-bottom-big margin-top-small') do
113
+ button_ :onclick => 'addSearch()', :type => 'button' do
114
+ small_img_ 'list-add', :alt => @strings.sfind('addsearch')
115
+ end
116
+ end
117
+ input_ :type => 'submit', :value => @strings.sfind('search')
118
+ end
119
+ div_(:class => 'invisible', :id => 'CEWebS_addsearch') do
120
+ div_ do
121
+ button_ :type => 'button', :onclick => 'this.parentNode.remove(this)' do
122
+ small_img_ 'list-remove', :alt => @strings.sfind('delsearch')
123
+ end
124
+ select_ :name => 'CEWebS_spath' do
125
+ columns.each do |ckey,cvalue|
126
+ option_ cvalue, :value => ckey
127
+ end
128
+ end
129
+ input_ :type => 'text', :name => 'CEWebS_svalue', :value => ''
130
+ end
131
+ end
132
+ javascript_ <<-end
133
+ var i = #{i};
134
+ function addSearch() {
135
+ var text = document.getElementById('CEWebS_addsearch').innerHTML;
136
+ text = text.replace(/CEWebS_spath/,"CEWebS_spath_" + i);
137
+ text = text.replace(/CEWebS_svalue/,"CEWebS_svalue_" + i);
138
+ document.getElementById('CEWebS_search').insertAdjacentHTML('beforeend',text);
139
+ i += 1;
140
+ }
141
+ end
142
+ pars = []
143
+ columns.each do |key,value|
144
+ par = crits.find_all{|k,v| k == key}.collect{|k,v| "contains(#{k},\"#{v.to_s.delete('"')}\")"}.join(' or ')
145
+ pars << "(#{par})" unless par == ""
146
+ end
147
+ if kind(sp) == 'choice'
148
+ npath ="[" + sp.find('r:element').map{|e| "name()='#{e.attributes['name']}'"}.join(" or ") + "]"
149
+ print_list(sp,ui,'/*' + npath,false,pars.join(" and "))
150
+ else
151
+ print_list(sp,ui,'/' + sp.sfind('r:element/@name'),false,pars.join(" and "))
152
+ end
153
+ end
154
+ nil
155
+ #}}}
156
+ end
157
+
158
+ def to_ui(schema_pos=@schema_pos,level=0,path="")
159
+ #{{{
160
+ schema_pos.each do |sp|
161
+ div_ :class => (level != 0 ? "border #{level == 1 ? '' : 'margin-left-huge '}margin-top-big" : nil) do
162
+ case kind(sp)
163
+ when "zeroOrMore", "oneOrMore"
164
+ # can include one choice or one element (nothing else)
165
+ ch = sp.find('r:*')
166
+ if ch.length == 1 and kind(ch.first) == 'choice'
167
+ fch = ch.first
168
+ ui = fch.lfind("c:ui",@language)
169
+ print_header(level,ui)
170
+ npath = "[" + fch.find('r:element').map{|e| "name()='#{e.attributes['name']}'"}.join(" or ") + "]"
171
+ print_list(fch,ui,path + "/*" + npath)
172
+ elsif ch.length == 1 and kind(ch.first) == 'element'
173
+ ui = sp.lfind("c:ui",@language)
174
+ print_header(level,ui)
175
+ print_list(sp,ui,path + "/" + ch.first.attributes['name'])
176
+ else
177
+ div_ "RelaxNGui Rule: only 1 choice or 1 element inside #{kind(sp)}"
178
+ end
179
+ when "optional"
180
+ # can include 1 element (nothing else)
181
+ ch = sp.find('r:*')
182
+ if ch.length == 1 and kind(ch.first) == 'element'
183
+ fch = ch.first
184
+
185
+ # if there is no element in the xml file
186
+ ui = fch.lfind("c:ui",@language)
187
+ if @file.find(@path + @id + path + "/" + fch.attributes["name"]).empty?
188
+ print_optional(path + "/" + fch.attributes["name"],true) # show new icon
189
+ print_header(level+1,ui)
190
+ else
191
+ print_optional(path + "/" + fch.attributes["name"],false) # show delete icon
192
+ print_element(fch,level+1,ui,path) # print and possibly recurse
193
+ end
194
+ end
195
+ when "choice"
196
+ # TODO can include multiple elements (nothing else)
197
+ div_ 'TODO: pure choice'
198
+ else
199
+ ui = sp.lfind("c:ui",@language)
200
+ print_element(sp,level,ui,path)
201
+ end
202
+ nil
203
+ end
204
+ end
205
+ nil
206
+ #}}}
207
+ end
208
+
209
+ def set_value(operation,set,value)
210
+ #{{{
211
+ set = set.gsub(/\/\.\//,"/")
212
+
213
+ @schema_pos.each do |sp|
214
+ # if not in subtree
215
+ return '' if @id == ''
216
+
217
+ # because columns are on level higher at choice or zeroOrMore level
218
+ sp = sp.parent
219
+
220
+ upath = []
221
+ ui = sp.lfind("c:ui",@language)
222
+ ui.find("c:list/c:column").each do |listitem|
223
+ col = path_to_schema_path("#{@path}#{@id}/#{listitem.attributes['search'] ? listitem.attributes['search'] : listitem.text}")
224
+ if listitem.attributes['ignoreunique'] != "true" && @schema.find(col + "/c:ui/c:unique").any?
225
+ if "/" + listitem.text == set
226
+ upath << "#{listitem.text}=#{literal(value)}"
227
+ else
228
+ upath << "#{listitem.text}=#{literal(@file.find("string(" + @path + @id + "/" + listitem.text + ")"))}"
229
+ end
230
+ end
231
+ end
232
+ return upath.length > 0 ? "[" + upath.join(" and ") + "]" : ""
233
+ end
234
+ ""
235
+ #}}}
236
+ end
237
+
238
+ def set_form(operation,set)
239
+ #{{{
240
+ schema_path = path_to_schema_path(@path+set)
241
+ schema_pos = @schema.find(schema_path)
242
+ schema_pos.each do |sp|
243
+ checkform = formatform = ""
244
+ data = sp.find("r:data").first
245
+ value = @file.sfind(@path + @id + set)
246
+ out = capture { checkform, formatform = set_form_fields(sp,data,set,value) }
247
+ if out != ''
248
+ form_(:id => "CEWebS_#{path_to_id(set)}", :onsubmit => "#{checkform != "" ? "if (!#{checkform}){ return false; }; " : ""}setPath('#{set}',true,'#{operation}');#{formatform != "" ? "#{formatform};" : ""}return false;") do
249
+ text_ out
250
+ input_(:type => "submit", :value => @strings.sfind("set"))
251
+ end
252
+ end
253
+ break
254
+ end
255
+ nil
256
+ #}}}
257
+ end
258
+
259
+ # returns javascript for checking and for formatting the value
260
+ def set_form_fields(sp,data,set,value)
261
+ #{{{
262
+ checkform = ""
263
+ formatform = ""
264
+
265
+ refchoice = Proc.new do |cchoice|
266
+ select_(:name => 'CEWebS_value') do
267
+ refpath = cchoice.first.attributes['refpath']
268
+ helper = refpath[/^(\w+)::/,1]
269
+ refpath = refpath.sub(/^(\w+)::/,"")
270
+ opts = []
271
+ if @helper_files.has_key?(helper)
272
+ tmp = XML::Smart::open(@helper_files[helper])
273
+ opts = tmp.find(refpath).to_a.map{|a| a.to_s}.uniq
274
+ else
275
+ opts = @file.find(@path + @id + set + "/" + refpath)
276
+ end
277
+ if opts.empty? # when no values found, use alt values
278
+ cchoice.first.find("c:alt").each do |ele|
279
+ option_ ele.to_s, (ele.to_s == value ? {:selected => 'selected'} : {})
280
+ end
281
+ else # when values found, use them
282
+ opts.each do |ele|
283
+ option_ ele.to_s, (ele.to_s == value ? {:selected => 'selected'} : {})
284
+ end
285
+ end
286
+ end
287
+ end
288
+
289
+ unless data.nil?
290
+ para = data.find("r:param")
291
+ case data.attributes["type"]
292
+ when "string"
293
+ cchoice = data.find("c:choice")
294
+ if cchoice.empty? # when no cewebs:choice
295
+ if !data.find("c:link").empty? # when cewebs:link
296
+ # the administration of the engine shows the links
297
+ input_(:type => "text", :class => "size-xxl", :name => 'CEWebS_value', :value => h(value), :placeholder => 'CEWebS://')
298
+ else
299
+ if para.empty? # when no parameters
300
+ textarea_(value, :name => 'CEWebS_value', :class => 'size-max', :cols => '30', :rows => '3', :style => 'overflow:hidden', :onfocus => 'resize_textarea(this)', :onkeyup => 'resize_textarea(this)')
301
+ else # when parameters
302
+ if !data.find("r:param[@name='pattern']").empty? # when pattern
303
+ checkform = "val_string_regex('#{path_to_id(set)}',new RegExp(/^#{data.find("string(r:param[@name='pattern'])")}$/),'#{@strings.sfind('nomatch')}')"
304
+ end
305
+ if data.find("r:param[@name='maxLength']").empty? # when no maxlenght
306
+ input_(:type => "text", :class => "size-xxl", :name => 'CEWebS_value', :value => h(value))
307
+ else # when maxlength
308
+ input_(:maxlength => "#{data.find("string(r:param[@name='maxLength'])")}", :type => "text", :class => "size-xxl", :name => 'CEWebS_value', :value => h(value))
309
+ end
310
+ end
311
+ end
312
+ else # when cewebs:choice
313
+ refchoice.call(cchoice)
314
+ end
315
+ when "integer", "short", "positiveInteger"
316
+ cchoice = data.find("c:choice")
317
+ if cchoice.empty? # when no cewebs:choice
318
+ if para.empty? # when no parameters
319
+ checkform = "val_integer('#{path_to_id(set)}',0,0,'#{@strings.sfind('noint')}')"
320
+ else # when parameters
321
+ min = data.find("string(r:param[@name='minInclusive'])")
322
+ if min == ""
323
+ min = data.find("string(r:param[@name='minExclusive'])")
324
+ min = (min=="" ? 0 : min.to_i+1)
325
+ else
326
+ min = (min=="" ? 0 : min.to_i)
327
+ end
328
+ max = data.find("string(r:param[@name='maxInclusive'])")
329
+ if max == ""
330
+ max = data.find("string(r:param[@name='maxExclusive'])")
331
+ max = (max=="" ? 0 : max.to_i-1)
332
+ else
333
+ max = (max=="" ? 0 : max.to_i)
334
+ end
335
+ min,max = max,min if min > max
336
+ checkform = "val_integer('#{path_to_id(set)}',#{min},#{max},'#{@strings.sfind('noint')}')"
337
+ end
338
+ input_(:type => "text", :name => 'CEWebS_value', :value => value)
339
+ else # when cewebs:choice
340
+ refchoice.call(cchoice)
341
+ end
342
+ when "float"
343
+ if para.empty? # when no parameters
344
+ checkform = "val_float('#{path_to_id(set)}',0,0,'#{@strings.sfind('nofloat')}')"
345
+ else # when parameters
346
+ # FIXME
347
+ end
348
+ input_(:type => "text", :name => 'CEWebS_value', :value => value)
349
+ when "boolean"
350
+ select_(:name => 'CEWebS_value') do
351
+ option_ "true", ("true" == value ? {:selected => "selected"} : {})
352
+ option_ "false", ("false" == value ? {:selected => "selected"} : {})
353
+ end
354
+ when "date"
355
+ date_('CEWebS_value', :value => value)
356
+ formatform = "format_dateTime('#{path_to_id(set)}','#{@strings.sfind('dateformat')}')"
357
+ when "time"
358
+ dt = Time.parse(value) rescue Time.now
359
+ time_('CEWebS_time', :hour => dt.strftime('%H'), :minute => dt.strftime('%M'))
360
+ input_(:type => 'hidden', :value => '', :name => 'CEWebS_value')
361
+ checkform = "collect_time('#{path_to_id(set)}')"
362
+ formatform = "format_time('#{path_to_id(set)}','#{@strings.sfind('timeformat')}')"
363
+ when "dateTime"
364
+ dt = Time.xmlschema(value) rescue Time.now
365
+ date_('CEWebS_date', :value => dt.strftime('%Y-%m-%d'))
366
+ time_('CEWebS_time', :hour => dt.strftime('%H'), :minute => dt.strftime('%M'))
367
+ input_(:type => 'hidden', :value => '', :name => 'CEWebS_value')
368
+ checkform = "collect_dateTime('#{path_to_id(set)}')"
369
+ formatform = "format_dateTime('#{path_to_id(set)}','#{@strings.sfind('datetimeformat')}')"
370
+ else
371
+ ""
372
+ end
373
+ end
374
+ data = sp.find("r:choice/r:value")
375
+ unless data.empty?
376
+ select_(:name => 'CEWebS_value') do
377
+ data.each do |ele|
378
+ option_ ele.to_s, (ele.to_s == value ? {:selected => "selected"} : {})
379
+ end
380
+ end
381
+ end
382
+ [checkform,formatform]
383
+ #}}}
384
+ end
385
+
386
+ def script
387
+ #{{{
388
+ javascript_ <<-end
389
+ var editPost = "#{@urls[:edit_value]}".replace(/&amp;/gi,'&');
390
+ var deletePost = "#{@urls[:delete_value]}".replace(/&amp;/gi,'&');
391
+ var newPost = "#{@urls[:new_value]}".replace(/&amp;/gi,'&');
392
+ var sortPost = "#{@urls[:sort_values]}".replace(/&amp;/gi,'&');
393
+ var childUrls = [];
394
+ childUrls['add_child'] = "#{@urls[:add_child]}".replace(/&amp;/gi,'&');
395
+ childUrls['more_list'] = "#{@urls[:more_list]}".replace(/&amp;/gi,'&');
396
+ childUrls['edit_child'] = "#{@urls[:edit_child]}".replace(/&amp;/gi,'&');
397
+ childUrls['delete_child'] = "#{@urls[:delete_child]}".replace(/&amp;/gi,'&');
398
+ var rPath = encodeURIComponent(Base64.encode("#{to_javascript(@rpath)}"));
399
+ var xmlPath = encodeURIComponent(Base64.encode("#{to_javascript(@path)}"));
400
+ var xmlId = encodeURIComponent(Base64.encode("#{to_javascript(@id)}"));
401
+ var active = false;
402
+
403
+ function byId(id) { return document.getElementById(id); }
404
+ function toMarkup(text) {
405
+ var div = document.createElement('div');
406
+ div.textContent = text;
407
+ return div.innerHTML.replace(/\\n/g,"<br/>");
408
+ }
409
+ function toggleElement(id) { byId(id).hidden = !byId(id).hidden; }
410
+
411
+ // parameters are already encoded
412
+ function sendParameters(url,parameters) {
413
+ return fetch(url,{ method: 'post', body: new URLSearchParams(parameters) }).then(function(response) {
414
+ return response.text().then(function(text) {
415
+ if (!response.ok) throw new Error(text);
416
+ return text;
417
+ });
418
+ }).catch(function(e) {
419
+ active = false;
420
+ alert(e.message);
421
+ throw e;
422
+ });
423
+ }
424
+
425
+ function setOrder(id) {
426
+ byId(id + "_button").disabled = true;
427
+ byId(id + "_button").blur();
428
+
429
+ var order = Array.from(byId(id).querySelectorAll('tr.sort')).map(function(row) {
430
+ return encodeURIComponent(Base64.encode(byId(row.id + '_data').textContent));
431
+ });
432
+ sendParameters(sortPost,'CEWebS_path=' + xmlPath + '&CEWebS_id=' + xmlId + '&CEWebS_set=' + encodeURIComponent(order.join(';')));
433
+ }
434
+
435
+ function setPath(set,save,operation) {
436
+ if (active==true && !save)
437
+ return false;
438
+ active = true;
439
+ var element_value = "";
440
+
441
+ set = Base64.encode(set);
442
+ var set_id = set.replace(/\\n|=/g,'');
443
+ set = encodeURIComponent(set);
444
+ if (save) {
445
+ if (operation == "new" || operation == "edit") {
446
+ var form = document.forms["CEWebS_" + set_id];
447
+ element_value = "&" + new URLSearchParams(new FormData(form));
448
+ byId(set_id).innerHTML = toMarkup(form.elements["CEWebS_value"].value);
449
+ if (operation == "new") {
450
+ byId("icon_" + set_id + "_new").className = 'invisible';
451
+ byId("icon_" + set_id + "_edit").className = 'visible';
452
+ }
453
+ } else {
454
+ byId(set_id).innerHTML = "";
455
+ byId("icon_" + set_id + "_new").className = 'visible';
456
+ byId("icon_" + set_id + "_edit").className = 'invisible';
457
+ }
458
+ }
459
+ var op = "";
460
+ if (operation == "edit")
461
+ op = editPost;
462
+ else if (operation == "new")
463
+ op = newPost;
464
+ else if (operation == "delete")
465
+ op = deletePost;
466
+ if (op != "") {
467
+ sendParameters(op,'CEWebS_path=' + xmlPath + '&CEWebS_id=' + xmlId + '&CEWebS_set=' + set + element_value).then(function(text) {
468
+ if (save) {
469
+ if (operation != "delete")
470
+ xmlId = encodeURIComponent(Base64.encode(text));
471
+ active = false;
472
+ } else {
473
+ byId(set_id).innerHTML = text;
474
+ document.forms["CEWebS_" + set_id].elements[0].focus();
475
+ }
476
+ });
477
+ }
478
+ }
479
+
480
+ function change_location(base,path,upath) {
481
+ tid = Base64.decode(decodeURIComponent(xmlId));
482
+ tpath = Base64.decode(decodeURIComponent(xmlPath));
483
+ url = "";
484
+ if (base == "add_child" || base == "more_list")
485
+ url = childUrls[base] + "&CEWebS_id=&CEWebS_path=" + encodeURIComponent(Base64.encode(tpath + tid + path)) + "&CEWebS_rpath=" + rPath + "&CEWebS_rid=" + xmlId;
486
+ else if (base == "edit_child")
487
+ url = childUrls[base] + "&CEWebS_id=" + encodeURIComponent(Base64.encode(upath)) + "&CEWebS_path=" + encodeURIComponent(Base64.encode(tpath + tid + path));
488
+ else if (base == "delete_child")
489
+ url = childUrls[base] + "&CEWebS_id=" + xmlId + "&CEWebS_path=" + xmlPath + "&CEWebS_del=" + encodeURIComponent(Base64.encode(tpath + tid + path + upath));
490
+ else if (base == "add_optional_child")
491
+ url = childUrls['add_child'] + "&CEWebS_optional=&CEWebS_id=" + xmlId + "&CEWebS_path=" + encodeURIComponent(Base64.encode(tpath + tid + path))
492
+ if (base == "more_list" || base == "edit_child") {
493
+ location.href = url;
494
+ } else {
495
+ // changes need a form
496
+ var form = document.createElement('form');
497
+ form.method = 'post';
498
+ form.action = url;
499
+ form.submit();
500
+ }
501
+ }
502
+
503
+ function val_string_regex(id,regex,error) {
504
+ if (!document.forms["CEWebS_" + id].elements["CEWebS_value"].value.match(regex)) {
505
+ alert(error);
506
+ return false;
507
+ }
508
+ return true;
509
+ }
510
+ function val_float(id,min,max,error) {
511
+ var num = document.forms["CEWebS_" + id].elements["CEWebS_value"].value;
512
+ if (num == "") return true;
513
+ if (!num.match(/^(\\+|-)?\\d+\\.\\d+$/)) { alert(error); return false; }
514
+ num = parseFloat(num);
515
+ if (min != max && (num<min || num>max)) { alert(error); return false; }
516
+ return true;
517
+ }
518
+ function val_integer(id,min,max,error) {
519
+ var num = document.forms["CEWebS_" + id].elements["CEWebS_value"].value;
520
+ if (num == "") return true;
521
+ if (!num.match(/^(\\+|-)?\\d+$/)) { alert(error); return false; }
522
+ num = parseInt(num);
523
+ if (min != max && (num<min || num>max)) { alert(error); return false; }
524
+ return true;
525
+ }
526
+ function collect_time(id) {
527
+ var thour = document.forms["CEWebS_" + id].elements["CEWebS_time_hour"].value;
528
+ var tminute = document.forms["CEWebS_" + id].elements["CEWebS_time_minute"].value;
529
+ document.forms["CEWebS_" + id].elements["CEWebS_value"].value = thour + ":" + tminute + ":00";
530
+ return true;
531
+ }
532
+ function collect_dateTime(id) {
533
+ var tdate = document.forms["CEWebS_" + id].elements["CEWebS_date"].value;
534
+ var thour = document.forms["CEWebS_" + id].elements["CEWebS_time_hour"].value;
535
+ var tminute = document.forms["CEWebS_" + id].elements["CEWebS_time_minute"].value;
536
+ document.forms["CEWebS_" + id].elements["CEWebS_value"].value = tdate + "T" + thour + ":" + tminute + ":00";
537
+ return true;
538
+ }
539
+ function format_time(id,format) {
540
+ var tdate = new Date();
541
+ var rex = /(\\d\\d):(\\d\\d)/;
542
+ var erg = rex.exec(byId(id).innerHTML);
543
+ tdate.setHours(parseInt(erg[1]));
544
+ tdate.setMinutes(parseInt(erg[2]));
545
+ tdate.setSeconds(0);
546
+ byId(id).innerHTML = tdate.strftime(format);
547
+ }
548
+ function format_dateTime(id,format) {
549
+ var tdate = new Date();
550
+ var rex = /(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(T(\\d\\d):(\\d\\d))?/;
551
+ var erg = rex.exec(byId(id).innerHTML);
552
+ tdate.setYear(parseInt(erg[1]));
553
+ tdate.setMonth(parseInt(erg[2])-1);
554
+ tdate.setDate(parseInt(erg[3]));
555
+ if (erg[4]) {
556
+ tdate.setHours(parseInt(erg[5]));
557
+ tdate.setMinutes(parseInt(erg[6]));
558
+ tdate.setSeconds(0);
559
+ }
560
+ byId(id).innerHTML = tdate.strftime(format);
561
+ }
562
+
563
+ function resize_textarea(txtBox) {
564
+ txtBox.style.height = "auto";
565
+ txtBox.style.height = Math.max(42,txtBox.scrollHeight) + "px";
566
+ }
567
+ end
568
+ #}}}
569
+ end
570
+
571
+ def path_pos
572
+ #{{{
573
+ tp = File.dirname(@path)
574
+ ppos = @schema_pos.first.parent
575
+ path = @schema_path
576
+ if kind(ppos) == 'choice' && ['zeroOrMore','oneOrMore'].include?(kind(ppos.parent))
577
+ path = File.dirname(File.dirname(path))
578
+ end
579
+ if ['zeroOrMore','oneOrMore','optional'].include?(kind(ppos))
580
+ path = File.dirname(path)
581
+ end
582
+ path = build_path_pos(path)
583
+ res = []
584
+ @schema.find(path).each do |e|
585
+ res << tp + "/" + e.attributes['name']
586
+ end
587
+ (res << @path).join('|')
588
+ #}}}
589
+ end
590
+
591
+ private
592
+ def build_path_pos(path)
593
+ #{{{
594
+ t = +''
595
+ # all elements before current node
596
+ t << "#{path}/preceding-sibling::r:element"
597
+ # or all elements under zeroOrMore, oneOrMore, optional
598
+ t << "|#{path}/preceding-sibling::r:*[name()='zeroOrMore' or name()='oneOrMore' or name()='optional']/r:element"
599
+ # or all elements in choices inside zeroOrMore, oneOrMore
600
+ t << "|#{path}/preceding-sibling::r:*[name()='zeroOrMore' or name()='oneOrMore']/r:choice/r:element"
601
+ #}}}
602
+ end
603
+
604
+ def print_header(level,ui)
605
+ #{{{
606
+ if level == 0
607
+ unless ui.nil?
608
+ heading = ui.sfind("c:heading")
609
+ text = ui.sffind("c:text")
610
+ h1_(heading) unless heading == ""
611
+ div_(:class => 'margin-bottom-huge') { text } unless text == ""
612
+ end
613
+ else
614
+ unless ui.nil?
615
+ heading = ui.sfind("c:heading")
616
+ text = ui.sffind("c:text")
617
+ unless heading == ""
618
+ div_(:class => "big background-baseA margin-bottom-big") do
619
+ strong_ heading
620
+ end
621
+ end
622
+ div_(:class => 'margin-bottom-huge') { text } unless text == ""
623
+ end
624
+ end
625
+ #}}}
626
+ end
627
+
628
+ def print_list(sp,ui,path,cutmax=true,filter="")
629
+ #{{{
630
+ choice = kind(sp) == 'choice'
631
+ columns = {:path => [],:format => [],:unique => [], :unique_path => [], :datatype => [], :content => [], :cut => [], :sort => []}
632
+ max = maxc = 0
633
+ sortable = ui.find("boolean(c:list/@sortable)")
634
+ cutmax = false if ui.find("boolean(c:list/@nonew)")
635
+
636
+ table_ :class => 'nowrap' do
637
+ thead_ do
638
+ tr_ do
639
+ if sortable
640
+ td_ :class => 'invisible'
641
+ td_ :class => 'margin-right-big'
642
+ end
643
+ td_ :class => 'margin-right-big'
644
+ td_ :class => 'margin-right-big'
645
+ max = ui.find("number(c:list/@max)")
646
+ max = max.nan? ? 0 : max.to_i
647
+ if choice
648
+ th_ @strings.sfind('element'), :class => 'margin-left-big margin-right-big'
649
+ end
650
+ ui.find("c:list/c:column").each do |listitem|
651
+ th_ listitem.attributes['hidden'] == 'true' ? '' : listitem.attributes['label'].to_s, :class => 'margin-left-big margin-right-big'
652
+ col = listitem.attributes['search'] ? listitem.attributes['search'].to_s : listitem.text
653
+ pcol = path_to_schema_path(@path + @id + path + '/' + col)
654
+ scol = @schema.find(pcol).first
655
+ unless scol.nil?
656
+ columns[:content] << listitem.text
657
+ columns[:cut] << listitem.attributes['cut']
658
+ columns[:sort] << (listitem.attributes['sort'] == 'true' ? true : false)
659
+ columns[:datatype] << scol.find("string(r:data/@type)")
660
+ columns[:format] << case columns[:datatype].last
661
+ when "integer", "float" then " align-right"
662
+ else
663
+ ""
664
+ end
665
+ columns[:path] << col
666
+ if listitem.attributes['ignoreunique'] != "true" && scol.find("c:ui/c:unique").any?
667
+ columns[:unique_path] << col
668
+ columns[:unique] << @file.find(@path + @id + path + (filter == "" ? "" : "[#{filter}]") + "/" + columns[:path].last)
669
+ end
670
+ end
671
+ end
672
+ end
673
+ end
674
+
675
+ tbody_ :id => (sortable ? "sortable_#{@sortables += 1}" : nil) do
676
+ if cutmax
677
+ tr_ do
678
+ if sortable
679
+ td_ :class => 'invisible'
680
+ td_ :class => 'margin-right-big' do
681
+ span_ :class => 'hidden' do
682
+ small_img_ 'weather-clear'
683
+ end
684
+ end
685
+ end
686
+ if choice
687
+ aid = path_to_id(path)
688
+ td_ :class => 'margin-right-big' do
689
+ div_ do
690
+ print_working_new :onclick => "toggleElement('element_#{aid}')", :class => 'click'
691
+ end
692
+ end
693
+ td_ :class => 'margin-right-big' do
694
+ span_ :class => 'hidden' do
695
+ small_img_ 'weather-clear'
696
+ end
697
+ end
698
+ td_ :colspan => '5', :class => 'margin-left-big margin-right-big' do
699
+ a_ @strings.sfind("newentry"), :onclick => "toggleElement('element_#{aid}')", :class => 'click link'
700
+ div_ :id => "element_#{aid}", :hidden => 'hidden' do
701
+ sp.find("r:element").each do |e|
702
+ sui = e.lfind('c:ui',@language)
703
+ div_ do
704
+ a_ @strings.sfind("newentry") + ' "' + sui.sfind('c:row') + '"', :onclick => "change_location('add_child',\"#{path.sub(/\*\[([^\[]+\[[^\]]+\])*.*?\]$/,e.attributes['name'].to_s)}\",'')", :class => 'click link'
705
+ end
706
+ end
707
+ end
708
+ end
709
+ else
710
+ td_ :class => 'margin-right-big' do
711
+ print_working_new :onclick => "change_location('add_child',\"#{exp_to_javascript(path)}\",'')", :class => 'click'
712
+ end
713
+ td_ :class => 'margin-right-big' do
714
+ span_ :class => 'hidden' do
715
+ small_img_ 'weather-clear'
716
+ end
717
+ end
718
+ td_ :colspan => '5', :class => 'margin-left-big margin-right-big' do
719
+ a_ @strings.sfind("newentry"), :onclick => "change_location('add_child',\"#{exp_to_javascript(path)}\",'')", :class => 'click link'
720
+ end
721
+ end
722
+ end
723
+ else
724
+ max = 0
725
+ end
726
+
727
+ retfield = []
728
+ 0.upto((columns[:unique][0] || []).length-1) do |i|
729
+ retdata = []
730
+
731
+ upath = []
732
+ columns[:unique_path].each_with_index do |up,j|
733
+ upath << "#{up}=#{literal(columns[:unique][j][i])}"
734
+ end
735
+ upath = upath.length > 0 ? "[" + upath.join(" and ") + "]" : ""
736
+ tnode = @file.find(@path + @id + path + upath).first
737
+ next if tnode.nil?
738
+
739
+ columns[:content].each_with_index do |colcontent,j|
740
+ retdata << case columns[:datatype][j]
741
+ when 'integer'; tnode.find("string(#{colcontent})").to_i
742
+ when 'float'; tnode.find("string(#{colcontent})").to_f
743
+ else
744
+ tnode.find("string(#{colcontent})")
745
+ end
746
+ end
747
+ retfield << [tnode,upath,retdata]
748
+ end
749
+
750
+ unless sortable
751
+ retfield = retfield.sort_by do |tn,up,rd|
752
+ ret = []
753
+ rd.each_with_index do |e,i|
754
+ ret << e if columns[:sort][i]
755
+ end
756
+ ret
757
+ end
758
+ retfield.reverse! if max != 0
759
+ end
760
+
761
+ retfield.each_with_index do |rl,i|
762
+ tnode, upath, retdata = rl
763
+ if maxc == max and max != 0
764
+ tr_ do
765
+ td_(:colspan => '2', :class => 'margin-right-big') { '&#160;' }
766
+ td_ :colspan => '5', :class => 'margin-left-big margin-right-big' do
767
+ a_ @strings.sfind("more"), :onclick => "change_location('more_list',\"#{exp_to_javascript(path)}\",'')", :class => 'click link'
768
+ end
769
+ end
770
+ break
771
+ end
772
+ tr_ :id => "sortable_#{@sortables}_#{i}", :class => 'sort' do
773
+ # when a choice eleminate the generic [] and add the specific [] (the id)
774
+
775
+ ### TODO replace with bracket eliminator from admin skeleton, plus replace everthing before | (pipe)
776
+ tpath = choice ? path.sub(/\*\[([^\[]+\[[^\]]+\])*.*?\]$/,kind(tnode)) : path
777
+
778
+ if sortable
779
+ td_ tpath + upath, :id => "sortable_#{@sortables}_#{i}_data", :class => 'invisible'
780
+ td_ :class => 'margin-right-big' do
781
+ small_img_ 'mail-send-receive', :class => 'handle', :alt => @strings.sfind('order')
782
+ end
783
+ end
784
+ td_ :class => 'margin-right-big' do
785
+ print_working_edit :onclick => "change_location('edit_child',\"#{exp_to_javascript(tpath)}\",\"#{exp_to_javascript(upath)}\")", :class => 'click'
786
+ end
787
+ td_ :class => 'margin-right-big' do
788
+ print_working_delete :onclick => "if (confirm('#{@strings.sfind('suredelete')}')) { change_location('delete_child',\"#{exp_to_javascript(tpath)}\",\"#{exp_to_javascript(upath)}\") }", :class => 'click'
789
+ end
790
+
791
+ # add the row type for choices
792
+ if choice
793
+ spath = path_to_schema_path(tnode.path)
794
+ sui = @schema.lfind("#{spath}/c:ui",@language)
795
+ td_ :class => "margin-left-big margin-right-big" do
796
+ text_ h(sui.sfind("c:row"))
797
+ end
798
+ end
799
+ retdata.each_with_index do |colcontent,j|
800
+ td_ :class => "margin-left-big margin-right-big#{columns[:format][j]}" do
801
+ print_content(columns[:datatype][j],colcontent,columns[:cut][j])
802
+ end
803
+ end
804
+ end
805
+ maxc += 1
806
+ end
807
+ end
808
+ end
809
+ if sortable
810
+ div_ :class => 'margin-top-huge' do
811
+ button_ @strings.sfind('order_save'), :id => "sortable_#{@sortables}_button", :disabled => 'disabled', :onclick => "setOrder('sortable_#{@sortables}')"
812
+ end
813
+ end
814
+ if sortable
815
+ javascript_ <<-end
816
+ jQuery("#sortable_#{@sortables}").sortable({
817
+ axis: 'y',
818
+ items: '.sort',
819
+ handle: '.handle',
820
+ update: function() { byId("sortable_#{@sortables}_button").disabled = false; }
821
+ });
822
+ end
823
+ end
824
+ #}}}
825
+ end
826
+
827
+ def print_optional(path,empty)
828
+ #{{{
829
+ table_ :class => 'margin-bottom-big' do
830
+ tr_ do
831
+ th_ :class => 'nowrap align-right margin-left-big margin-right-big background-baseB' do
832
+ strong_ @strings.sfind("optional")
833
+ end
834
+ td_ :class => 'margin-left-big margin-right-big size-max background-baseB' do
835
+ span_(:id => "icon_#{path_to_id(path)}_new", :class => (empty ? 'visible' : 'invisible')) do
836
+ print_working_new :onclick => "change_location('add_optional_child',\"#{exp_to_javascript(path)}\",'')", :class => 'click'
837
+ end
838
+ span_(:id => "icon_#{path_to_id(path)}_edit", :class => (empty ? 'invisible' : 'visible')) do
839
+ print_working_delete :onclick => "if (confirm('#{@strings.sfind('suredelete')}')) { change_location('delete_child',\"#{exp_to_javascript(path)}\",'') }", :class => 'click'
840
+ end
841
+ end
842
+ end
843
+ end
844
+ #}}}
845
+ end
846
+
847
+ def print_element(sp,level,ui,path)
848
+ #{{{
849
+ path = (level == 0 ? '/.' : "#{path}/#{sp.attributes["name"]}")
850
+
851
+ print_header(level,ui)
852
+ attrs = sp.find("r:attribute")
853
+ attro = sp.find("r:optional/r:attribute")
854
+ if attrs.length > 0
855
+ table_(:class => 'margin-bottom-big border') do
856
+ attrs.each do |attr|
857
+ print_attribute(attr,path,false)
858
+ end
859
+ attro.each do |attr|
860
+ print_attribute(attr,path,true)
861
+ end
862
+ end
863
+ end
864
+
865
+ if sp.find("r:data").empty? && sp.find("r:choice/r:value").empty?
866
+ ""
867
+ else
868
+ table_ do
869
+ tr_ do
870
+ td_ :class => 'nowrap align-right margin-left-big margin-right-big' do
871
+ strong_ ui.sfind("c:label")
872
+ end
873
+ print_icons(ui,path,false)
874
+ td_ :class => 'margin-left-big margin-right-big size-max', :id => path_to_id(path) do
875
+ print_content sp.find("string(r:data/@type)"), @file.find("string(#{@path + @id + path})")
876
+ end
877
+ end
878
+ end
879
+ end
880
+
881
+ sub = sp.find("r:element|r:optional[count(r:element)=1]|r:zeroOrMore|r:oneOrMore")
882
+ to_ui(sub,level+1,level == 0 ? '' : path) unless sub.empty?
883
+ #}}}
884
+ end
885
+
886
+ def print_attribute(sp,path,optional)
887
+ #{{{
888
+ path += "/@" + sp.attributes["name"]
889
+ ui = sp.lfind("c:ui",@language)
890
+ return unless ui.find("c:hidden").empty?
891
+ tr_ do
892
+ th_ :class => 'nowrap align-right margin-left-big margin-right-big' do
893
+ strong_ ui.sfind("c:label")
894
+ end
895
+ print_icons(ui,path,optional)
896
+ td_ :class => 'margin-left-big margin-right-big size-max', :id => path_to_id(path) do
897
+ print_content sp.find("string(r:data/@type)"), @file.find("string(#{@path + @id + path})")
898
+ end
899
+ end
900
+ #}}}
901
+ end
902
+
903
+ def print_icons(ui,path,optional)
904
+ #{{{
905
+ td_ :class => 'nowrap' do
906
+ if ui.find("c:readonly").empty?
907
+ if optional
908
+ empty = @file.find(@path + @id + path).empty?
909
+ span_(:id => "icon_#{path_to_id(path)}_new", :class => (empty ? 'visible' : 'invisible')) do
910
+ print_working_new :onclick => "setPath('#{path}',false,'new');", :class => 'click'
911
+ end
912
+ span_(:id => "icon_#{path_to_id(path)}_edit", :class => (empty ? 'invisible' : 'visible')) do
913
+ print_working_edit :onclick => "setPath('#{path}',false,'edit');", :class => 'click margin-right-small'
914
+ print_working_delete :onclick => "if (confirm('#{@strings.sfind('suredelete')}')) { setPath('#{path}',true,'delete'); }", :class => 'click'
915
+ end
916
+ else
917
+ print_working_edit :onclick => "setPath('#{path}',false,'edit');", :class => 'click'
918
+ end
919
+ else
920
+ print_readonly
921
+ end
922
+ end
923
+ #}}}
924
+ end
925
+
926
+ def print_content(type,cont,cut=nil)
927
+ #{{{
928
+ cont = cont.to_s
929
+ short = cut.nil? || cont.length < cut.to_i ? h(cont).gsub(/\n/,"<br/>") : h(cont[0,cut.to_i]) + (cut.to_i == 0 ? "" : "...")
930
+ format = { 'dateTime' => 'datetimeformat', 'time' => 'timeformat', 'date' => 'dateformat' }[type]
931
+ if format && cont != ''
932
+ text_ Time.parse(cont).strftime(@strings.sfind(format))
933
+ elsif type == 'anyURI'
934
+ a_(:href => h(cont)) { short }
935
+ else
936
+ text_ short
937
+ end
938
+ #}}}
939
+ end
940
+
941
+ def print_readonly
942
+ #{{{
943
+ small_img_ "emblem-readonly", :alt => @strings.sfind('readonly')
944
+ #}}}
945
+ end
946
+ def print_working_new (a) print_working_general(a,"document-new", @strings.sfind('new') ) end
947
+ def print_working_edit (a) print_working_general(a,"edit-find-replace",@strings.sfind('edit') ) end
948
+ def print_working_delete(a) print_working_general(a,"edit-delete", @strings.sfind('delete')) end
949
+ def print_working_general(a,img,string)
950
+ #{{{
951
+ a_ a do
952
+ small_img_ img, :alt => string
953
+ end
954
+ #}}}
955
+ end
956
+
957
+ def path_to_schema_path(path)
958
+ #{{{
959
+
960
+ # all names
961
+ # if names present, it must be a choice -> always connect names with or
962
+ r = /name\(\)\s*=\s*(['][^']+[']|["][^"]+["])?/
963
+ # cut out all irrelevant (nested) []
964
+ tpath = path.gsub(CEWebS::Configuration::PREDICATE) do |m|
965
+ t = m.scan(r).flatten.map{|e| "@name=#{e}"}.join(' or ')
966
+ t == '' ? t : "[#{t}]"
967
+ end
968
+ tpath = tpath.split("\/").collect do |i|
969
+ case i
970
+ when "."
971
+ nil
972
+ when ""
973
+ ""
974
+ when /^@/
975
+ "r:attribute[@name='#{i[1..-1]}']"
976
+ when /^\*$/
977
+ "r:element"
978
+ when /^\*(\[[^\]]+\])$/
979
+ "r:element#{$1}"
980
+ else
981
+ "r:element[@name='#{i}']"
982
+ end
983
+ end.compact.join('//')
984
+
985
+ if tpath == ""
986
+ "."
987
+ else
988
+ npath = []
989
+ @schema.find(tpath).each do |n|
990
+ tp = ""
991
+ while n.is_a?(XML::Smart::Dom::Element)
992
+ tp = '/' + (%w{element attribute}.include?(kind(n)) ? "r:#{kind(n)}[@name='#{n.attributes['name']}']" : "r:#{kind(n)}") + tp
993
+ n = n.parent
994
+ end
995
+ npath << tp
996
+ end
997
+ npath = npath.min{|a,b| a.length <=> b.length}
998
+ npath.nil? ? "." : npath
999
+ end
1000
+ #}}}
1001
+ end
1002
+
1003
+ def literal(value) CEWebS::Configuration::literal(value.to_s) end
1004
+
1005
+ # element name, nil for the document
1006
+ def kind(node)
1007
+ node.is_a?(XML::Smart::Dom::Element) ? node.qname.name : nil
1008
+ end
1009
+
1010
+ def path_to_id(path)
1011
+ [path].pack('m').gsub(/\n|=/,'')
1012
+ end
1013
+ def path_to_send(path)
1014
+ RelaxNGUI::path_to_send(path)
1015
+ end
1016
+ # for script elements
1017
+ def to_javascript(exp)
1018
+ exp.gsub(/["\\]/) { |m| "\\#{m}" }.gsub('</','<\/')
1019
+ end
1020
+ # for onclick="..."
1021
+ def exp_to_javascript(exp)
1022
+ to_javascript(exp).gsub('&','&amp;').gsub('<','&lt;')
1023
+ end
1024
+ end
1025
+
1026
+ class RelaxNGUI
1027
+ def self::new(file,schema,helper_files,strings,id,urls,path="/",language=["en"])
1028
+ ts = XML::Smart.open(schema)
1029
+ ts.register_namespace 'r', 'http://relaxng.org/ns/structure/1.0'
1030
+ ts.register_namespace 'c', 'http://www.cewebs.org'
1031
+ case ts.find('string(/r:element/@c:uiversion)')
1032
+ when '1.2'
1033
+ RelaxNGUI_1_2.new(file,ts,helper_files,strings,id,urls,path,language)
1034
+ else
1035
+ raise CEWebS::Error.new('RelaxNGUI version not suitable (uiversion not present, or wrong)!',500)
1036
+ end
1037
+ end
1038
+
1039
+ def self::path_to_send(path)
1040
+ [path].pack('m0').gsub(/=/,'%3D').gsub(/\+/,'%2B')
1041
+ end
1042
+ end