-
Notifications
You must be signed in to change notification settings - Fork 16
/
node.rb
1881 lines (1600 loc) · 61.1 KB
/
node.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
=begin rdoc
A Node is the root class of all elements in the zena application. Class inheritance diagram:
FIXME: some parts are not correct (Partial, Task, Request, Milestone). Either correct this tree or add these classes.
Node (manages access and publication cycle)
|
+-- Page (web pages)
| |
| +--- Project (has it's own project_id. Can contain notes, collaborators, etc)
| |
| +--- Section (has it's own section_id = group of pages)
| |
| +--- Skin (theme: contains css, templates, etc)
|
+--- Document
| |
| +--- Image
| |
| +--- TextDocument (for css, scripts)
| |
| +--- Partial (uses the zafu templating language)
| |
| +--- Template (entry for rendering)
|
+-- Note (date related information, event)
|
+--- Post (blog entry)
=== Properties
The Version class stores the node's properties (attributes). You need to declare the attributes either in the virtual class or as a Role attached to an existing class in order to use them.
=== Attributes
Each node uses the following basic attributes:
Base attributes:
zip:: unique id (incremented in each site's scope).
_id:: cached title (used to identify nodes in DB: not used in Zena)
site_id:: site to which this node belongs to.
parent_id:: parent node (every node except root is inserted in a unique place through this attribute).
user_id:: creator of the node.
ref_lang:: original node language.
created_at:: creation date.
updated_at:: modification date.
log_at:: announcement date.
event_at:: event date.
custom_base:: boolean value. When set to true, the node's url becomes it's fullpath. All it descendants will use this node's fullpath as their base url. See below for an example.
inherit:: inheritance mode (0=custom, 1=inherit, -1=private).
Attributes inherited from the parent:
section_id:: reference project (cannot be overwritten even if inheritance mode is custom).
rgroup_id:: id of the readers group.
wgroup_id:: id of the writers group.
dgroup_id:: id of the publishers group.
skin_id:: Skin to use when rendering the page ('theme').
Attributes used internally:
publish_from:: earliest publication date from all published versions.
kpath:: inheritance hierarchy. For example an Image has 'NPDI' (Node, Page, Document, Image), a Letter would have 'NNTL' (Node, Note, Task. Letter). This is used to optimize sql queries.
fullpath:: cached full path made of ancestors' zip (<gdparent zip>/<parent zip>/<self zip>).
basepath:: cached base path (the base path is used to build the url depending on the 'custom_base' flag).
=== Node url
A node's url is made of it's class and +zip+. For the examples below, this is our site tree:
root
|
+--- projects (Page)
|
+--- worldTour (Project)
| |
| +--- photos (Page)
|
+--- music (Project)
The worldTour project's url would look like:
/en/project21.html
The 'photos' url would be:
/en/page23.html
When custom base is set (only for descendants of Page), worldTour url becomes its fullpath:
/en/projects/worldTour
and the 'photos' url is now in the worldTour project's basepath:
/en/projects/worldTour/page23.html
Setting 'custom_base' on a node should be done with caution as the node's zip is on longer in the url and when you move the node around, there is no way to find the new location from the old url. Custom_base should therefore only be used for nodes that are not going to move.
=end
class Node < ActiveRecord::Base
# Only store partial class name in 'type' field (Page instead of ::Page)
self.store_full_sti_class = false
extend Zena::Use::Upload::UploadedFile
extend Zena::Use::Search::NodeClassMethods
include Property
# This must come before the first call to make_schema.
include Zena::Use::Kpath::InstanceMethods
def virtual_class
@virtual_class ||= if self[:vclass_id]
VirtualClass.find_by_id(self[:vclass_id])
else
VirtualClass.find_by_name(self.class.name)
end
end
def klass_changed?
kpath_changed?
end
def virtual_class=(vclass)
@virtual_class = vclass
self[:vclass_id] = vclass.id
self[:kpath] = vclass.kpath
end
# We want to use a Role as schema for properties defined in the real_class instead of Property::Schema.
def self.make_schema
::Role.new(:name => name).tap do |role|
role.kpath = self.kpath
# Enable property method definitions.
role.klass = self
# Used for property inheritance.
role.real_class = self
end
end
alias schema virtual_class
# We use the virtual_class as proxy for method type resolution.
# def safe_eval(code)
# eval RubyLess.translate(schema, code)
# end
def safe_method_type(signature, receiver = nil)
schema.safe_method_type(signature, receiver)
end
# Should be the same serialization as in Version and Site
include Property::Serialization::JSON
store_properties_in :version
invalid_property_failover 'title' => 'INVALID PROPERTY', 'ext' => 'txt', 'content/type' => 'text/plain'
property do |p|
# Multilingual string index on 'title'
p.string 'title', :index => :ml_string
p.string 'text'
p.string 'summary'
end
# This is used to enable multilingual indexes
include Zena::Use::MLIndex::ModelMethods
# Must come after Property
include Zena::Use::FieldIndex::ModelMethods
include RubyLess
# This is used to load roles in an instance or on a class during compilation. Module
# inclusion has to come *after* RubyLess because we overwrite safe_method_type.
include Zena::Acts::Enrollable::ModelMethods
#attr_accessible :version_content
has_many :discussions, :dependent => :destroy
has_many :links
has_and_belongs_to_many :cached_pages
belongs_to :site
belongs_to :skin
before_validation :set_defaults
before_validation :node_before_validation
# We need to change class before validation so that prop_eval is triggered with
# the new class.
before_validation :change_klass
validate :validate_node
before_create :node_before_create
after_save :spread_project_and_section
after_create :node_after_create
after_destroy :node_after_destroy
attr_protected :zip, :id, :section_id, :project_id, :publish_from, :created_at, :updated_at
attr_protected :site_id
# Until we find another way to write friend_ids, we need NestedAttributesAlias in Relations
# A possible solution could be to use the other syntax exclusively ('rel' => {'friend' => [4,5,6]})
include Zena::Use::NestedAttributesAlias::ModelMethods
# Dynamic resolution of the author class from the user prototype
def self.author_proc
Proc.new do |h, r, s|
res = {:method => 'author', :nil => true}
if prototype = visitor.prototype
res[:class] = prototype.vclass
else
res[:class] = VirtualClass['Node']
end
res
end
end
safe_property :title, :text, :summary
safe_attribute :created_at, :updated_at, :event_at, :log_at, :publish_from, :basepath, :inherit, :position
safe_attribute :idx_datetime1, :idx_datetime2, :idx_float1, :idx_float2, :idx_string1, :idx_string2, :idx_integer1, :idx_integer2
# safe_node_context defined in Enrollable
safe_node_context :parent => 'Node', :project => 'Project', :section => 'Section',
:real_project => 'Project', :real_section => 'Section'
safe_context :custom_a => Number, :custom_b => Number, #, :score => Number
:comments => ['Comment'],
# Code language for syntax highlighting
:content_lang => String,
:data => {:class => ['DataEntry'], :zafu => {:data_root => 'node_a'}},
:data_a => {:class => ['DataEntry'], :zafu => {:data_root => 'node_a'}},
:data_b => {:class => ['DataEntry'], :zafu => {:data_root => 'node_b'}},
:data_c => {:class => ['DataEntry'], :zafu => {:data_root => 'node_c'}},
:data_d => {:class => ['DataEntry'], :zafu => {:data_root => 'node_d'}},
:traductions => ['Version'], :discussion => 'Discussion',
:login_info => 'User'
# we use safe_method because the columns can be null, but the values are never null
safe_method :kpath => String, :user_zip => Number, :user_id => Number,
:parent_zip => Number, :project_zip => Number, :section_zip => Number,
:ref_lang => String,
:position => Number, :rgroup_id => Number,
:wgroup_id => Number, :dgroup_id => Number, :custom_base => Boolean,
:klass => String,
:m_text => String, :m_title => String, :m_author => String,
:id => {:class => Number, :method => 'zip'},
:skin => 'Skin', :ref_lang => String,
:visitor => 'User', [:is_ancestor?, Node] => Boolean,
:comments_count => Number,
:v => {:class => 'Version', :method => 'version'},
:versions => {:class => ['Version'], :method => 'zafu_versions'},
:version => 'Version', :v_status => Number, :v_lang => String,
:v_publish_from => Time, :v_backup => Boolean,
:zip => Number, :parent_id => {:class => Number, :nil => true, :method => 'parent_zip'},
:user => 'User',
:author => author_proc,
:vclass => {:class => 'VirtualClass', :method => 'virtual_class'},
:new_record? => Boolean,
[:eval, String] => {:class => String, :method => 'zafu_eval'},
[:eval, String, Hash] => {:class => String, :method => 'zafu_eval'}
# This is needed so that we can use secure_scope and secure in search.
extend Zena::Acts::Secure
extend Zena::Acts::SecureNode
acts_as_secure_node
# These *must* be included in this order
include Versions::Multi
has_multiple :versions, :inverse => 'node'
include Zena::Use::Workflow
include Zena::Use::Ancestry::ModelMethods
# to_xml
include Zena::Acts::Serializable::ModelMethods
# compute vhash (must come before Fulltext)
include Zena::Use::VersionHash::ModelMethods
# computed properties (vclass prop_eval, must come after MLIndex)
include Zena::Use::PropEval::ModelMethods
# fulltext indices (must come after PropEval)
include Zena::Use::Fulltext::ModelMethods
# List of version attributes that should be accessed as proxies 'v_lang', 'v_status', etc
VERSION_ATTRIBUTES = %w{status lang publish_from backup}
# The following methods are used in forms and affect the version.
VERSION_ATTRIBUTES.each do |attribute|
eval %Q{
def v_#{attribute}
version.#{attribute}
end
def v_#{attribute}=(value)
version.#{attribute} = value
end
}
end
def v_number
version.number
end
Caster = ::ActiveRecord::ConnectionAdapters::Column
# Return class of cast value.
def self.cast_to_class(type)
case type
when :string then String
when :text then String
when :integer then Number
when :float then Number
when :decimal then Number
when :datetime then Time
when :timestamp then Time
when :time then Time
when :date then Time
when :binary then String
when :boolean then Boolean
else nil
end
end
# Read with cast to an appropriate instance. This is used along with
# custom select in QueryBuilder queries.
def rcast(key, type)
@rcast_cache ||= {}
@rcast_cache[key] ||= begin
value = @attributes[key]
return nil if value.nil?
case type
when :string then value
when :text then value
when :integer then value.to_i rescue value ? 1 : 0
when :float then value.to_f
when :decimal then Caster.value_to_decimal(value)
when :datetime then Caster.string_to_time(value)
when :timestamp then Caster.string_to_time(value)
when :time then Caster.string_to_time(value)
when :date then Caster.string_to_time(value)
when :binary then Caster.binary_to_string(value)
when :boolean then Caster.value_to_boolean(value)
else value
end
end
end
# This is an adaptation of Versions::Multi code to use our special v_ shortcut
# to access version attributes.
def merge_multi_errors(key, object)
if key == 'version'
super('v', object)
else
super
end
end
include Zena::Use::Relations::ModelMethods
# model based indices (must come after Relations)
include Zena::Use::ScopeIndex::ModelMethods
include Zena::Use::QueryNode::ModelMethods
# Used by zafu_eval when parsing dates.
include Zena::Use::Dates::ModelMethods
@@native_node_classes = {'N' => self}
@@native_node_classes_by_name = {'Node' => self}
@@unhandled_children = []
class << self
def new(hash={}, vclass = nil)
node = super()
# set virtual_class (acts as schema) before setting attributes
node.virtual_class = vclass || VirtualClass[self.name]
node.attributes = hash
node
end
# Compatibility with VirtualClass
alias new_instance new
# Compatibility with VirtualClass
alias create_instance create
def inherited(child)
super
unless child.name.blank?
# Do not register anonymous classes created during Zafu compilation
@@unhandled_children << child
end
end
def find_by_parent_title_and_kpath(parent_id, title, kpath = nil, opts = {})
if cond = opts[:conditions]
cond[0] = Array(cond[0])
else
cond = opts[:conditions] = [[]]
end
if kpath
cond[0] << "kpath like ?"
cond << "#{kpath}%"
end
cond[0] << "site_id = ? AND parent_id = ?"
cond << current_site.id << parent_id
find_by_title(title, opts)
end
# Find node by the indexed title.
def find_by_title(title, opts = {})
if cond = opts[:conditions]
cond[0] = Array(cond[0])
else
cond = opts[:conditions] = [[]]
end
if opts.delete(:like)
cond[0] << "id1.value LIKE ?"
else
cond[0] << "id1.value = ?"
end
cond << title
cond[0] = cond[0].join(' AND ')
opts[:joins] = Node.title_join
opts[:select] = 'nodes.*'
Node.find(:first, opts)
end
# Return the list of (kpath,subclasses) for the current class.
def native_classes
load_unhandled_children
@@native_node_classes
end
# Return the list of (name,class) for the current class.
def native_classes_by_name
load_unhandled_children
@@native_node_classes_by_name
end
def load_unhandled_children
# this is to make sure subclasses are loaded before the first call
# TODO: find a better way to make sure they are all loaded
[Note,Page,Project,Section,Document,Image,TextDocument,Skin,Template]
while child = @@unhandled_children.pop
@@native_node_classes[child.kpath] = child
@@native_node_classes_by_name[child.name] = child
end
end
# check inheritance chain through kpath
def kpath_match?(kpath)
self.kpath =~ /^#{kpath}/
end
# Class list to which this class can change to
def change_to_classes_for_form
classes_for_form(:class => 'Node', :without => 'Document')
end
# List of classes that a node can change to.
def allowed_change_to_classes
change_to_classes_for_form.map {|k,v| v}
end
# TODO: remove and use VirtualClass[...].classes_for_form directly
def classes_for_form(opts={})
VirtualClass[self.name].classes_for_form(opts)
end
# FIXME: how to make sure all sub-classes of Node are loaded before this is called ?
# TODO: move into helper
def kpaths_for_form(opts={})
VirtualClass.all_classes(opts).map do |vclass|
# white spaces are insecable spaces (not ' ')
a, b = vclass.kpath, vclass.name
[a[1..-1].gsub(/./,' ') + b, a]
end
end
# Return class or virtual class from name.
# FIXME: remove once everything can use VirtualClass[name]
def get_class(rel, opts={})
# mushroom_types ==> MushroomType
class_name = rel =~ /\A[a-z]/ ? rel.singularize.camelize : rel
vclass = VirtualClass[class_name]
if vclass && opts[:create] && vclass.id
# TODO: how do we deal with real class ? (Currently = pass).
visitor.group_ids.include?(vclass.create_group_id) ? vclass : nil
else
vclass
end
end
# Find a role by name.
def get_role(rel)
# mushroom_types ==> MushroomType
role_name = rel =~ /\A[a-z]/ ? rel.singularize.camelize : rel
Role.first(:conditions => ['name = ? AND site_id = ?', role_name, current_site.id])
end
# Find a node's attribute based on a pseudo (id or path). Used by zazen to create a link for ""::art or "":(people/ant) for example.
def translate_pseudo_id(id, sym = :id, base_node = nil)
if id.to_s =~ /\A(-?)(\d+)\Z/
# zip
# FIXME: this is not secure
res = Zena::Db.fetch_attribute("SELECT #{sym} FROM nodes WHERE site_id = #{current_site[:id]} AND zip = '#{$2}'")
res ? ($1.blank? ? res.to_i : -res.to_i) : nil
elsif node = find_node_by_pseudo(id,base_node)
node[sym]
else
nil
end
end
# Find a node based on a query shortcut. Used by zazen to create a link for ""::art for example.
def find_node_by_pseudo(id, base_node = nil)
raise Zena::AccessViolation if self.scoped_methods == []
str = id.to_s
if str =~ /\A\d+\Z/
# zip
find_by_zip(str)
elsif path = str[/\A\(([^\)]+)\)\Z/,1]
if path[0..0] == '/'
path = path[1..-1].split('/').map {|p| String.from_filename(p) }
find_by_path(path)
elsif base_node
# transform ../../foo and 45/32/61/72 ==> 'foo' and 45/32
path = path.split('/')
root = base_node.fullpath.split('/')
while path[0] == '..'
root.pop
path.shift
end
path = path.map {|p| String.from_filename(p) }
if base_node.zip == root.last.to_i
find_by_path(path, base_node.id)
elsif root.last
if base = find_by_zip(root.last)
find_by_path(path, base.id)
else
nil
end
else
find_by_path(path)
end
else
# do not use (path) pseudo when there is no base_node (during create_or_update_node for example).
# FIXME: path pseudo is needed for links... and it should be done here (egg and hen problem)
nil
end
elsif str =~ /\A:?([^\+]+)(\+*)\Z/
offset = $2.to_s.size
Node.search_records($1.gsub('-',' '), :offset => offset, :limit => 1).first
end
end
# def attr_public?(attribute)
# if attribute.to_s =~ /(.*)_zips?$/
# return true if self.ancestors.include?(Node) && RelationProxy.find_by_role($1.singularize)
# end
# super
# end
def create_or_update_node(new_attributes)
attributes = transform_attributes(new_attributes)
v_lang = attributes['v_lang']
if !current_site.lang_list.include?(v_lang)
attributes['v_lang'] = current_site.lang_list.first
end
if zip = attributes.delete('parent_zip')
if id = secure(Node) { Node.translate_pseudo_id(zip, :id, self) }
attributes['parent_id'] = id
else
node = Node.new
node.errors.add('parent_id', 'could not be found')
return node
end
end
unless attributes['title'] && attributes['parent_id']
node = Node.new
node.errors.add('title', "can't be blank") if attributes['title'].blank?
node.errors.add('parent_id', "can't be blank") if attributes['parent_id'].blank?
return node
end
# FIXME: remove 'with_exclusive_scope' once scopes are clarified and removed from 'secure'
node = Node.send(:with_exclusive_scope) do
find_by_parent_title_and_kpath(attributes['parent_id'], attributes['title'], nil)
end
if node
visitor.visit(node) # secure
# TODO: class ignored (could be used to transform from one class to another...)
attributes.delete('class')
attributes.delete('klass')
updated_date = node.updated_at
node.update_attributes(attributes)
if updated_date != node.updated_at
node[:create_or_update] = 'updated'
else
node[:create_or_update] = 'same'
end
else
node = create_node(attributes, false)
node[:create_or_update] = 'new'
end
node
end
# TODO: cleanup and rename with something indicating the attrs cleanup that this method does.
def new_node(new_attributes, transform = true)
attributes = transform ? transform_attributes(new_attributes) : new_attributes
klass_name = attributes.delete('class') || attributes.delete('klass')
klass_name ||= attributes['file'] ? 'Document' : 'Page'
if klass_name.kind_of?(VirtualClass) || klass_name.kind_of?(Class)
klass = klass_name
else
unless klass = get_class(klass_name, :create => true)
node = Node.new
node.instance_eval { @attributes.merge!(attributes) }
node.errors.add('klass', 'invalid')
# This is to show the klass in the form seizure
node.instance_variable_set(:@klass, klass_name.to_s)
def node.klass; @klass; end
return node
end
end
if attributes['file'] && !(klass.kpath =~ %r{^ND})
klass = VirtualClass['Document']
end
if klass.kind_of?(VirtualClass)
node = secure(klass.real_class) { klass.new_instance(attributes) }
else
node = secure(klass) { klass.new_instance(attributes) }
end
node
end
# TODO: cleanup and rename with something indicating the attrs cleanup that this method does.
def create_node(new_attributes, transform = true)
node = new_node(new_attributes, transform)
if node.errors.empty?
node.save
end
node
end
# Create new nodes from the data in a folder or archive.
def create_nodes_from_folder(opts)
# TODO: all this needs refactoring (and moved into a module).
# It's probably the messiest part of Zena.
return [] unless (opts[:folder] || opts[:archive]) && (opts[:parent] || opts[:parent_id])
scope = self.scoped_methods[0] || {}
parent_id = opts[:parent_id] || opts[:parent][:id]
folder = opts[:folder]
defaults = (opts[:defaults] || {}).stringify_keys
# Initial object class
klass = opts[:class] || opts[:klass] || "Page"
res = {}
unless folder
# Create from archive
res = nil
extract_archive(opts[:archive]) do |folder|
res = create_nodes_from_folder(:folder => folder, :parent_id => parent_id, :defaults => defaults, :klass => klass)
end
return res
end
entries = Dir.entries(folder).reject { |f| f =~ /^[\.~]|^__/ }.map do |filename|
[filename, String.from_filename(filename)]
end.sort
index = 0
while entries[index]
catch (:next_entry) do
type = current_obj = sub_folder = document_path = nil
versions = []
filename, title = *entries[index]
path = File.join(folder, filename)
if File.stat(path).directory?
type = :folder
sub_folder = path
attrs = defaults.dup
attrs['v_lang'] ||= visitor.lang
elsif title =~ /^(.+?)(\.\w\w|)(\.\d+|)\.zml$/ # bird.jpg.en.zml
# node content in yaml
type = :node
title = "#{$1}#{$4}"
lang = $2.blank? ? nil : $2[1..-1]
# no need for base_node (this is done after all with parse_assets in the controller)
attrs = defaults.merge(get_attributes_from_yaml(path))
attrs['title'] = title
attrs['v_lang'] = lang || attrs['v_lang'] || visitor.lang
versions << attrs
elsif title =~ /^((.+?)\.(.+?))(\.\w\w|)(\.\d+|)$/ # bird.jpg.en
type = :document
title = $1
attrs = defaults.dup
lang = $4.blank? ? nil : $4[1..-1]
attrs['v_lang'] = lang || attrs['v_lang'] || visitor.lang
attrs['ext'] = $3
document_path = path
else
# Document without extension
type = :document
attrs = defaults.dup
lang = nil
attrs['v_lang'] = lang || attrs['v_lang'] || visitor.lang
attrs['ext'] = 'bin'
document_path = path
end
index += 1
while entries[index] && entries[index][1] =~ /^#{title}(\.\w\w|)(\.\d+|)\.zml$/ # bird.jpg.en.zml
lang = $1.blank? ? visitor.lang : $1[1..-1]
path = File.join(folder,entries[index][0])
# we have a zml file. Create a version with this file
# no need for base_node (this is done after all with parse_assets in the controller)
attrs = defaults.merge(get_attributes_from_yaml(path))
attrs['title'] ||= title
attrs['v_lang'] ||= lang
versions << attrs
index += 1
end
if versions.empty?
if type == :folder
# minimal node for a folder
attrs['title'] = title
attrs['v_lang'] ||= lang
attrs['class'] = klass
versions << attrs
elsif type == :document
# minimal node for a document
attrs['title'] = title
attrs['v_lang'] ||= lang
versions << attrs
end
end
new_object = false
versions.each do |attrs|
# FIXME: same lang: remove before update current_obj.remove if current_obj.v_lang == attrs['v_lang'] && current_obj.v_status != Zena::Status::Red
# FIXME: current_obj.publish if attrs['v_status'].to_i == Zena::Status::Pub
if type == :document
attrs['title' ] = attrs['title'].split('.')[0..-2].join('.')
if document_path
attrs['ext'] ||= document_path.split('.').last
# file
insert_zafu_headings = false
if opts[:parent_class] == 'Skin'
if ['html','xhtml'].include?(attrs['ext']) && attrs['title'] == 'index'
attrs['ext'] = 'zafu'
attrs['title'] = 'Node'
attrs['content_type'] = 'text/zafu'
insert_zafu_headings = true
elsif attrs['ext'] == 'yml' && attrs['title'] == '_roles'
# import roles
# FIXME: security. We should show diff and ask for validation...
::Role.import(YAML.load(File.read(document_path)))
# Continue in outer loop.
throw :next_entry
end
end
ctype = Zena::EXT_TO_TYPE[attrs['ext']]
ctype = ctype ? ctype[0] : "application/octet-stream"
attrs['content_type'] = ctype
File.open(document_path) do |f|
file = uploaded_file(f, filename, ctype)
(class << file; self; end;).class_eval do
alias o_read read
define_method(:read) do
if insert_zafu_headings
o_read.sub(%r{</head>}," <r:stylesheets/>\n <r:javascripts/>\n <r:uses_datebox/>\n</head>")
else
o_read
end
end
end
current_obj = create_or_update_node(attrs.merge(:file => file, :klass => 'Document', :_parent_id => parent_id))
end
document_path = nil
else
current_obj = create_or_update_node(attrs.merge(:_parent_id => parent_id, :klass => 'Document'))
end
else
# :folder, :node
current_obj = create_or_update_node(attrs.merge(:_parent_id => parent_id))
end
new_object = new_object || current_obj.instance_variable_get(:@new_record_before_save)
end
current_obj.instance_variable_set(:@new_record_before_save, new_object)
current_obj.instance_variable_set(:@versions_count, versions.size)
res[current_obj[:id].to_i] = current_obj
res.merge!(create_nodes_from_folder(:folder => sub_folder, :parent_id => current_obj[:id], :defaults => defaults, :parent_class => current_obj.klass)) if sub_folder && !current_obj.new_record?
end # catch :next_entry
end
res
end
def extract_archive(archive)
begin
n = 0
# TODO: we could move the tmp folder inside sites/{current_site}/tmp
folder = File.join(RAILS_ROOT, 'tmp', sprintf('%s.%d.%d', 'import', $$, n))
end while File.exists?(folder)
begin
FileUtils::mkpath(folder)
if archive.kind_of?(StringIO)
filename = archive.original_filename
tempf = Tempfile.new(archive.original_filename)
File.open(tempf.path, 'wb') { |f| f.syswrite(archive.read) }
archive = tempf
else
filename = archive.original_filename
end
# extract file in this temporary folder.
# FIXME: SECURITY is there a security risk here ?
# FIXME: not compatible with Windows.
if filename =~ /\.tgz$/
`tar -C '#{folder}' -xz < '#{archive.path}'`
elsif filename =~ /\.tar$/
`tar -C '#{folder}' -x < '#{archive.path}'`
elsif filename =~ /\.zip$/
`unzip -d '#{folder}' '#{archive.path}'`
elsif filename =~ /(.*)(\.gz|\.z)$/
`gzip -d '#{archive.path}' -c > '#{folder}/#{$1.gsub("'",'')}'`
else
# FIXME: send errors back
puts "BAD #{archive.inspect}"
end
yield folder
ensure
FileUtils::rmtree(folder)
end
end
def find_by_zip(zip)
node = find(:first, :conditions=>"zip = #{zip.to_i}")
raise ActiveRecord::RecordNotFound unless node
node
end
# FIXME: Where is this used ?
def class_for_relation(rel)
case rel
when 'author'
User
when 'traductions'
Version
when 'versions'
Version
else
Node
end
end
def plural_relation?(rel)
rel = rel.split(/\s/).first
if ['root', 'parent', 'self', 'children', 'documents_only', 'all_pages'].include?(rel) || Node.get_class(rel)
rel.pluralize == rel
elsif rel =~ /\A\d+\Z/
false
else
relation = RelationProxy.find_by_role(rel.singularize)
return rel =~ /s$/ unless relation
relation.target_role == rel.singularize ? !relation.target_unique : !relation.source_unique
end
end
# Translate attributes from the visitor's reference to the application.
# This method translates dates, zazen shortcuts and zips and returns a stringified hash.
def transform_attributes(new_attributes, base_node = nil, change_timezone = true, is_link = false)
res = {}
res['parent_id'] = new_attributes[:_parent_id] if new_attributes[:_parent_id] # real id set inside zena.
copy_node = new_attributes.delete(:_copy)
attributes = new_attributes.stringify_keys
if copy_node || attributes['copy_id']
if !copy_node && attributes['copy_id'].blank?
attributes = Node.new.replace_attributes_in_values(attributes)
else
copy_node ||= Node.find_by_zip(attributes.delete('copy_id'))
attributes = copy_node.replace_attributes_in_values(attributes)
end
end
if !res['parent_id'] && p = attributes['parent_id']
res['parent_zip'] = p unless p.blank?
end
attributes.each do |key, value|
next if ['parent_id', 'parent_zip', '_parent_id'].include?(key)
if %w{rgroup_id wgroup_id dgroup_id}.include?(key)
res[key] = Group.translate_pseudo_id(value, :id) || value
elsif %w{rgroup wgroup dgroup}.include?(key)
res["#{key}_id"] = Group.translate_pseudo_id(value, :id) || value
elsif %w{user_id}.include?(key)
res[key] = User.translate_pseudo_id(value, :id) || value
elsif %w{link_id}.include?(key)
# Link id, not translated
res[key] = value
elsif %w{id create_at updated_at}.include?(key)
# ignore (can be present in xml)
elsif %w{log_at event_at v_publish_from}.include?(key) || (is_link && %w{date}.include?(key))
# FIXME: !!! We need to fix timezone parsing in dates depending on the Schema used. This means
# that we probably need to do this at the property level (during write).
if value.kind_of?(Time)
res[key] = value
elsif value
# parse date
if key == 'date'
# TODO: this is a temporary hack because date in links do not support timezones/formats properly
res[key] = value.to_utc("%Y-%m-%d %H:%M:%S")
else
res[key] = value.to_utc(_(Zena::Use::Dates::DATETIME), change_timezone ? visitor.tz : nil)
end
end
elsif key =~ /^(\w+)_id$/
res["#{$1}_zip"] = value
elsif key =~ /^(\w+)_ids$/
res["#{$1}_zips"] = value.kind_of?(Array) ? value : value.split(',').map(&:strip)
elsif key == 'v_status' || key == 'file'
res[key] = value unless value.blank?
elsif value.kind_of?(Hash)
res[key] = transform_attributes(value, base_node, change_timezone, %w{link rel rel_attributes}.include?(key) || is_link)
else
# translate zazen
if value.kind_of?(String)
# FIXME: ignore if 'text' of a TextDocument...
res[key] = ZazenParser.new(value,:helper=>self).render(:translate_ids=>:zip, :node=>base_node)
else
res[key] = value
end
end
end
res
end
def get_attributes_from_yaml(filepath, base_node = nil)
attributes = YAML::load( File.read( filepath ) )
attributes.delete(:_parent_id)
transform_attributes(attributes, base_node)
end
# Return a safe string to access node attributes in compiled templates and compiled sql.
def zafu_attribute(node, attribute)
if node.kind_of?(String)
raise Exception.new("You should use safe_method_type...")
else
node.safe_read(attribute)
end
end
# Seeing all the columns of the Node class on every inspect does not help at all.
def inspect
to_s
end
def auto_create_discussion
false
end
end
def zafu_versions