/
Story.pm
1236 lines (935 loc) · 39.4 KB
/
Story.pm
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
package Bric::SOAP::Story;
###############################################################################
use strict;
use warnings;
use Bric::Biz::Asset::Business::Story;
use Bric::Biz::AssetType;
use Bric::Biz::Category;
use Bric::Biz::Site;
use Bric::Biz::OutputChannel;
use Bric::Util::Grp::Parts::Member::Contrib;
use Bric::Util::Fault qw(throw_ap);
use Bric::Biz::Workflow qw(STORY_WORKFLOW);
use Bric::App::Session qw(get_user_id);
use Bric::App::Authz qw(chk_authz READ CREATE);
use Bric::App::Event qw(log_event);
use XML::Writer;
use IO::Scalar;
use Bric::Util::Priv::Parts::Const qw(:all);
use Bric::SOAP::Util qw(category_path_to_id
output_channel_name_to_id
workflow_name_to_id
site_to_id
xs_date_to_db_date
db_date_to_xs_date
parse_asset_document
serialize_elements
deserialize_elements
load_ocs
);
use Bric::SOAP::Media;
use SOAP::Lite;
import SOAP::Data 'name';
use base qw(Bric::SOAP::Asset);
use constant DEBUG => 0;
require Data::Dumper if DEBUG;
=head1 NAME
Bric::SOAP::Story - SOAP interface to Bricolage stories.
=head1 VERSION
$LastChangedRevision$
=cut
{
no warnings;
INIT {
require Bric; our $VERSION = Bric->VERSION
}
}
=head1 DATE
$LastChangedDate$
=head1 SYNOPSIS
use SOAP::Lite;
import SOAP::Data 'name';
# setup soap object to login with
my $soap = new SOAP::Lite
uri => 'http://bricolage.sourceforge.net/Bric/SOAP/Auth',
readable => DEBUG;
$soap->proxy('http://localhost/soap',
cookie_jar => HTTP::Cookies->new(ignore_discard => 1));
# login
$soap->login(name(username => USER),
name(password => PASSWORD));
# set uri for Story module
$soap->uri('http://bricolage.sourceforge.net/Bric/SOAP/Story');
# get a list of story_ids for published stories w/ "foo" in their title
my $story_ids = $soap->list_ids(name(title => '%foo%'),
name(publish_status => 1) )->result;
# export a story
my $xml = $soap->export(name(story_id => $story_id)->result;
# create a new story from an xml document
my $story_ids = $soap->create(name(document => $xml_document))->result;
# update an existing story from an xml document
my $story_ids = $soap->create(name(document => $xml_document),
name(update_ids =>xs
[ name(story_id => 1024) ]))->result;
=head1 DESCRIPTION
This module provides a SOAP interface to manipulating Bricolage stories.
=head1 INTERFACE
=head2 Public Class Methods
=over 4
=item list_ids
This method queries the story database for matching stories and
returns a list of ids. If no stories are found an empty list will be
returned.
This method can accept the following named parameters to specify the
search. Some fields support matching and are marked with an (M). The
value for these fields will be interpreted as an SQL match expression
and will be matched case-insensitively. Other fields must specify an
exact string to match. Match fields combine to narrow the search
results (via ANDs in an SQL WHERE clause).
=over 4
=item title (M)
The story's title.
=item description (M)
The story's description.
=item slug (M)
The story's slug.
=item category
A category containing the story, given as the complete category path
from the root. Example: "/news/linux".
=item keyword (M)
A keyword associated with the story.
=item simple (M)
a single OR search that hits title, description, primary_uri
and keywords.
=item workflow
The name of the workflow containing the story. (ex. Story)
=item no_workflow
Set to 1 to return only stories that are out of workflow. This is
true after stories are published and until they are recalled into
workflow for editing.
=item primary_uri (M)
The primary uri of the story.
=item priority
The priority of the story.
=item publish_status
Stories that have been published have a publish_status of "1",
otherwise "0". This value never changes after being turned on. For a
more accurate read on a story's current status see no_workflow above.
=item element
The name of the top-level element for the story. Also known as the
"Story Type". This value corresponds to the element attribute on the
story element in the asset schema.
=item site
The name of the site which the story is in.
=item publish_date_start
Lower bound on publishing date. Given in XML Schema dateTime format
(CCYY-MM-DDThh:mm:ssTZ).
=item publish_date_end
Upper bound on publishing date. Given in XML Schema dateTime format
(CCYY-MM-DDThh:mm:ssTZ).
=item first_publish_date_start
Lower bound on the first date a story was published. Given in XML Schema
dateTime format (CCYY-MM-DDThh:mm:ssTZ).
=item first_publish_date_end
Upper bound on the first date a story was published. Given in XML Schema
dateTime format (CCYY-MM-DDThh:mm:ssTZ).
=item cover_date_start
Lower bound on cover date. Given in XML Schema dateTime format
(CCYY-MM-DDThh:mm:ssTZ).
=item cover_date_end
Upper bound on cover date. Given in XML Schema dateTime format
(CCYY-MM-DDThh:mm:ssTZ).
=item expire_date_start
Lower bound on cover date. Given in XML Schema dateTime format
(CCYY-MM-DDThh:mm:ssTZ).
=item expire_date_end
Upper bound on cover date. Given in XML Schema dateTime format
(CCYY-MM-DDThh:mm:ssTZ).
=item element_key_name (M)
The key name of the top-level element for the story. This is more accurate
than the C<element> parameter, since there can be multiple elements with the
same name.
=item unexpired
Set to a true value to get a list of only unexpired stories.
=item subelement_key_name (M)
The key name for a container element that's a subelement of a story.
=item data_text (M)
Text stored in the fields of the story element or any of its subelements. Only
fields that use the "short" storage type will be searched.
=item output_channel
The name of an ouput channel that stories must be associated with.
=item contrib_id
A Bricolage contributor object ID. Only stories associated with that
contributor will have their IDs listed.
=back
Throws:
=over
=item Exception::AP
=back
Side Effects: NONE
Notes: In addition to the parameters listed above, you can use most of the
parameters listed in the documentation for the list method in
Bric::Biz::Asset::Business::Story.
=cut
sub list_ids {
my $self = shift;
my $env = pop;
my $args = $env->method || {};
my $method = 'list_ids';
print STDERR __PACKAGE__ . "->list_ids() called : args : ",
Data::Dumper->Dump([$args],['args']) if DEBUG;
# check for bad parameters
for (keys %$args) {
throw_ap(error => __PACKAGE__ . "::list_ids : unknown parameter \"$_\".")
unless $self->is_allowed_param($_, $method);
}
# handle site => site_id conversion
$args->{site_id} = site_to_id(__PACKAGE__, $args->{site})
if exists $args->{site};
# handle workflow => workflow__id mapping
$args->{workflow_id} =
workflow_name_to_id(__PACKAGE__, delete $args->{workflow}, $args)
if exists $args->{workflow};
# handle output_channel => output_channel__id mapping
$args->{output_channel_id} =
output_channel_name_to_id(__PACKAGE__, delete $args->{output_channel}, $args)
if exists $args->{output_channel};
# handle category => category_id conversion
$args->{category_id} =
category_path_to_id(__PACKAGE__, delete $args->{category}, $args)
if exists $args->{category};
# no_workflow means workflow__id => 0
if ($args->{no_workflow}) {
$args->{workflow__id} = 0;
delete $args->{no_workflow};
}
# handle element => element__id conversion
if (exists $args->{element}) {
my ($element_id) = Bric::Biz::AssetType->list_ids(
{ key_name => $args->{element}, media => 0 });
throw_ap(error => __PACKAGE__ . "::list_ids : no story element found matching "
. "(element => \"$args->{element}\")")
unless defined $element_id;
$args->{element__id} = $element_id;
delete $args->{element};
}
# translate dates into proper format
for my $name (grep { /_date_/ } keys %$args) {
my $date = xs_date_to_db_date($args->{$name});
throw_ap(error => __PACKAGE__ . "::list_ids : bad date format for $name parameter "
. "\"$args->{$name}\" : must be proper XML Schema dateTime format.")
unless defined $date;
$args->{$name} = $date;
}
# perform list using existing Bricolage list_ids functionality
my @list = Bric::Biz::Asset::Business::Story->list_ids($args);
print STDERR "Bric::Biz::Asset::Business::Story->list_ids() called : ",
"returned : ", Data::Dumper->Dump([\@list],['list'])
if DEBUG;
# name the results
my @result = map { name(story_id => $_) } @list;
# name the array and return
return name(story_ids => \@result);
}
=item export
The export method retrieves a set of stories from the database,
serializes them and returns them as a single XML document. See
L<Bric::SOAP|Bric::SOAP> for the schema of the returned
document.
Accepted paramters are:
=over 4
=item story_id
Specifies a single story_id to be retrieved.
=item story_ids
Specifies a list of story_ids. The value for this option should be an
array of interger "story_id" elements.
=item export_related_media
If set to 1 any related media attached to the story will be included
in the exported document. The story will refer to these included
media objects using the relative form of related-media linking. (see
the XML Schema document in L<Bric::SOAP|Bric::SOAP> for
details)
=item export_related_stories
If set to 1 then the export will work recursively across related
stories. If export_media is also set then media attached to related
stories will also be returned. The story element will refer to the
included story objects using relative references (see the XML Schema
document in L<Bric::SOAP|Bric::SOAP> for details).
=back
Throws:
=over
=item Exception::AP
=back
Side Effects: NONE
Notes: NONE
=cut
sub export {
my $pkg = shift;
my $env = pop;
my $args = $env->method || {};
my $method = 'export';
print STDERR __PACKAGE__ . "->export() called : args : ",
Data::Dumper->Dump([$args],['args']) if DEBUG;
# check for bad parameters
for (keys %$args) {
throw_ap(error => __PACKAGE__ . "::export : unknown parameter \"$_\".")
unless $pkg->is_allowed_param($_, $method);
}
# story_id is sugar for a one-element story_ids arg
$args->{story_ids} = [ $args->{story_id} ] if exists $args->{story_id};
# make sure story_ids is an array
throw_ap(error => __PACKAGE__ . "::export : missing required story_id(s) setting.")
unless defined $args->{story_ids};
throw_ap(error => __PACKAGE__ . "::export : malformed story_id(s) setting.")
unless ref $args->{story_ids} and ref $args->{story_ids} eq 'ARRAY';
# setup XML::Writer
my $document = "";
my $document_handle = new IO::Scalar \$document;
my $writer = XML::Writer->new(OUTPUT => $document_handle,
DATA_MODE => 1,
DATA_INDENT => 1);
# open up an assets document, specifying the schema namespace
$writer->xmlDecl("UTF-8", 1);
$writer->startTag("assets",
xmlns => 'http://bricolage.sourceforge.net/assets.xsd');
# iterate through story_ids, serializing stories as we go, storing
# media ids to serialize for later.
my @story_ids = @{$args->{story_ids}};
my @media_ids;
my %done;
while(my $story_id = shift @story_ids) {
next if exists $done{$story_id}; # been here before?
my @related = $pkg->serialize_asset(writer => $writer,
story_id => $story_id,
args => $args);
$done{$story_id} = 1;
# queue up the related stories, story the media for later
foreach my $obj (@related) {
push(@story_ids, $obj->[1]) if $obj->[0] eq 'story';
push(@media_ids, $obj->[1]) if $obj->[0] eq 'media';
}
}
# serialize related media if we have any
%done = ();
foreach my $media_id (@media_ids) {
next if $done{$media_id};
Bric::SOAP::Media->serialize_asset(media_id => $media_id,
writer => $writer,
args => {});
$done{$media_id} = 1;
}
# end the assets element and end the document
$writer->endTag("assets");
$writer->end();
$document_handle->close();
# name, type and return
return name(document => $document)->type('base64');
}
=item create
The create method creates new objects using the data contained in an
XML document of the format created by export().
The create will fail if your story element contains non-relative
related_story_ids or related_media_ids that do not refer to existing
stories or media in the system.
Returns a list of new story_ids and media_ids created in the order of
the assets in the document.
Available options:
=over 4
=item document (required)
The XML document containing objects to be created. The document must
contain at least one story and may contain any number of related media
objects.
=item workflow
Specifies the initial workflow the story is to be created in
=item desk
Specifies the initial desk the story is to be created on
=back
Throws:
=over
=item Exception::AP
=back
Side Effects: NONE
Notes: The setting for publish_status in the incoming story is ignored
and always 0 for new stories.
New stories are put in the first "story workflow" unless you pass in
the --workflow option. The start desk of the workflow is used unless
you pass the --desk option.
=cut
=item update
The update method updates stories using the data in an XML document
of the format created by export(). A common use of update() is to
export() a selected story, make changes to one or more fields and
then submit the changes with update().
Returns a list of new story_ids and media_ids updated or created in
the order of the assets in the document.
Takes the following options:
=over 4
=item document (required)
The XML document where the objects to be updated can be found. The
document must contain at least one story and may contain any number of
related media objects.
=item update_ids (required)
A list of "story_id" integers for the assets to be updated. These
must match id attributes on story elements in the document. If you
include objects in the document that are not listed in update_ids then
they will be treated as in create(). For that reason an update() with
an empty update_ids list is equivalent to a create().
=item workflow
Specifies the workflow to move the story to
=item desk
Specifies the desk to move the story to
=back
Throws:
=over
=item Exception::AP
=back
Side Effects: NONE
Notes: The setting for publish_status in a newly created story is
ignored and always 0 for new stories. Updated stories do get
publish_status set from the document setting.
=cut
=item delete
The delete() method deletes stories. It takes the following options:
=over 4
=item story_id
Specifies a single story_id to be deleted.
=item story_ids
Specifies a list of story_ids to delete.
=back
Throws:
=over
=item Exception::AP
=back
Side Effects: NONE
Notes: NONE
=cut
sub delete {
my $pkg = shift;
my $env = pop;
my $args = $env->method || {};
my $method = 'delete';
print STDERR __PACKAGE__ . "->delete() called : args : ",
Data::Dumper->Dump([$args],['args']) if DEBUG;
# check for bad parameters
for (keys %$args) {
throw_ap(error => __PACKAGE__ . "::delete : unknown parameter \"$_\".")
unless $pkg->is_allowed_param($_, $method);
}
# story_id is sugar for a one-element story_ids arg
$args->{story_ids} = [ $args->{story_id} ] if exists $args->{story_id};
# make sure story_ids is an array
throw_ap(error => __PACKAGE__ . "::delete : missing required story_id(s) setting.")
unless defined $args->{story_ids};
throw_ap(error => __PACKAGE__ . "::delete : malformed story_id(s) setting.")
unless ref $args->{story_ids} and ref $args->{story_ids} eq 'ARRAY';
# delete the stories
foreach my $story_id (@{$args->{story_ids}}) {
print STDERR __PACKAGE__ . "->delete() : deleting story_id $story_id\n"
if DEBUG;
# first look for a checked out version
my $story = Bric::Biz::Asset::Business::Story->lookup({ id => $story_id,
checkout => 1 });
unless ($story) {
# settle for a non-checked-out version and check it out
$story = Bric::Biz::Asset::Business::Story->lookup({ id => $story_id });
throw_ap(error => __PACKAGE__ . "::delete : no story found for id \"$story_id\"")
unless $story;
throw_ap(error => __PACKAGE__ . "::delete : access denied for story \"$story_id\".")
unless chk_authz($story, EDIT, 1);
$story->checkout({ user__id => get_user_id });
log_event("story_checkout", $story);
}
# Remove the story from any desk it's on.
if (my $desk = $story->get_current_desk) {
$desk->checkin($story);
$desk->remove_asset($story);
$desk->save;
}
# Remove the story from workflow.
if ($story->get_workflow_id) {
$story->set_workflow_id(undef);
log_event("story_rem_workflow", $story);
}
# Deactivate the story and save it.
$story->deactivate;
$story->save;
log_event("story_deact", $story);
}
return name(result => 1);
}
=item $self->module
Returns the module name, that is the first argument passed
to bric_soap.
=cut
sub module { 'story' }
=item is_allowed_param
=item $pkg->is_allowed_param($param, $method)
Returns true if $param is an allowed parameter to the $method method.
=cut
my $allowed = {
list_ids => { map { $_ => 1 } qw(title description slug category keyword
simple primary_uri priority workflow
no_workflow publish_status element
publish_date_start publish_date_end
cover_date_start first_publish_date_start
first_publish_date_end cover_date_end
expire_date_start expire_date_end site
alias_id element_key_name unexpired
data_text output_channel contrib_id
subelement_key_name Order OrderDirection
Limit Offset),
grep { /^[^_]/}
keys %{ Bric::Biz::Asset::Business::Story->PARAM_WHERE_MAP }
},
export => { map { $_ => 1 } qw(story_id story_ids
export_related_media
export_related_stories) },
create => { map { $_ => 1 } qw(document workflow desk) },
update => { map { $_ => 1 } qw(document update_ids workflow desk) },
delete => { map { $_ => 1 } qw(story_id story_ids) },
};
sub is_allowed_param {
my ($pkg, $param, $method) = @_;
return exists($allowed->{$method}->{$param});
}
=back
=head2 Private Class Methods
=over 4
=item $pkg->load_asset($args)
This method provides the meat of both create() and update(). The only
difference between the two methods is that update_ids will be empty on
create().
=cut
sub load_asset {
my ($pkg, $args) = @_;
my $document = $args->{document};
my %to_update = map { $_ => 1 } @{$args->{update_ids}};
# parse and catch errors
my $data;
eval { $data = parse_asset_document($document) };
throw_ap(error => __PACKAGE__ . " : problem parsing asset document : $@")
if $@;
throw_ap(error => __PACKAGE__ . " : problem parsing asset document : no stories found!")
unless ref $data and ref $data eq 'HASH' and exists $data->{story};
print STDERR Data::Dumper->Dump([$data],['data']) if DEBUG;
# Determine workflow and desk for stories if not default
my ($workflow, $desk, $no_wf_or_desk_param);
$no_wf_or_desk_param = ! (exists $args->{workflow} || exists $args->{desk});
if (exists $args->{workflow}) {
$workflow = Bric::Biz::Workflow->lookup({ name => $args->{workflow} })
|| throw_ap error => "workflow '" . $args->{workflow} . "' not found!";
}
if (exists $args->{desk}) {
$desk = Bric::Biz::Workflow::Parts::Desk->lookup({ name => $args->{desk} })
|| throw_ap error => "desk '" . $args->{desk} . "' not found!";
}
# loop over stories, filling in %story_ids and @relations
my (%story_ids, @story_ids, @relations, %selems);
foreach my $sdata (@{$data->{story}}) {
my $id = $sdata->{id};
# are we updating?
my $update = exists $to_update{$id};
# are we aliasing?
my $aliased = exists($sdata->{alias_id}) && $sdata->{alias_id} && ! $update
? Bric::Biz::Asset::Business::Story->lookup({
id => $story_ids{$sdata->{alias_id}} || $sdata->{alias_id} })
: undef;
# setup init data for create
my %init;
# get user__id from Bric::App::Session
$init{user__id} = get_user_id;
# Get the site ID.
$sdata->{site} = 'Default Site' unless exists $sdata->{site};
$init{site_id} = site_to_id(__PACKAGE__, $sdata->{site});
if (exists $sdata->{element} and not $aliased) {
# It's a normal story.
unless ($selems{$sdata->{element}}) {
my $e = (Bric::Biz::AssetType->list
({ key_name => $sdata->{element}, media => 0 }))[0]
or throw_ap(error => __PACKAGE__ . "::create : no story"
. " element found matching (element => "
. "\"$sdata->{element}\")");
$selems{$sdata->{element}} =
[ $e->get_id,
{ map { $_->get_name => $_ } $e->get_output_channels } ];
}
# get element__id from story element
$init{element__id} = $selems{$sdata->{element}}->[0];
} elsif ($aliased) {
# It's an alias.
$init{alias_id} = $sdata->{alias_id};
} else {
# It's bogus.
throw_ap(error => __PACKAGE__ . "::create: No story element or alias ID found");
}
# get source__id from source
($init{source__id}) = Bric::Biz::Org::Source->list_ids
({ source_name => $sdata->{source} });
throw_ap(error => __PACKAGE__ . "::create : no source found matching "
. "(source => \"$sdata->{source}\")")
unless defined $init{source__id};
# get base story object
my $story;
unless ($update) {
# create empty story
$story = Bric::Biz::Asset::Business::Story->new(\%init);
throw_ap(error => __PACKAGE__ . "::create : failed to create empty story object.")
unless $story;
print STDERR __PACKAGE__ . "::create : created empty story object\n"
if DEBUG;
# is this is right way to check create access for stories?
throw_ap(error => __PACKAGE__ . " : access denied.")
unless chk_authz($story, CREATE, 1);
if ($aliased) {
# Log that we've created an alias.
my $origin_site = Bric::Biz::Site->lookup
({ id => $aliased->get_site_id });
log_event("story_alias_new", $story,
{ 'From Site' => $origin_site->get_name });
my $site = Bric::Biz::Site->lookup({ id => $init{site_id} });
log_event("story_aliased", $aliased,
{ 'To Site' => $site->get_name });
} else {
# Log that we've created a new story asset.
log_event('story_new', $story);
}
} else {
# updating - first look for a checked out version
$story = Bric::Biz::Asset::Business::Story->lookup({ id => $id,
checkout => 1
});
if ($story) {
# make sure it's ours
throw_ap(error => __PACKAGE__ .
"::update : story \"$id\" is checked out to another user.")
unless $story->get_user__id == get_user_id;
throw_ap(error => __PACKAGE__ . " : access denied.")
unless chk_authz($story, EDIT, 1);
} else {
# try a non-checked out version
$story = Bric::Biz::Asset::Business::Story->lookup({ id => $id });
throw_ap(error => __PACKAGE__ . "::update : no story found for \"$id\"")
unless $story;
throw_ap(error => __PACKAGE__ . " : access denied.")
unless chk_authz($story, RECALL, 1);
# FIX: race condition here - between lookup and checkout
# someone else could checkout...
# check it out
$story->checkout( { user__id => get_user_id });
$story->save;
log_event('story_checkout', $story);
}
# update %init fields
# $story->set_element__id($init{element__id});
# $story->set_alias_id($init{alias_id});
$story->set_source__id($init{source__id});
}
# set simple fields
my @simple_fields = qw(name description slug primary_uri
priority);
$story->_set(\@simple_fields, [ @{$sdata}{@simple_fields} ]);
# avoid setting publish_status on create
$story->set_publish_status($sdata->{publish_status}) if $update;
# assign dates
for my $name qw(cover_date expire_date publish_date first_publish_date) {
my $date = $sdata->{$name};
next unless $date; # skip missing date
my $db_date = xs_date_to_db_date($date);
throw_ap(error => __PACKAGE__ . "::export : bad date format for $name : $date")
unless defined $db_date;
$story->_set([$name],[$db_date]);
}
# remove all categories if updating
if ($update) {
if (my $cats = $story->get_categories) {
# Delete 'em and log it.
$story->delete_categories($cats);
foreach my $cat (@$cats) {
log_event('story_del_category', $story,
{ Category => $cat->get_name });
}
}
}
# assign categories
my @cids;
my $primary_cid;
foreach my $cdata (@{$sdata->{categories}{category}}) {
# get cat id
my $path = ref $cdata ? $cdata->{content} : $cdata;
my $cat = Bric::Biz::Category->lookup({ uri => $path,
site_id => $init{site_id} });
throw_ap(error => __PACKAGE__ . "::create : no category found matching "
. "(category => \"$path\")")
unless defined $cat;
my $category_id = $cat->get_id;
push(@cids, $category_id);
$primary_cid = $category_id
if ref $cdata and $cdata->{primary};
# Log it!
log_event('story_add_category', $story,
{ Category => $cat->get_name });
}
# sanity checks
throw_ap(error => __PACKAGE__ . "::create : no categories defined!")
unless @cids;
throw_ap(error => __PACKAGE__ . "::create : no primary category defined!")
unless defined $primary_cid;
# add categories to story
$story->add_categories(\@cids);
$story->set_primary_category($primary_cid);
unless ($aliased) {
if ($update) {
if (my $contribs = $story->get_contributors) {
foreach my $contrib (@$contribs) {
log_event('story_del_contrib', $story,
{ Name => $contrib->get_name });
}
$story->delete_contributors($contribs);
}
}
# add contributors, if any
if ($sdata->{contributors} and $sdata->{contributors}{contributor}) {
foreach my $c (@{$sdata->{contributors}{contributor}}) {
my %init = (fname => defined $c->{fname} ? $c->{fname} : "",
mname => defined $c->{mname} ? $c->{mname} : "",
lname => defined $c->{lname} ? $c->{lname} : "");
my ($contrib) =
Bric::Util::Grp::Parts::Member::Contrib->list(\%init);
throw_ap(error => __PACKAGE__ . "::create : no contributor found matching "
. "(contributer => "
. join(', ', map { "$_ => $c->{$_}" } keys %$c))
unless defined $contrib;
$story->add_contributor($contrib, $c->{role});
log_event('story_add_contrib', $story,
{ Name => $contrib->get_name });
}
}
}
# save the story in an inactive state. this is necessary to
# allow element addition - you can't add elements to an
# unsaved story, strangely.
$story->deactivate;
$story->save;
# Manage the output channels if any are included in the XML file.
load_ocs($story, $sdata->{output_channels}{output_channel},
$selems{$sdata->{element}}->[1], 'story', $update)
if $sdata->{output_channels}{output_channel};
# sanity checks
throw_ap(error => __PACKAGE__ . "::create : no output channels defined!")
unless $story->get_output_channels;
throw_ap(error => __PACKAGE__ . "::create : no primary output channel defined!")
unless defined $story->get_primary_oc_id;
# remove all keywords if updating
$story->del_keywords($story->get_keywords) if $update;
# add keywords, if we have any
if ($sdata->{keywords} and $sdata->{keywords}{keyword}) {
# collect keyword objects
my @kws;
foreach (@{$sdata->{keywords}{keyword}}) {
my $kw = Bric::Biz::Keyword->lookup({ name => $_ });
unless ($kw) {
$kw = Bric::Biz::Keyword->new({ name => $_})->save;
log_event('keyword_new', $kw);
}
push @kws, $kw;
}
# add keywords to the story