diff --git a/asset_status.ods b/asset_status.ods new file mode 100644 index 000000000..943ffb5b7 Binary files /dev/null and b/asset_status.ods differ diff --git a/docs/migration.txt b/docs/migration.txt index c1aafab6a..11f5fd6f7 100644 --- a/docs/migration.txt +++ b/docs/migration.txt @@ -4,6 +4,7 @@ WebGUI 8 Migration Guide The information contained herein documents the API changes that have occurred in the WebGUI 8 development effort and how to migrate your code to accomodate the new APIs. + WebGUI::Cache ============= WebGUI::Cache has been completely rewritten. If you were using the cache API in the past, you'll need to update your code to reflect the changes. NOTE: you can get a cached reference to the cache object from WebGUI::Session, which will be substantially faster than instantiating the object yourself. @@ -12,4 +13,148 @@ my $cache = $session->cache; +WebGUI::Asset +============= +The Asset API has been changed in small, but significant ways. You'll need to make a few changes to your asset subclasses to support these changes. +Definition +---------- +You must migrate your asset to use the new WebGUI::Definition::Asset class instead of the definition() method. This executes several orders of magnitude faster, but is different in a few ways. + +1) You define your definition using property and aspect calls, as well as standard Moose syntax. + +2) You no longer have a reference to $session, so you'll need to make sub routine refs to to method calls. However, you cannot use sub refs on any attributes or the following property elements: tableName. + +3) You no longer have the "customDrawMethod" element. You must make custom form controls. + +4) You no longer have filters. Instead, each property has a method called propertyName (so a property called 'title' would be title()). You can override that to achieve the same result. You can see examples of this in Asset.pm, look at the url and title properties. + +5) Because you don't have a reference to $session, you can't internationalize right in the definition. So property elements like "label" and "hoverHelp" are just i18n identifiers and will automatically be run through internationalization on calling the getFormProperties() method. To specify +an i18n identifier, place the label and namespace in an arrayref, like this: + + label => ['i18n key', 'namespace'], + +6) Definition's are now rigid. This means that every property needs to be defined in the definition, and it must at least have a "fieldType" element. If the field is to be displayed (ie: it doesn't have a noFormPost=>1 element) then it must also at minimum have label elements. In addition, you must specify assetName, tableName, and properties aspects at minimum. Anything less is invalid. + +7) The properties attribute must be an array reference of properties. No more Tie::IxHash. + +8) The autoGenerateForms has been removed. All edit forms are autogenerated in WebGUI 8. + +9) You no longer have the "visible" element. It was a duplicate of "noFormPost", so use "noFormPost" instead. + +10) You no longer have the "displayOnly" element. Make a custom form control instead. + +11) Defaults for properties are set by the default key in the property. This sets form defaults as well. This means that newly created +Assets always have sane defaults. Unless specifically overridden, any property can be set to undef. This takes care of the long +standing problem with sticky titles and other fields. + +12) You no longer have the "allowEmpty" element. However, you can now specify an initial value in the "value" element, and set "default" to undef if you want to have an initial value but allow the field to become empty or undef. + +Here's an example. + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => 'Gadget'; +aspect tableName => 'gadget'; +aspect uiLevel => 5; +aspect icon => 'gadget.gif'; +property urlToJavascript => ( + fieldType => 'url', + label => ['URL to Javascript Class','Asset_Gadget'], + hoverHelp => ['URL to Javascript Class help','Asset_Gadget'], + ); +property foo => ( + fieldType => 'text', + noFormPost => 1, + ); +property bar => ( + fieldType => 'codearea', + uiLevel => 9, + label => ['Bar','Asset_Gadget'], + hoverHelp => ['Bar help','Asset_Gadget'], + builder => '_bar_builder', ##Set default using Moose's builder and lazy method + lazy => 1, + ); +sub _bar_builder { + my $self = shift; + return $self->callSomeMethod; +} +property baz => ( + fieldType => 'checkboxList', + label => ['Baz','Asset_Gadget'], + hoverHelp => ['Baz help','Asset_Gadget'], + default => 1, + options => \&_baz_options, ##method called when getFormProperties called, automatically lazy + ); +sub _baz_options { + my ($self, $property_meta_object, $property_name) = @_; + my $session = $self->session; + my $i18n = WebGUI::International->new($session, 'Asset_Gadget'); + tie my %options, 'Tie::IxHash'; + %options = ( + one => $i18n->get('one'), + two => $i18n->get('two'), + three => $i18n->get('three'), + ); + return \%options; +} + +Asset Instanciators +------------------- +Moose does not allow a dynamic class to be passed into ->new. Trying to access an asset from the database like this: + + WebGUI::Asset->new($session, $assetId, 'WebGUI::Asset::Template'); + +will give you back an object with class WebGUI::Asset, with some of the data from the Template. + +You have two options to deal with this: + +1) Brute force method + +my $class = WebGUI::Asset->loadModule($asset_module_name); +my $asset = $class->new($session, $assetId); + +2) Use newById + +newById replaces the older, and longer, newByDynamicClass method. + +my $asset = WebGUI::Asset->newById($session, $assetId); + +->new itself will either lookup an asset in the database and return you an object, or build you +an object without storing the data into the database, depending on how it's called. + +WebGUI::Asset::SomeClass->new($session, $assetId, $revisionDate) will try to look up the requested object +of type SomeClass, populated with information from the database. + +WebGUI::Asset::SomeClass->new($propertyHashRef) will return you an object of type SomeClass populated +with the properties you have passed in. Missing properties will have default set from the definition. + +Exceptions +---------- +All Asset instanciators, new, newById, newByUrl, newPending, newByPropertyHashRef throw exceptions instead +of returning undef to indicate an error. You should wrap any call to an instanciator in an eval, and catch +any exceptions that are thrown and deal with them. + +my $asset = eval { WebGUI::Asset->newById($session, $assetId); }; +if (my $exception = Exception::Class->caught() ) { + ##Log or handle the exception. Exceptions can also be rethrown to be passed farther up the call chain. +} + +Removed Methods +--------------- +assetDbProperties - Simply instantiate the asset if you want it's properties. + +assetExists - Simply instantiate the asset if you want to know if it exists. + +getValue - Use get() or the individual property accessors instead. + +fixTitle - The title() method does what this used to do as the title is set. + +fixUrlFromParent - This functionality is built into fixUrl, so that all fixes happen and can't cause breakages. + +fixId - Never assign the asset anything other than a GUID. + +Asset API +---------- +->get will still work, but will be slightly slower since inside it calls the direct Moose accessor. Similarly, +getId is slightly slower than ->assetId. diff --git a/docs/upgrades/_upgrade.skeleton b/docs/upgrades/_upgrade.skeleton index 60222c641..624b61dad 100644 --- a/docs/upgrades/_upgrade.skeleton +++ b/docs/upgrades/_upgrade.skeleton @@ -70,7 +70,7 @@ sub addPackage { # Turn off the package flag, and set the default flag for templates added my $assetIds = $package->getLineage( ['self','descendants'] ); for my $assetId ( @{ $assetIds } ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); + my $asset = WebGUI::Asset->newById( $session, $assetId ); if ( !$asset ) { print "Couldn't instantiate asset with ID '$assetId'. Please check package '$file' for corruption.\n"; next; diff --git a/docs/upgrades/upgrade_7.8.0-7.8.1.pl b/docs/upgrades/upgrade_7.8.0-7.8.1.pl index c18bcd7d0..b195e1110 100644 --- a/docs/upgrades/upgrade_7.8.0-7.8.1.pl +++ b/docs/upgrades/upgrade_7.8.0-7.8.1.pl @@ -79,7 +79,7 @@ sub addPackage { # Turn off the package flag, and set the default flag for templates added my $assetIds = $package->getLineage( ['self','descendants'] ); for my $assetId ( @{ $assetIds } ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); + my $asset = WebGUI::Asset->newById( $session, $assetId ); if ( !$asset ) { print "Couldn't instantiate asset with ID '$assetId'. Please check package '$file' for corruption.\n"; next; diff --git a/lib/WebGUI/Account.pm b/lib/WebGUI/Account.pm index 5727469bd..8dd0bdda0 100644 --- a/lib/WebGUI/Account.pm +++ b/lib/WebGUI/Account.pm @@ -482,9 +482,11 @@ sub processTemplate { return sprintf($i18n->get('Error: Cannot instantiate template'),$templateId,$className); } - $template = WebGUI::Asset->new($session, $templateId,"WebGUI::Asset::Template") unless (defined $template); + if (!defined $template) { + $template = eval { WebGUI::Asset->newById($session, $templateId); }; + } - unless (defined $template) { + if (Exception::Class->caught()) { $session->log->error("Can't instantiate template $templateId for class ".$className); my $i18n = WebGUI::International->new($session, 'Account'); return sprintf($i18n->get('Error: Cannot instantiate template'),$templateId,$className); diff --git a/lib/WebGUI/Account/Contributions.pm b/lib/WebGUI/Account/Contributions.pm index d5e38c671..6247c1d38 100644 --- a/lib/WebGUI/Account/Contributions.pm +++ b/lib/WebGUI/Account/Contributions.pm @@ -195,9 +195,13 @@ sub www_view { #Export page to template my @contribs = (); - foreach my $row ( @{$p->getPageData} ) { + ROW: foreach my $row ( @{$p->getPageData} ) { my $assetId = $row->{assetId}; - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); + my $asset = eval { WebGUI::Asset->newById( $session, $assetId ); }; + if (Exception::Class->caught()) { + $session->log->error("Unable to instanciate assetId $assetId: $@"); + next ROW; + } my $props = $asset->get; $props->{url} = $asset->getUrl; if (ref $asset eq "WebGUI::Asset::Post") { diff --git a/lib/WebGUI/Account/Shop.pm b/lib/WebGUI/Account/Shop.pm index 135f3bb73..ffd86e53d 100644 --- a/lib/WebGUI/Account/Shop.pm +++ b/lib/WebGUI/Account/Shop.pm @@ -267,11 +267,15 @@ sub www_viewSales { . q{ group by assetId order by quantity desc }, [ $vendor->getId ] ); - while (my $row = $sth->hashRef) { + ROW: while (my $row = $sth->hashRef) { my $data = $row; # Add asset properties to tmpl_vars. - my $asset = WebGUI::Asset->newByDynamicClass( $session, $row->{ assetId } ); + my $asset = eval { WebGUI::Asset->newById( $session, $row->{ assetId } ); }; + if (Exception::Class->caught()) { + $session->log->error('Unable to instanciate assetId '.$row->{ assetId }.": $@"); + next ROW; + } $row = { %{ $row }, %{ $asset->get } } if $asset; push @products, $row; diff --git a/lib/WebGUI/Asset.pm b/lib/WebGUI/Asset.pm index 195322ac3..2a80f9388 100644 --- a/lib/WebGUI/Asset.pm +++ b/lib/WebGUI/Asset.pm @@ -14,12 +14,339 @@ package WebGUI::Asset; =cut -use Carp qw( croak confess ); +use Carp; use Scalar::Util qw( blessed ); use Clone qw(clone); use JSON; use HTML::Packer; +use WebGUI::Definition::Asset; +aspect assetName => 'asset'; +aspect tableName => 'assetData'; +aspect icon => 'assets.gif'; +aspect uiLevel => 1; +property title => ( + tab => "properties", + label => ['99','Asset'], + hoverHelp => ['99 description','Asset'], + fieldType => 'text', + default => 'Untitled', + ); +around title => sub { + my $orig = shift; + my $self = shift; + if (@_ > 0) { + my $title = shift; + $title = WebGUI::HTML::filter($title, 'all'); + $title = $self->meta->find_attribute_by_name('title')->default if $title eq ''; + unshift @_, $title; + } + $self->$orig(@_); +}; + +property menuTitle => ( + tab => "properties", + label => ['411','Asset'], + hoverHelp => ['411 description','Asset'], + uiLevel => 1, + fieldType => 'text', + builder => '_default_menuTitle', + lazy => 1, + ); +sub _default_menuTitle { + my $self = shift; + return $self->title; +} +around menuTitle => sub { + my $orig = shift; + my $self = shift; + if (@_ > 0) { + my $title = shift; + $title = WebGUI::HTML::filter($title, 'all'); + $title = $self->_default_menuTitle if $title eq ''; + unshift @_, $title; + } + $self->$orig(@_); +}; + +property url => ( + tab => "properties", + label => ['104','Asset'], + hoverHelp => ['104 description','Asset'], + uiLevel => 3, + fieldType => 'text', + lazy => 1, + builder => '_default_url', + ); +sub _default_url { + return $_[0]->assetId; +} + +around url => sub { + my $orig = shift; + my $self = shift; + if (@_ > 0) { + my $url = $_[0]; + $url = $self->fixUrl($url); + unshift @_, $url; + } + $self->$orig(@_); +}; +property isHidden => ( + tab => "display", + label => ['886','Asset'], + hoverHelp => ['886 description','Asset'], + uiLevel => 6, + fieldType => 'yesNo', + default => 0, + ); +property newWindow => ( + tab => "display", + label => ['940','Asset'], + hoverHelp => ['940 description','Asset'], + uiLevel => 9, + fieldType => 'yesNo', + default => 0, + ); +property encryptPage => ( + fieldType => 'yesNo', + noFormPost => sub { return $_[0]->session->config->get("sslEnabled"); }, + tab => "security", + label => ['encrypt page','Asset'], + hoverHelp => ['encrypt page description','Asset'], + uiLevel => 6, + default => 0, + ); +property ownerUserId => ( + tab => "security", + label => ['108','Asset'], + hoverHelp => ['108 description','Asset'], + uiLevel => 6, + fieldType => 'user', + default => '3', + trigger => \&_set_ownerUserId, + ); +sub _set_ownerUserId { + return; +} +property groupIdView => ( + tab => "security", + label => ['872','Asset'], + hoverHelp => ['872 description','Asset'], + uiLevel => 6, + fieldType => 'group', + default => '7', + trigger => \&_set_groupIdView, + ); +sub _set_groupIdView { + return; +} +property groupIdEdit => ( + tab => "security", + label => ['871','Asset'], + excludeGroups => [1,7], + hoverHelp => ['871 description','Asset'], + uiLevel => 6, + fieldType => 'group', + default => '4', + trigger => \&_set_groupIdEdit, + ); +sub _set_groupIdEdit { + return; +} +property synopsis => ( + tab => "meta", + label => ['412','Asset'], + hoverHelp => ['412 description','Asset'], + uiLevel => 3, + fieldType => 'textarea', + default => undef, + ); +property extraHeadTags => ( + tab => "meta", + label => ["extra head tags",'Asset'], + hoverHelp => ['extra head tags description','Asset'], + uiLevel => 5, + fieldType => 'codearea', + default => undef, + customDrawMethod=> 'drawExtraHeadTags', + ); +around extraHeadTags => sub { + my $orig = shift; + my $self = shift; + if (@_ > 1) { + my $unpacked = $_[0]; + my $packed = $unpacked; ##Undo magic aliasing since a reference is passed below + HTML::Packer::minify( \$packed, { + remove_comments => 1, + remove_newlines => 1, + do_javascript => "shrink", + do_stylesheet => "minify", + } ); + $self->extraHeadTagsPacked($packed); + } + $self->$orig(@_); +}; +property extraHeadTagsPacked => ( + fieldType => 'hidden', + default => undef, + noFormPost => 1, + init_args => undef, + ); +property usePackedHeadTags => ( + tab => "meta", + label => ['usePackedHeadTags label','Asset'], + hoverHelp => ['usePackedHeadTags description','Asset'], + uiLevel => 7, + fieldType => 'yesNo', + default => 0, + ); +property isPackage => ( + label => ["make package",'Asset'], + tab => "meta", + hoverHelp => ['make package description','Asset'], + uiLevel => 7, + fieldType => 'yesNo', + default => 0, + ); +property isPrototype => ( + tab => "meta", + label => ["make prototype",'Asset'], + hoverHelp => ['make prototype description','Asset'], + uiLevel => 9, + fieldType => 'yesNo', + default => 0, + ); +property isExportable => ( + tab => 'meta', + label => ['make asset exportable','Asset'], + hoverHelp => ['make asset exportable description','Asset'], + uiLevel => 9, + fieldType => 'yesNo', + default => 1, + ); +property inheritUrlFromParent => ( + tab => 'meta', + label => ['does asset inherit URL from parent','Asset'], + hoverHelp => ['does asset inherit URL from parent description','Asset'], + uiLevel => 9, + fieldType => 'yesNo', + default => 0, + trigger => \&_set_inheritUrlFromParent, + ); +sub _set_inheritUrlFromParent { + my ($self, $new, $old) = @_; + if ($new && ($new != $old)) { + $self->url($self->url); + } +}; +property status => ( + noFormPost => 1, + fieldType => 'text', + default => 'pending', + ); +property lastModified => ( + noFormPost => 1, + fieldType => 'DateTime', + default => sub { return time() }, + ); +property assetSize => ( + noFormPost => 1, + fieldType => 'integer', + default => 0, + ); +property tagId => ( + noFormPost => 1, + fieldType => 'guid', + default => 0, + ); +has session => ( + is => 'ro', + required => 1, + ); +has assetId => ( + is => 'ro', + lazy => 1, + default => sub { shift->session->id->generate() }, + ); +has revisionDate => ( + is => 'rw', + ); +property revisedBy => ( + is => 'rw', + noFormPost => 1, + fieldType => 'guid', + ); +has [qw/parentId lineage + creationDate createdBy + state stateChanged stateChangedBy + isLockedBy isSystem lastExportedAs/] => ( + is => 'rw', + ); +has className => ( + is => 'ro', + builder => '_build_className', + lazy => 1, + init_arg => undef, + ); +sub _build_className { + my $self = shift; + return ref $self; +} + +around BUILDARGS => sub { + my $orig = shift; + my $className = shift; + + ##Original arguments start here. + if (ref $_[0] eq 'HASH') { + return $className->$orig(@_); + } + my $session = shift; + my $assetId = shift; + my $revisionDate = shift; + + unless ($assetId) { + WebGUI::Error::InvalidParam->throw(error => "Asset constructor new() requires an assetId."); + } + + if ( $revisionDate eq '' ) { + $revisionDate = $className->getCurrentRevisionDate( $session, $assetId ); + if ($revisionDate eq '') { + WebGUI::Error::InvalidParam->throw(error => "Cannot find revision date for assetId", param => $assetId); + } + } + + my $properties = eval{$session->cache->get(["asset",$assetId,$revisionDate])}; + unless (exists $properties->{assetId}) { # can we get it from cache? + my $sql = "select * from asset"; + my $where = " where asset.assetId=?"; + my $placeHolders = [$assetId]; + + # join all the tables + foreach my $table ($className->meta->get_tables) { + $sql .= ",".$table; + $where .= " and (asset.assetId=".$table.".assetId and ".$table.".revisionDate=".$revisionDate.")"; + } + + # fetch properties + $properties = $session->db->quickHashRef($sql.$where, $placeHolders); + unless (exists $properties->{assetId}) { + $session->errorHandler->error("Asset $assetId $className $revisionDate is missing properties. Consult your database tables for corruption. "); + return undef; + } + eval{ $session->cache->set(["asset",$assetId,$revisionDate], $properties, 60*60*24) }; + } + + if (defined $properties) { + $properties->{session} = $session; + return $className->$orig($properties); + } + $session->errorHandler->error("Something went wrong trying to instanciate a '$className' with assetId '$assetId', but I don't know what!"); + return undef; +}; + + use WebGUI::AssetBranch; use WebGUI::AssetClipboard; use WebGUI::AssetExportHtml; @@ -28,6 +355,7 @@ use WebGUI::AssetMetaData; use WebGUI::AssetPackage; use WebGUI::AssetTrash; use WebGUI::AssetVersioning; +use WebGUI::Exception; use strict; use Tie::IxHash; use WebGUI::AdminConsole; @@ -107,79 +435,6 @@ sub addMissing { return $ac->render($output); } -#------------------------------------------------------------------- - -=head2 assetDbProperties ( session, assetId, className, revisionDate ) - -Class method to return all properties in all tables used by a particular Asset. -Returns a hash ref with data from the table. - -=head3 session - -A reference to the current session. - -=head3 assetId - -The assetId of the asset you're creating an object reference for. Must not be blank. - -=head3 className - -By default we'll use whatever class it is called by like WebGUI::Asset::File->new(), so WebGUI::Asset::File would be used. - -=head3 revisionDate - -An epoch date that represents a specific version of an asset. - -=cut - -sub assetDbProperties { - my $class = shift; - my $session = shift; - my ($assetId, $className, $revisionDate) = @_; - my $sql = "select * from asset"; - my $where = " where asset.assetId=?"; - my $placeHolders = [$assetId]; - foreach my $definition (@{$className->definition($session)}) { - $sql .= ",".$definition->{tableName}; - $where .= " and (asset.assetId=".$definition->{tableName}.".assetId and ".$definition->{tableName}.".revisionDate=".$revisionDate.")"; - } - return $session->db->quickHashRef($sql.$where, $placeHolders); -} - -#------------------------------------------------------------------- - -=head2 assetExists ( session, assetId, className, revisionDate ) - -Class method that checks to see if an asset exists in all the proper tables for -the requested asset class. Returns true or false. - -=head3 session - -A reference to the current session. - -=head3 assetId - -The assetId of the asset you're creating an object reference for. Must not be blank. - -=head3 className - -By default we'll use whatever class it is called by like WebGUI::Asset::File->new(), so WebGUI::Asset::File would be used. - -=head3 revisionDate - -An epoch date that represents a specific version of an asset. - -=cut - -sub assetExists { - my $class = shift; - my $session = shift; - my ($assetId, $className, $revisionDate) = @_; - my $dbProperties = $class->assetDbProperties($session, $assetId, $className, $revisionDate); - return exists $dbProperties->{assetId}; -} - - #------------------------------------------------------------------- =head2 canAdd ( session, [userId, groupId] ) @@ -356,207 +611,12 @@ Returns the new Asset object. sub cloneFromDb { my $self = shift; - return WebGUI::Asset->new($self->session, + return WebGUI::Asset->newById($self->session, $self->getId, - $self->get('className'), - $self->get('revisionDate') + $self->revisionDate ); } -#------------------------------------------------------------------- - -=head2 definition ( session, [ definition ] ) - -Basic definition of an Asset. Properties, default values. Returns an array reference containing tableName,className,properties - -=head3 session - -The current session object. - -=head3 definition - -An array reference containing additional information to include with the default definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift || []; - my $i18n = WebGUI::International->new($session, "Asset"); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - title=>{ - tab=>"properties", - label=>$i18n->get(99), - hoverHelp=>$i18n->get('99 description'), - fieldType=>'text', - defaultValue=>'Untitled', - filter=>'fixTitle', - }, - menuTitle=>{ - tab=>"properties", - label=>$i18n->get(411), - hoverHelp=>$i18n->get('411 description'), - uiLevel=>1, - fieldType=>'text', - filter=>'fixTitle', - defaultValue=>'Untitled', - }, - url=>{ - tab=>"properties", - label=>$i18n->get(104), - hoverHelp=>$i18n->get('104 description'), - uiLevel=>3, - fieldType=>'text', - defaultValue=>'', - filter=>'fixUrl', - }, - isHidden=>{ - tab=>"display", - label=>$i18n->get(886), - hoverHelp=>$i18n->get('886 description'), - uiLevel=>6, - fieldType=>'yesNo', - defaultValue=>0, - }, - newWindow=>{ - tab=>"display", - label=>$i18n->get(940), - hoverHelp=>$i18n->get('940 description'), - uiLevel=>9, - fieldType=>'yesNo', - defaultValue=>0, - }, - encryptPage=>{ - fieldType => ($session->config->get("sslEnabled") ? 'yesNo' : 'hidden'), - tab => "security", - label => $i18n->get('encrypt page'), - hoverHelp => $i18n->get('encrypt page description'), - uiLevel => 6, - defaultValue => 0, - }, - ownerUserId=>{ - tab=>"security", - label=>$i18n->get(108), - hoverHelp=>$i18n->get('108 description'), - uiLevel=>6, - fieldType=>'user', - filter=>'fixId', - defaultValue=>'3', - }, - groupIdView=>{ - tab=>"security", - label=>$i18n->get(872), - hoverHelp=>$i18n->get('872 description'), - uiLevel=>6, - fieldType=>'group', - filter=>'fixId', - defaultValue=>'7', - }, - groupIdEdit=>{ - tab=>"security", - label=>$i18n->get(871), - excludeGroups=>[1,7], - hoverHelp=>$i18n->get('871 description'), - uiLevel=>6, - fieldType=>'group', - filter=>'fixId', - defaultValue=>'4', - }, - synopsis=>{ - tab=>"meta", - label=>$i18n->get(412), - hoverHelp=>$i18n->get('412 description'), - uiLevel=>3, - fieldType=>'textarea', - defaultValue=>undef, - }, - extraHeadTags=>{ - tab=>"meta", - label=>$i18n->get("extra head tags"), - hoverHelp=>$i18n->get('extra head tags description'), - uiLevel=>5, - fieldType=>'codearea', - defaultValue=>undef, - customDrawMethod => 'drawExtraHeadTags', - filter => 'packExtraHeadTags', - }, - extraHeadTagsPacked => { - fieldType => 'hidden', - defaultValue => undef, - noFormPost => 1, - }, - usePackedHeadTags => { - tab => "meta", - label => $i18n->get('usePackedHeadTags label'), - hoverHelp => $i18n->get('usePackedHeadTags description'), - uiLevel => 7, - fieldType => 'yesNo', - defaultValue => 0, - }, - isPackage=>{ - label=>$i18n->get("make package"), - tab=>"meta", - hoverHelp=>$i18n->get('make package description'), - uiLevel=>7, - fieldType=>'yesNo', - defaultValue=>0, - }, - isPrototype=>{ - tab=>"meta", - label=>$i18n->get("make prototype"), - hoverHelp=>$i18n->get('make prototype description'), - uiLevel=>9, - fieldType=>'yesNo', - defaultValue=>0, - }, - isExportable=>{ - tab=>'meta', - label=>$i18n->get('make asset exportable'), - hoverHelp=>$i18n->get('make asset exportable description'), - uiLevel=>9, - fieldType=>'yesNo', - defaultValue=>1, - }, - inheritUrlFromParent=>{ - tab=>'meta', - label=>$i18n->get('does asset inherit URL from parent'), - hoverHelp=>$i18n->get('does asset inherit URL from parent description'), - uiLevel=>9, - fieldType=>'yesNo', - defaultValue=>0, - }, - status=>{ - noFormPost=>1, - fieldType=>'hidden', - defaultValue=>'pending', - }, - lastModified=>{ - noFormPost=>1, - fieldType=>'hidden', - defaultValue=>time(), - }, - assetSize=>{ - noFormPost=>1, - fieldType=>'hidden', - defaultValue=>0, - }, - ); - push(@{$definition}, { - assetName=>$i18n->get("asset"), - tableName=>'assetData', - autoGenerateForms=>1, - className=>'WebGUI::Asset', - icon=>'assets.gif', - properties=>\%properties - } - ); - return $definition; -} - - #------------------------------------------------------------------- =head2 drawExtraHeadTags ( ) @@ -598,58 +658,19 @@ sub DESTROY { #------------------------------------------------------------------- -=head2 fixId ( id, fieldName ) +=head2 extraHeadTags ( value ) -Returns the default Id for a field if we get an invalid Id, otherwise returns the id passed in. An valid id either looks like a GUID or is an integer. +Returns extraHeadTags -=head3 id +=head3 value -The id to check. - -=head3 fieldName - -The name of the property we're checking. This is used to retrieve whatever the default is set to in the definition. +If specified, stores it, but also updates extraHeadTagsPacked with the packed version. =cut -sub fixId { - my $self = shift; - my $id = shift; - my $field = shift; - if ($id =~ m/\A \d{1,22} \z/xms || $id =~ m/\A [A-Za-z0-9\-\_]{22} \z/xms) { - return $id; - } - return $self->getValue($field); -} - - #------------------------------------------------------------------- -=head2 fixTitle ( string ) - -Fixes a title by eliminating HTML from it. - -=head3 string - -Any text string. Most likely will have been the Asset's name or title. If -no string is supplied, then it will fetch the default title for the asset, -or the word Untitled. - -=cut - -sub fixTitle { - my $self = shift; - my $string = shift; - if (lc($string) eq "untitled" || $string eq "") { - $string = $self->getValue("title") || 'Untitled'; - } - return WebGUI::HTML::filter($string, 'all'); -} - - -#------------------------------------------------------------------- - -=head2 fixUrl ( url ) +=head2 fixUrl ( [value] ) Returns a URL, removing invalid characters and making it unique by adding a digit to the end if necessary. URLs are not allowed to be @@ -663,7 +684,7 @@ Assets have a maximum length of 250 characters. Any URL longer than URLs will be passed through $session->url->urlize to make them WebGUI compliant. That includes any languages specific constraints set up in the default language pack. -=head3 url +=head3 value Any text string. Most likely will have been the Asset's name or title. If the string is not passed in, then a url will be constructed from @@ -676,14 +697,18 @@ sub fixUrl { # build a URL from the parent unless ($url) { - $url = $self->getParent->get("url"); + $url = $self->getParent->url; $url =~ s/(.*)\..*/$1/; - $url .= '/'.$self->getValue("menuTitle"); + $url .= '/'.$self->menuTitle; } # if we're inheriting the URL from our parent, set that appropriately - if($self->get('inheritUrlFromParent')) { - $url = $self->fixUrlFromParent($url); + if ($self->inheritUrlFromParent) { + # if we're inheriting the URL from our parent, set that appropriately + my @parts = split(m{/}, $url); + # don't do anything unless we need to + my $inheritUrl = $self->getParent->get('url') . '/' . $parts[-1]; + $url = $inheritUrl if $url ne $inheritUrl; } $url = $self->session->url->urlize($url); @@ -746,67 +771,6 @@ sub fixUrl { } -#------------------------------------------------------------------- - -=head2 fixUrlFromParent ( url ) - -URLs will be passed through $session->url->urlize to make them WebGUI compliant. -That includes any languages specific constraints set up in the default language pack. - -=head3 url - -Any text string. - -=cut - -sub fixUrlFromParent { - my $self = shift; - my $url = shift; - - # if we're inheriting the URL from our parent, set that appropriately - my @parts = split(m{/}, $url); - - # don't do anything unless we need to - if($url ne $self->getParent->get('url') . '/' . $parts[-1]) { - $url = $self->getParent->get('url') . '/' . $parts[-1]; - } - - return $url; -} - - -#------------------------------------------------------------------- - -=head2 get ( [propertyName] ) - -Returns a reference to a list of properties (or specified property) of an Asset. - -If C is omitted, it will return a safe copy of the entire property hash. - -=head3 propertyName - -Any of the values associated with the properties of an Asset. Default choices are "title", "menutTitle", -"synopsis", "url", "groupIdEdit", "groupIdView", "ownerUserId", "keywords", and "assetSize". - -=cut - -sub get { - my $self = shift; - my $propertyName = shift; - if (defined $propertyName) { - if ($propertyName eq "keywords") { - return WebGUI::Keyword->new($self->session)->getKeywordsForAsset({asset => $self}); - } - return $self->{_properties}{$propertyName}; - } - my %copyOfHashRef = %{$self->{_properties}}; - my $keywords = WebGUI::Keyword->new($self->session)->getKeywordsForAsset({asset => $self}); - if( $keywords ne '' ) { $copyOfHashRef{ keywords } = $keywords ; } - return \%copyOfHashRef; -} - - - #------------------------------------------------------------------- =head2 getAdminConsole ( ) @@ -825,6 +789,49 @@ sub getAdminConsole { } +#------------------------------------------------------------------- + +=head2 getClassById ( $session, $assetId ) + +Class method that looks up a className for an object in the database, using it's assetId. + +If a class cannot be found for the requested assetId, then it throws a WebGUI::Error::InvalidParam +exception. + +=head3 $session + +A WebGUI::Session object. + +=head3 $assetId + +The assetId of the object to lookup in the database. + +=cut + +sub getClassById { + my $class = shift; + my $session = shift; + my $assetId = shift; + # Cache the className lookup + my $assetClass = $session->stow->get("assetClass"); + my $className = $assetClass->{$assetId}; + + return $className if $className; + + $className = $session->db->quickScalar( + "select className from asset where assetId=?", + [$assetId] + ); + $assetClass->{ $assetId } = $className; + $session->stow->set("assetClass", $assetClass); + + return $className if $className; + + WebGUI::Error::InvalidParam->throw(error => "Couldn't lookup className", param => $assetId); + +} + + #------------------------------------------------------------------- =head2 getContainer ( ) @@ -858,7 +865,7 @@ A reference to the current session. sub getDefault { my $class = shift; my $session = shift; - return $class->newByDynamicClass($session, $session->setting->get("defaultPage")); + return $class->newById($session, $session->setting->get("defaultPage")); } @@ -960,39 +967,34 @@ sub getEditForm { } # build the definition to the generate form - my @definitions = reverse @{$self->definition($session)}; - tie my %baseProperties, 'Tie::IxHash'; - %baseProperties = ( + my @properties = ( assetId => { fieldType => "guid", - label => $i18n->get("asset id"), + label => ["asset id",'Asset'], value => $assetId, - hoverHelp => $i18n->get('asset id description'), + hoverHelp => ['asset id description','Asset'], uiLevel => 9, tab => "meta", }, class => { fieldType => "className", - label => $i18n->get("class name",'WebGUI'), + label => ["class name",'WebGUI'], value => $class, uiLevel => 9, tab => "meta", }, keywords => { - label => $i18n->get('keywords'), - hoverHelp => $i18n->get('keywords help'), + label => ['keywords','Asset'], + hoverHelp => ['keywords help','Asset'], value => $self->get('keywords'), fieldType => 'keywords', tab => 'meta', - } + }, ); - unshift @definitions, { - autoGenerateForms => 1, - properties => \%baseProperties - }; + foreach my $property ($self->getProperties) { + push @properties, $property => $self->getProperty($property); + } - # extend the definition with metadata - tie my %extendedProperties, 'Tie::IxHash'; if ($session->setting->get("metaDataEnabled")) { my $meta = $self->getMetaDataFields(); foreach my $field (keys %$meta) { @@ -1003,7 +1005,7 @@ sub getEditForm { if("\l$fieldType" eq "selectBox") { $options = "|" . $i18n->get("Select") . "\n" . $options; } - $extendedProperties{"metadata_".$meta->{$field}{fieldId}} = { + push @properties, "metadata_".$meta->{$field}{fieldId} => { tab => "meta", label => $meta->{$field}{fieldName}, uiLevel => 5, @@ -1016,7 +1018,7 @@ sub getEditForm { } # add metadata management if ($session->user->isAdmin) { - $extendedProperties{_metadatamanagement} = { + push @properties, '_metadatamanagement' => { tab => "meta", fieldType => "readOnly", value => '

'.$i18n->get('Add new field').'

', @@ -1024,55 +1026,32 @@ sub getEditForm { }; } } - push @definitions, { - autoGenerateForms => 1, - properties => \%extendedProperties - }; # generate the form - foreach my $definition (@definitions) { - my $properties = $definition->{properties}; - - # depricated...by WebGUI 8 they all must autogen forms - next unless ($definition->{autoGenerateForms}); + for (my $i = 0; $i < @properties; $i += 2) { + my $fieldName = $properties[$i]; + my %fieldHash = %{$properties[$i+1]}; + my %params = (name => $fieldName, value => $self->get($fieldName)); - foreach my $fieldName (keys %{$properties}) { - my %fieldHash = %{$properties->{$fieldName}}; - my %params = (name => $fieldName, value => $self->getValue($fieldName)); - next if exists $fieldHash{autoGenerate} and not $fieldHash{autoGenerate}; - - # apply config file changes - foreach my $key (keys %{$overrides->{fields}{$fieldName}}) { - $fieldHash{$key} = $overrides->{fields}{$fieldName}{$key}; - } - - # Kludge. - if (isIn($fieldHash{fieldType}, 'selectBox', 'workflow') and ref $params{value} ne 'ARRAY') { - $params{value} = [$params{value}]; - } - - if (exists $fieldHash{visible} and not $fieldHash{visible}) { - $params{fieldType} = 'hidden'; - } - else { - %params = (%params, %fieldHash); - delete $params{tab}; - } - - # if there isnt a tab specified lets define one - my $tab = $fieldHash{tab} || "properties"; - - # use a custom draw method - my $drawMethod = $properties->{$fieldName}{customDrawMethod}; - if ($drawMethod) { - $params{value} = $self->$drawMethod(\%params); - delete $params{name}; # don't want readOnly to generate a hidden field - $params{fieldType} = "readOnly"; - } - - #draw the field - $tabform->getTab($tab)->dynamicField(%params); + # apply config file changes + foreach my $key (keys %{$overrides->{fields}{$fieldName}}) { + $fieldHash{$key} = $overrides->{fields}{$fieldName}{$key}; } + + # Kludge. + if (isIn($fieldHash{fieldType}, 'selectBox', 'workflow') and ref $params{value} ne 'ARRAY') { + $params{value} = [$params{value}]; + } + + %params = (%fieldHash, %params); + delete $params{tab}; + delete $params{tableName}; + + # if there isnt a tab specified lets define one + my $tab = $fieldHash{tab} || "properties"; + + #draw the field + $tabform->getTab($tab)->dynamicField(%params); } # send back the rendered form @@ -1157,10 +1136,8 @@ If this evaluates to True, then the smaller extras/adminConsole/small/assets.gif =cut sub getIcon { - my $self = shift; - my $small = shift; - my $definition = $self->definition($self->session); - my $icon = $definition->[0]{icon} || "assets.gif"; + my ($self, $small) = @_; + my $icon = $self->icon; return $self->session->url->extras('assets/small/'.$icon) if ($small); return $self->session->url->extras('assets/'.$icon); } @@ -1176,7 +1153,7 @@ Returns the assetId of an Asset. sub getId { my $self = shift; - return $self->get("assetId"); + return $self->assetId; } #------------------------------------------------------------------- @@ -1194,7 +1171,7 @@ A reference to the current session. sub getImportNode { my $class = shift; my $session = shift; - return WebGUI::Asset->newByDynamicClass($session, "PBasset000000000000002"); + return WebGUI::Asset->newById($session, "PBasset000000000000002"); } @@ -1226,11 +1203,8 @@ returning results. This allows very large sets of results to be handled in chun =cut sub getIsa { - my $class = shift; - my $session = shift; - my $offset = shift; - my $def = $class->definition($session); - my $tableName = $def->[0]->{tableName}; + my ($class, $session, $offset) = @_; + my $tableName = $class->tableName; my $sql = "select distinct(assetId) from $tableName"; if (defined $offset) { $sql .= ' LIMIT '. $offset . ',1234567890'; @@ -1277,7 +1251,7 @@ A reference to the current session. sub getMedia { my $class = shift; my $session = shift; - return WebGUI::Asset->newByDynamicClass($session, "PBasset000000000000003"); + return WebGUI::Asset->newById($session, "PBasset000000000000003"); } @@ -1302,14 +1276,13 @@ sub getMenuTitle { =head2 getName ( ) -Returns the internationalization of the word "Asset". +Returns the human readable name of the asset. =cut sub getName { my $self = shift; - my $definition = $self->definition($self->session); - return $definition->[0]{assetName}; + return WebGUI::International->new($self->session, 'Asset')->get(@{ $self->assetName }); } @@ -1328,7 +1301,7 @@ A reference to the current session. sub getNotFound { my $class = shift; my $session = shift; - return WebGUI::Asset->newByDynamicClass($session, $session->setting->get("notFoundPage")); + return WebGUI::Asset->newById($session, $session->setting->get("notFoundPage")); } @@ -1348,7 +1321,7 @@ sub getPrototypeList { my $userUiLevel = $session->user->profileField('uiLevel'); my @assets; ID: foreach my $id (@prototypeIds) { - my $asset = WebGUI::Asset->newByDynamicClass($session, $id); + my $asset = WebGUI::Asset->newById($session, $id); next ID unless defined $asset; next ID unless $asset->get('isPrototype'); next ID unless ($asset->get('status') eq 'approved' || $asset->get('tagId') eq $session->scratch->get("versionTag")); @@ -1373,7 +1346,7 @@ A reference to the current session. sub getRoot { my $class = shift; my $session = shift; - return WebGUI::Asset->new($session, "PBasset000000000000001"); + return WebGUI::Asset->newById($session, "PBasset000000000000001"); } @@ -1409,7 +1382,7 @@ A reference to the current session. sub getTempspace { my $class = shift; my $session = shift; - return WebGUI::Asset->newByDynamicClass($session, "tempspace0000000000000"); + return WebGUI::Asset->newById($session, "tempspace0000000000000"); } @@ -1423,10 +1396,11 @@ Returns the title of this asset. If it's not specified or it's "Untitled" then t sub getTitle { my $self = shift; - if ($self->get("title") eq "" || lc($self->get("title")) eq "untitled") { + my $title = $self->title; + if ($title eq "" || lc($title) eq "untitled") { return $self->getName; } - return $self->get("title"); + return $title; } @@ -1571,7 +1545,7 @@ sub getUiLevel { my $className = $self->get("className"); return $uiLevel # passed in || $self->session->config->get("assets/".$className."/uiLevel") # from config - || $self->definition($self->session)->[0]{uiLevel} # from definition + || $self->uiLevel # from definition || 1; # if all else fails } @@ -1593,9 +1567,9 @@ Name value pairs to add to the URL in the form of: sub getUrl { my $self = shift; my $params = shift; - my $url = $self->get("url"); + my $url = $self->url; $url = $self->session->url->gateway($url,$params); - if ($self->get("encryptPage")) { + if ($self->encryptPage) { $url = $self->session->url->getSiteURL().$url; $url =~ s/http:/https:/; } @@ -1619,40 +1593,6 @@ sub getContentLastModified { } -#------------------------------------------------------------------- - -=head2 getValue ( key ) - -Tries to look up C in the asset object's property cache. If it can't find it in there, then it -tries to look it up in the definition sub for the asset. - -Unlike get, it will not return the whole property hash if you omit the key. - -=head3 key - -An asset property name, or a propertyDefinition. - -=cut - -sub getValue { - my $self = shift; - my $key = shift; - if (defined $key) { - my $storedValue = $self->get($key); - return $storedValue if (defined $storedValue); - unless (exists $self->{_propertyDefinitions}) { # check to see if the definitions have been merged and cached - my %properties; - foreach my $definition (@{$self->definition($self->session)}) { - %properties = (%properties, %{$definition->{properties}}); - } - $self->{_propertyDefinitions} = \%properties; - } - return $self->{_propertyDefinitions}{$key}{defaultValue}; - } - return undef; -} - - #------------------------------------------------------------------- =head2 indexContent ( ) @@ -1683,22 +1623,29 @@ sub isValidRssItem { 1 } #------------------------------------------------------------------- -=head2 loadModule ( $session, $className ) +=head2 loadModule ( $className ) -Loads an asset module if it's not already in memory. This is a class method. Returns undef on failure to load, otherwise returns the classname. Will only load classes in the WebGUI::Asset namespace. +Loads an asset module if it's not already in memory. This is a class method. Returns +undef on failure to load, otherwise returns the classname. Will only load classes +in the WebGUI::Asset namespace. + +Throws a WebGUI::Invalid::Param error if a non-WebGUI::Asset class is requested to be +loaded. If there are compilation problems, it will throw a WebGUI::Error::Compile +exception. =cut sub loadModule { - my ($class, $session, $className) = @_; + my ($class, $className) = @_; if ($className !~ /^WebGUI::Asset(?:::\w+)*$/ ) { - return undef; + WebGUI::Error::InvalidParam->throw(param => $className, error => "Not a WebGUI::Asset class",); } (my $module = $className . '.pm') =~ s{::}{/}g; if (eval { require $module; 1 }) { return $className; } - $session->errorHandler->error("Couldn't compile asset package: ".$className.". Root cause: ".$@); + + WebGUI::Error::Compile->throw(class => $className, cause => $@); return undef; } @@ -1722,9 +1669,45 @@ sub logView { #------------------------------------------------------------------- -=head2 new ( session, assetId [, className, revisionDate ] ) +=head2 title ( [value] ) -Constructor. This does not create an asset. +Returns the title of the asset. + +=head3 value + +If specified this value will be used to set the title after it goes through some validation checking. + +=cut + +#------------------------------------------------------------------- + +=head2 menuTitle ( [value] ) + +Returns the menuTitle of the asset, which is used in navigations. + +=head3 value + +If specified this value will be used to set the title after it goes through some validation checking. + +=cut + +#------------------------------------------------------------------- + +=head2 new ( propertyHashRef ) + +Asset Constructor. This does not create an asset in the database, or look up +properties in the database, but creates a WebGUI::Asset object. + +=head3 propertyHashRef + +A hash reference of properties to assign to the object. + +=cut + +=head2 new ( session, assetId [,revisionDate ] ) + +Instanciator. This does not create an asset in the database, but looks up the object's +properties in the database and returns an object with the correct WebGUI::Asset subclass. =head3 session @@ -1734,10 +1717,6 @@ A reference to the current session. The assetId of the asset you're creating an object reference for. Must not be blank. -=head3 className - -By default we'll use whatever class it is called by like WebGUI::Asset::File->new(), so WebGUI::Asset::File would be used. - =head3 revisionDate An epoch date that represents a specific version of an asset. By default the most recent version will be used. If @@ -1745,69 +1724,11 @@ no revision date is available it will return undef. =cut -sub new { - my $class = shift; - my $session = shift; - my $assetId = shift; - my $className = shift; - my $revisionDate = shift; - - unless (defined $assetId) { - $session->errorHandler->error("Asset constructor new() requires an assetId."); - return undef; - } - - if ($class eq 'WebGUI::Asset' && !$className) { - ($className) = $session->db->quickArray("select className from asset where assetId=?", [$assetId]); - unless ($className) { - $session->errorHandler->error("Couldn't instantiate asset: ".$assetId. ": couldn't find class name"); - return undef; - } - } - - if ($className) { - $class = $class->loadModule($session, $className); - return undef unless (defined $class); - } - - if ( !$revisionDate ) { - $revisionDate = $className - ? $className->getCurrentRevisionDate( $session, $assetId ) - : $class->getCurrentRevisionDate( $session, $assetId ); - return undef unless $revisionDate; - } - - my $properties = eval{$session->cache->get(["asset",$assetId,$revisionDate])}; - unless (exists $properties->{assetId}) { - $properties = WebGUI::Asset->assetDbProperties($session, $assetId, $class, $revisionDate); - unless (exists $properties->{assetId}) { - $session->errorHandler->error("Asset $assetId $class $revisionDate is missing properties. Consult your database tables for corruption. "); - return undef; - } - eval{ $session->cache->set(["asset",$assetId,$revisionDate], $properties, 60*60*24) }; - } - - if (defined $properties) { - my $object = { _session=>$session, _properties => $properties }; - bless $object, $class; - foreach my $definition (@{ $object->definition($session) }) { - foreach my $property (keys %{ $definition->{properties} }) { - if ($definition->{properties}->{$property}->{serialize} && $object->{_properties}->{$property} ne '') { - $object->{_properties}->{$property} = JSON->new->canonical->decode($object->{_properties}->{$property}); - } - } - } - return $object; - } - $session->errorHandler->error("Something went wrong trying to instanciate a '$className' with assetId '$assetId', but I don't know what!"); - return undef; -} - #------------------------------------------------------------------- -=head2 newByDynamicClass ( session, assetId [ , revisionDate ] ) +=head2 newById ( session, assetId [ , revisionDate ] ) -Instances an existing Asset, by looking up the classname of the asset specified by the assetId, and then calling new. +Instances an existing Asset, by looking up the className of the asset specified by the assetId, and then calling new. Returns undef if it can't find the classname. =head3 session @@ -1816,49 +1737,29 @@ A reference to the current session. =head3 assetId -Must be a valid assetId +Must be a valid assetId. + +Throws a WebGUI::Error::InvalidParam exception if the assetId is not passed. =head3 revisionDate -A specific revision date for the asset to retrieve. If not specified, the most recent one will be used. +An optional, specific revision date for the asset to retrieve. If not specified, the most recent one will be used. =cut -sub newByDynamicClass { - my $class = shift; +sub newById { + my $requestedClass = shift; my $session = shift; my $assetId = shift; + if (!$assetId) { + WebGUI::Error::InvalidParam->throw(error => 'newById must get an assetId'); + } my $revisionDate = shift; - -# Some code requires that these situations not die. -# confess "newByDynamicClass requires WebGUI::Session" -# unless $session && blessed $session eq 'WebGUI::Session'; -# confess "newByDynamicClass requires assetId" -# unless $assetId; -# So just return instead - return undef unless ( $session && blessed $session eq 'WebGUI::Session' ) - && $assetId; - # Cache the className lookup - my $assetClass = $session->stow->get("assetClass"); - my $className = $assetClass->{$assetId}; + my $className = WebGUI::Asset->getClassById($session, $assetId); + my $class = WebGUI::Asset->loadModule($className); - unless ($className) { - $className - = $session->db->quickScalar( - "select className from asset where assetId=?", - [$assetId] - ); - $assetClass->{ $assetId } = $className; - $session->stow->set("assetClass", $assetClass); - } - - unless ( $className ) { - $session->errorHandler->error("Couldn't find className for asset '$assetId'"); - return undef; - } - - return WebGUI::Asset->new($session,$assetId,$className,$revisionDate); + return $class->new($session, $assetId, $revisionDate); } @@ -1866,7 +1767,10 @@ sub newByDynamicClass { =head2 newByPropertyHashRef ( session, properties ) -Constructor. This creates a standalone asset with no parent. It does not update the database. +Constructor. This is a class method. It creates a standalone asset with no parent, with a +varying class, determined by the className entry in the properties hash ref. + +The object created is not persisted to the database. =head3 session @@ -1874,19 +1778,20 @@ A reference to the current session. =head3 properties -A properties hash reference. The className of the properties hash must be valid. +A hash reference of Asset properties. =cut sub newByPropertyHashRef { - my $class = shift; - my $session = shift; - my $properties = shift; - return undef unless defined $properties; - return undef unless exists $properties->{className}; - my $className = $class->loadModule($session, $properties->{className}); + my $class = shift; + my $session = shift; + my $properties = shift || {}; + $properties->{className} //= $class; + $properties->{session} = $session; + my $className = $class->loadModule($properties->{className}); return undef unless (defined $className); - bless {_session=>$session, _properties => $properties}, $className; + my $object = $className->new($properties); + return $object; } #------------------------------------------------------------------- @@ -1912,23 +1817,20 @@ A specific revision to instanciate. By default we instanciate the newest publish =cut sub newByUrl { - my $class = shift; - my $session = shift; - my $url = shift || $session->url->getRequestedUrl; + my $class = shift; + my $session = shift; + my $url = shift || $session->url->getRequestedUrl; my $revisionDate = shift; - $url = lc($url); + $url = lc($url); $url =~ s/\/$//; $url =~ s/^\///; - $url =~ s/\'//; - $url =~ s/\"//; + $url =~ tr/'"//d; if ($url ne "") { - my ($id, $class) = $session->db->quickArray("select asset.assetId, asset.className from assetData join asset using (assetId) where assetData.url = ? limit 1", [ $url ]); - if ($id ne "" || $class ne "") { - return WebGUI::Asset->new($session,$id, $class, $revisionDate); - } else { - $session->errorHandler->warn("The URL $url was requested, but does not exist in your asset tree."); - return undef; - } + my ($id) = $session->db->quickArray("select assetId from assetData where url = ? limit 1", [ $url ]); + if (!$id) { + WebGUI::Error::ObjectNotFound->throw(error => "The URL was requested, but does not exist in your asset tree.", id => $url); + } + return WebGUI::Asset->newById($session, $id, $revisionDate); } return WebGUI::Asset->getDefault($session); } @@ -1945,24 +1847,25 @@ A reference to the current session. =head3 assetId -The asset's id +The asset's id. If an assetId is not passed, throws a WebGUI::Error::InvalidParam exception. If +a revision cannot be found for the requested assetId, then it throws a WebGUI::Error::InvalidParam +exception. =cut sub newPending { - my $class = shift; + my $class = shift; my $session = shift; my $assetId = shift; - croak "First parameter to newPending needs to be a WebGUI::Session object" - unless $session && $session->isa('WebGUI::Session'); - croak "Second parameter to newPending needs to be an assetId" - unless $assetId; - my ($className, $revisionDate) = $session->db->quickArray("SELECT asset.className, assetData.revisionDate FROM asset INNER JOIN assetData ON asset.assetId = assetData.assetId WHERE asset.assetId = ? ORDER BY assetData.revisionDate DESC LIMIT 1", [ $assetId ]); - if ($className ne "" || $revisionDate ne "") { - return WebGUI::Asset->new($session, $assetId, $className, $revisionDate); + if (!$assetId) { + WebGUI::Error::InvalidParam->throw(error => 'newPending must get an assetId'); + } + my $revisionDate = $session->db->quickScalar("SELECT revisionDate FROM assetData WHERE assetId = ? ORDER BY revisionDate DESC LIMIT 1", [ $assetId ]); + if ($revisionDate ne "") { + return WebGUI::Asset->newById($session, $assetId, $revisionDate); } else { - croak "Invalid asset id '$assetId' requested!"; + WebGUI::Error::InvalidParam->throw(error => "Couldn't lookup revisionDate", param => $assetId); } } @@ -2107,29 +2010,6 @@ OUTPUT #------------------------------------------------------------------- -=head2 packExtraHeadTags ( unpacked ) - -Pack the extra head tags. Return the unpacked head tags (as per -filter guidelines). - -=cut - -sub packExtraHeadTags { - my ( $self, $unpacked ) = @_; - return $unpacked if !$unpacked; - my $packed = $unpacked; - HTML::Packer::minify( \$packed, { - remove_comments => 1, - remove_newlines => 1, - do_javascript => "shrink", - do_stylesheet => "minify", - } ); - $self->update({ extraHeadTagsPacked => $packed }); - return $unpacked; -} - -#------------------------------------------------------------------- - =head2 prepareView ( ) Executes what is necessary to make the view() method work with content chunking. @@ -2188,33 +2068,31 @@ sub processPropertiesFromFormPost { my $form = $self->session->form; my $overrides = $self->session->config->get("assets/".$self->get("className")."/fields"); - foreach my $definition (@{$self->definition($self->session)}) { - foreach my $property (keys %{$definition->{properties}}) { - my %params = %{$definition->{properties}{$property}}; + foreach my $property ($self->getProperties) { + my %params = %{$self->getProperty($property)}; - # apply config file changes - foreach my $key (keys %{$overrides->{$property}}) { - $params{$key} = $overrides->{$property}{$key}; - } - - # deal with properties that can't be posted through the form - if ($params{noFormPost}) { - if ($form->process("assetId") eq "new" && $self->get($property) eq "") { - $data{$property} = $params{defaultValue}; - } - next; - } - - # process the form element - $params{name} = $property; - $params{value} = $self->get($property); - $data{$property} = $form->process( - $property, - $params{fieldType}, - $params{defaultValue}, - \%params - ); + # apply config file changes + foreach my $key (keys %{$overrides->{$property}}) { + $params{$key} = $overrides->{$property}{$key}; } + + # deal with properties that can't be posted through the form + if ($params{noFormPost}) { + if ($form->process("assetId") eq "new" && $self->get($property) eq "") { + $data{$property} = $params{defaultValue}; + } + next; + } + + # process the form element + $params{name} = $property; + $params{value} = $self->get($property); + $data{$property} = $form->process( + $property, + $params{fieldType}, + $params{defaultValue}, + \%params + ); } $data{keywords} = $form->process("keywords"); if ($self->session->setting->get("metaDataEnabled")) { @@ -2263,12 +2141,12 @@ sub processTemplate { $self->session->errorHandler->error("First argument to processTemplate() should be a hash reference."); return "Error: Can't process template for asset ".$self->getId." of type ".$self->get("className"); } - $template = WebGUI::Asset->new($self->session, $templateId,"WebGUI::Asset::Template") unless (defined $template); - if (defined $template) { + $template = eval { WebGUI::Asset->newById($self->session, $templateId) unless (defined $template); }; + if (! Exception::Class->caught() ) { $var = { %{ $var }, %{ $self->getMetaDataAsTemplateVariables } }; $var->{'controls'} = $self->getToolbar if $self->session->var->isAdminOn; my %vars = ( - %{$self->{_properties}}, + %{$self->get}, 'title' => $self->getTitle, 'menuTitle' => $self->getMenuTitle, %{$var}, @@ -2342,12 +2220,12 @@ sub publish { $self->session->db->write("update asset set state='published', stateChangedBy=".$self->session->db->quote($self->session->user->userId).", stateChanged=".$self->session->datetime->time()." where assetId in (".$idList.")"); foreach my $id (@{$assetIds}) { - my $asset = WebGUI::Asset->newByDynamicClass($self->session, $id); + my $asset = WebGUI::Asset->newById($self->session, $id); if (defined $asset) { $asset->purgeCache; } } - $self->{_properties}{state} = "published"; + $self->state("published"); # Also publish any shortcuts to this asset that are in the trash my $shortcuts @@ -2387,12 +2265,6 @@ Returns a reference to the current session. =cut -sub session { - my ($self) = @_; - return $self->{_session}; -} - - #------------------------------------------------------------------- =head2 setSize ( [extra] ) @@ -2413,9 +2285,9 @@ sub setSize { $sizetest .= $self->get($key); } my $size = length($sizetest) + $extra; - $self->session->db->write("update assetData set assetSize=".$size." where assetId=".$self->session->db->quote($self->getId)." and revisionDate=".$self->session->db->quote($self->get("revisionDate"))); + $self->session->db->write("update assetData set assetSize=? where assetId=? and revisionDate=?",[$size, $self->getId, $self->revisionDate]); $self->purgeCache; - $self->{_properties}{assetSize} = $size; + $self->assetSize($size); } @@ -2439,117 +2311,44 @@ sub toggleToolbar { #------------------------------------------------------------------- -=head2 update ( properties ) +=head2 write ( ) -Updates the properties of an existing revision. If you want to create a new revision, please use addRevision(). - -=head3 properties - -Hash reference of properties and values to set. - -NOTE: C is a special property that uses the WebGUI::Keyword API -to set the keywords for this asset. +Stores the current properties of the asset in the database. =cut -sub update { +sub write { my $self = shift; - my $requestedProperties = shift; - my $properties = clone($requestedProperties); - $properties->{lastModified} = time(); + $self->lastModified(time()); - # if keywords were specified, then let's set them the right way - if (exists $properties->{keywords}) { - WebGUI::Keyword->new($self->session)->setKeywordsForAsset( - {keywords=>$properties->{keywords}, asset=>$self}); + my $db = $self->session->db; + CLASS: foreach my $meta (reverse $self->meta->get_all_class_metas()) { + my $table = $db->quoteIdentifier($meta->tableName); + my @properties = $meta->get_property_list; + my @values = map { $self->$_ } @properties; + my @columnNames = map { $db->quoteIdentifier($_).'=?' } @properties; + push @values, $self->getId, $self->revisionDate; + $db->write("update ".$table." set ".join(",",@columnNames)." where assetId=? and revisionDate=?",\@values); } - ##If inheritUrlFromParent was sent, and it is true, then muck with the url - ##The URL may have been sent too, so use it or the current Asset's URL. - if (exists $properties->{inheritUrlFromParent} and $properties->{inheritUrlFromParent}) { - $properties->{'url'} = $self->fixUrlFromParent($properties->{'url'} || $self->get('url')); - } - - # check the definition of all properties against what was given to us - foreach my $definition (reverse @{$self->definition($self->session)}) { - my %setPairs = (); - - # get a list of the fields available in this table so we don't try to insert - # something for a field that doesn't exist - my %tableFields = (); - my $sth = $self->session->db->read('DESCRIBE `'.$definition->{tableName}.'`'); - while (my ($col) = $sth->array) { - $tableFields{$col} = 1; - } - - # deal with all the properties in this part of the definition - foreach my $property (keys %{$definition->{properties}}) { - -# # skip a property unless it was specified to be set by the properties field or has a default value -# next unless (exists $properties->{$property} || exists $definition->{properties}{$property}{defaultValue}); - # skip a property unless it was specified to be set by the properties field - next unless (exists $properties->{$property}); - my $propertyDefinition = $definition->{properties}{$property}; - # skip a property if it has the display only flag set - next if ($propertyDefinition->{displayOnly}); - - # skip properties that aren't yet in the table - if (!exists $tableFields{$property}) { - $self->session->log->error("update() tried to set field named '".$property."' which doesn't exist in table '".$definition->{tableName}."'"); - next; - } - - # use the update value - my $value = $properties->{$property}; - # use the current value because the update value was undef - unless (defined $value) { - $value = $self->get($property); - } - - # apply filter logic on a property to validate or fix it's value - if (exists $propertyDefinition->{filter}) { - my $filter = $propertyDefinition->{filter}; - $value = $self->$filter($value, $property); - } - - # if the value is undefined, use the default if possible - # unless allowEmpty has been set, do this for empty strings as well - if ( ( !defined $value || ( $value eq q{} && ! $propertyDefinition->{allowEmpty} ) ) - && exists $propertyDefinition->{defaultValue} ) { - $value = $propertyDefinition->{defaultValue}; - if (ref($value) eq 'ARRAY') { - $value = $value->[0]; - } - } - - # set the property - if ($propertyDefinition->{serialize}) { - $setPairs{$property} = JSON->new->canonical->encode($value); - } - else { - $setPairs{$property} = $value; - } - $self->{_properties}{$property} = $value; - } - - # if there's anything to update, then do so - if (scalar(keys %setPairs) > 0) { - my @values = values %setPairs; - my @columnNames = map { $_.'=?' } keys %setPairs; - push(@values, $self->getId, $self->get("revisionDate")); - $self->session->db->write("update ".$definition->{tableName}." set ".join(",",@columnNames)." where assetId=? and revisionDate=?",\@values); - } - } - - # we've changed something so we need to update our size + # update the asset's size, which also purges the cache. $self->setSize(); - # we've changed something so cache is no longer valid - $self->purgeCache; } #------------------------------------------------------------------- +=head2 url ( [ value ] ) + +Returns the asset's url without any site specific prefixes. If you want a browser friendly url see the getUrl() method. + +=head3 value + +The new value to set the URL to. + +=cut + +#------------------------------------------------------------------- =head2 urlExists ( session, url [, options] ) @@ -2634,17 +2433,16 @@ new Asset will inherit security and style properties from the current asset, the sub www_add { my $self = shift; my %prototypeProperties; - my $class = $self->loadModule($self->session, $self->session->form->process("class","className")); + my $class = $self->loadModule($self->session->form->process("class","className")); return undef unless (defined $class); return $self->session->privilege->insufficient() unless ($class->canAdd($self->session)); if ($self->session->form->process('prototype')) { my $prototype = WebGUI::Asset->new($self->session, $self->session->form->process("prototype"),$class); - foreach my $definition (@{$prototype->definition($self->session)}) { # cycle through rather than copying properties to avoid grabbing stuff we shouldn't grab - foreach my $property (keys %{$definition->{properties}}) { - next if (isIn($property,qw(title menuTitle url isPrototype isPackage))); - next if ($definition->{properties}{$property}{noFormPost}); - $prototypeProperties{$property} = $prototype->get($property); - } + foreach my $property ($prototype->getProperties) { # cycle through rather than copying properties to avoid grabbing stuff we shouldn't grab + my $definition = $prototype->getProperty($property); + next if (isIn($property,qw(title menuTitle url isPrototype isPackage))); + next if ($definition->{noFormPost}); + $prototypeProperties{$property} = $prototype->get($property); } } my %properties = ( @@ -2778,7 +2576,7 @@ sub www_editSave { $object = $self->addChild({className=>$session->form->process("class","className")}); return $self->www_view unless defined $object; $object->{_parent} = $self; - $object->{_properties}{url} = undef; + $object->url(undef); } else { if ($self->canEditIfLocked) { diff --git a/lib/WebGUI/Asset/Event.pm b/lib/WebGUI/Asset/Event.pm index a83f44a9e..c08ad0266 100644 --- a/lib/WebGUI/Asset/Event.pm +++ b/lib/WebGUI/Asset/Event.pm @@ -27,12 +27,116 @@ use WebGUI::Form; use WebGUI::Storage; use Storable; -use base 'WebGUI::Asset'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_Event']; +aspect icon => 'calendar.gif'; +aspect tableName => 'Event'; +property description => ( + label => ['description', 'Asset_Event'], + fieldType => "HTMLArea", + default => "", + ); +property startDate => ( + label => ['start date', 'Asset_Event'], + fieldType => "Date", + builder => '_defaultMysqlDate', + lazy => 1, + ); +property endDate => ( + label => ['end date', 'Asset_Event'], + fieldType => "Date", + builder => '_defaultMysqlDate', + lazy => 1, + ); +sub _defaultMysqlDate { + my $self = shift; + my $dt = WebGUI::DateTime->new($self->session, time); + return $dt->toMysqlDate; +} +property startTime => ( + label => ['start', 'Asset_Event'], + fieldType => "TimeField", + default => undef, + format => 'mysql', + + ); +property endTime => ( + label => ['end', 'Asset_Event'], + fieldType => "TimeField", + default => undef, + format => 'mysql', + ); + +property recurId => ( + label => ['recurrence', 'Asset_Event'], + fieldType => "Text", + default => undef, + ); + +property location => ( + label => ['location', 'Asset_Event'], + fieldType => "Text", + default => undef, + ); +property feedId => ( + noFormPost => 1, + fieldType => "Text", + default => undef, + ); +property storageId => ( + label => ['attachments for event', 'Asset_Event'], + fieldType => "Image", + default => '', + maxAttachments => 1, + ); +property feedUid => ( + noFormPost => 1, + fieldType => "Text", + default => undef, + ); +property timeZone => ( + label => ['time zone', 'DateTime'], + fieldType => 'TimeZone', + ); +property sequenceNumber => ( + noFormPost => 1, + fieldType => 'hidden', + ); +property iCalSequenceNumber => ( + noFormPost => 1, + fieldType => 'hidden', + ); +property userDefined1 => ( + label => 'userDefined1', + fieldType => 'text', + default => '', + ); +property userDefined2 => ( + label => 'userDefined2', + fieldType => 'text', + default => '', + ); +property userDefined3 => ( + label => 'userDefined3', + fieldType => 'text', + default => '', + ); +property userDefined4 => ( + label => 'userDefined4', + fieldType => 'text', + default => '', + ); +property userDefined5 => ( + label => 'userDefined5', + fieldType => 'text', + default => '', + ); + +with 'WebGUI::Role::Asset::AlwaysHidden'; use WebGUI::DateTime; - - =head1 NAME WebGUI::Asset::Event @@ -57,7 +161,7 @@ Extent the method from the super class to handle iCalSequenceNumbers. sub addRevision { my $self = shift; my $newRev = $self->SUPER::addRevision(@_); - my $sequenceNumber = $newRev->get('iCalSequenceNumber'); + my $sequenceNumber = $newRev->iCalSequenceNumber; if (defined $sequenceNumber) { $sequenceNumber++; } @@ -65,115 +169,14 @@ sub addRevision { $sequenceNumber = 0; } $newRev->update({iCalSequenceNumber => $sequenceNumber}); - if ($newRev->get("storageId") && $newRev->get("storageId") eq $self->get('storageId')) { - my $newStorage = WebGUI::Storage->get($self->session,$self->get("storageId"))->copy; + if ($newRev->storageId && $newRev->storageId eq $self->storageId) { + my $newStorage = WebGUI::Storage->get($self->session,$self->storageId)->copy; $newRev->update({storageId => $newStorage->getId}); } return $newRev; } -#################################################################### - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - - my $i18n = WebGUI::International->new($session, 'Asset_Event'); - my $dt = WebGUI::DateTime->new($session, time); - - ### Set up list options ### - - - - ### Build properties hash ### - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - - ##### DEFAULTS ##### - 'description' => { - fieldType => "HTMLArea", - defaultValue => "", - }, - 'startDate' => { - fieldType => "Date", - defaultValue => $dt->toMysqlDate, - }, - 'endDate' => { - fieldType => "Date", - defaultValue => $dt->toMysqlDate, - }, - 'startTime' => { - fieldType => "TimeField", - defaultValue => undef, - format => 'mysql', - }, - 'endTime' => { - fieldType => "TimeField", - defaultValue => undef, - format => 'mysql', - }, - - 'recurId' => { - fieldType => "Text", - defaultValue => undef, - }, - - 'location' => { - fieldType => "Text", - defaultValue => undef, - }, - 'feedId' => { - fieldType => "Text", - defaultValue => undef, - }, - 'storageId' => { - fieldType => "Image", - defaultValue => '', - maxAttachments => 1, - }, - 'feedUid' => { - fieldType => "Text", - defaultValue => undef, - }, - 'timeZone' => { - fieldType => 'TimeZone', - }, - sequenceNumber => { - fieldType => 'hidden', - }, - iCalSequenceNumber => { - fieldType => 'hidden', - }, - ); - - - ### Add user defined fields - for my $num (1..5) { - $properties{"userDefined".$num} = { - fieldType => "text", - defaultValue => "", - }; - } - - - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'calendar.gif', - tableName => 'Event', - className => 'WebGUI::Asset::Event', - properties => \%properties - }); - - return $class->SUPER::definition($session, $definition); -} - - - - - #------------------------------------------------------------------- =head2 canAdd ( session ) @@ -213,7 +216,7 @@ sub canEdit { $userId = $self->session->user->userId; } - return 1 if ( $userId eq $self->get('ownerUserId') ); + return 1 if ( $userId eq $self->ownerUserId ); return $self->getParent->canEdit( $userId ); } @@ -234,7 +237,7 @@ sub generateRecurringEvents { my $session = $self->session; my $properties = $self->get; - my $recurId = $self->get("recurId"); + my $recurId = $self->recurId; my $recur = {$self->getRecurrence}; # This method only works on events that have recurrence patterns @@ -314,7 +317,7 @@ sub getAutoCommitWorkflowId { my $self = shift; my $parent = $self->getParent; if ($parent->hasBeenCommitted) { - return $parent->get('workflowIdCommit') + return $parent->workflowIdCommit || $self->session->setting->get('defaultVersionTagWorkflow'); } return undef; @@ -338,8 +341,8 @@ adjusted. sub getDateTimeStart { my $self = shift; - my $date = $self->get("startDate"); - my $time = $self->get("startTime"); + my $date = $self->startDate; + my $time = $self->startTime; my $tz = $self->session->datetime->getTimeZone; #$self->session->errorHandler->warn($self->getId.":: Date: $date -- Time: $time"); @@ -377,8 +380,8 @@ adjusted. sub getDateTimeEnd { my $self = shift; - my $date = $self->get("endDate"); - my $time = $self->get("endTime"); + my $date = $self->endDate; + my $time = $self->endTime; my $tz = $self->session->datetime->getTimeZone; #$self->session->errorHandler->warn($self->getId.":: Date: $date -- Time: $time"); @@ -417,7 +420,7 @@ is used EVERYWHERE. sub getDateTimeEndNI { my $self = shift; my $dt = $self->getDateTimeEnd; - if ($self->get('endTime') ) { + if ($self->endTime ) { $dt->subtract(seconds => 1); } return $dt; @@ -440,20 +443,20 @@ sub getEventNext { my $self = shift; my $db = $self->session->db; - my $where = 'Event.startDate > "'.$self->get("startDate").'"' - . '|| (Event.startDate = "'.$self->get("startDate").'" && '; + my $where = 'Event.startDate > "'.$self->startDate.'"' + . '|| (Event.startDate = "'.$self->startDate.'" && '; # All day events must either look for null time or greater than 00:00:00 if ($self->isAllDay) { $where .= "((Event.startTime IS NULL " - . "&& assetData.title > ".$db->quote($self->get("title")).") " + . "&& assetData.title > ".$db->quote($self->title).") " . "|| Event.startTime >= '00:00:00')"; } # Non all-day events must look for greater than time else { - $where .= "((Event.startTime = '".$self->get("startTime")."' " - . "&& assetData.title > ".$db->quote($self->get("title")).")" - . "|| Event.startTime > '".$self->get("startTime")."')"; + $where .= "((Event.startTime = '".$self->startTime."' " + . "&& assetData.title > ".$db->quote($self->title).")" + . "|| Event.startTime > '".$self->startTime."')"; } $where .= ")"; @@ -478,7 +481,7 @@ sub getEventNext { return undef unless $events->[0]; - return WebGUI::Asset->newByDynamicClass($self->session,$events->[0]); + return WebGUI::Asset->newById($self->session,$events->[0]); } @@ -499,19 +502,19 @@ sub getEventPrev { my $self = shift; my $db = $self->session->db; - my $where = 'Event.startDate < "'.$self->get("startDate").'"' - . '|| (Event.startDate = "'.$self->get("startDate").'" && '; + my $where = 'Event.startDate < "'.$self->startDate.'"' + . '|| (Event.startDate = "'.$self->startDate.'" && '; # All day events must either look for null time or greater than 00:00:00 if ($self->isAllDay) { $where .= "(Event.startTime IS NULL " - . "&& assetData.title < ".$db->quote($self->get("title")).")"; + . "&& assetData.title < ".$db->quote($self->title).")"; } # Non all-day events must look for greater than time else { - $where .= "((Event.startTime = '".$self->get("startTime")."' " - . "&& assetData.title < ".$db->quote($self->get("title")).")" - . "|| Event.startTime < '".$self->get("startTime")."')"; + $where .= "((Event.startTime = '".$self->startTime."' " + . "&& assetData.title < ".$db->quote($self->title).")" + . "|| Event.startTime < '".$self->startTime."')"; } $where .= ")"; @@ -534,7 +537,7 @@ sub getEventPrev { }); return undef unless $events->[0]; - return WebGUI::Asset->newByDynamicClass($self->session,$events->[0]); + return WebGUI::Asset->newById($self->session,$events->[0]); } @@ -556,13 +559,13 @@ sub getIcalStart { my $self = shift; if ($self->isAllDay) { - my $date = $self->get("startDate"); + my $date = $self->startDate; $date =~ s/\D//g; return $date; } else { - my $date = $self->get("startDate"); - my $time = $self->get("startTime"); + my $date = $self->startDate; + my $time = $self->startTime; $date =~ s/\D//g; $time =~ s/\D//g; @@ -595,8 +598,8 @@ sub getIcalEnd { return $date; } else { - my $date = $self->get("endDate"); - my $time = $self->get("endTime"); + my $date = $self->endDate; + my $time = $self->endTime; $date =~ s/\D//g; $time =~ s/\D//g; @@ -696,12 +699,12 @@ sub getRecurrence { my $self = shift; #use Data::Dumper; #$self->session->errorHandler->warn("recurId: ".$self->get("recurId")); - return () unless $self->get("recurId"); + return () unless $self->recurId; my %data = $self->session->db->quickHash( "select * from Event_recur where recurId=?", - [$self->get("recurId")] + [$self->recurId] ); my %recurrence = ( @@ -1252,11 +1255,11 @@ Get the storage location associated with this Event. sub getStorageLocation { my $self = shift; unless (exists $self->{_storageLocation}) { - if ($self->get("storageId") eq "") { + if ($self->storageId eq "") { $self->{_storageLocation} = WebGUI::Storage->create($self->session); $self->update({storageId=>$self->{_storageLocation}->getId}); } else { - $self->{_storageLocation} = WebGUI::Storage->get($self->session,$self->get("storageId")); + $self->{_storageLocation} = WebGUI::Storage->get($self->session,$self->storageId); } } return $self->{_storageLocation}; @@ -1281,9 +1284,9 @@ sub getTemplateVars { # Some miscellaneous stuff $var{'canEdit'} = $self->canEdit; $var{"isPublic"} = 1 - if $self->get("groupIdView") eq "7"; - $var{"groupToView"} = $self->get("groupIdView"); - $var{"timeZone"} = $self->get('timeZone'); + if $self->groupIdView eq "7"; + $var{"groupToView"} = $self->groupIdView; + $var{"timeZone"} = $self->timeZone; # Start date/time my $dtStart = $self->getDateTimeStart; @@ -1377,7 +1380,7 @@ sub getTemplateVars { my $gotImage; my $gotAttachment; $var{'attachment_loop'} = []; - unless ($self->get("storageId") eq "") { + unless ($self->storageId eq "") { my $storage = $self->getStorageLocation; foreach my $filename (@{$storage->getFiles}) { # Set top-level template vars for the first image and first non-image @@ -1418,12 +1421,12 @@ Indexing the content of attachments and user defined fields. See WebGUI::Asset:: sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get("userDefined1")); - $indexer->addKeywords($self->get("userDefined2")); - $indexer->addKeywords($self->get("userDefined3")); - $indexer->addKeywords($self->get("userDefined4")); - $indexer->addKeywords($self->get("userDefined5")); - $indexer->addKeywords($self->get("location")); + $indexer->addKeywords($self->userDefined1); + $indexer->addKeywords($self->userDefined2); + $indexer->addKeywords($self->userDefined3); + $indexer->addKeywords($self->userDefined4); + $indexer->addKeywords($self->userDefined5); + $indexer->addKeywords($self->location); my $storage = $self->getStorageLocation; foreach my $file (@{$storage->getFiles}) { $indexer->addFile($storage->getPath($file)); @@ -1443,7 +1446,7 @@ Returns true if this event is an all day event. sub isAllDay { my $self = shift; - return 1 unless ($self->get("startTime") || $self->get("endTime")); + return 1 unless ($self->startTime || $self->endTime); return 0; } @@ -1469,11 +1472,11 @@ sub prepareView { if ($parent) { if ($self->session->form->param("print")) { - $templateId = $parent->get("templateIdPrintEvent"); + $templateId = $parent->templateIdPrintEvent; $self->session->style->makePrintable(1); } else { - $templateId = $parent->get("templateIdEvent"); + $templateId = $parent->templateIdEvent; } } else { @@ -1521,13 +1524,13 @@ sub processPropertiesFromFormPost { my @errors; # If the start date is after the end date my $i18n = WebGUI::International->new($session, 'Asset_Event'); - if ($self->get("startDate") gt $self->get("endDate")) { + if ($self->startDate gt $self->endDate) { push @errors, $i18n->get("The event end date must be after the event start date."); } # If the dates are the same and the start time is after the end time - if ($self->get("startDate") eq $self->get("endDate") - && $self->get("startTime") gt $self->get("endTime") + if ($self->startDate eq $self->endDate + && $self->startTime gt $self->endTime ) { push @errors, $i18n->get("The event end time must be after the event start time."); } @@ -1544,15 +1547,15 @@ sub processPropertiesFromFormPost { undef $activeVersionTag; } else { - WebGUI::VersionTag->new($session, $self->get('tagId'))->setWorking; + WebGUI::VersionTag->new($session, $self->tagId)->setWorking; } ### Form is verified # Events are always hidden from navigation if (!$self->get("groupIdEdit")) { - my $groupIdEdit = $self->getParent->get("groupIdEventEdit") - || $self->getParent->get("groupIdEdit") + my $groupIdEdit = $self->getParent->groupIdEventEdit + || $self->getParent->groupIdEdit ; $self->update({ @@ -1570,17 +1573,17 @@ sub processPropertiesFromFormPost { } # Non-allday events need timezone conversion else { - my $tz = $self->get('timeZone'); + my $tz = $self->timeZone; my $dtStart = WebGUI::DateTime->new($session, - mysql => $self->get("startDate") . " " . $self->get("startTime"), + mysql => $self->startDate . " " . $self->startTime, time_zone => $tz, ); my $dtEnd = WebGUI::DateTime->new($session, - mysql => $self->get("endDate") . " " . $self->get("endTime"), + mysql => $self->endDate . " " . $self->endTime, time_zone => $tz, ); @@ -1594,8 +1597,8 @@ sub processPropertiesFromFormPost { my $top_val = $session->db->dbh->selectcol_arrayref("SELECT sequenceNumber FROM Event ORDER BY sequenceNumber desc LIMIT 1")->[0]; $top_val += 16384; - my $assetId = $self->get('assetId'); - my $revisionDate = $self->get('revisionDate'); + my $assetId = $self->getId; + my $revisionDate = $self->revisionDate; $session->db->write("UPDATE Event SET sequenceNumber =? WHERE assetId = ? AND revisionDate =?",[($form->param('sequenceNumber') || $top_val), $assetId, $revisionDate]); @@ -1675,7 +1678,7 @@ sub processPropertiesFromFormPost { # Pattern keys if (Storable::freeze(\%recurrence_new) ne Storable::freeze(\%recurrence_old)) { # Delete all old events and create new ones - my $old_id = $self->get("recurId"); + my $old_id = $self->recurId; # Set the new recurrence pattern if (%recurrence_new) { @@ -1718,15 +1721,15 @@ sub processPropertiesFromFormPost { #returnObjects => 1, includeOnlyClasses => ['WebGUI::Asset::Event'], joinClass => 'WebGUI::Asset::Event', - whereClause => q{Event.recurId = "}.$self->get("recurId").q{"}, + whereClause => q{Event.recurId = "}.$self->recurId.q{"}, }); for my $eventId (@{$events}) { - my $event = WebGUI::Asset->newByDynamicClass($session, $eventId); + my $event = WebGUI::Asset->newById($session, $eventId); # Add a revision - $properties{ startDate } = $event->get("startDate"); - $properties{ endDate } = $event->get("endDate"); + $properties{ startDate } = $event->startDate; + $properties{ endDate } = $event->endDate; # addRevision returns the new revision $event = $event->addRevision(\%properties, undef, { skipAutoCommitWorkflows => 1 }); @@ -1896,21 +1899,6 @@ sub setRelatedLinks { return undef; } -#################################################################### - -=head2 update - -Wrap update so that isHidden is always set to be a 1. - -=cut - -sub update { - my $self = shift; - my $properties = shift; - return $self->SUPER::update({%$properties, isHidden => 1}); -} - - #------------------------------------------------------------------- =head2 validParent @@ -1992,7 +1980,7 @@ sub www_edit { my $self = shift; my $session = $self->session; my $form = $self->session->form; - my $tz = $form->param('timeZone') || $self->get('timeZone') || $session->datetime->getTimeZone; + my $tz = $form->param('timeZone') || $self->timeZone || $session->datetime->getTimeZone; my $func = lc $session->form->param("func"); my $var = {}; @@ -2024,7 +2012,7 @@ sub www_edit { }) . WebGUI::Form::hidden($self->session, { name => "sequenceNumber", - value => $self->get("sequenceNumber"), + value => $self->sequenceNumber, }) . WebGUI::Form::hidden( $self->session, { name => 'ownerUserId', @@ -2040,7 +2028,7 @@ sub www_edit { }) . WebGUI::Form::hidden($self->session, { name => "recurId", - value => $self->get("recurId"), + value => $self->recurId, }); $var->{"formFooter"} = WebGUI::Form::formFooter($session); @@ -2051,14 +2039,14 @@ sub www_edit { $var->{"formTitle"} = WebGUI::Form::text($session, { name => "title", - value => $form->process("title") || $self->get("title"), + value => $form->process("title") || $self->title, }); # menu title AS short title $var->{"formMenuTitle"} = WebGUI::Form::text($session, { name => "menuTitle", - value => $form->process("menuTitle") || $self->get("menuTitle"), + value => $form->process("menuTitle") || $self->menuTitle, maxlength => 15, size => 22, }); @@ -2067,27 +2055,27 @@ sub www_edit { $var->{"formGroupIdView"} = WebGUI::Form::Group($session, { name => "groupIdView", - value => $form->process("groupIdView") || $self->get("groupIdView"), - defaultValue => $self->getParent->get("groupIdView"), + value => $form->process("groupIdView") || $self->groupIdView, + defaultValue => $self->getParent->groupIdView, }); # location $var->{"formLocation"} = WebGUI::Form::text($session, { name => "location", - value => $form->process("location") || $self->get("location"), + value => $form->process("location") || $self->location, }); # description $var->{"formDescription"} = WebGUI::Form::HTMLArea($session, { name => "description", - value => $form->process("description") || $self->get("description"), + value => $form->process("description") || $self->description, }); # User defined for my $x (1..5) { - my $userDefinedValue = $self->getValue("userDefined".$x); + my $userDefinedValue = $self->get("userDefined".$x); $var->{'formUserDefined'.$x} = WebGUI::Form::text($session, { name => "userDefined" . $x, value => $userDefinedValue, @@ -2115,7 +2103,7 @@ sub www_edit { = WebGUI::Form::Image($session, { name => "storageId", maxAttachments => 5, - value => $form->process("storageId") || $self->get("storageId"), + value => $form->process("storageId") || $self->storageId, deleteFileUrl=>$self->getUrl("func=deleteFile;filename=") }); @@ -2231,8 +2219,8 @@ sub www_edit { $_->{delete_id} = "rel_del_id_".$_->{eventlinkId}; $_->{group_id} = WebGUI::Form::Group($session, { name => "rel_group_id_".$_->{eventlinkId}, - value => $form->process("rel_group_id_".$_->{eventlinkId}) || $_->{groupIdView} || $self->getParent->get("groupIdView"), - defaultValue => $self->getParent->get("groupIdView"), + value => $form->process("rel_group_id_".$_->{eventlinkId}) || $_->{groupIdView} || $self->getParent->groupIdView, + defaultValue => $self->getParent->groupIdView, }); $_->{seq_num_name} = "rel_seq_".$_->{eventlinkId}; $_->{seq_num_id} = "rel_seq_id_".$_->{eventlinkId}; @@ -2242,8 +2230,8 @@ sub www_edit { $var->{"genericGroup"} = WebGUI::Form::Group($session, { name => "rel_group_id_ZZZZZZZZZZ", - value => $self->getParent->get("groupIdView"), - defaultValue => $self->getParent->get("groupIdView"), + value => $self->getParent->groupIdView, + defaultValue => $self->getParent->groupIdView, }); chomp $var->{"genericGroup"}; @@ -2389,7 +2377,7 @@ sub www_edit { = WebGUI::Form::date($session, { name => "recurStart", value => $recur{startDate}, - defaultValue => $self->get("startDate"), + defaultValue => $self->startDate, }); # End @@ -2490,7 +2478,7 @@ ENDJS my $template; if ($parent) { $template - = WebGUI::Asset::Template->new($session,$parent->get("templateIdEventEdit")); + = WebGUI::Asset::Template->new($session,$parent->templateIdEventEdit); } else { $template @@ -2536,7 +2524,7 @@ sub www_view { return $self->session->privilege->noAccess() unless $self->canView; my $check = $self->checkView; return $check if (defined $check); - $self->session->http->setCacheControl($self->get("visitorCacheTimeout")) if ($self->session->user->isVisitor); + $self->session->http->setCacheControl($self->visitorCacheTimeout) if ($self->session->user->isVisitor); $self->session->http->sendHeader; $self->prepareView; my $style = $self->getParent->processStyle($self->getSeparator); diff --git a/lib/WebGUI/Asset/File.pm b/lib/WebGUI/Asset/File.pm index 19b5410b9..53727b38f 100644 --- a/lib/WebGUI/Asset/File.pm +++ b/lib/WebGUI/Asset/File.pm @@ -15,8 +15,49 @@ package WebGUI::Asset::File; =cut use strict; -use base 'WebGUI::Asset'; use Carp; + + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; + +aspect assetName => ['assetName', 'Asset_File']; +aspect tableName => 'FileAsset'; +property cacheTimeout => ( + tab => "display", + fieldType => "interval", + default => 3600, + uiLevel => 8, + label => ["cache timeout", 'Asset_File'], + hoverHelp => ["cache timeout help", 'Asset_File'], + ); +property filename => ( + noFormPost => 1, + fieldType => 'hidden', + default => '', + ); +property storageId => ( + noFormPost => 1, + fieldType => 'hidden', + default => '', + trigger => \&_set_storageId, + ); +sub _set_storageId { + my ($self, $new, $old) = @_; + if ($new ne $old) { + $self->setStorageLocation; + } +} +property templateId => ( + fieldType => 'template', + default => 'PBtmpl0000000000000024', + label => ['file template', 'Asset_File'], + hoverHelp => ['file template description', 'Asset_File'], + namespace => "FileAsset", + ); + +with 'WebGUI::Role::Asset::SetStoragePermissions'; + use WebGUI::Storage; use WebGUI::SQL; use WebGUI::Utility; @@ -55,8 +96,8 @@ sub addRevision { my $self = shift; my $newSelf = $self->SUPER::addRevision(@_); - if ($newSelf->get("storageId") && $newSelf->get("storageId") eq $self->get('storageId')) { - my $newStorage = $self->getStorageClass->get($self->session,$self->get("storageId"))->copy; + if ($newSelf->storageId && $newSelf->storageId eq $self->storageId) { + my $newStorage = $self->getStorageClass->get($self->session, $self->storageId)->copy; $newSelf->update({storageId => $newStorage->getId}); } @@ -77,61 +118,11 @@ A hash reference of optional parameters. None at this time. sub applyConstraints { my $self = shift; - $self->getStorageLocation->setPrivileges($self->get('ownerUserId'), $self->get('groupIdView'), $self->get('groupIdEdit')); + $self->getStorageLocation->setPrivileges($self->ownerUserId, $self->groupIdView, $self->groupIdEdit); $self->setSize; } -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_File"); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - tableName=>'FileAsset', - className=>'WebGUI::Asset::File', - properties=>{ - cacheTimeout => { - tab => "display", - fieldType => "interval", - defaultValue => 3600, - uiLevel => 8, - label => $i18n->get("cache timeout"), - hoverHelp => $i18n->get("cache timeout help") - }, - filename=>{ - noFormPost=>1, - fieldType=>'hidden', - defaultValue=>'', - }, - storageId=>{ - noFormPost=>1, - fieldType=>'hidden', - defaultValue=>'', - }, - templateId=>{ - fieldType=>'template', - defaultValue=>'PBtmpl0000000000000024' - } - } - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 duplicate @@ -160,7 +151,7 @@ See WebGUI::AssetPackage::exportAssetData() for details. sub exportAssetData { my $self = shift; my $data = $self->SUPER::exportAssetData; - push(@{$data->{storage}}, $self->get("storageId")) if ($self->get("storageId") ne ""); + push(@{$data->{storage}}, $self->storageId) if ($self->storageId ne ""); return $data; } @@ -195,8 +186,8 @@ sub exportWriteFile { WebGUI::Error->throw(error => "could not make directory " . $parent->absolute->stringify); } - if ( ! File::Copy::copy($self->getStorageLocation->getPath($self->get('filename')), $dest->stringify) ) { - WebGUI::Error->throw(error => "can't copy " . $self->getStorageLocation->getPath($self->get('filename')) + if ( ! File::Copy::copy($self->getStorageLocation->getPath($self->filename), $dest->stringify) ) { + WebGUI::Error->throw(error => "can't copy " . $self->getStorageLocation->getPath($self->filename) . ' to ' . $dest->absolute->stringify . ": $!"); } } @@ -238,9 +229,9 @@ sub getEditFormUploadControl { my $i18n = WebGUI::International->new($session, 'Asset_File'); my $html = ''; - if ($self->get("filename") ne "") { + if ($self->filename ne "") { $html .= WebGUI::Form::readOnly( $session, { - value => '

'.$self->get( '.$self->get("filename").'

' + value => '

'.$self->filename.' '.$self->filename.'

' }); } @@ -265,7 +256,7 @@ Returns the URL for the file stored in the storage location. sub getFileUrl { my $self = shift; #return $self->get("url"); - return $self->getStorageLocation->getUrl($self->get("filename")); + return $self->getStorageLocation->getUrl($self->filename); } #------------------------------------------------------------------- @@ -279,8 +270,8 @@ file, then it returns undef. sub getFileIconUrl { my $self = shift; - return undef unless $self->get("filename"); ## Why do I have to do this when creating new Files? - return $self->getStorageLocation->getFileIconUrl($self->get("filename")); + return undef unless $self->filename; ## Why do I have to do this when creating new Files? + return $self->getStorageLocation->getFileIconUrl($self->filename); } @@ -368,7 +359,7 @@ Indexing the content of the attachment. See WebGUI::Asset::indexContent() for ad sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addFile($self->getStorageLocation->getPath($self->get("filename"))); + $indexer->addFile($self->getStorageLocation->getPath($self->filename)); } @@ -383,7 +374,7 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; } @@ -545,36 +536,10 @@ sub setStorageLocation { $self->update({storageId=>$self->{_storageLocation}->getId}); } else { - $self->{_storageLocation} = $self->getStorageClass->get($self->session,$self->get("storageId")); + $self->{_storageLocation} = $self->getStorageClass->get($self->session,$self->storageId); } } -#------------------------------------------------------------------- - -=head2 update - -We override the update method from WebGUI::Asset in order to handle file system privileges. - -=cut - -sub update { - my $self = shift; - my %before = ( - owner => $self->get("ownerUserId"), - view => $self->get("groupIdView"), - edit => $self->get("groupIdEdit"), - storageId => $self->get('storageId'), - ); - $self->SUPER::update(@_); - ##update may have entered a new storageId. Reset the cached one just in case. - if ($self->get("storageId") ne $before{storageId}) { - $self->setStorageLocation; - } - if ($self->get("ownerUserId") ne $before{owner} || $self->get("groupIdEdit") ne $before{edit} || $self->get("groupIdView") ne $before{view}) { - $self->getStorageLocation->setPrivileges($self->get("ownerUserId"),$self->get("groupIdView"),$self->get("groupIdEdit")); - } -} - #---------------------------------------------------------------------------- =head2 updatePropertiesFromStorage ( ) @@ -615,11 +580,11 @@ sub view { $var{fileUrl} = $self->getFileUrl; $var{fileIcon} = $self->getFileIconUrl; $var{fileSize} = formatBytes($self->get("assetSize")); - my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); + my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10) { eval{$self->session->cache->set("view_".$self->getId, $out, $self->get("cacheTimeout"))}; } - return $out; + return $out; } @@ -639,7 +604,7 @@ sub www_edit { my $i18n = WebGUI::International->new($self->session); my $tabform = $self->getEditForm; $tabform->getTab("display")->template( - -value=>$self->getValue("templateId"), + -value=>$self->templateId, -hoverHelp=>$i18n->get('file template description','Asset_File'), -namespace=>"FileAsset" ); @@ -660,14 +625,14 @@ sub www_view { return $session->privilege->noAccess() unless $self->canView; # Check to make sure it's not in the trash or some other weird place - if ($self->get("state") ne "published") { + if ($self->state ne "published") { my $i18n = WebGUI::International->new($session,'Asset_File'); $session->http->setStatus("404"); return sprintf($i18n->get("file not found"), $self->getUrl()); } $session->http->setRedirect($self->getFileUrl) unless $session->config->get('enableStreamingUploads'); - $session->http->setStreamedFile($self->getStorageLocation->getPath($self->get("filename"))); + $session->http->setStreamedFile($self->getStorageLocation->getPath($self->filename)); $session->http->sendHeader; return 'chunked'; } diff --git a/lib/WebGUI/Asset/File/GalleryFile.pm b/lib/WebGUI/Asset/File/GalleryFile.pm index 210bccb25..b6a62a752 100644 --- a/lib/WebGUI/Asset/File/GalleryFile.pm +++ b/lib/WebGUI/Asset/File/GalleryFile.pm @@ -15,7 +15,31 @@ package WebGUI::Asset::File::GalleryFile; =cut use strict; -use base 'WebGUI::Asset::File'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::File'; +aspect assetName => ['assetName', 'Asset_GalleryFile']; +aspect tableName => 'GalleryFile'; +property views => ( + noFormPost => 1, + default => 0, + ); +property friendsOnly => ( + label => ['editForm friendsOnly','Asset_Photo'], + default => 0, + ); +property rating => ( + noFormPost => 1, + default => 0, + ); +for my $i ( 1 .. 5 ) { + property 'userDefined'.$i => ( + default => undef, + label => '', + fieldType => 'text', + ); +} + +with 'WebGUI::Role::Asset::AlwaysHidden'; use Carp qw( croak confess ); use URI::Escape; @@ -53,15 +77,6 @@ sub definition { my $i18n = WebGUI::International->new($session,'Asset_Photo'); tie my %properties, 'Tie::IxHash', ( - views => { - defaultValue => 0, - }, - friendsOnly => { - defaultValue => 0, - }, - rating => { - defaultValue => 0, - }, ); # UserDefined Fields @@ -72,9 +87,6 @@ sub definition { } push @{$definition}, { - assetName => $i18n->get('assetName'), - autoGenerateForms => 0, - tableName => 'GalleryFile', className => 'WebGUI::Asset::File::GalleryFile', properties => \%properties, }; @@ -137,7 +149,7 @@ sub appendTemplateVarsCommentForm { $var->{ commentForm_bodyText } = WebGUI::Form::HTMLArea( $session, { name => "bodyText", - richEditId => $self->getGallery->get("richEditIdComment"), + richEditId => $self->getGallery->richEditIdComment, value => $comment->{ bodyText }, }); @@ -203,7 +215,7 @@ sub canEdit { my $userId = shift || $self->session->user->userId; my $album = $self->getParent; - return 1 if $userId eq $self->get("ownerUserId"); + return 1 if $userId eq $self->ownerUserId; return $album->canEdit($userId); } @@ -241,8 +253,8 @@ sub canView { my $album = $self->getParent; return 0 unless $album->canView($userId); - if ($self->isFriendsOnly && $userId ne $self->get("ownerUserId") ) { - my $owner = WebGUI::User->new( $self->session, $self->get("ownerUserId") ); + if ($self->isFriendsOnly && $userId ne $self->ownerUserId ) { + my $owner = WebGUI::User->new( $self->session, $self->ownerUserId ); return 0 unless WebGUI::Friends->new($self->session, $owner)->isFriend($userId); } @@ -284,7 +296,7 @@ sub getAutoCommitWorkflowId { my $self = shift; my $gallery = $self->getGallery; if ($gallery->hasBeenCommitted) { - return $gallery->get("workflowIdCommit") + return $gallery->workflowIdCommit || $self->session->setting->get('defaultVersionTagWorkflow'); } return undef; @@ -377,7 +389,7 @@ sub getCurrentRevisionDate { return undef unless $asset; - if ( $asset->get( 'status' ) eq "approved" || $asset->canEdit ) { + if ( $asset->approved || $asset->canEdit ) { return $revisionDate; } else { @@ -416,7 +428,7 @@ sub getParent { return $album; } # Only get the pending version if we're allowed to see this photo in its pending status - elsif ( $self->getGallery->canEdit || $self->get( 'ownerUserId' ) eq $self->session->user->userId ) { + elsif ( $self->getGallery->canEdit || $self->ownerUserId eq $self->session->user->userId ) { my $album = $self->getLineage( ['ancestors'], { includeOnlyClasses => [ 'WebGUI::Asset::Wobject::GalleryAlbum' ], @@ -456,13 +468,13 @@ sub getTemplateVars { my $self = shift; my $session = $self->session; my $var = $self->get; - my $owner = WebGUI::User->new( $session, $self->get("ownerUserId") ); + my $owner = WebGUI::User->new( $session, $self->ownerUserId ); $var->{ fileUrl } = $self->getFileUrl; $var->{ thumbnailUrl } = $self->getThumbnailUrl; # Set a flag for pending files - if ( $self->get( "status" ) eq "pending" ) { + if ( $self->status eq "pending" ) { $var->{ 'isPending' } = 1; } @@ -474,7 +486,7 @@ sub getTemplateVars { } # Add a text-only synopsis - $var->{ synopsis_textonly } = WebGUI::HTML::filter( $self->get('synopsis'), "all" ); + $var->{ synopsis_textonly } = WebGUI::HTML::filter( $self->synopsis, "all" ); # Figure out on what page of the album the gallery file belongs. my $album = $self->getParent; @@ -483,7 +495,7 @@ sub getTemplateVars { my $pageNumber = int ( ( first_index { $_ eq $id } @{ $fileIdsInAlbum } ) # Get index of file in album - / $album->getParent->get( 'defaultFilesPerPage' ) # Divide by the number of files per page + / $album->getParent->defaultFilesPerPage # Divide by the number of files per page ) + 1; # Round upwards $var->{ canComment } = $self->canComment; @@ -501,7 +513,7 @@ sub getTemplateVars { $var->{ url_slideshow } = $self->getParent->getUrl('func=slideshow'); $var->{ url_makeShortcut } = $self->getUrl('func=makeShortcut'); $var->{ url_listFilesForOwner } - = $self->getGallery->getUrl('func=listFilesForUser;userId=' . $self->get("ownerUserId")); + = $self->getGallery->getUrl('func=listFilesForUser;userId=' . $self->ownerUserId); $var->{ url_promote } = $self->getUrl('func=promote'); return $var; @@ -518,7 +530,7 @@ Returns true if this GalleryFile is friends only. Returns false otherwise. sub isFriendsOnly { my $self = shift; - return $self->get("friendsOnly"); + return $self->friendsOnly; } #---------------------------------------------------------------------------- @@ -541,7 +553,7 @@ sub makeShortcut { croak "GalleryFile->makeShortcut: parentId must be defined" unless $parentId; - my $parent = WebGUI::Asset->newByDynamicClass($session, $parentId) + my $parent = WebGUI::Asset->newById($session, $parentId) || croak "GalleryFile->makeShortcut: Could not instanciate asset '$parentId'"; my $shortcut @@ -570,7 +582,7 @@ sub prepareView { $self->SUPER::prepareView(); my $template - = WebGUI::Asset::Template->new($self->session, $self->getGallery->get("templateIdViewFile")); + = WebGUI::Asset::Template->new($self->session, $self->getGallery->templateIdViewFile); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; @@ -637,7 +649,7 @@ sub processPropertiesFromFormPost { my $errors = $self->SUPER::processPropertiesFromFormPost || []; # Make sure we have the disk space for this - if ( !$self->getGallery->hasSpaceAvailable( $self->get( 'assetSize' ) ) ) { + if ( !$self->getGallery->hasSpaceAvailable( $self->assetSize ) ) { push @{ $errors }, $i18n->get( "error no space" ); } @@ -647,7 +659,7 @@ sub processPropertiesFromFormPost { ### Passes all checks # If the album doesn't yet have a thumbnail, make this File the thumbnail - if ( !$self->getParent->get('assetIdThumbnail') ) { + if ( !$self->getParent->assetIdThumbnail ) { $self->getParent->update( { assetIdThumbnail => $self->getId, } ); @@ -723,21 +735,6 @@ sub setComment { ); } -#################################################################### - -=head2 update - -Wrap update so that isHidden is always set to be a 1. - -=cut - -sub update { - my $self = shift; - my $properties = shift; - return $self->SUPER::update({%$properties, isHidden => 1}); -} - - #---------------------------------------------------------------------------- =head2 view ( ) @@ -788,7 +785,7 @@ sub view { url_searchKeywordUser => $self->getGallery->getUrl( "func=search;submit=1;" - . "userId=" . $self->get("ownerUserId") . ';' + . "userId=" . $self->ownerUserId . ';' . 'keywords=' . uri_escape( $keyword ) ), }; @@ -836,7 +833,7 @@ sub www_delete { # TODO Get albums with shortcuts to this asset return $self->processStyle( - $self->processTemplate( $var, $self->getGallery->get("templateIdDeleteFile") ) + $self->processTemplate( $var, $self->getGallery->templateIdDeleteFile ) ); } @@ -934,7 +931,7 @@ sub www_editComment { $var->{ isNew } = $commentId eq "new"; return $self->processStyle( - $self->processTemplate( $var, $self->getGallery->get("templateIdEditComment") ) + $self->processTemplate( $var, $self->getGallery->templateIdEditComment ) ); } @@ -1013,9 +1010,9 @@ sub www_makeShortcut { my $albums = $self->getGallery->getAlbumIds; my %albumOptions; for my $assetId ( @$albums ) { - my $asset = WebGUI::Asset->newByDynamicClass($session, $assetId); + my $asset = WebGUI::Asset->newById($session, $assetId); if ($asset->canAddFile) { - $albumOptions{ $assetId } = $asset->get("title"); + $albumOptions{ $assetId } = $asset->title; } } $var->{ form_parentId } @@ -1026,7 +1023,7 @@ sub www_makeShortcut { }); return $self->processStyle( - $self->processTemplate($var, $self->getGallery->get("templateIdMakeShortcut")) + $self->processTemplate($var, $self->getGallery->templateIdMakeShortcut) ); } @@ -1065,7 +1062,7 @@ sub www_view { return $self->session->privilege->insufficient unless $self->canView; # Add to views - $self->update({ views => $self->get('views') + 1 }); + $self->update({ views => $self->views + 1 }); $self->session->http->setLastModified($self->getContentLastModified); $self->session->http->sendHeader; diff --git a/lib/WebGUI/Asset/File/GalleryFile/Photo.pm b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm index d09cfb6fd..eee7ca776 100644 --- a/lib/WebGUI/Asset/File/GalleryFile/Photo.pm +++ b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm @@ -15,13 +15,26 @@ package WebGUI::Asset::File::GalleryFile::Photo; =cut use strict; -use base 'WebGUI::Asset::File::GalleryFile'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::File::GalleryFile'; +aspect assetName => ['assetName', 'Asset_Photo']; +aspect icon => 'photo.gif'; +aspect tableName => 'Photo'; +property exifData => ( + fieldType => 'text', + noFormPost => 1, + default => undef, + ); +property location => ( + fieldType => 'text', + label => ['editForm location','Asset_Photo'], + default => undef, + ); use Carp qw( carp croak ); use Image::ExifTool qw( :Public ); use JSON qw/ to_json from_json /; use URI::Escape; -use Tie::IxHash; use WebGUI::DateTime; use WebGUI::Friends; @@ -58,41 +71,6 @@ These methods are available from this class: =cut -#------------------------------------------------------------------- - -=head2 definition ( session, definition ) - -Define the properties of the Photo asset. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session, 'Asset_Photo'); - - tie my %properties, 'Tie::IxHash', ( - exifData => { - defaultValue => undef, - }, - location => { - defaultValue => undef, - }, - ); - - push @{$definition}, { - assetName => $i18n->get('assetName'), - autoGenerateForms => 0, - icon => 'photo.gif', - tableName => 'Photo', - className => 'WebGUI::Asset::File::GalleryFile::Photo', - properties => \%properties, - }; - - return $class->SUPER::definition($session, $definition); -} - #---------------------------------------------------------------------------- =head2 applyConstraints ( options ) @@ -113,18 +91,18 @@ sub applyConstraints { my $gallery = $self->getGallery; # Update the asset's size and make a thumbnail - my $maxImageSize = $gallery->get("imageViewSize") + my $maxImageSize = $gallery->imageViewSize || $self->session->setting->get("maxImageSize"); - my $parameters = $self->get("parameters"); + my $parameters = $self->parameters; my $storage = $self->getStorageLocation; - my $file = $self->get("filename"); + my $file = $self->filename; # Make resolutions before fixing image, so that we can get higher quality # resolutions $self->makeResolutions; # adjust density before size, so that the dimensions won't change - $storage->resize( $file, undef, undef, $gallery->get( 'imageDensity' ) ); + $storage->resize( $file, undef, undef, $gallery->imageDensity ); $storage->adjustMaxImageSize($file, $maxImageSize); $self->generateThumbnail; @@ -144,8 +122,8 @@ Generates a thumbnail for this image. sub generateThumbnail { my $self = shift; $self->getStorageLocation->generateThumbnail( - $self->get("filename"), - $self->getGallery->get("imageThumbnailSize"), + $self->filename, + $self->getGallery->imageThumbnailSize, ); return; } @@ -187,9 +165,9 @@ sub getEditFormUploadControl { my $i18n = WebGUI::International->new($session, 'Asset_File'); my $html = ''; - if ($self->get("filename") ne "") { + if ($self->filename ne "") { $html .= WebGUI::Form::readOnly( $session, { - value => '

'.$self->get( '.$self->get("filename").'

' + value => '

'.$self->filename.' '.$self->filename.'

' }); } @@ -215,14 +193,14 @@ Gets a hash reference of Exif data about this Photo. sub getExifData { my $self = shift; - return unless $self->get('exifData'); + return unless $self->exifData; # Our processing and eliminating of bad / unparsable keys # isn't perfect, so handle errors gracefully - my $exif = eval { from_json( $self->get('exifData') ) }; + my $exif = eval { from_json( $self->exifData ) }; if ( $@ ) { $self->session->errorHandler->warn( - "Could not parse JSON data for EXIF in Photo '" . $self->get('title') + "Could not parse JSON data for EXIF in Photo '" . $self->title . "' (" . $self->getId . "): " . $@ ); return; @@ -245,7 +223,7 @@ sub getResolutions { my $storage = $self->getStorageLocation; # Return a list not including the web view image. - return [ sort { $a <=> $b } grep { $_ ne $self->get("filename") } @{ $storage->getFiles } ]; + return [ sort { $a <=> $b } grep { $_ ne $self->filename } @{ $storage->getFiles } ]; } #---------------------------------------------------------------------------- @@ -310,7 +288,7 @@ Get the URL to the thumbnail for this Photo. sub getThumbnailUrl { my $self = shift; return $self->getStorageLocation->getThumbnailUrl( - $self->get("filename") + $self->filename ); } @@ -336,7 +314,7 @@ sub makeResolutions { $resolutions ||= $self->getGallery->getImageResolutions; my $storage = $self->getStorageLocation; - $self->session->errorHandler->info(" Making resolutions for '" . $self->get("filename") . q{'}); + $self->session->errorHandler->info(" Making resolutions for '" . $self->filename . q{'}); for my $res ( @$resolutions ) { # carp if resolution is bad @@ -345,8 +323,8 @@ sub makeResolutions { next; } my $newFilename = $res . ".jpg"; - $storage->copyFile( $self->get("filename"), $newFilename ); - $storage->resize( $newFilename, $res, undef, $self->getGallery->get( 'imageDensity' ) ); + $storage->copyFile( $self->filename, $newFilename ); + $storage->resize( $newFilename, $res, undef, $self->getGallery->imageDensity ); } } @@ -371,7 +349,7 @@ sub processPropertiesFromFormPost { ### Passes all checks # If no title was given, make it the file name if ( !$form->get('title') ) { - my $title = $self->get('filename'); + my $title = $self->filename; $title =~ s/\.[^.]*$//; $title =~ tr/-/ /; # De-mangle the spaces at the expense of the dashes $self->update( { @@ -382,7 +360,7 @@ sub processPropertiesFromFormPost { # If this is a new Photo, change some other things too if ( $form->get('assetId') eq "new" ) { $self->update( { - url => $self->session->url->urlize( join "/", $self->getParent->get('url'), $title ), + url => $self->session->url->urlize( join "/", $self->getParent->url, $title ), } ); } } @@ -418,7 +396,7 @@ sub updateExifDataFromFile { my $exifTool = Image::ExifTool->new; $exifTool->Options( PrintConv => 1 ); - my $info = $exifTool->ImageInfo( $storage->getPath( $self->get('filename') ) ); + my $info = $exifTool->ImageInfo( $storage->getPath( $self->filename ) ); # Sanitize Exif data by removing keys with references as values for my $key ( keys %$info ) { @@ -461,7 +439,7 @@ sub www_download { return $storage->getFileContentsAsScalar( $resolution . ".jpg" ); } else { - return $storage->getFileContentsAsScalar( $self->get("filename") ); + return $storage->getFileContentsAsScalar( $self->filename ); } } @@ -524,7 +502,7 @@ sub www_edit { }) . WebGUI::Form::hidden( $session, { name => 'ownerUserId', - value => $self->get('ownerUserId'), + value => $self->ownerUserId, }) ; } @@ -545,7 +523,7 @@ sub www_edit { $var->{ form_title } = WebGUI::Form::Text( $session, { name => "title", - value => ( $form->get("title") || $self->get("title") ), + value => ( $form->get("title") || $self->title ), }); $self->getGallery; @@ -553,8 +531,8 @@ sub www_edit { $var->{ form_synopsis } = WebGUI::Form::HTMLArea( $session, { name => "synopsis", - value => ( $form->get("synopsis") || $self->get("synopsis") ), - richEditId => $self->getGallery->get("richEditIdFile"), + value => ( $form->get("synopsis") || $self->synopsis ), + richEditId => $self->getGallery->richEditIdFile, }); $var->{ form_photo } = $self->getEditFormUploadControl; @@ -562,19 +540,19 @@ sub www_edit { $var->{ form_keywords } = WebGUI::Form::Text( $session, { name => "keywords", - value => ( $form->get("keywords") || $self->get("keywords") ), + value => ( $form->get("keywords") || $self->keywords ), }); $var->{ form_location } = WebGUI::Form::Text( $session, { name => "location", - value => ( $form->get("location") || $self->get("location") ), + value => ( $form->get("location") || $self->location ), }); $var->{ form_friendsOnly } = WebGUI::Form::yesNo( $session, { name => "friendsOnly", - value => ( $form->get("friendsOnly") || $self->get("friendsOnly") ), + value => ( $form->get("friendsOnly") || $self->friendsOnly ), defaultValue => undef, }); diff --git a/lib/WebGUI/Asset/File/Image.pm b/lib/WebGUI/Asset/File/Image.pm index 711ae6b4c..1ca02e2aa 100644 --- a/lib/WebGUI/Asset/File/Image.pm +++ b/lib/WebGUI/Asset/File/Image.pm @@ -15,12 +15,39 @@ package WebGUI::Asset::File::Image; =cut use strict; -use base 'WebGUI::Asset::File'; use WebGUI::Storage; use WebGUI::HTMLForm; use WebGUI::Utility; use WebGUI::Form::Image; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::File'; +aspect assetName => ['assetName', 'Asset_Image']; +aspect tableName => 'ImageAsset'; +aspect icon => 'image.gif'; +property thumbnailSize => ( + label => ['thumbnail size', 'Asset_Image'], + hoverHelp => ['Thumbnail size description', 'Asset_Image'], + fieldType => 'integer', + builder => '_default_thumbnailSize', + lazy => 1, + ); +sub _default_thumbnailSize { + my $self = shift; + return $self->session->setting->get('thumbnailSize'); +} +property parameters => ( + label => ['parameters', 'Asset_Image'], + hoverHelp => ['Parameters description', 'Asset_Image'], + fieldType => 'textarea', + default => 'style="border-style:none;"', + ); +property annotations => ( + fieldType => 'hidden', + noFormPost => 1, + default => '', + ); + =head1 NAME Package WebGUI::Asset::File::Image @@ -66,14 +93,14 @@ sub applyConstraints { my $self = shift; my $options = shift; $self->SUPER::applyConstraints($options); - my $maxImageSize = $options->{maxImageSize} || $self->get('maxImageSize') || $self->session->setting->get("maxImageSize"); - my $thumbnailSize = $options->{thumbnailSize} || $self->get('thumbnailSize') || $self->session->setting->get("thumbnailSize"); - my $parameters = $self->get("parameters"); + my $maxImageSize = $options->{maxImageSize} || $self->maxImageSize || $self->session->setting->get("maxImageSize"); + my $thumbnailSize = $options->{thumbnailSize} || $self->thumbnailSize || $self->session->setting->get("thumbnailSize"); + my $parameters = $self->parameters; my $storage = $self->getStorageLocation; unless ($parameters =~ /alt\=/) { - $self->update({parameters=>$parameters.' alt="'.$self->get("title").'"'}); + $self->update({parameters=>$parameters.' alt="'.$self->title.'"'}); } - my $file = $self->get("filename"); + my $file = $self->filename; $storage->adjustMaxImageSize($file, $maxImageSize); $self->generateThumbnail($thumbnailSize); $self->setSize; @@ -81,49 +108,6 @@ sub applyConstraints { -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Image"); - push @{$definition}, { - assetName => $i18n->get('assetName'), - tableName => 'ImageAsset', - className => 'WebGUI::Asset::File::Image', - icon => 'image.gif', - properties => { - thumbnailSize => { - fieldType => 'integer', - defaultValue => $session->setting->get("thumbnailSize"), - }, - parameters => { - fieldType => 'textarea', - defaultValue => 'style="border-style:none;"', - }, - annotations => { - fieldType => 'hidden', - noFormPost => 1, - defaultValue => '', - }, - }, - }; - return $class->SUPER::definition($session,$definition); -} - - - #------------------------------------------------------------------- =head2 generateThumbnail ( [ thumbnailSize ] ) @@ -142,7 +126,7 @@ sub generateThumbnail { if (defined $thumbnailSize) { $self->update({thumbnailSize=>$thumbnailSize}); } - $self->getStorageLocation->generateThumbnail($self->get("filename"),$self->get("thumbnailSize")); + $self->getStorageLocation->generateThumbnail($self->filename,$self->thumbnailSize); } @@ -162,13 +146,13 @@ sub getEditForm { -name=>"thumbnailSize", -label=>$i18n->get('thumbnail size'), -hoverHelp=>$i18n->get('Thumbnail size description'), - -value=>$self->getValue("thumbnailSize") + -value=>$self->thumbnailSize, ); $tabform->getTab("properties")->textarea( -name=>"parameters", -label=>$i18n->get('parameters'), -hoverHelp=>$i18n->get('Parameters description'), - -value=>$self->getValue("parameters") + -value=>$self->parameters, ); if ($self->get("filename") ne "") { $tabform->getTab("properties")->readOnly( @@ -195,7 +179,7 @@ Returns the URL to the thumbnail of the image stored in the Asset. sub getThumbnailUrl { my $self = shift; - return $self->getStorageLocation->getThumbnailUrl($self->get("filename")); + return $self->getStorageLocation->getThumbnailUrl($self->filename); } #------------------------------------------------------------------- @@ -223,7 +207,7 @@ Renders this asset. sub view { my $self = shift; my $cache = $self->session->cache; - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10) { + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10) { my $out = eval{$cache->get("view_".$self->getId)}; return $out if $out; } @@ -239,15 +223,15 @@ sub view { $style->setScript($url->extras('yui/build/container/container-min.js'), {type=>'text/javascript'}); } - $var{controls} = $self->getToolbar; - $var{fileUrl} = $self->getFileUrl; - $var{fileIcon} = $self->getFileIconUrl; - $var{thumbnail} = $self->getThumbnailUrl; + $var{controls} = $self->getToolbar; + $var{fileUrl} = $self->getFileUrl; + $var{fileIcon} = $self->getFileIconUrl; + $var{thumbnail} = $self->getThumbnailUrl; $var{annotateJs} = "$crop_js$domMe"; $var{parameters} = sprintf("id=%s", $self->getId()); my $form = $self->session->form; my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10) { + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10) { eval{$cache->set("view_".$self->getId, $out, $self->get("cacheTimeout"))}; } return $out; @@ -282,11 +266,11 @@ sub www_edit { return $self->session->privilege->insufficient() unless $self->canEdit; return $self->session->privilege->locked() unless $self->canEditIfLocked; my $i18n = WebGUI::International->new($self->session, 'Asset_Image'); - $self->getAdminConsole->addSubmenuItem($self->getUrl('func=resize'),$i18n->get("resize image")) if ($self->get("filename")); - $self->getAdminConsole->addSubmenuItem($self->getUrl('func=rotate'),$i18n->get("rotate image")) if ($self->get("filename")); - $self->getAdminConsole->addSubmenuItem($self->getUrl('func=crop'),$i18n->get("crop image")) if ($self->get("filename")); - $self->getAdminConsole->addSubmenuItem($self->getUrl('func=annotate'),$i18n->get("annotate image")) if ($self->get("filename")); - $self->getAdminConsole->addSubmenuItem($self->getUrl('func=undo'),$i18n->get("undo image")) if ($self->get("filename")); + $self->getAdminConsole->addSubmenuItem($self->getUrl('func=resize'),$i18n->get("resize image")) if ($self->filename); + $self->getAdminConsole->addSubmenuItem($self->getUrl('func=rotate'),$i18n->get("rotate image")) if ($self->filename); + $self->getAdminConsole->addSubmenuItem($self->getUrl('func=crop'),$i18n->get("crop image")) if ($self->filename); + $self->getAdminConsole->addSubmenuItem($self->getUrl('func=annotate'),$i18n->get("annotate image")) if ($self->filename); + $self->getAdminConsole->addSubmenuItem($self->getUrl('func=undo'),$i18n->get("undo image")) if ($self->filename); my $tabform = $self->getEditForm; $tabform->getTab("display")->template( -value=>$self->get("templateId"), @@ -339,8 +323,8 @@ sub www_annotate { if (1) { my $newSelf = $self->addRevision(); delete $newSelf->{_storageLocation}; - $newSelf->getStorageLocation->annotate($newSelf->get("filename"),$newSelf,$newSelf->session->form); - $newSelf->setSize($newSelf->getStorageLocation->getFileSize($newSelf->get("filename"))); + $newSelf->getStorageLocation->annotate($newSelf->filename,$newSelf,$newSelf->session->form); + $newSelf->setSize($newSelf->getStorageLocation->getFileSize($newSelf->filename)); $self = $newSelf; $self->generateThumbnail; } @@ -360,7 +344,7 @@ sub www_annotate { # my $imageAsset = $self->session->db->getRow("ImageAsset","assetId",$self->getId); - my @pieces = split(/\n/, $self->get('annotations')); + my @pieces = split(/\n/, $self->annotations); # my ($top_left, $width_height, $note) = split(/\n/, $imageAsset->{annotations}); my ($img_null, $tooltip_block, $tooltip_none) = ('', '', ''); @@ -372,9 +356,9 @@ sub www_annotate { # warn("i: $i: ", $self->session->form->process("delAnnotate$i")); } - my $image = '
'.$self->get(
'; + my $image = '
'.$self->filename.'
'; - my ($width, $height) = $self->getStorageLocation->getSize($self->get("filename")); + my ($width, $height) = $self->getStorageLocation->getSize($self->filename); my @checkboxes = (); my $i18n = WebGUI::International->new($self->session,"Asset_Image"); @@ -438,7 +422,7 @@ sub annotate_js { my $self = shift; my $opts = shift; - my @pieces = split(/\n/, $self->get('annotations')); + my @pieces = split(/\n/, $self->annotations); # warn("pieces: $#pieces: ". $self->getId()); return "" if !@pieces && $opts->{just_image}; @@ -561,20 +545,20 @@ sub www_rotate { if (defined $self->session->form->process("Rotate")) { my $newSelf = $self->addRevision(); delete $newSelf->{_storageLocation}; - $newSelf->getStorageLocation->rotate($newSelf->get("filename"),$newSelf->session->form->process("Rotate")); - $newSelf->setSize($newSelf->getStorageLocation->getFileSize($newSelf->get("filename"))); + $newSelf->getStorageLocation->rotate($newSelf->filename,$newSelf->session->form->process("Rotate")); + $newSelf->setSize($newSelf->getStorageLocation->getFileSize($newSelf->filename)); $self = $newSelf; $self->generateThumbnail; } - my ($x, $y) = $self->getStorageLocation->getSizeInPixels($self->get("filename")); + my ($x, $y) = $self->getStorageLocation->getSizeInPixels($self->filename); ##YUI specific datatable CSS my ($style, $url) = $self->session->quick(qw(style url)); - my $img_name = $self->getStorageLocation->getUrl($self->get("filename")); - my $img_file = $self->get("filename"); - my $image = '
'.$self->get(
'; + my $img_name = $self->getStorageLocation->getUrl($self->filename); + my $img_file = $self->filename; + my $image = '
'.$self->filename.'
'; my $i18n = WebGUI::International->new($self->session,"Asset_Image"); $self->getAdminConsole->addSubmenuItem($self->getUrl('func=edit'),$i18n->get("edit image")); @@ -618,13 +602,13 @@ sub www_resize { if ($self->session->form->process("newWidth") || $self->session->form->process("newHeight")) { my $newSelf = $self->addRevision(); delete $newSelf->{_storageLocation}; - $newSelf->getStorageLocation->resize($newSelf->get("filename"),$newSelf->session->form->process("newWidth"),$newSelf->session->form->process("newHeight")); - $newSelf->setSize($newSelf->getStorageLocation->getFileSize($newSelf->get("filename"))); + $newSelf->getStorageLocation->resize($newSelf->filename,$newSelf->session->form->process("newWidth"),$newSelf->session->form->process("newHeight")); + $newSelf->setSize($newSelf->getStorageLocation->getFileSize($newSelf->filename)); $self = $newSelf; $self->generateThumbnail; } - my ($x, $y) = $self->getStorageLocation->getSizeInPixels($self->get("filename")); + my ($x, $y) = $self->getStorageLocation->getSizeInPixels($self->filename); ##YUI specific datatable CSS my ($style, $url) = $self->session->quick(qw(style url)); @@ -699,7 +683,7 @@ sub www_resize { -value=>$y, ); $f->submit; - my $image = '
'.$self->get(
'.$resize_js; + my $image = '
'.$self->filename.'
'.$resize_js; return $self->getAdminConsole->render($f->print.$image,$i18n->get("resize image")); } @@ -725,7 +709,7 @@ sub www_crop { my $newSelf = $self->addRevision(); delete $newSelf->{_storageLocation}; $newSelf->getStorageLocation->crop( - $newSelf->get("filename"), + $newSelf->filename, $newSelf->session->form->process("Width"), $newSelf->session->form->process("Height"), $newSelf->session->form->process("Top"), @@ -735,7 +719,7 @@ sub www_crop { $self->generateThumbnail; } - my $filename = $self->get("filename"); + my $filename = $self->filename; ##YUI specific datatable CSS my ($style, $url) = $self->session->quick(qw(style url)); diff --git a/lib/WebGUI/Asset/File/ZipArchive.pm b/lib/WebGUI/Asset/File/ZipArchive.pm index 9fbca6fd7..51220ec2f 100644 --- a/lib/WebGUI/Asset/File/ZipArchive.pm +++ b/lib/WebGUI/Asset/File/ZipArchive.pm @@ -15,7 +15,29 @@ package WebGUI::Asset::File::ZipArchive; =cut use strict; -use base 'WebGUI::Asset::File'; + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::File'; +aspect assetName => ['assetName', 'Asset_ZipArchive']; +aspect tableName => 'ZipArchiveAsset'; +aspect icon => 'ziparchive.gif'; +property showPage => ( + tab => "properties", + label => ['show page', 'Asset_ZipArchive'], + hoverHelp => ['show page description', 'Asset_ZipArchive'], + fieldType => 'text', + default => 'index.html', + ); +property templateId => ( + tab => "display", + label => ['template label', 'Asset_ZipArchive'], + hoverHelp => ['template description', 'Asset_ZipArchive'], + namespace => "ZipArchiveAsset", + fieldType => 'template', + default => '', + ); + + use WebGUI::HTMLForm; use WebGUI::SQL; use WebGUI::Utility; @@ -94,65 +116,6 @@ sub unzip { return 1; } -#------------------------------------------------------------------- - -=head2 addRevision ( ) - -This method exists for demonstration purposes only. The superclass -handles revisions to ZipArchive Assets. - -=cut - -sub addRevision { - my $self = shift; - my $newSelf = $self->SUPER::addRevision(@_); - return $newSelf; -} - -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_ZipArchive"); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - tableName=>'ZipArchiveAsset', - autoGenerateForms=>1, - icon=>'ziparchive.gif', - className=>'WebGUI::Asset::File::ZipArchive', - properties=>{ - showPage=>{ - tab=>"properties", - label=>$i18n->get('show page'), - hoverHelp=>$i18n->get('show page description'), - fieldType=>'text', - defaultValue=>'index.html' - }, - templateId=>{ - tab=>"display", - label=>$i18n->get('template label'), - namespace=>"ZipArchiveAsset", - fieldType=>'template', - defaultValue=>'' - }, - } - }); - return $class->SUPER::definition($session,$definition); -} - - #------------------------------------------------------------------- =head2 prepareView ( ) @@ -164,7 +127,7 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId")); + my $template = WebGUI::Asset::Template->newById($self->session, $self->get("templateId")); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; } @@ -185,7 +148,7 @@ sub processPropertiesFromFormPost { $self->SUPER::processPropertiesFromFormPost; my $storage = $self->getStorageLocation(); - my $file = $self->get("filename"); + my $file = $self->filename; #return undef unless $file; my $i18n = WebGUI::International->new($self->session, 'Asset_ZipArchive'); @@ -203,7 +166,7 @@ sub processPropertiesFromFormPost { return undef; } - unless ($self->unzip($storage,$self->get("filename"))) { + unless ($self->unzip($storage,$self->filename)) { $self->session->errorHandler->warn($i18n->get("unzip_error")); } } @@ -221,7 +184,7 @@ used to show the file to administrators. sub view { my $self = shift; my $cache = $self->session->cache; - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10) { + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10) { my $out = eval{$cache->get("view_".$self->getId)}; return $out if $out; } @@ -233,19 +196,19 @@ sub view { } $self->session->scratch->delete("za_error"); my $storage = $self->getStorageLocation; - if($self->get("filename") ne "") { - $var{fileUrl} = $storage->getUrl($self->get("showPage")); - $var{fileIcon} = $storage->getFileIconUrl($self->get("showPage")); + if($self->filename ne "") { + $var{fileUrl} = $storage->getUrl($self->showPage); + $var{fileIcon} = $storage->getFileIconUrl($self->showPage); } - unless($self->get("showPage")) { + unless($self->showPage) { $var{pageError} = "true"; } my $i18n = WebGUI::International->new($self->session,"Asset_ZipArchive"); $var{noInitialPage} = $i18n->get('noInitialPage'); $var{noFileSpecified} = $i18n->get('noFileSpecified'); my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10) { - eval{$cache->set("view_".$self->getId, $out, $self->get("cacheTimeout"))}; + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10) { + eval{$cache->set("view_".$self->getId, $out, $self->cacheTimeout)}; } return $out; } @@ -283,7 +246,7 @@ sub www_view { if ($self->session->var->isAdminOn) { return $self->session->asset($self->getContainer)->www_view; } - $self->session->http->setRedirect($self->getFileUrl($self->getValue("showPage"))); + $self->session->http->setRedirect($self->getFileUrl($self->showPage)); return "1"; } diff --git a/lib/WebGUI/Asset/MapPoint.pm b/lib/WebGUI/Asset/MapPoint.pm index 55e105148..25237aaf7 100644 --- a/lib/WebGUI/Asset/MapPoint.pm +++ b/lib/WebGUI/Asset/MapPoint.pm @@ -16,12 +16,113 @@ package WebGUI::Asset::MapPoint; use strict; use Tie::IxHash; -use base 'WebGUI::Asset'; -use WebGUI::Utility; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_MapPoint']; +aspect icon => 'MapPoint.gif'; +aspect tableName => 'MapPoint'; +property latitude => ( + tab => "properties", + fieldType => "float", + label => ["latitude label", 'Asset_MapPoint'], + hoverHelp => ["latitude description", 'Asset_MapPoint'], + ); +property longitude => ( + tab => "properties", + fieldType => "float", + label => ["longitude label", 'Asset_MapPoint'], + hoverHelp => ["longitude description", 'Asset_MapPoint'], + ); +property website => ( + tab => "properties", + fieldType => "text", + label => ["website label", 'Asset_MapPoint'], + hoverHelp => ["website description", 'Asset_MapPoint'], + ); +property address1 => ( + tab => "properties", + fieldType => "text", + label => ["address1 label", 'Asset_MapPoint'], + hoverHelp => ["address1 description", 'Asset_MapPoint'], + ); +property address2 => ( + tab => "properties", + fieldType => "text", + label => ["address2 label", 'Asset_MapPoint'], + hoverHelp => ["address2 description", 'Asset_MapPoint'], + ); +property city => ( + tab => "properties", + fieldType => "text", + label => ["city label", 'Asset_MapPoint'], + hoverHelp => ["city description", 'Asset_MapPoint'], + ); +property state => ( + tab => "properties", + fieldType => "text", + label => ["state label", 'Asset_MapPoint'], + hoverHelp => ["state description", 'Asset_MapPoint'], + ); +property zipCode => ( + tab => "properties", + fieldType => "text", + label => ["zipCode label", 'Asset_MapPoint'], + hoverHelp => ["zipCode description", 'Asset_MapPoint'], + ); +property country => ( + tab => "properties", + fieldType => "country", + label => ["country label", 'Asset_MapPoint'], + hoverHelp => ["country description", 'Asset_MapPoint'], + ); +property phone => ( + tab => "properties", + fieldType => "phone", + label => ["phone label", 'Asset_MapPoint'], + hoverHelp => ["phone description", 'Asset_MapPoint'], + ); +property fax => ( + tab => "properties", + fieldType => "phone", + label => ["fax label", 'Asset_MapPoint'], + hoverHelp => ["fax description", 'Asset_MapPoint'], + ); +property email => ( + tab => "properties", + fieldType => "email", + label => ["email label", 'Asset_MapPoint'], + hoverHelp => ["email description", 'Asset_MapPoint'], + ); +property storageIdPhoto => ( + tab => "properties", + fieldType => "image", + forceImageOnly => 1, + label => ["storageIdPhoto label", 'Asset_MapPoint'], + hoverHelp => ["storageIdPhoto description", 'Asset_MapPoint'], + noFormPost => 1, + ); +property userDefined1 => ( + fieldType => "hidden", + noFormPost => 1, + ); +property userDefined2 => ( + fieldType => "hidden", + noFormPost => 1, + ); +property userDefined3 => ( + fieldType => "hidden", + noFormPost => 1, + ); +property userDefined4 => ( + fieldType => "hidden", + noFormPost => 1, + ); +property userDefined5 => ( + fieldType => "hidden", + noFormPost => 1, + ); -# To get an installer for your wobject, add the Installable AssetAspect -# See WebGUI::AssetAspect::Installable and sbin/installClass.pl for more -# details +use WebGUI::Utility; =head1 NAME @@ -44,134 +145,6 @@ These methods are available from this class: #------------------------------------------------------------------- -=head2 definition ( session, definition ) - -defines asset properties for New Asset instances. You absolutely need -this method in your new Assets. - -=head3 session - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new( $session, "Asset_MapPoint" ); - tie my %properties, 'Tie::IxHash', ( - latitude => { - tab => "properties", - fieldType => "float", - label => $i18n->get("latitude label"), - hoverHelp => $i18n->get("latitude description"), - }, - longitude => { - tab => "properties", - fieldType => "float", - label => $i18n->get("longitude label"), - hoverHelp => $i18n->get("longitude description"), - }, - website => { - tab => "properties", - fieldType => "text", - label => $i18n->get("website label"), - hoverHelp => $i18n->get("website description"), - }, - address1 => { - tab => "properties", - fieldType => "text", - label => $i18n->get("address1 label"), - hoverHelp => $i18n->get("address1 description"), - }, - address2 => { - tab => "properties", - fieldType => "text", - label => $i18n->get("address2 label"), - hoverHelp => $i18n->get("address2 description"), - }, - city => { - tab => "properties", - fieldType => "text", - label => $i18n->get("city label"), - hoverHelp => $i18n->get("city description"), - }, - state => { - tab => "properties", - fieldType => "text", - label => $i18n->get("state label"), - hoverHelp => $i18n->get("state description"), - }, - zipCode => { - tab => "properties", - fieldType => "text", - label => $i18n->get("zipCode label"), - hoverHelp => $i18n->get("zipCode description"), - }, - country => { - tab => "properties", - fieldType => "country", - label => $i18n->get("country label"), - hoverHelp => $i18n->get("country description"), - }, - phone => { - tab => "properties", - fieldType => "phone", - label => $i18n->get("phone label"), - hoverHelp => $i18n->get("phone description"), - }, - fax => { - tab => "properties", - fieldType => "phone", - label => $i18n->get("fax label"), - hoverHelp => $i18n->get("fax description"), - }, - email => { - tab => "properties", - fieldType => "email", - label => $i18n->get("email label"), - hoverHelp => $i18n->get("email description"), - }, - storageIdPhoto => { - tab => "properties", - fieldType => "image", - forceImageOnly => 1, - label => $i18n->get("storageIdPhoto label"), - hoverHelp => $i18n->get("storageIdPhoto description"), - noFormPost => 1, - }, - userDefined1 => { - fieldType => "hidden", - }, - userDefined2 => { - fieldType => "hidden", - }, - userDefined3 => { - fieldType => "hidden", - }, - userDefined4 => { - fieldType => "hidden", - }, - userDefined5 => { - fieldType => "hidden", - }, - ); - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'MapPoint.gif', - autoGenerateForms => 1, - tableName => 'MapPoint', - className => 'WebGUI::Asset::MapPoint', - properties => \%properties, - }; - return $class->SUPER::definition( $session, $definition ); -} ## end sub definition - -#------------------------------------------------------------------- - =head2 canEdit ( [userId] ) Returns true if the user can edit this MapPoint. Only the owner or the @@ -182,7 +155,7 @@ group to edit the parent Map are allowed to edit MapPoint. sub canEdit { my $self = shift; my $userId = shift || $self->session->user->userId; - return 1 if $userId eq $self->get('ownerUserId'); + return 1 if $userId eq $self->ownerUserId; return $self->SUPER::canEdit( $userId ); } @@ -196,7 +169,7 @@ Get the workflowId to commit this MapPoint sub getAutoCommitWorkflowId { my ( $self ) = @_; - return $self->getParent->get('workflowIdPoint'); + return $self->getParent->workflowIdPoint; } #------------------------------------------------------------------- @@ -229,7 +202,7 @@ sub getMapInfo { $var->{ assetId } = $self->getId; my @keys = qw( latitude longitude title ); for my $key ( @keys ) { - $var->{ $key } = $self->get( $key ); + $var->{ $key } = $self->$key; } # Get permissions @@ -287,11 +260,11 @@ sub getTemplateVarsEditForm { } ) . WebGUI::Form::hidden( $session, { name => 'latitude', - value => $self->get('latitude'), + value => $self->latitude, } ) . WebGUI::Form::hidden( $session, { name => 'longitude', - value => $self->get('longitude'), + value => $self->longitude, } ) ; $var->{ form_footer } = WebGUI::Form::formFooter( $session ); @@ -305,7 +278,7 @@ sub getTemplateVarsEditForm { for my $key ( keys %{$definition} ) { next if $definition->{$key}->{noFormPost}; $definition->{$key}->{name} = $key; - $definition->{$key}->{value} = $self->getValue($key); + $definition->{$key}->{value} = $self->$key; $var->{ "form_$key" } = WebGUI::Form::dynamicField( $session, %{$definition->{$key}} ); } @@ -314,20 +287,20 @@ sub getTemplateVarsEditForm { $var->{ "form_title" } = WebGUI::Form::text( $session, { name => "title", - value => $self->get("title"), + value => $self->title, } ); $var->{ "form_synopsis" } = WebGUI::Form::textarea( $session, { name => "synopsis", - value => $self->get("synopsis"), + value => $self->synopsis, resizable => 0, } ); # Fix storageIdPhoto because scripts do not get executed in ajax requests $var->{ "form_storageIdPhoto" } = ''; - if ( $self->get('storageIdPhoto') ) { - my $storage = WebGUI::Storage->get( $self->session, $self->get('storageIdPhoto') ); + if ( $self->storageIdPhoto ) { + my $storage = WebGUI::Storage->get( $self->session, $self->storageIdPhoto ); $var->{ "currentPhoto" } = sprintf '', $storage->getUrl($storage->getFiles->[0]); } @@ -371,8 +344,8 @@ sub processAjaxEditForm { # Photo magic if ( $form->get('storageIdPhoto') ) { my $storage; - if ( $self->get('storageIdPhoto') ) { - $storage = WebGUI::Storage->get( $session, $self->get('storageIdPhoto') ); + if ( $self->storageIdPhoto ) { + $storage = WebGUI::Storage->get( $session, $self->storageIdPhoto ); $storage->deleteFile( $storage->getFiles->[0] ); } else { diff --git a/lib/WebGUI/Asset/MatrixListing.pm b/lib/WebGUI/Asset/MatrixListing.pm index 7539558bc..2b5989793 100644 --- a/lib/WebGUI/Asset/MatrixListing.pm +++ b/lib/WebGUI/Asset/MatrixListing.pm @@ -16,10 +16,107 @@ package WebGUI::Asset::MatrixListing; use strict; use Tie::IxHash; -use Class::C3; -use base qw(WebGUI::AssetAspect::Comments WebGUI::Asset); -use WebGUI::Utility; +#use base qw(WebGUI::AssetAspect::Comments WebGUI::Asset); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_MatrixListing']; +aspect tableName => 'MatrixListing'; +property screenshots => ( + tab => "properties", + fieldType => "image", + default => undef, + maxAttachments => 20, + label => ["screenshots label", 'Asset_MatrixListing'], + hoverHelp => ["screenshots description", 'Asset_MatrixListing'], + ); +property description => ( + tab => "properties", + fieldType => "HTMLArea", + default => undef, + label => ["description label", 'Asset_MatrixListing'], + hoverHelp => ["description description", 'Asset_MatrixListing'], + ); +property version => ( + tab => "properties", + fieldType => "text", + default => undef, + label => ["version label", 'Asset_MatrixListing'], + hoverHelp => ["version description", 'Asset_MatrixListing'], + ); +property score => ( + fieldType => 'integer', + default => 0, + noFormPost => 1, + ); +property views => ( + fieldType => 'integer', + default => 0, + noFormPost => 1, + ); +property compares => ( + fieldType => 'integer', + default => 0, + noFormPost => 1, + ); +property clicks => ( + fieldType => 'integer', + default => 0, + noFormPost => 1, + ); +property viewsLastIp => ( + fieldType => 'text', + default => undef, + noFormPost => 1, + ); +property comparesLastIp => ( + fieldType => 'text', + default => undef, + noFormPost => 1, + ); +property clicksLastIp => ( + fieldType => 'text', + default => undef, + noFormPost => 1, + ); +property maintainer => ( + tab => "properties", + fieldType => "user", + builder => '_maintainer_default', + lazy => 1, + label => ["maintainer label", 'Asset_MatrixListing'], + hoverHelp => ["maintainer description", 'Asset_MatrixListing'], + ); +sub _maintainer_default { + return shift->session->user->userId; +} +property manufacturerName => ( + tab => "properties", + fieldType => "text", + default => undef, + label => ["manufacturerName label", 'Asset_MatrixListing'], + hoverHelp => ["manufacturerName description", 'Asset_MatrixListing'] + ); +property manufacturerURL => ( + tab => "properties", + fieldType => "url", + default => undef, + label => ["manufacturerURL label", 'Asset_MatrixListing'], + hoverHelp => ["manufacturerURL description", 'Asset_MatrixListing'] + ); +property productURL => ( + tab => "properties", + fieldType => "url", + default => undef, + label => ["productURL label", 'Asset_MatrixListing'], + hoverHelp => ["productURL description", 'Asset_MatrixListing'] + ); +property lastUpdated => ( + default => sub { time() }, + noFormPost => 1, + fieldType => 'hidden', + ); +use WebGUI::Utility; =head1 NAME @@ -117,100 +214,8 @@ sub definition { tie %properties, 'Tie::IxHash'; my $i18n = WebGUI::International->new($session, "Asset_MatrixListing"); %properties = ( - screenshots => { - tab =>"properties", - fieldType =>"image", - defaultValue =>undef, - maxAttachments =>20, - label =>$i18n->get("screenshots label"), - hoverHelp =>$i18n->get("screenshots description") - }, - description => { - tab =>"properties", - fieldType =>"HTMLArea", - defaultValue =>undef, - label =>$i18n->get("description label"), - hoverHelp =>$i18n->get("description description") - }, - version => { - tab =>"properties", - fieldType =>"text", - defaultValue =>undef, - label =>$i18n->get("version label"), - hoverHelp =>$i18n->get("version description") - }, - score => { - defaultValue =>0, - autoGenerate =>0, - noFormPost =>1, - }, - views => { - defaultValue =>0, - autoGenerate =>0, - noFormPost =>1, - }, - compares => { - defaultValue =>0, - autoGenerate =>0, - noFormPost =>1, - }, - clicks => { - defaultValue =>0, - autoGenerate =>0, - noFormPost =>1, - }, - viewsLastIp => { - defaultValue =>undef, - autoGenerate =>0, - noFormPost =>1, - }, - comparesLastIp => { - defaultValue =>undef, - autoGenerate =>0, - noFormPost =>1, - }, - clicksLastIp => { - defaultValue =>undef, - autoGenerate =>0, - noFormPost =>1, - }, - maintainer => { - tab =>"properties", - fieldType =>"user", - defaultValue =>$session->user->userId, - label =>$i18n->get("maintainer label"), - hoverHelp =>$i18n->get("maintainer description") - }, - manufacturerName => { - tab =>"properties", - fieldType =>"text", - defaultValue =>undef, - label =>$i18n->get("manufacturerName label"), - hoverHelp =>$i18n->get("manufacturerName description") - }, - manufacturerURL => { - tab =>"properties", - fieldType =>"url", - defaultValue =>undef, - label =>$i18n->get("manufacturerURL label"), - hoverHelp =>$i18n->get("manufacturerURL description") - }, - productURL => { - tab =>"properties", - fieldType =>"url", - defaultValue =>undef, - label =>$i18n->get("productURL label"), - hoverHelp =>$i18n->get("productURL description") - }, - lastUpdated => { - defaultValue =>time(), - fieldType =>'hidden', - }, ); push(@{$definition}, { - assetName=>$i18n->get('assetName'), - autoGenerateForms=>1, - tableName=>'MatrixListing', className=>'WebGUI::Asset::MatrixListing', properties=>\%properties }); @@ -289,7 +294,7 @@ sub getEditForm { -defaultValue =>'Untitled', -label =>$i18n->get("product name label"), -hoverHelp =>$i18n->get('product name description'), - -value =>$self->getValue('title'), + -value =>$self->title, ); $form->image( -name =>'screenshots', @@ -297,19 +302,19 @@ sub getEditForm { -maxAttachments =>20, -label =>$i18n->get("screenshots label"), -hoverHelp =>$i18n->get("screenshots description"),, - -value =>$self->getValue('screenshots'), + -value =>$self->screenshots, ); $form->HTMLArea( -name =>'description', -defaultValue =>undef, -label =>$i18n->get("description label"), -hoverHelp =>$i18n->get("description description"), - -value =>$self->getValue('description'), + -value =>$self->description, ); if ($self->getParent->canEdit) { $form->user( name =>"ownerUserId", - value =>$self->getValue('ownerUserId'), + value =>$self->ownerUserId, label =>$i18n->get('maintainer label'), hoverHelp =>$i18n->get('maintainer description'), ); @@ -332,28 +337,28 @@ sub getEditForm { -defaultValue =>undef, -label =>$i18n->get("version label"), -hoverHelp =>$i18n->get("version description"), - -value =>$self->getValue('version'), + -value =>$self->version, ); $form->text( -name =>'manufacturerName', -defaultValue =>undef, -label =>$i18n->get("manufacturerName label"), -hoverHelp =>$i18n->get("manufacturerName description"), - -value =>$self->getValue('manufacturerName'), + -value =>$self->manufacturerName, ); $form->url( -name =>'manufacturerURL', -defaultValue =>undef, -label =>$i18n->get("manufacturerURL label"), -hoverHelp =>$i18n->get("manufacturerURL description"), - -value =>$self->getValue('manufacturerURL'), + -value =>$self->manufacturerURL, ); $form->url( -name =>'productURL', -defaultValue =>undef, -label =>$i18n->get("productURL label"), -hoverHelp =>$i18n->get("productURL description"), - -value =>$self->getValue('productURL'), + -value =>$self->productURL, ); foreach my $category (keys %{$self->getParent->getCategories}) { diff --git a/lib/WebGUI/Asset/Post.pm b/lib/WebGUI/Asset/Post.pm index 4f23e02fe..007f91188 100644 --- a/lib/WebGUI/Asset/Post.pm +++ b/lib/WebGUI/Asset/Post.pm @@ -12,8 +12,72 @@ package WebGUI::Asset::Post; use strict; use Tie::CPHash; -use Tie::IxHash; -use WebGUI::Asset; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_Post']; +aspect icon => 'post.gif'; +aspect tableName => 'Post'; +property storageId => ( + fieldType => "image", + default => '', + enforceSizeLimits => 0, + label => ['attachement', 'Asset_Collaboration'], + ); +property threadId => ( + noFormPost => 1, + fieldType => "hidden", + default => '', + ); +property originalEmail => ( + noFormPost => 1, + fieldType => "hidden", + default => undef, + ); +property username => ( + noFormPost => 1, + fieldType => "hidden", + builder => '_username_builder', + lazy => 1, + ); +sub _username_builder { + my $session = shift->session; + return $session->form->process("visitorUsername") + || $session->user->profileField("alias") + || $session->user->username; +} +property rating => ( + noFormPost => 1, + fieldType => "hidden", + default => undef, + ); +property views => ( + noFormPost => 1, + fieldType => "hidden", + default => undef, + ); +property contentType => ( + label => ['contentType', 'Asset_Collaboration'], + fieldType => "contentType", + default => "mixed", + ); +for my $i ( 1 .. 5 ) { + property 'userDefined'.$i => ( + default => undef, + label => '', + fieldType => 'HTMLArea', + ); +} +property content => ( + label => ['message', 'Asset_Collaboration'], + fieldType => "HTMLArea", + default => undef, + ); + +with 'WebGUI::Role::Asset::AlwaysHidden'; + +with 'WebGUI::Role::Asset::SetStoragePermissions'; + + use WebGUI::Asset::Template; use WebGUI::Asset::Post::Thread; use WebGUI::Group; @@ -31,7 +95,6 @@ use WebGUI::Storage; use WebGUI::User; use WebGUI::Utility; use WebGUI::VersionTag; -our @ISA = qw(WebGUI::Asset); #------------------------------------------------------------------- @@ -62,7 +125,7 @@ sub _fixReplyCount { } )->[0]; if ($lastPost) { - $asset->incrementReplies( $lastPost->get( 'revisionDate' ), $lastPost->getId ); + $asset->incrementReplies( $lastPost->revisionDate, $lastPost->getId ); } else { $asset->incrementReplies( undef, undef ); @@ -82,7 +145,7 @@ sub addChild { my $properties = shift; my @other = @_; if ($properties->{className} ne "WebGUI::Asset::Post") { - $self->session->errorHandler->security("add a ".$properties->{className}." to a ".$self->get("className")); + $self->session->errorHandler->security("add a ".$properties->{className}." to a ".$self->className); return undef; } return $self->SUPER::addChild($properties, @other); @@ -99,17 +162,17 @@ Override the default method in order to deal with attachments. sub addRevision { my $self = shift; my $newSelf = $self->SUPER::addRevision(@_); - if ($newSelf->get("storageId") && $newSelf->get("storageId") eq $self->get('storageId')) { - my $newStorage = WebGUI::Storage->get($self->session,$self->get("storageId"))->copy; + if ($newSelf->storageId && $newSelf->storageId eq $self->storageId) { + my $newStorage = WebGUI::Storage->get($self->session,$self->storageId)->copy; $newSelf->update({storageId=>$newStorage->getId}); } - my $threadId = $newSelf->get("threadId"); + my $threadId = $newSelf->threadId; my $now = time(); if ($threadId eq "") { # new post if ($newSelf->getParent->isa("WebGUI::Asset::Wobject::Collaboration")) { $newSelf->update({threadId=>$newSelf->getId}); } else { - $newSelf->update({threadId=>$newSelf->getParent->get("threadId")}); + $newSelf->update({threadId=>$newSelf->getParent->threadId}); } delete $newSelf->{_thread}; } @@ -170,14 +233,14 @@ sub canEdit { # User who posted can edit their own post if ( $self->isPoster( $userId ) ) { - my $editTimeout = $self->getThread->getParent->get( 'editTimeout' ); - if ( $editTimeout > time - $self->get( "revisionDate" ) ) { + my $editTimeout = $self->getThread->getParent->editTimeout; + if ( $editTimeout > time - $self->revisionDate ) { return 1; } } # Users in groupToEditPost of the Collab can edit any post - if ( $user->isInGroup( $self->getThread->getParent->get('groupToEditPost') ) ) { + if ( $user->isInGroup( $self->getThread->getParent->groupToEditPost ) ) { return 1; } @@ -194,7 +257,7 @@ Returns a boolean indicating whether the user can view the current post. sub canView { my $self = shift; - if (($self->get("status") eq "approved" || $self->get("status") eq "archived") && $self->getThread->getParent->canView) { + if (($self->status eq "approved" || $self->status eq "archived") && $self->getThread->getParent->canView) { return 1; } elsif ($self->canEdit) { return 1; @@ -214,7 +277,7 @@ Cuts a title string off at 30 characters. sub chopTitle { my $self = shift; - return substr($self->get("title"),0,30); + return substr($self->title,0,30); } #------------------------------------------------------------------- @@ -233,11 +296,11 @@ sub commit { $self->notifySubscribers unless ($self->shouldSkipNotification); if ($self->isNew) { - if ($self->session->setting->get("useKarma") && $self->getThread->getParent->get("karmaPerPost")) { - my $u = WebGUI::User->new($self->session, $self->get("ownerUserId")); - $u->karma($self->getThread->getParent->get("karmaPerPost"), $self->getId, "Collaboration post"); + if ($self->session->setting->get("useKarma") && $self->getThread->getParent->karmaPerPost) { + my $u = WebGUI::User->new($self->session, $self->ownerUserId); + $u->karma($self->getThread->getParent->karmaPerPost, $self->getId, "Collaboration post"); } - $self->getThread->incrementReplies($self->get("revisionDate"),$self->getId);# if ($self->isReply); + $self->getThread->incrementReplies($self->revisionDate,$self->getId);# if ($self->isReply); } } @@ -280,69 +343,9 @@ sub definition { my $i18n = WebGUI::International->new($session,"Asset_Post"); my $properties = { - storageId => { - fieldType=>"image", - defaultValue=>'', - enforceSizeLimits => 0, - }, - threadId => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>'', - }, - originalEmail => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - username => { - fieldType=>"hidden", - defaultValue=>$session->form->process("visitorUsername") || $session->user->profileField("alias") || $session->user->username - }, - rating => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - views => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - contentType => { - fieldType=>"contentType", - defaultValue=>"mixed" - }, - userDefined1 => { - fieldType=>"HTMLArea", - defaultValue=>undef - }, - userDefined2 => { - fieldType=>"HTMLArea", - defaultValue=>undef - }, - userDefined3 => { - fieldType=>"HTMLArea", - defaultValue=>undef - }, - userDefined4 => { - fieldType=>"HTMLArea", - defaultValue=>undef - }, - userDefined5 => { - fieldType=>"HTMLArea", - defaultValue=>undef - }, - content => { - fieldType=>"HTMLArea", - defaultValue=>undef - }, }; push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'post.gif', - tableName=>'Post', className=>'WebGUI::Asset::Post', properties=>$properties, }); @@ -376,7 +379,7 @@ Extend the base class to handle storage locations. sub exportAssetData { my $self = shift; my $data = $self->SUPER::exportAssetData; - push(@{$data->{storage}}, $self->get("storageId")) if ($self->get("storageId") ne ""); + push(@{$data->{storage}}, $self->storageId) if ($self->storageId ne ""); return $data; } @@ -418,16 +421,16 @@ The content type to use for formatting. Defaults to the content type specified i sub formatContent { my $self = shift; - my $content = shift || $self->get("content"); - my $contentType = shift || $self->get("contentType"); + my $content = shift || $self->content; + my $contentType = shift || $self->contentType; my $msg = undef ; if (!$self->isa("WebGUI::Asset::Post::Thread")) { # apply appropriate content filter - $msg = WebGUI::HTML::filter($content,$self->getThread->getParent->get("replyFilterCode")); + $msg = WebGUI::HTML::filter($content,$self->getThread->getParent->replyFilterCode); } else { - $msg = WebGUI::HTML::filter($content,$self->getThread->getParent->get("filterCode")); + $msg = WebGUI::HTML::filter($content,$self->getThread->getParent->filterCode); } $msg = WebGUI::HTML::format($msg, $contentType); - if ($self->getThread->getParent->get("useContentFilter")) { + if ($self->getThread->getParent->useContentFilter) { $msg = WebGUI::HTML::processReplacements($self->session,$msg); } return $msg; @@ -445,7 +448,7 @@ sub getAutoCommitWorkflowId { my $self = shift; my $cs = $self->getThread->getParent; if ($cs->hasBeenCommitted) { - return $cs->get('approvalWorkflow') + return $cs->approvalWorkflow || $self->session->setting->get('defaultVersionTagWorkflow'); } return undef; @@ -462,8 +465,8 @@ Returns a URL to the owner's avatar. sub getAvatarUrl { my $self = shift; my $parent = $self->getThread->getParent; - return '' unless $parent and $parent->getValue("avatarsEnabled"); - my $user = WebGUI::User->new($self->session, $self->get('ownerUserId')); + return '' unless $parent and $parent->avatarsEnabled; + my $user = WebGUI::User->new($self->session, $self->ownerUserId); #Get avatar field, storage Id. my $storageId = $user->profileField("avatar"); return '' unless $storageId; @@ -491,7 +494,7 @@ Formats the url to delete a post. sub getDeleteUrl { my $self = shift; - return $self->getUrl("func=delete;revision=".$self->get("revisionDate")); + return $self->getUrl("func=delete;revision=".$self->revisionDate); } #------------------------------------------------------------------- @@ -504,7 +507,7 @@ Formats the url to edit a post. sub getEditUrl { my $self = shift; - return $self->getUrl("func=edit;revision=".$self->get("revisionDate")); + return $self->getUrl("func=edit;revision=".$self->revisionDate); } @@ -519,7 +522,7 @@ are not stored files, it returns undef. sub getImageUrl { my $self = shift; - return undef if ($self->get("storageId") eq ""); + return undef if ($self->storageId eq ""); my $storage = $self->getStorageLocation; my $url; foreach my $filename (@{$storage->getFiles}) { @@ -542,7 +545,7 @@ Formats the url to view a users profile. sub getPosterProfileUrl { my $self = shift; - return WebGUI::User->new($self->session,$self->get("ownerUserId"))->getProfileUrl; + return WebGUI::User->new($self->session,$self->ownerUserId)->getProfileUrl; } #------------------------------------------------------------------- @@ -591,7 +594,7 @@ Returns the status of this Post, 'approved', 'pending', or 'archived'. sub getStatus { my $self = shift; - my $status = $self->get("status"); + my $status = $self->status; my $i18n = WebGUI::International->new($self->session,"Asset_Post"); if ($status eq "approved") { return $i18n->get('approved'); @@ -614,11 +617,11 @@ creates one. sub getStorageLocation { my $self = shift; unless (exists $self->{_storageLocation}) { - if ($self->get("storageId") eq "") { + if ($self->storageId eq "") { $self->{_storageLocation} = WebGUI::Storage->create($self->session); $self->update({storageId=>$self->{_storageLocation}->getId}); } else { - $self->{_storageLocation} = WebGUI::Storage->get($self->session,$self->get("storageId")); + $self->{_storageLocation} = WebGUI::Storage->get($self->session,$self->storageId); } } return $self->{_storageLocation}; @@ -683,7 +686,7 @@ sub getTemplateMetadataVars { my $self = shift; my $var = shift; if ($self->session->setting->get("metaDataEnabled") - && $self->getThread->getParent->get('enablePostMetaData')) { + && $self->getThread->getParent->enablePostMetaData) { my $meta = $self->getMetaDataFields(); my @meta_loop = (); foreach my $field (keys %{ $meta }) { @@ -712,13 +715,13 @@ sub getTemplateVars { my $self = shift; my $session = $self->session; my %var = %{$self->get}; - my $postUser = WebGUI::User->new($session, $self->get("ownerUserId")); - $var{"userId"} = $self->get("ownerUserId"); + my $postUser = WebGUI::User->new($session, $self->ownerUserId); + $var{"userId"} = $self->ownerUserId; $var{"user.isPoster"} = $self->isPoster; $var{"avatar.url"} = $self->getAvatarUrl; $var{"userProfile.url"} = $postUser->getProfileUrl($self->getUrl()); - $var{"dateSubmitted.human"} =$self->session->datetime->epochToHuman($self->get("creationDate")); - $var{"dateUpdated.human"} =$self->session->datetime->epochToHuman($self->get("revisionDate")); + $var{"dateSubmitted.human"} =$self->session->datetime->epochToHuman($self->creationDate); + $var{"dateUpdated.human"} =$self->session->datetime->epochToHuman($self->revisionDate); $var{'title.short'} = $self->chopTitle; $var{content} = $self->formatContent if ($self->getThread); $var{'user.canEdit'} = $self->canEdit if ($self->getThread); @@ -729,14 +732,14 @@ sub getTemplateVars { $var{'reply.withquote.url'} = $self->getReplyUrl(1); $var{'url'} = $self->getUrl.'#id'.$self->getId; $var{'url.raw'} = $self->getUrl; - $var{'rating.value'} = $self->get("rating")+0; + $var{'rating.value'} = $self->rating+0; $var{'rate.url.thumbsUp'} = $self->getRateUrl(1); $var{'rate.url.thumbsDown'} = $self->getRateUrl(-1); $var{'hasRated'} = $self->hasRated; my $gotImage; my $gotAttachment; @{$var{'attachment_loop'}} = (); - unless ($self->get("storageId") eq "") { + unless ($self->storageId eq "") { my $storage = $self->getStorageLocation; foreach my $filename (@{$storage->getFiles}) { if (!$gotImage && $storage->isImage($filename)) { @@ -774,12 +777,12 @@ Returns the Thread that this Post belongs to. The method caches the result of t sub getThread { my $self = shift; unless (defined $self->{_thread}) { - my $threadId = $self->get("threadId"); + my $threadId = $self->threadId; if ($threadId eq "") { # new post if ($self->getParent->isa("WebGUI::Asset::Wobject::Collaboration")) { $threadId=$self->getId; } else { - $threadId=$self->getParent->get("threadId"); + $threadId=$self->getParent->threadId; } } $self->{_thread} = WebGUI::Asset::Post::Thread->new($self->session, $threadId); @@ -798,7 +801,7 @@ is stored in it. Otherwise, it returns undef. sub getThumbnailUrl { my $self = shift; - return undef if ($self->get("storageId") eq ""); + return undef if ($self->storageId eq ""); my $storage = $self->getStorageLocation; my $url; foreach my $filename (@{$storage->getFiles}) { @@ -842,13 +845,13 @@ Indexing the content of attachments and user defined fields. See WebGUI::Asset:: sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get("content")); - $indexer->addKeywords($self->get("userDefined1")); - $indexer->addKeywords($self->get("userDefined2")); - $indexer->addKeywords($self->get("userDefined3")); - $indexer->addKeywords($self->get("userDefined4")); - $indexer->addKeywords($self->get("userDefined5")); - $indexer->addKeywords($self->get("username")); + $indexer->addKeywords($self->content); + $indexer->addKeywords($self->userDefined1); + $indexer->addKeywords($self->userDefined2); + $indexer->addKeywords($self->userDefined3); + $indexer->addKeywords($self->userDefined4); + $indexer->addKeywords($self->userDefined5); + $indexer->addKeywords($self->username); my $storage = $self->getStorageLocation; foreach my $file (@{$storage->getFiles}) { $indexer->addFile($storage->getPath($file)); @@ -865,7 +868,7 @@ Increments the views counter for this post. sub incrementViews { my ($self) = @_; - $self->update({views=>$self->get("views")+1}); + $self->update({views=>$self->views+1}); } #------------------------------------------------------------------- @@ -904,7 +907,7 @@ Returns a boolean indicating whether this post is new (not an edit). sub isNew { my $self = shift; - return $self->get("creationDate") == $self->get("revisionDate"); + return $self->creationDate == $self->revisionDate; } #------------------------------------------------------------------- @@ -918,7 +921,7 @@ Returns a boolean that is true if the current user created this post and is not sub isPoster { my $self = shift; my $userId = shift || $self->session->user->userId; - return ( $userId ne "1" && $userId eq $self->get("ownerUserId") ); + return ( $userId ne "1" && $userId eq $self->ownerUserId ); } @@ -932,7 +935,7 @@ Returns a boolean indicating whether this post is a reply. sub isReply { my $self = shift; - return $self->getId ne $self->get("threadId"); + return $self->getId ne $self->threadId; } @@ -955,11 +958,11 @@ sub notifySubscribers { my $siteurl = $self->session->url->getSiteURL(); $var->{url} = $siteurl.$self->getUrl; $var->{'notify.subscription.message'} = $i18n->get(875,"Asset_Post"); - my $user = WebGUI::User->new($self->session, $self->get("ownerUserId")); + my $user = WebGUI::User->new($self->session, $self->ownerUserId); my $setting = $self->session->setting; my $returnAddress = $setting->get("mailReturnPath"); my $companyAddress = $setting->get("companyEmail"); - my $listAddress = $cs->get("mailAddress"); + my $listAddress = $cs->mailAddress; my $posterAddress = $user->getProfileFieldPrivacySetting('email') eq "all" ? $user->profileField('email') : ''; @@ -969,21 +972,21 @@ sub notifySubscribers { my $returnPath = $returnAddress || $sender; my $listId = $sender; $listId =~ s/\@/\./; - my $domain = $cs->get("mailAddress"); + my $domain = $cs->mailAddress; $domain =~ s/.*\@(.*)/$1/; my $messageId = "cs-".$self->getId.'@'.$domain; my $replyId = ""; if ($self->isReply) { $replyId = "cs-".$self->getParent->getId.'@'.$domain; } - my $subject = $cs->get("mailPrefix").$self->get("title"); + my $subject = $cs->mailPrefix.$self->title; foreach my $subscriptionAsset ($cs, $thread) { $var->{unsubscribeUrl} = $siteurl.$subscriptionAsset->getUnsubscribeUrl; $var->{unsubscribeLinkText} = $i18n->get("unsubscribe","Asset_Collaboration"); - my $message = $self->processTemplate($var, $cs->get("notificationTemplateId")); + my $message = $self->processTemplate($var, $cs->notificationTemplateId); WebGUI::Macro::process($self->session, \$message); - my $groupId = $subscriptionAsset->get('subscriptionGroupId'); + my $groupId = $subscriptionAsset->subscriptionGroupId; my $mail = WebGUI::Mail::Send->create($self->session, { from=>"<".$from.">", returnPath => "<".$returnPath.">", @@ -1037,7 +1040,7 @@ sub paste { } )->[0]; # If the pasted asset is not a thread we'll have to update the threadId of it and all posts below it. - if ( $self->get('threadId') ne $self->getId ) { + if ( $self->threadId ne $self->getId ) { # Check if we're actually pasting under a thread. if ($thread) { # If so, get the threadId from the thread and fetch all posts that must be updated. @@ -1088,7 +1091,7 @@ sub processPropertiesFromFormPost { $self->update({synopsis => ($form->process("synopsis") || "")}); if ($form->process("archive") && $self->getThread->getParent->canModerate) { $self->getThread->archive; - } elsif ($self->getThread->get("status") eq "archived") { + } elsif ($self->getThread->status eq "archived") { $self->getThread->unarchive; } if ($form->process("subscribe")) { @@ -1118,7 +1121,7 @@ adding edit stamp to posts and setting the size. sub postProcess { my $self = shift; my %data = (); - ($data{synopsis}, $data{content}) = $self->getSynopsisAndContent($self->get("synopsis"), $self->get("content")); + ($data{synopsis}, $data{content}) = $self->getSynopsisAndContent($self->synopsis, $self->content); my $spamStopWords = $self->session->config->get('spamStopWords'); if (ref $spamStopWords eq 'ARRAY') { my $spamRegex = join('|',@{$spamStopWords}); @@ -1128,21 +1131,21 @@ sub postProcess { $self->trash; } } - my $user = WebGUI::User->new($self->session, $self->get("ownerUserId")); + my $user = WebGUI::User->new($self->session, $self->ownerUserId); my $i18n = WebGUI::International->new($self->session, "Asset_Post"); - if ($self->getThread->getParent->get("addEditStampToPosts")) { + if ($self->getThread->getParent->addEditStampToPosts) { $data{content} .= "

\n\n --- (".$i18n->get('Edited_on')." ".$self->session->datetime->epochToHuman(undef,"%z %Z [GMT%O]")." ".$i18n->get('By')." ".$user->profileField("alias").") --- \n

"; } - $data{url} = $self->fixUrl($self->getThread->get("url")."/1") if ($self->isReply && $self->isNew); - $data{groupIdView} = $self->getThread->getParent->get("groupIdView"); - $data{groupIdEdit} = $self->getThread->getParent->get("groupIdEdit"); + $data{url} = $self->fixUrl($self->getThread->url."/1") if ($self->isReply && $self->isNew); + $data{groupIdView} = $self->getThread->getParent->groupIdView; + $data{groupIdEdit} = $self->getThread->getParent->groupIdEdit; $self->update(\%data); my $size = 0; my $storage = $self->getStorageLocation; foreach my $file (@{$storage->getFiles}) { if ($storage->isImage($file)) { - $storage->adjustMaxImageSize($file, $self->getThread->getParent->get('maxImageSize')); - $storage->generateThumbnail($file, $self->getThread->getParent->get("thumbnailSize")); + $storage->adjustMaxImageSize($file, $self->getThread->getParent->maxImageSize); + $storage->generateThumbnail($file, $self->getThread->getParent->thumbnailSize); } $size += $storage->getFileSize($file); } @@ -1229,10 +1232,10 @@ sub rate { my $thread = $self->getThread; $thread->updateThreadRating(); if ($self->session->setting->get("useKarma") - && $self->session->user->karma > $thread->getParent->get('karmaSpentToRate')) { - $self->session->user->karma(-$self->getThread->getParent->get("karmaSpentToRate"), "Rated Post ".$self->getId, "Rated a CS Post."); - my $u = WebGUI::User->new($self->session, $self->get("ownerUserId")); - $u->karma($self->getThread->getParent->get("karmaRatingMultiplier"), "Post ".$self->getId." Rated by ".$self->session->user->userId, "Had post rated."); + && $self->session->user->karma > $thread->getParent->karmaSpentToRate) { + $self->session->user->karma(-$self->getThread->getParent->karmaSpentToRate, "Rated Post ".$self->getId, "Rated a CS Post."); + my $u = WebGUI::User->new($self->session, $self->ownerUserId); + $u->karma($self->getThread->getParent->karmaRatingMultiplier, "Post ".$self->getId." Rated by ".$self->session->user->userId, "Had post rated."); } } @@ -1299,10 +1302,10 @@ An asset object to make the parent of this asset. =cut sub setParent { - my $self = shift; - my $newParent = shift; - return 0 unless ($newParent->get("className") eq "WebGUI::Asset::Post" || $newParent->get("className") eq "WebGUI::Asset::Post::Thread"); - return $self->SUPER::setParent($newParent); + my $self = shift; + my $newParent = shift; + return 0 unless ($newParent->isa('WebGUI::Asset::Post')); + return $self->SUPER::setParent($newParent); } @@ -1332,7 +1335,7 @@ Sets the status of this post to approved, but does so without any of the normal sub setStatusUnarchived { my ($self) = @_; - $self->update({status=>'approved'}) if ($self->get("status") eq "archived"); + $self->update({status=>'approved'}) if ($self->status eq "archived"); } #------------------------------------------------------------------- @@ -1348,15 +1351,15 @@ sub trash { $self->SUPER::trash; $self->getThread->sumReplies if ($self->isReply); $self->getThread->updateThreadRating; - if ($self->getThread->get("lastPostId") eq $self->getId) { - my $threadLineage = $self->getThread->get("lineage"); + if ($self->getThread->lastPostId eq $self->getId) { + my $threadLineage = $self->getThread->lineage; my ($id, $date) = $self->session->db->quickArray("select assetId, creationDate from asset where lineage like ? and assetId<>? and asset.state='published' and className like 'WebGUI::Asset::Post%' order by creationDate desc",[$threadLineage.'%', $self->getId]); $self->getThread->update({lastPostId=>$id, lastPostDate=>$date}); } - if ($self->getThread->getParent->get("lastPostId") eq $self->getId) { - my $forumLineage = $self->getThread->getParent->get("lineage"); + if ($self->getThread->getParent->lastPostId eq $self->getId) { + my $forumLineage = $self->getThread->getParent->lineage; my ($id, $date) = $self->session->db->quickArray("select assetId, creationDate from asset where lineage like ? and assetId<>? and asset.state='published' and className like 'WebGUI::Asset::Post%' order by creationDate desc",[$forumLineage.'%', $self->getId]); @@ -1366,31 +1369,6 @@ sub trash { #------------------------------------------------------------------- -=head2 update ( ) - -We overload the update method from WebGUI::Asset in order to handle file system privileges. - -=cut - -sub update { - my $self = shift; - my $properties = shift; - my %before = ( - owner => $self->get("ownerUserId"), - view => $self->get("groupIdView"), - edit => $self->get("groupIdEdit") - ); - $self->SUPER::update({%$properties, isHidden => 1}); - if ($self->get("ownerUserId") ne $before{owner} || $self->get("groupIdEdit") ne $before{edit} || $self->get("groupIdView") ne $before{view}) { - my $storage = $self->getStorageLocation; - if (-d $storage->getPath) { - $storage->setPrivileges($self->get("ownerUserId"),$self->get("groupIdView"),$self->get("groupIdEdit")); - } - } -} - -#------------------------------------------------------------------- - =head2 prepareView Extend the base method to also prepare the Thread containing this Post. @@ -1457,7 +1435,7 @@ sub www_edit { my $i18n = WebGUI::International->new($session); - my $className = $form->process("class","className") || $self->get('className'); + my $className = $form->process("class","className") || $self->className; if ($func eq "add" || ($func eq "editSave" && $form->process("assetId") eq "new")) { # new post #Post to the parent if this is a new request my $action = $self->getParent->getUrl; @@ -1481,7 +1459,7 @@ sub www_edit { value=>$form->process("class","className") }); - if($self->getThread->getParent->getValue("useCaptcha")) { + if($self->getThread->getParent->useCaptcha) { $var{'useCaptcha' } = "true"; use WebGUI::Form::Captcha; @@ -1511,15 +1489,15 @@ sub www_edit { return $privilege->insufficient() unless ($self->getThread->canReply); $var{'isReply' } = 1; - $var{'reply.title' } = $title || $parent->get("title"); - $var{'reply.synopsis'} = $synopsis || $parent->get("synopsis"); + $var{'reply.title' } = $title || $parent->title; + $var{'reply.synopsis'} = $synopsis || $parent->synopsis; $var{'reply.content' } = $content || $parent->formatContent; for my $i (1..5) { $var{'reply.userDefined'.$i} = WebGUI::HTML::filter($parent->get('userDefined'.$i),"macros"); } unless ($content || $title) { - $content = "[quote]".$parent->get("content")."[/quote]" if ($form->process("withQuote")); - $title = $parent->get("title"); + $content = "[quote]".$parent->content."[/quote]" if ($form->process("withQuote")); + $title = $parent->title; $title = "Re: ".$title unless ($title =~ /^Re:/i); } my $subscribe = $form->process("subscribe"); @@ -1556,16 +1534,16 @@ sub www_edit { }); $var{'form.header'} .= WebGUI::Form::hidden($session, { name=>"ownerUserId", - value=>$self->getValue("ownerUserId") + value=>$self->ownerUserId }); $var{'form.header'} .= WebGUI::Form::hidden($session, { name=>"username", - value=>$self->getValue("username") + value=>$self->username }); $var{isEdit} = 1; - $content = $form->process('content') || $self->getValue("content"); - $title = $form->process('title') || $self->getValue("title"); - $synopsis = $form->process('synopsis') || $self->getValue("synopsis"); + $content = $form->process('content') || $self->content; + $title = $form->process('title') || $self->title; + $synopsis = $form->process('synopsis') || $self->synopsis; } $var{'archive.form'} = WebGUI::Form::yesNo($session, { @@ -1585,18 +1563,18 @@ sub www_edit { } } $var{'form.footer' } = WebGUI::Form::formFooter($session); - $var{'usePreview' } = $self->getThread->getParent->get("usePreview"); + $var{'usePreview' } = $self->getThread->getParent->usePreview; $var{'user.isModerator'} = $self->getThread->getParent->canModerate; $var{'user.isVisitor' } = ($user->isVisitor); $var{'visitorName.form'} = WebGUI::Form::text($session, { name => "visitorName", - value => $form->process('visitorName') || $self->getValue("visitorName") + value => $form->process('visitorName') || $self->visitorName }); for my $x (1..5) { my $userDefinedValue = $form->process("userDefined".$x) - || $self->getValue("userDefined".$x) + || $self->get("userDefined".$x) ; $var{'userDefined'.$x} = $userDefinedValue; $var{'userDefined'.$x.'.form'} @@ -1646,18 +1624,18 @@ sub www_edit { name=>"content", value=>$content, richEditId=>($self->isa("WebGUI::Asset::Post::Thread") ? - $self->getThread->getParent->get("richEditor") : - $self->getThread->getParent->get("replyRichEditor")), + $self->getThread->getParent->richEditor : + $self->getThread->getParent->replyRichEditor), }); ##Edit variables just for Threads if ($className eq 'WebGUI::Asset::Post::Thread' && $self->getThread->getParent->canEdit) { $var{'sticky.form'} = WebGUI::Form::yesNo($session, { name=>'isSticky', - value=>$form->process('isSticky') || $self->get('isSticky'), + value=>$form->process('isSticky') || $self->isSticky, }); $var{'lock.form' } = WebGUI::Form::yesNo($session, { name=>'isLocked', - value=>$form->process('isLocked') || $self->get('isLocked'), + value=>$form->process('isLocked') || $self->isLocked, }); } $var{'form.submit'} = WebGUI::Form::submit($session, { @@ -1665,27 +1643,27 @@ sub www_edit { }); $var{'karmaScale.form'} = WebGUI::Form::integer($session, { name=>"karmaScale", - defaultValue=>$self->getThread->getParent->get("defaultKarmaScale"), - value=>$self->getValue("karmaScale"), + defaultValue=>$self->getThread->getParent->defaultKarmaScale, + value=>$self->karmaScale, }); - $var{karmaIsEnabled} = $session->setting->get("useKarma"); + $var{karmaIsEnabled} = $session->setting->useKarma; $var{'form.preview'} = WebGUI::Form::submit($session, { value=>$i18n->get("preview","Asset_Collaboration") }); - my $numberOfAttachments = $self->getThread->getParent->getValue("attachmentsPerPost"); + my $numberOfAttachments = $self->getThread->getParent->attachmentsPerPost; $var{'attachment.form'} = WebGUI::Form::image($session, { name=>"storageId", - value=>$self->get("storageId"), + value=>$self->storageId, maxAttachments=>$numberOfAttachments, ##Removed deleteFileUrl, since it will go around the revision control system. }) if ($numberOfAttachments); $var{'contentType.form'} = WebGUI::Form::contentType($session, { name=>'contentType', - value=>$self->getValue("contentType") || "mixed", + value=>$self->contentType || "mixed", }); if ($session->setting->get("metaDataEnabled") - && $self->getThread->getParent->get('enablePostMetaData')) { + && $self->getThread->getParent->enablePostMetaData) { my $meta = $self->getMetaDataFields(); my $formGen = $form; my @meta_loop = (); @@ -1719,11 +1697,11 @@ sub www_edit { #keywords field $var{'keywords.form'} = WebGUI::Form::text($session,{ name => 'keywords', - value => $self->get('keywords'), + value => $self->keywords, }); $self->getThread->getParent->appendTemplateLabels(\%var); - return $self->getThread->getParent->processStyle($self->processTemplate(\%var,$self->getThread->getParent->get("postFormTemplateId"))); + return $self->getThread->getParent->processStyle($self->processTemplate(\%var,$self->getThread->getParent->postFormTemplateId)); } @@ -1738,18 +1716,18 @@ We're extending www_editSave() here to deal with editing a post that has been de sub www_editSave { my $self = shift; my $assetId = $self->session->form->param("assetId"); - if($assetId eq "new" && $self->getThread->getParent->getValue("useCaptcha")) { + if($assetId eq "new" && $self->getThread->getParent->useCaptcha) { my $captcha = $self->session->form->process("captcha","Captcha"); unless ($captcha) { return $self->www_edit; } } my $currentTag; - if ($assetId ne "new" && $self->get("status") eq "pending") { + if ($assetId ne "new" && $self->status eq "pending") { # When editting posts pending approval, temporarily switch to their version tag so # we don't get denied because it is locked $currentTag = WebGUI::VersionTag->getWorking($self->session, 1); - my $tag = WebGUI::VersionTag->new($self->session, $self->get("tagId")); + my $tag = WebGUI::VersionTag->new($self->session, $self->tagId); if ($tag) { if ($tag->getId eq $currentTag->getId) { undef $currentTag; # don't restore tag afterward if we are already using it @@ -1806,7 +1784,7 @@ sub www_showConfirmation { else { $collabSystem = $parent->getParent; } - my $templateId = $collabSystem->get('postReceivedTemplateId'); + my $templateId = $collabSystem->postReceivedTemplateId; my $template = WebGUI::Asset->new($self->session, $templateId); my %var = ( url => $url, diff --git a/lib/WebGUI/Asset/Post/Thread.pm b/lib/WebGUI/Asset/Post/Thread.pm index 02f8dd9c1..2065115fa 100644 --- a/lib/WebGUI/Asset/Post/Thread.pm +++ b/lib/WebGUI/Asset/Post/Thread.pm @@ -11,6 +11,63 @@ package WebGUI::Asset::Post::Thread; #------------------------------------------------------------------- use strict; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Post'; +aspect assetName => ['assetName', 'Asset_Thread']; +aspect icon => 'thread.gif'; +aspect tableName => 'Thread'; +property subscriptionGroupId => ( + noFormPost => 1, + fieldType => "hidden", + default => '', + ); +property replies => ( + noFormPost => 1, + fieldType => "hidden", + default => 0, + ); +property isSticky => ( + label => ['sticky', 'Asset_Collaboration'], + fieldType => "yesNo", + default => 0 + ); +property isLocked => ( + label => ['lock', 'Asset_Collaboration'], + fieldType => "yesNo", + default => 0, + ); +property lastPostId => ( + noFormPost => 1, + fieldType => "hidden", + default => '', + ); +property lastPostDate => ( + noFormPost => 1, + fieldType => "dateTime", + default => undef, + ); +property karma => ( + noFormPost => 1, + fieldType => "integer", + default => 0, + ); +property karmaRank => ( + noFormPost => 1, + fieldType => "float", + default => 0, + ); +property karmaScale => ( + noFormPost => 1, + fieldType => "integer", + default => 10, + ); +property threadRating => ( + noFormPost => 1, + fieldType => "hidden", + default => undef, + ); + + use WebGUI::Asset::Template; use WebGUI::Asset::Post; use WebGUI::Group; @@ -19,7 +76,6 @@ use WebGUI::Paginator; use WebGUI::SQL; use WebGUI::Utility; -our @ISA = qw(WebGUI::Asset::Post); #------------------------------------------------------------------- @@ -63,7 +119,7 @@ in the default asset, which better be a Collaboration System. sub canAdd { my $class = shift; my $session = shift; - return $session->user->isInGroup($session->asset->get('canStartThreadGroupId')); + return $session->user->isInGroup($session->asset->canStartThreadGroupId); } #------------------------------------------------------------------- @@ -83,7 +139,7 @@ sub canReply { my $self = shift; my $userId = shift || $self->session->user->userId; return !$self->isThreadLocked - && $self->getParent->get("allowReplies") + && $self->getParent->allowReplies && $self->getParent->canPost( $userId ) ; } @@ -120,7 +176,7 @@ sub commit { my $self = shift; $self->SUPER::commit; if ($self->isNew) { - $self->getParent->incrementThreads($self->get("revisionDate"),$self->getId); + $self->getParent->incrementThreads($self->revisionDate,$self->getId); } } @@ -158,7 +214,7 @@ already have one. sub createSubscriptionGroup { my $self = shift; - return undef if ($self->get("subscriptionGroupId")); + return undef if ($self->subscriptionGroupId); my $group = WebGUI::Group->new($self->session, "new"); $group->name($self->getId); $group->description("The group to store subscriptions for the thread ".$self->getId); @@ -170,71 +226,6 @@ sub createSubscriptionGroup { }); } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Thread"); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'thread.gif', - tableName=>'Thread', - className=>'WebGUI::Asset::Post::Thread', - properties=>{ - subscriptionGroupId => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>'', - }, - replies => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>0, - }, - isSticky => { - fieldType=>"yesNo", - defaultValue=>0 - }, - isLocked => { - fieldType=>"yesNo", - defaultValue=>0, - }, - lastPostId => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>'', - }, - lastPostDate => { - noFormPost=>1, - fieldType=>"dateTime", - defaultValue=>undef - }, - karma => { - noFormPost=>1, - fieldType=>"integer", - defaultValue=>0 - }, - karmaRank => { - noFormPost=>1, - fieldType=>"float", - defaultValue=>0 - }, - karmaScale => { - noFormPost=>1, - fieldType=>"integer", - defaultValue=>10 - }, - threadRating => { - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - }, - }); - return $class->SUPER::definition($session,$definition); -} - #------------------------------------------------------------------- =head2 DESTROY @@ -301,7 +292,7 @@ sub getAdjacentThread { ORDER BY $sortBy $sortOrder, assetData.revisionDate $sortOrder LIMIT 1 END_SQL - [$self->get('parentId'), $self->getId, $sortCompareValue, $tagId, $session->user->userId] + [$self->parentId, $self->getId, $sortCompareValue, $tagId, $session->user->userId] ); if ($id) { return WebGUI::Asset->new($session, $id, $class, $version); @@ -332,7 +323,7 @@ Override the base method to fetch the threadApprovalWorkflow from the parent CS. sub getAutoCommitWorkflowId { my $self = shift; - return $self->getThread->getParent->get("threadApprovalWorkflow"); + return $self->getThread->getParent->threadApprovalWorkflow; } #------------------------------------------------------------------- @@ -345,7 +336,7 @@ Fetches the last post in this thread, otherwise, returns itself. sub getLastPost { my $self = shift; - my $lastPostId = $self->get("lastPostId"); + my $lastPostId = $self->lastPostId; my $lastPost; if ($lastPostId) { $lastPost = WebGUI::Asset::Post->new($self->session, $lastPostId); @@ -546,7 +537,7 @@ Returns a boolean indicating whether this thread is locked from new posts and ot sub isThreadLocked { my ($self) = @_; - return $self->get("isLocked"); + return $self->isLocked; } @@ -582,7 +573,7 @@ Increments the views counter for this thread. sub incrementViews { my ($self) = @_; - $self->update({views=>$self->get("views")+1}); + $self->update({views=>$self->views+1}); $self->getParent->incrementViews; } @@ -601,20 +592,6 @@ sub isMarkedRead { return $isRead; } -#------------------------------------------------------------------- - -=head2 isSticky ( ) - -Returns a boolean indicating whether this thread should be "stuck" a the top of the forum and not be sorted with the rest of the threads. - -=cut - -sub isSticky { - my ($self) = @_; - return $self->get("isSticky"); -} - - #------------------------------------------------------------------- =head2 isSubscribed ( ) @@ -625,7 +602,7 @@ Returns a boolean indicating whether the user is subscribed to this thread. sub isSubscribed { my $self = shift; - return $self->session->user->isInGroup($self->get("subscriptionGroupId")); + return $self->session->user->isInGroup($self->subscriptionGroupId); } #------------------------------------------------------------------- @@ -666,7 +643,7 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->getParent->get("threadTemplateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->getParent->threadTemplateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; } @@ -683,8 +660,8 @@ Extend the base method from Post to process the karmaScale. sub postProcess { my $self = shift; if ($self->getParent->canEdit) { - my $karmaScale = $self->session->form->process("karmaScale","integer") || $self->getParent->get("defaultKarmaScale"); - my $karmaRank = $self->get("karma")/$karmaScale; + my $karmaScale = $self->session->form->process("karmaScale","integer") || $self->getParent->defaultKarmaScale; + my $karmaRank = $self->karma/$karmaScale; $self->update({karmaScale=>$karmaScale, karmaRank=>$karmaRank}); } $self->SUPER::postProcess; @@ -701,7 +678,7 @@ Extend the base method to do captcha processing. sub processPropertiesFromFormPost { my $self = shift; - if ($self->isNew && $self->getParent->getValue('useCaptcha')) { + if ($self->isNew && $self->getParent->useCaptcha) { my $captchaOk = $self->session->form->process("captcha","Captcha"); return [ 'invalid captcha' ] unless $captchaOk; @@ -722,7 +699,7 @@ the subscriptionGroup for this thread. sub purge { my $self = shift; $self->session->db->write("delete from Thread_read where threadId=?",[$self->getId]); - my $group = WebGUI::Group->new($self->session, $self->get("subscriptionGroupId")); + my $group = WebGUI::Group->new($self->session, $self->subscriptionGroupId); if ($group) { $group->delete; } @@ -750,10 +727,10 @@ sub rate { ##Thread specific karma adjustment for CS if ($self->session->setting->get("useKarma")) { - my $poster = WebGUI::User->new($self->session, $self->get("ownerUserId")); - $poster->karma($rating*$self->getParent->get("karmaRatingMultiplier"),"collaboration rating","someone rated post ".$self->getId); + my $poster = WebGUI::User->new($self->session, $self->ownerUserId); + $poster->karma($rating*$self->getParent->karmaRatingMultiplier,"collaboration rating","someone rated post ".$self->getId); my $rater = WebGUI::User->new($self->session->user->userId); - $rater->karma(-$self->getParent->get("karmaSpentToRate"),"collaboration rating","spent karma to rate post ".$self->getId); + $rater->karma(-$self->getParent->karmaSpentToRate,"collaboration rating","spent karma to rate post ".$self->getId); } } @@ -845,7 +822,7 @@ Subscribes the user to this thread. sub subscribe { my $self = shift; $self->createSubscriptionGroup; - my $group = WebGUI::Group->new($self->session,$self->get("subscriptionGroupId")); + my $group = WebGUI::Group->new($self->session,$self->subscriptionGroupId); $group->addUsers([$self->session->user->userId]); } @@ -875,8 +852,8 @@ sub trash { my $self = shift; $self->SUPER::trash; $self->getParent->sumReplies; - if ($self->getParent->get("lastPostId") eq $self->getId) { - my $parentLineage = $self->getThread->get("lineage"); + if ($self->getParent->lastPostId eq $self->getId) { + my $parentLineage = $self->getThread->lineage; my ($id, $date) = $self->session->db->quickArray("select assetId, creationDate from asset where lineage like ? and assetId<>? and asset.state='published' and className like 'WebGUI::Asset::Post%' order by creationDate desc",[$parentLineage.'%', $self->getId]); @@ -954,7 +931,7 @@ Negates the subscribe method. sub unsubscribe { my $self = shift; - my $group = WebGUI::Group->new($self->session,$self->get("subscriptionGroupId")); + my $group = WebGUI::Group->new($self->session,$self->subscriptionGroupId); return if !$group; $group->deleteUsers([$self->session->user->userId]); @@ -1040,7 +1017,7 @@ sub view { $var->{'user.isModerator' } = $self->getParent->canModerate; $var->{'user.canPost' } = $self->getParent->canPost; $var->{'user.canReply' } = $self->canReply; - $var->{'repliesAllowed' } = $self->getParent->get("allowReplies"); + $var->{'repliesAllowed' } = $self->getParent->allowReplies; $var->{'layout.nested.url' } = $self->getLayoutUrl("nested"); $var->{'layout.flat.url' } = $self->getLayoutUrl("flat"); @@ -1054,7 +1031,7 @@ sub view { $var->{'thumbsUp.icon.url' } = $self->session->url->extras('thumbup.gif'); $var->{'thumbsDown.icon.url'} = $self->session->url->extras('thumbdown.gif'); - $var->{'isArchived' } = $self->get("status") eq "archived"; + $var->{'isArchived' } = $self->status eq "archived"; $var->{'archive.url' } = $self->getArchiveUrl; $var->{'unarchive.url' } = $self->getUnarchiveUrl; @@ -1081,10 +1058,10 @@ sub view { $var->{'transfer.karma.form'} .= WebGUI::Form::submit($self->session); $var->{'transfer.karma.form'} .= WebGUI::Form::formFooter($self->session); - my $p = WebGUI::Paginator->new($self->session,$self->getUrl,$self->getParent->get("postsPerPage")); + my $p = WebGUI::Paginator->new($self->session,$self->getUrl,$self->getParent->postsPerPage); my $sql = "select asset.assetId, asset.className, assetData.revisionDate as revisionDate, assetData.url as url from asset left join assetData on assetData.assetId=asset.assetId - where asset.lineage like ".$self->session->db->quote($self->get("lineage").'%') + where asset.lineage like ".$self->session->db->quote($self->lineage.'%') ." and asset.state='published' and asset.className like 'WebGUI::Asset::Post%' and assetData.revisionDate=(SELECT max(assetData.revisionDate) from assetData where assetData.assetId=asset.assetId @@ -1129,12 +1106,12 @@ sub view { $var->{"search.url" } = $self->getParent->getSearchUrl; $var->{"collaboration.url" } = $self->getThread->getParent->getUrl; - $var->{'collaboration.title' } = $self->getParent->get("title"); - $var->{'collaboration.description'} = $self->getParent->get("description"); + $var->{'collaboration.title' } = $self->getParent->title; + $var->{'collaboration.description'} = $self->getParent->description; my $out = $self->processTemplate($var,undef,$self->{_viewTemplate}); if ($self->session->user->isVisitor && !$self->session->form->process("layout")) { - eval{$cache->set("view_".$self->getId, $out, $self->getThread->getParent->get("visitorCacheTimeout"))}; + eval{$cache->set("view_".$self->getId, $out, $self->getThread->getParent->visitorCacheTimeout)}; } return $out; } @@ -1253,8 +1230,8 @@ sub www_transferKarma { # cant have them giving more karma then they have if ($amount > 0 && $amount <= $self->session->user->karma) { $self->session->user->karma(-$amount, "Thread ".$self->getId, "Transferring karma to a thread."); - my $newKarma = $self->get("karma")+$amount; - my $karmaScale = $self->get("karmaScale") || 1; + my $newKarma = $self->karma+$amount; + my $karmaScale = $self->karmaScale || 1; $self->update({karma=>$newKarma,karmaRank=>$newKarma/$karmaScale}); } return $self->www_view; @@ -1330,7 +1307,7 @@ sub www_view { return $self->session->privilege->noAccess() unless $self->canView; my $check = $self->checkView; return $check if (defined $check); - $self->session->http->setCacheControl($self->get("visitorCacheTimeout")) if ($self->session->user->isVisitor); + $self->session->http->setCacheControl($self->visitorCacheTimeout) if ($self->session->user->isVisitor); $self->session->http->sendHeader; $self->prepareView; my $style = $self->getParent->processStyle($self->getSeparator); diff --git a/lib/WebGUI/Asset/Redirect.pm b/lib/WebGUI/Asset/Redirect.pm index 8c625924f..535ba8265 100644 --- a/lib/WebGUI/Asset/Redirect.pm +++ b/lib/WebGUI/Asset/Redirect.pm @@ -15,11 +15,37 @@ package WebGUI::Asset::Redirect; =cut use strict; -use WebGUI::Asset; use WebGUI::Macro; -our @ISA = qw(WebGUI::Asset); - +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_Redirect']; +aspect uiLevel => 9; +aspect icon => 'redirect.gif'; +aspect tableName => 'redirect'; +property redirectUrl => ( + tab => "properties", + label => ['redirect url', 'Asset_Redirect'], + hoverHelp => ['redirect url description', 'Asset_Redirect'], + fieldType => 'url', + default => undef, + ); +property redirectType => ( + tab => "properties", + label => ['Redirect Type', 'Asset_Redirect'], + hoverHelp => ['redirect type description', 'Asset_Redirect'], + fieldType => 'selectBox', + default => 302, + options => \&_redirectType_options, + ); +sub _redirectType_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, "Asset_Redirect"); + return { + 302 => $i18n->get('302 Moved Temporarily'), + 301 => $i18n->get('301 Moved Permanently'), + }; +} =head1 NAME @@ -40,56 +66,6 @@ These methods are available from this class: =cut - - -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Redirect"); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - uiLevel => 9, - autoGenerateForms=>1, - icon=>'redirect.gif', - tableName=>'redirect', - className=>'WebGUI::Asset::Redirect', - properties=>{ - redirectUrl=>{ - tab => "properties", - label => $i18n->get('redirect url'), - hoverHelp => $i18n->get('redirect url description'), - fieldType => 'url', - defaultValue => undef - }, - redirectType=>{ - tab => "properties", - label => $i18n->get('Redirect Type'), - hoverHelp => $i18n->get('redirect type description'), - fieldType => 'selectBox', - defaultValue => 302, - options => { - 302 => $i18n->get('302 Moved Temporarily'), - 301 => $i18n->get('301 Moved Permanently'), - } - }, - }, - }); - return $class->SUPER::definition($session,$definition); -} - #------------------------------------------------------------------- =head2 exportHtml_view @@ -101,9 +77,9 @@ Override the method from AssetExportHtml to handle the redirect. sub exportHtml_view { my $self = shift; return $self->session->privilege->noAccess() unless $self->canView; - my $url = $self->get("redirectUrl"); + my $url = $self->redirectUrl; WebGUI::Macro::process($self->session, \$url); - return '' if ($url eq $self->get("url")); + return '' if ($url eq $self->url); $self->session->http->setRedirect($url); return $self->session->style->process('', 'PBtmpl0000000000000060'); } @@ -119,7 +95,7 @@ Display the redirect url when in admin mode. sub view { my $self = shift; if ($self->session->var->isAdminOn) { - return $self->getToolbar.' '.$self->getTitle.' '.$self->get('redirectUrl'); + return $self->getToolbar.' '.$self->getTitle.' '.$self->redirectUrl; } else { return ""; @@ -138,7 +114,7 @@ sub www_view { my $self = shift; return $self->session->privilege->noAccess() unless $self->canView; my $i18n = WebGUI::International->new($self->session, "Asset_Redirect"); - my $url = $self->get("redirectUrl"); + my $url = $self->redirectUrl; WebGUI::Macro::process($self->session, \$url); if ($self->session->var->isAdminOn() && $self->canEdit) { return $self->getAdminConsole->render($i18n->get("what do you want to do with this redirect").' @@ -148,8 +124,8 @@ sub www_view {
  • '.$i18n->get("go to the redirect parent page").'
  • ',$i18n->get("assetName")); } - unless ($url eq $self->get("url")) { - $self->session->http->setRedirect($url,$self->get('redirectType')); + unless ($url eq $self->url) { + $self->session->http->setRedirect($url,$self->redirectType); return undef; } return $i18n->get('self_referential'); diff --git a/lib/WebGUI/Asset/RichEdit.pm b/lib/WebGUI/Asset/RichEdit.pm index 9c4946d05..56dc4f665 100644 --- a/lib/WebGUI/Asset/RichEdit.pm +++ b/lib/WebGUI/Asset/RichEdit.pm @@ -15,13 +15,160 @@ package WebGUI::Asset::RichEdit; =cut use strict; -use WebGUI::Asset; use WebGUI::Form; use WebGUI::Utility; use WebGUI::International; use JSON; -our @ISA = qw(WebGUI::Asset); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_RichEdit']; +aspect icon => 'richEdit.gif'; +aspect uiLevel => 5; +aspect tableName => 'RichEdit'; +property disableRichEditor => ( + fieldType => 'yesNo', + default => 0, + label => ['disable rich edit', 'Asset_RichEdit'], + hoverHelp => ['disable rich edit description', 'Asset_RichEdit'], + ); +property askAboutRichEdit => ( + fieldType => 'yesNo', + default => 0, + label => ['using rich edit', 'Asset_RichEdit'], + hoverHelp => ['using rich edit description', 'Asset_RichEdit'], + ); +property validElements => ( + fieldType => 'textarea', + default => 'a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]', + label => ['elements', 'Asset_RichEdit'], + hoverHelp => ['elements description', 'Asset_RichEdit'], + subtext => ['elements subtext', 'Asset_RichEdit'], + uiLevel => 9, + ); +property preformatted => ( + fieldType => 'yesNo', + default => 0, + label => ['preformatted', 'Asset_RichEdit'], + hoverHelp => ['preformatted description', 'Asset_RichEdit'], + uiLevel => 9, + ); +property editorWidth => ( + fieldType => 'integer', + default => 0, + label => ['editor width', 'Asset_RichEdit'], + hoverHelp => ['editor width description', 'Asset_RichEdit'], + uiLevel => 9, + ); +property editorHeight => ( + fieldType => 'integer', + default => 0, + label => ['editor height', 'Asset_RichEdit'], + hoverHelp => ['editor height description', 'Asset_RichEdit'], + uiLevel => 9, + ); +property sourceEditorWidth => ( + fieldType => 'integer', + default => 0, + label => ['source editor height', 'Asset_RichEdit'], + hoverHelp => ['source editor height description', 'Asset_RichEdit'], + ); +property sourceEditorHeight => ( + fieldType => 'integer', + default => 0, + label => ['source editor height', 'Asset_RichEdit'], + hoverHelp => ['source editor height description', 'Asset_RichEdit'], + ); +property useBr => ( + fieldType => 'yesNo', + default => 0, + label => ['use br', 'Asset_RichEdit'], + hoverHelp => ['use br description', 'Asset_RichEdit'], + uiLevel => 9, + ); +property removeLineBreaks => ( + fieldType => 'yesNo', + default => 0, + label => ['remove line breaks', 'Asset_RichEdit'], + hoverHelp => ['remove line breaks description', 'Asset_RichEdit'], + uiLevel => 9, + ); +property nowrap => ( + fieldType => 'yesNo', + default => 0, + label => ['no wrap', 'Asset_RichEdit'], + hoverHelp => ['no wrap description', 'Asset_RichEdit'], + uiLevel => 9, + ); +property directionality => ( + fieldType => 'selectBox', + default => 'ltr', + label => ['directionality', 'Asset_RichEdit'], + hoverHelp => ['directionality description', 'Asset_RichEdit'], + options => \&_directionality_options, + ); +sub _directionality_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_RichEdit'); + return { + ltr=>$i18n->get('left to right'), + rtl=>$i18n->get('right to left'), + }; +} +property toolbarLocation => ( + fieldType => 'selectBox', + default => 'bottom', + label => ['toolbar location', 'Asset_RichEdit'], + hoverHelp => ['toolbar location description', 'Asset_RichEdit'], + options => \&_toolbarLocation_options, + ); +sub _toolbarLocation_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_RichEdit'); + return { + top => $i18n->get('top'), + bottom => $i18n->get('bottom'), + }; +} +property cssFile => ( + fieldType => 'text', + default => undef, + label => ['css file', 'Asset_RichEdit'], + hoverHelp => ['css file description', 'Asset_RichEdit'], + ); +property toolbarRow1 => ( + fieldType => 'checkList', + default => undef, + label => '', + ); +property toolbarRow2 => ( + fieldType => 'checkList', + default => undef, + label => '', + ); +property toolbarRow3 => ( + fieldType => 'checkList', + default => undef, + label => '', + ); +property enableContextMenu => ( + fieldType => "yesNo", + default => 0, + label => ['enable context menu', 'Asset_RichEdit'], + hoverHelp => ['enable context menu description', 'Asset_RichEdit'], + ); +property inlinePopups => ( + fieldType => "yesNo", + default => 0, + label => ['inline popups', 'Asset_RichEdit'], + hoverHelp => ['inline popups description', 'Asset_RichEdit'], + ); +property allowMedia => ( + fieldType => "yesNo", + default => 0, + label => ['editForm allowMedia label', 'Asset_RichEdit'], + hoverHelp => ['editForm allowMedia description', 'Asset_RichEdit'], + ); =head1 NAME @@ -45,117 +192,6 @@ These methods are available from this class: -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,'Asset_RichEdit'); - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'richEdit.gif', - uiLevel => 5, - tableName => 'RichEdit', - className => 'WebGUI::Asset::RichEdit', - properties => { - disableRichEditor => { - fieldType => 'yesNo', - defaultValue => 0, - }, - askAboutRichEdit => { - fieldType => 'yesNo', - defaultValue => 0, - }, - validElements => { - fieldType => 'textarea', - defaultValue => 'a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]', - }, - preformatted => { - fieldType => 'yesNo', - defaultValue => 0, - }, - editorWidth => { - fieldType => 'integer', - defaultValue => 0, - }, - editorHeight => { - fieldType => 'integer', - defaultValue => 0, - }, - sourceEditorWidth => { - fieldType => 'integer', - defaultValue => 0, - }, - sourceEditorHeight => { - fieldType => 'integer', - defaultValue => 0, - }, - useBr => { - fieldType => 'yesNo', - defaultValue => 0, - }, - removeLineBreaks => { - fieldType => 'yesNo', - defaultValue => 0, - }, - nowrap=>{ - fieldType => 'yesNo', - defaultValue => 0, - }, - directionality => { - fieldType => 'selectBox', - defaultValue => 'ltr', - }, - toolbarLocation => { - fieldType => 'selectBox', - defaultValue => 'bottom', - }, - cssFile => { - fieldType => 'text', - defaultValue => undef, - }, - toolbarRow1 => { - fieldType => 'checkList', - defaultValue => undef, - }, - toolbarRow2 => { - fieldType => 'checkList', - defaultValue => undef, - }, - toolbarRow3 => { - fieldType => 'checkList', - defaultValue => undef, - }, - enableContextMenu => { - fieldType => "yesNo", - defaultValue => 0, - }, - inlinePopups => { - fieldType => "yesNo", - defaultValue => 0, - }, - allowMedia => { - fieldType => "yesNo", - defaultValue => 0, - }, - }, - }); - return $class->SUPER::definition($session, $definition); -} - - - #------------------------------------------------------------------- =head2 getEditForm ( ) @@ -244,9 +280,9 @@ sub getEditForm { $i18n->get('row 1'), $i18n->get('row 2'), $i18n->get('row 3'); - my @toolbarRow1 = split("\n",$self->getValue("toolbarRow1")); - my @toolbarRow2 = split("\n",$self->getValue("toolbarRow2")); - my @toolbarRow3 = split("\n",$self->getValue("toolbarRow3")); + my @toolbarRow1 = split("\n",$self->toolbarRow1); + my @toolbarRow2 = split("\n",$self->toolbarRow2); + my @toolbarRow3 = split("\n",$self->toolbarRow3); my $evenOddToggle = 0; foreach my $key (keys %buttons) { $evenOddToggle = $evenOddToggle ? 0 : 1; @@ -285,7 +321,7 @@ sub getEditForm { -value=>$buttonGrid ); $tabform->getTab("properties")->yesNo( - -value=>$self->getValue("disableRichEditor"), + -value=>$self->disableRichEditor, -label=>$i18n->get('disable rich edit'), -hoverHelp=>$i18n->get('disable rich edit description'), -name=>"disableRichEditor" @@ -364,8 +400,6 @@ sub getEditForm { -hoverHelp=>$i18n->get('directionality description'), -name=>"directionality", -options=>{ - ltr=>$i18n->get('left to right'), - rtl=>$i18n->get('right to left'), } ); $tabform->getTab("display")->selectBox( @@ -397,7 +431,7 @@ sub getEditForm { -name=>"inlinePopups" ); $tabform->getTab("properties")->yesNo( - value => $self->getValue("allowMedia"), + value => $self->allowMedia, label => $i18n->get('editForm allowMedia label'), hoverHelp => $i18n->get('editForm allowMedia description'), name => "allowMedia", @@ -462,22 +496,22 @@ for a HTML tag. sub getRichEditor { my $self = shift; - return '' if ($self->getValue('disableRichEditor')); + return '' if ($self->disableRichEditor); my $nameId = shift; my @plugins; my %loadPlugins; push @plugins, "safari"; push @plugins, "contextmenu" - if $self->getValue("enableContextMenu"); + if $self->enableContextMenu; push @plugins, "inlinepopups" - if $self->getValue("inlinePopups"); + if $self->inlinePopups; push @plugins, "media" - if $self->getValue( 'allowMedia' ); + if $self->allowMedia; - my @toolbarRows = map{[split "\n", $self->getValue("toolbarRow$_")]} (1..3); + my @toolbarRows = map{[split "\n", $self->get("toolbarRow$_")]} (1..3); my @toolbarButtons = map{ @{$_} } @toolbarRows; my $i18n = WebGUI::International->new($self->session, 'Asset_RichEdit'); - my $ask = $self->getValue("askAboutRichEdit"); + my $ask = $self->askAboutRichEdit; my %config = ( mode => $ask ? "none" : "exact", elements => $nameId, @@ -492,16 +526,16 @@ sub getRichEditor { (0..$#toolbarRows)), #ask => $self->getValue("askAboutRichEdit") ? JSON::true() : JSON::false(), ask => JSON::false(), - preformatted => $self->getValue("preformatted") ? JSON::true() : JSON::false(), - force_br_newlines => $self->getValue("useBr") ? JSON::true() : JSON::false(), - force_p_newlines => $self->getValue("useBr") ? JSON::false() : JSON::true(), - $self->getValue("useBr") ? ( forced_root_block => JSON::false() ) : (), - remove_linebreaks => $self->getValue("removeLineBreaks") ? JSON::true() : JSON::false(), - nowrap => $self->getValue("nowrap") ? JSON::true() : JSON::false(), - directionality => $self->getValue("directionality"), - theme_advanced_toolbar_location => $self->getValue("toolbarLocation"), + preformatted => $self->preformatted ? JSON::true() : JSON::false(), + force_br_newlines => $self->useBr ? JSON::true() : JSON::false(), + force_p_newlines => $self->useBr ? JSON::false() : JSON::true(), + $self->useBr ? ( forced_root_block => JSON::false() ) : (), + remove_linebreaks => $self->removeLineBreaks ? JSON::true() : JSON::false(), + nowrap => $self->nowrap ? JSON::true() : JSON::false(), + directionality => $self->directionality, + theme_advanced_toolbar_location => $self->toolbarLocation, theme_advanced_statusbar_location => "bottom", - valid_elements => $self->getValue("validElements"), + valid_elements => $self->validElements, wg_userIsVisitor => $self->session->user->isVisitor ? JSON::true() : JSON::false(), ); # if ($ask) { @@ -558,8 +592,8 @@ sub getRichEditor { $loadPlugins{wgmacro} = $self->session->url->extras("tinymce-webgui/plugins/wgmacro/editor_plugin.js"); } if ($button eq "code") { - $config{theme_advanced_source_editor_width} = $self->getValue("sourceEditorWidth") if ($self->getValue("sourceEditorWidth") > 0); - $config{theme_advanced_source_editor_height} = $self->getValue("sourceEditorHeight") if ($self->getValue("sourceEditorHeight") > 0); + $config{theme_advanced_source_editor_width} = $self->sourceEditorWidth if ($self->sourceEditorWidth > 0); + $config{theme_advanced_source_editor_height} = $self->sourceEditorHeight if ($self->sourceEditorHeight > 0); } } my $language = $i18n->getLanguage($self->session->user->profileField("language"),"languageAbbreviation"); @@ -567,9 +601,9 @@ sub getRichEditor { $language = $i18n->getLanguage("English","languageAbbreviation"); } $config{language} = $language; - $config{content_css} = $self->getValue("cssFile") || $self->session->url->extras('tinymce-webgui/defaultcontent.css'); - $config{width} = $self->getValue("editorWidth") if ($self->getValue("editorWidth") > 0); - $config{height} = $self->getValue("editorHeight") if ($self->getValue("editorHeight") > 0); + $config{content_css} = $self->cssFile || $self->session->url->extras('tinymce-webgui/defaultcontent.css'); + $config{width} = $self->editorWidth if ($self->editorWidth > 0); + $config{height} = $self->editorHeight if ($self->editorHeight > 0); $config{plugins} = join(",",@plugins); $self->session->style->setScript($self->session->url->extras('yui/build/yahoo/yahoo-min.js'),{type=>"text/javascript"}); diff --git a/lib/WebGUI/Asset/Shortcut.pm b/lib/WebGUI/Asset/Shortcut.pm index 9b0f6edc0..a90194347 100644 --- a/lib/WebGUI/Asset/Shortcut.pm +++ b/lib/WebGUI/Asset/Shortcut.pm @@ -11,9 +11,62 @@ package WebGUI::Asset::Shortcut; #------------------------------------------------------------------- use strict; -use Carp; +use Carp qw/croak/; use Tie::IxHash; -use WebGUI::Asset; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; + +aspect assetName => ['assetName', 'Asset_Shortcut']; +aspect icon => 'shortcut.gif'; +aspect tableName => 'Shortcut'; + +property shortcutToAssetId => ( + noFormPost => 1, + fieldType => "hidden", + default => undef, + noFormPost => 1, + ); +property shortcutByCriteria => ( + fieldType => "yesNo", + default => 0, + noFormPost => 1, + ); +property disableContentLock => ( + fieldType => "yesNo", + default => 0, + noFormPost => 1, + ); +property resolveMultiples => ( + fieldType => "selectBox", + default => "mostRecent", + noFormPost => 1, + ); +property shortcutCriteria => ( + fieldType => "textarea", + default => "", + noFormPost => 1, + ); +property templateId => ( + fieldType => "template", + default => "PBtmpl0000000000000140", + noFormPost => 1, + ); +property prefFieldsToShow => ( + fieldType => "checkList", + default => undef, + noFormPost => 1, + ); +property prefFieldsToImport => ( + fieldType => "checkList", + default => undef, + noFormPost => 1, + ); +property showReloadIcon => ( + fieldType => "yesNo", + default => 1, + noFormPost => 1, + ); + use WebGUI::International; use WebGUI::Operation::Profile; use WebGUI::ProfileField; @@ -22,8 +75,6 @@ use WebGUI::Macro; use HTML::Entities qw(encode_entities); use Data::Dumper; -our @ISA = qw(WebGUI::Asset); - #------------------------------------------------------------------- sub _drawQueryBuilder { my $self = shift; @@ -56,7 +107,7 @@ sub _drawQueryBuilder { # Static form fields my $shortcutCriteriaField = WebGUI::Form::textarea($session, { name=>"shortcutCriteria", - value=>$self->getValue("shortcutCriteria"), + value=>$self->shortcutCriteria, extras=>'style="width: 100%" '.$self->{_disabled} }); my $conjunctionField = WebGUI::Form::selectBox($session, { @@ -174,48 +225,7 @@ sub definition { my $definition = shift; my $i18n = WebGUI::International->new($session,"Asset_Shortcut"); push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'shortcut.gif', - tableName=>'Shortcut', - className=>'WebGUI::Asset::Shortcut', properties=>{ - shortcutToAssetId=>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - shortcutByCriteria=>{ - fieldType=>"yesNo", - defaultValue=>0, - }, - disableContentLock=>{ - fieldType=>"yesNo", - defaultValue=>0 - }, - resolveMultiples=>{ - fieldType=>"selectBox", - defaultValue=>"mostRecent", - }, - shortcutCriteria=>{ - fieldType=>"textarea", - defaultValue=>"", - }, - templateId=>{ - fieldType=>"template", - defaultValue=>"PBtmpl0000000000000140" - }, - prefFieldsToShow=>{ - fieldType=>"checkList", - defaultValue=>undef - }, - prefFieldsToImport=>{ - fieldType=>"checkList", - defaultValue=>undef - }, - showReloadIcon=>{ - fieldType=>"yesNo", - defaultValue=>1 - } } }); return $class->SUPER::definition($session,$definition); @@ -297,7 +307,7 @@ sub getEditForm { ); } $tabform->getTab("display")->template( - -value=>$self->getValue("templateId"), + -value=>$self->templateId, -label=>$i18n->get('shortcut template title'), -hoverHelp=>$i18n->get('shortcut template title description'), -namespace=>"Shortcut" @@ -589,9 +599,9 @@ sub getShortcutByCriteria { my $scratchId; if ($assetId) { $scratchId = "Shortcut_" . $assetId; - if($self->session->scratch->get($scratchId) && !$self->getValue("disableContentLock")) { + if($self->session->scratch->get($scratchId) && !$self->disableContentLock) { unless ($self->session->var->isAdminOn) { - return WebGUI::Asset->newByDynamicClass($self->session, $self->session->scratch->get($scratchId)); + return WebGUI::Asset->newById($self->session, $self->session->scratch->get($scratchId)); } } } @@ -675,7 +685,7 @@ sub getShortcutByCriteria { # Store the matching assetId in user scratch. $self->session->scratch->set($scratchId,$id) if ($scratchId); - return WebGUI::Asset->newByDynamicClass($self->session, $id); + return WebGUI::Asset->newById($self->session, $id); } #------------------------------------------------------------------- @@ -688,7 +698,7 @@ Return the asset that this Shortcut points to. sub getShortcutDefault { my $self = shift; - return WebGUI::Asset->newByDynamicClass($self->session, $self->get("shortcutToAssetId")); + return WebGUI::Asset->newById($self->session, $self->get("shortcutToAssetId")); } #------------------------------------------------------------------- @@ -719,7 +729,7 @@ Returns an array of profile fields to show to the user as preferences. sub getPrefFieldsToShow { my $self = shift; - return split("\n",$self->getValue("prefFieldsToShow")); + return split("\n",$self->prefFieldsToShow); } #------------------------------------------------------------------- @@ -733,7 +743,7 @@ for overrides. sub getPrefFieldsToImport { my $self = shift; - return split("\n",$self->getValue("prefFieldsToImport")); + return split("\n",$self->prefFieldsToImport); } #---------------------------------------------------------------------------- @@ -836,7 +846,7 @@ sub setOverride { my $self = shift; my $override = shift; - croak "Shortcut->setOverride - first argument must be hash reference" + Carp::croak "Shortcut->setOverride - first argument must be hash reference" unless $override && ref $override eq "HASH"; for my $key ( %$override ) { @@ -1126,7 +1136,7 @@ sub www_editOverride { # Cannot fetch the original value from the overrides hash b/c it will be empty if # the override has not been set before. Also getOverrides uses a cached version of # the origValue, which can be out of date. - my $origValue = $self->getShortcutOriginal->getValue($fieldName); + my $origValue = $self->getShortcutOriginal->$fieldName; my $output = ''; $output .= ''; @@ -1163,7 +1173,7 @@ sub www_editOverride { $params{label} = $params{label} || $i18n->get("Edit Field Directly"); $params{hoverHelp} = $params{hoverHelp} || $i18n->get("Use this field to edit the override using the native form handler for this field type"); - if ($params{fieldType} eq 'template') {$params{namespace} = $params{namespace} || WebGUI::Asset->newByDynamicClass($self->session, $origValue)->get("namespace");} + if ($params{fieldType} eq 'template') {$params{namespace} = $params{namespace} || WebGUI::Asset->newById($self->session, $origValue)->get("namespace");} $f->dynamicField(%params); $f->textarea( @@ -1271,11 +1281,11 @@ sub getShortcutsForAssetId { my $assetId = shift; my $properties = shift || {}; - croak "First argument to getShortcutsForAssetId must be WebGUI::Session" + Carp::croak "First argument to getShortcutsForAssetId must be WebGUI::Session" unless $session && $session->isa("WebGUI::Session"); - croak "Second argument to getShortcutsForAssetId must be assetId" + Carp::croak "Second argument to getShortcutsForAssetId must be assetId" unless $assetId; - croak "Third argument to getShortcutsForAssetId must be hash reference" + Carp::croak "Third argument to getShortcutsForAssetId must be hash reference" if $properties && !ref $properties eq "HASH"; my $db = $session->db; diff --git a/lib/WebGUI/Asset/Sku.pm b/lib/WebGUI/Asset/Sku.pm index be4b02efb..7bd35f27e 100644 --- a/lib/WebGUI/Asset/Sku.pm +++ b/lib/WebGUI/Asset/Sku.pm @@ -16,12 +16,59 @@ package WebGUI::Asset::Sku; use strict; use Tie::IxHash; -use base 'WebGUI::Asset'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; use WebGUI::International; use WebGUI::Inbox; use WebGUI::Shop::Cart; use JSON qw{ from_json to_json }; +aspect assetName => ['assetName', 'Asset_Sku']; +aspect icon => 'Sku.gif'; +aspect tableName => 'sku'; + +property description => ( + tab => "properties", + fieldType => "HTMLArea", + default => undef, + label => ["description", 'Asset_Sku'], + hoverHelp => ["description help", 'Asset_Sku'], + ); +property sku => ( + tab => "shop", + fieldType => "text", + default => sub { shift->session->id->generate }, + lazy => 1, + label => ["sku", 'Asset_Sku'], + hoverHelp => ["sku help", 'Asset_Sku'], + ); +property displayTitle => ( + tab => "display", + fieldType => "yesNo", + default => 1, + label => ["display title", 'Asset_Sku'], + hoverHelp => ["display title help", 'Asset_Sku'], + ); +property vendorId => ( + tab => "shop", + fieldType => "vendor", + default => 'defaultvendor000000000', + label => ["vendor", 'Asset_Sku'], + hoverHelp => ["vendor help", 'Asset_Sku'], + ); +property taxConfiguration => ( + noFormPost => 1, + fieldType => 'hidden', + defaultValue => '{}', + ); +property shipsSeparately => ( + tab => 'shop', + fieldType => 'yesNo', + default => 0, + label => ['shipsSeparately', 'Asset_Sku'], + hoverHelp => ['shipsSeparately help', 'Asset_Sku'], + ); + =head1 NAME Package WebGUI::Asset::Sku @@ -88,76 +135,6 @@ sub applyOptions { $self->{_skuOptions} = $options; } -#------------------------------------------------------------------- - -=head2 definition ( session, definition ) - -See super class. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - - my $i18n = WebGUI::International->new($session, "Asset_Sku"); - %properties = ( - description => { - tab => "properties", - fieldType => "HTMLArea", - defaultValue => undef, - label => $i18n->get("description"), - hoverHelp => $i18n->get("description help") - }, - sku => { - tab => "shop", - fieldType => "text", - defaultValue => $session->id->generate, - label => $i18n->get("sku"), - hoverHelp => $i18n->get("sku help") - }, - displayTitle => { - tab => "display", - fieldType => "yesNo", - defaultValue => 1, - label => $i18n->get("display title"), - hoverHelp => $i18n->get("display title help") - }, - vendorId => { - tab => "shop", - fieldType => "vendor", - defaultValue => 'defaultvendor000000000', - label => $i18n->get("vendor"), - hoverHelp => $i18n->get("vendor help") - }, - taxConfiguration => { - noFormPost => 1, - fieldType => 'hidden', - defaultValue => '{}', - }, - shipsSeparately => { - tab => 'shop', - fieldType => 'yesNo', - defaultValue => 0, - label => $i18n->get('shipsSeparately'), - hoverHelp => $i18n->get('shipsSeparately help'), - }, - ); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'Sku.gif', - autoGenerateForms=>1, - tableName=>'sku', - className=>'WebGUI::Asset::Sku', - properties=>\%properties - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 getAddToCartForm ( ) @@ -348,7 +325,7 @@ sub getTaxConfiguration { my $self = shift; my $namespace = shift; - my $configs = eval { from_json( $self->getValue('taxConfiguration') ) }; + my $configs = eval { from_json( $self->taxConfiguration ) }; if ($@) { $self->session->log->error( 'Tax configuration of asset ' . $self->getId . ' appears to be corrupt. :' . $@ ); return undef; @@ -420,7 +397,7 @@ Adding sku as a keyword. See WebGUI::Asset::indexContent() for additonal details sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get('sku')); + $indexer->addKeywords($self->sku); return $indexer; } @@ -482,7 +459,7 @@ The sku attached to the object you wish to instanciate. sub newBySku { my ($class, $session, $sku) = @_; my $assetId = $session->db->quickScalar("select assetId from sku where sku=?", [$sku]); - return WebGUI::Asset->newByDynamicClass($session, $assetId); + return WebGUI::Asset->newById($session, $assetId); } #------------------------------------------------------------------- @@ -640,7 +617,7 @@ sub setTaxConfiguration { my $configuration = shift; # Fetch current tax configurations - my $configs = eval { from_json( $self->getValue('taxConfiguration') ) }; + my $configs = eval { from_json( $self->taxConfiguration ) }; if ($@) { $self->session->log->error( 'Tax configuration of asset ' . $self->getId . ' is corrupt.' ); return undef; @@ -657,7 +634,7 @@ sub setTaxConfiguration { #------------------------------------------------------------------- -=head2 shipsSeparately +=head2 isShippingSeparately Returns a boolean indicating whether this item must be shipped separately from other items. If the shipsSeparately property is true, but isShippingRequired is false, this will return @@ -665,9 +642,9 @@ false. =cut -sub shipsSeparately { +sub isShippingSeparately { my ($self) = @_; - return $self->isShippingRequired && $self->get('shipsSeparately'); + return $self->isShippingRequired && $self->shipsSeparately; } diff --git a/lib/WebGUI/Asset/Sku/Ad.pm b/lib/WebGUI/Asset/Sku/Ad.pm index f0e9a2c1d..ec894513d 100644 --- a/lib/WebGUI/Asset/Sku/Ad.pm +++ b/lib/WebGUI/Asset/Sku/Ad.pm @@ -16,7 +16,82 @@ package WebGUI::Asset::Sku::Ad; use strict; use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['assetName', 'Asset_WikiMaster']; +aspect icon => 'adsku.gif'; +aspect tableName => 'AdSku'; + +property purchaseTemplate => ( + tab => "display", + fieldType => "template", + namespace => "AdSku/Purchase", + default => 'AldPGu0u-jm_5xK13atCSQ', + label => ["property purchase template", 'Asset_WikiMaster'], + hoverHelp => ["property purchase template help", 'Asset_WikiMaster'], + ); +property manageTemplate => ( + tab => "display", + fieldType => "template", + namespace => "AdSku/Manage", + default => 'ohjyzab5i-yW6GOWTeDUHg', + label => ["property manage template", 'Asset_WikiMaster'], + hoverHelp => ["property manage template help", 'Asset_WikiMaster'], + ); +property adSpace => ( + tab => "properties", + fieldType => "AdSpace", + label => ["property ad space", 'Asset_WikiMaster'], + hoverHelp => ["property ad Space help", 'Asset_WikiMaster'], + ); +property priority => ( + tab => "properties", + default => '1', + fieldType => "integer", + label => ["property priority", 'Asset_WikiMaster'], + hoverHelp => ["property priority help", 'Asset_WikiMaster'], + ); +property pricePerClick => ( + tab => "shop", + default => '0.00', + fieldType => "float", + label => ["property price per click", 'Asset_WikiMaster'], + hoverHelp => ["property price per click help", 'Asset_WikiMaster'], + ); +property pricePerImpression => ( + tab => "shop", + default => '0.00', + fieldType => "float", + label => ["property price per impression", 'Asset_WikiMaster'], + hoverHelp => ["property price per impression help", 'Asset_WikiMaster'], + ); +property clickDiscounts => ( + tab => "shop", + fieldType => 'textarea', + label => ['property click discounts', 'Asset_WikiMaster'], + hoverHelp => ['property click discounts help', 'Asset_WikiMaster'], + default => '', + ); +property impressionDiscounts => ( + tab => "shop", + fieldType => 'textarea', + label => ['property impression discounts', 'Asset_WikiMaster'], + hoverHelp => ['property impression discounts help', 'Asset_WikiMaster'], + default => '', + ); +property karma => ( + fieldType => 'integer', + noFormPost => \&_karma_noFormPost, + label => ['property adsku karma', 'Asset_WikiMaster'], + hoverHelp => ['property adsku karma description', 'Asset_WikiMaster'], + defaultvalue => 0, + ); +sub _karma_noFormPost { + my $session = shift->session; + return ! $session->setting->get('useKarma'); +} + + use WebGUI::Asset::Template; use WebGUI::Form; use WebGUI::Storage; @@ -46,102 +121,6 @@ These methods are available from this class: #------------------------------------------------------------------- -=head2 definition - -Adds purchaseTemplate, manageTemplate, adSpace, priority, pricePerClick, pricePerImpression, clickDiscounts, impresisonDiscounts - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_AdSku"); - %properties = ( - purchaseTemplate => { - tab => "display", - fieldType => "template", - namespace => "AdSku/Purchase", - defaultValue => 'AldPGu0u-jm_5xK13atCSQ', - label => $i18n->get("property purchase template"), - hoverHelp => $i18n->get("property purchase template help"), - }, - manageTemplate => { - tab => "display", - fieldType => "template", - namespace => "AdSku/Manage", - defaultValue => 'ohjyzab5i-yW6GOWTeDUHg', - label => $i18n->get("property manage template"), - hoverHelp => $i18n->get("property manage template help"), - }, - adSpace => { - tab => "properties", - fieldType => "AdSpace", - label => $i18n->get("property ad space"), - hoverHelp => $i18n->get("property ad Space help"), - }, - priority => { - tab => "properties", - defaultValue => '1', - fieldType => "integer", - label => $i18n->get("property priority"), - hoverHelp => $i18n->get("property priority help"), - }, - pricePerClick => { - tab => "shop", - defaultValue => '0.00', - fieldType => "float", - label => $i18n->get("property price per click"), - hoverHelp => $i18n->get("property price per click help"), - }, - pricePerImpression => { - tab => "shop", - defaultValue => '0.00', - fieldType => "float", - label => $i18n->get("property price per impression"), - hoverHelp => $i18n->get("property price per impression help"), - }, - clickDiscounts => { - tab => "shop", - fieldType => 'textarea', - label => $i18n->get('property click discounts'), - hoverHelp => $i18n->get('property click discounts help'), - defaultValue => '', - }, - impressionDiscounts => { - tab => "shop", - fieldType => 'textarea', - label => $i18n->get('property impression discounts'), - hoverHelp => $i18n->get('property impression discounts help'), - defaultValue => '', - }, - ); - - # Show the karma field only if karma is enabled - if ($session->setting->get("useKarma")) { - $properties{ karma } = { - type => 'integer', - label => $i18n->get('property adsku karma'), - hoverHelp => $i18n->get('property adsku karma description'), - defaultvalue => 0, - }; - } - - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'adsku.gif', - autoGenerateForms => 1, - tableName => 'AdSku', - className => 'WebGUI::Asset::Sku::AdSku', - properties => \%properties, - }); - return $class->SUPER::definition($session, $definition); -} - -#------------------------------------------------------------------- - =head2 getAddToCartForm Returns an empty string, since the add to cart form is complex. @@ -162,7 +141,7 @@ Returns an AdSpace object for this Ad Sku. sub getAdSpace { my $self = shift; - my $adSpace = WebGUI::AdSpace->new($self->session,$self->get('adSpace')); + my $adSpace = WebGUI::AdSpace->new($self->session,$self->adSpace); return $adSpace; } @@ -177,7 +156,7 @@ returns the text to display the number of clicks purchasaed where discounts appl sub getClickDiscountText { my $self = shift; return getDiscountText($self->i18n->get('click discount'), - $self->get('clickDiscounts')); + $self->clickDiscounts); } #------------------------------------------------------------------- @@ -190,7 +169,7 @@ combines the adSKu title with the customers ad title sub getConfiguredTitle { my $self = shift; - return $self->get('title') . ' (' . $self->getOptions->{'adtitle'} . ')'; + return $self->title . ' (' . $self->getOptions->{'adtitle'} . ')'; } #------------------------------------------------------------------- @@ -236,7 +215,7 @@ returns the text to display the number of impressions purchased where discounts sub getImpressionDiscountText { my $self = shift; return getDiscountText($self->i18n->get('impression discount'), - $self->get('impressionDiscounts')); + $self->impressionDiscounts); } #------------------------------------------------------------------- @@ -252,10 +231,10 @@ sub getPrice { my $options = $self->getOptions; my $impressionCount = $options->{impressions} || $self->{formImpressions}; my $clickCount = $options->{clicks}; - my $impressionDiscount = getDiscountAmount($self->get('impressionDiscounts'),$impressionCount ); - my $clickDiscount = getDiscountAmount($self->get('clickDiscounts'),$clickCount ); - my $impressionPrice = $self->get('pricePerImpression') * ( 100 - $impressionDiscount ) / 100 ; - my $clickPrice = $self->get('pricePerClick') * ( 100 - $clickDiscount ) / 100 ; + my $impressionDiscount = getDiscountAmount($self->impressionDiscounts,$impressionCount ); + my $clickDiscount = getDiscountAmount($self->clickDiscounts,$clickCount ); + my $impressionPrice = $self->pricePerImpression * ( 100 - $impressionDiscount ) / 100 ; + my $clickPrice = $self->pricePerClick * ( 100 - $clickDiscount ) / 100 ; return sprintf "%.2f", $impressionPrice * $impressionCount + $clickPrice * $clickCount; } @@ -335,7 +314,7 @@ sub onCompletePurchase { }); } else { - $ad = WebGUI::AdSpace::Ad->create($self->session,$self->get('adSpace'),{ + $ad = WebGUI::AdSpace::Ad->create($self->session,$self->adSpace,{ title => $options->{'adtitle'}, clicksBought => $options->{'clicks'}, impressionsBought => $options->{'impressions'}, @@ -344,8 +323,8 @@ sub onCompletePurchase { ownerUserId => $self->session->user->userId, isActive => 1, type => 'image', - priority => $self->get('priority'), - adSpace => $self->get('adSpace'), + priority => $self->priority, + adSpace => $self->adSpace, }); } @@ -437,7 +416,7 @@ Prepares the template. sub prepareManage { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get("manageTemplate"); + my $templateId = $self->manageTemplate; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; @@ -454,7 +433,7 @@ Prepares the template. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get("purchaseTemplate"); + my $templateId = $self->purchaseTemplate; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; @@ -485,8 +464,8 @@ sub view { hasAddedToCart => $self->{_hasAddedToCart}, continueShoppingUrl => $self->getUrl, manageLink => $self->getUrl("func=manage"), - adSkuTitle => $self->get('title'), - adSkuDescription => $self->get('description'), + adSkuTitle => $self->title, + adSkuDescription => $self->description, formTitle => WebGUI::Form::text($session, { -name => "formTitle", -value => $options->{adtitle}, @@ -518,8 +497,8 @@ sub view { -name=>"formAdId", -value=>$options->{adId} || '', }), - clickPrice => $self->get('pricePerClick'), - impressionPrice => $self->get('pricePerImpression'), + clickPrice => $self->pricePerClick, + impressionPrice => $self->pricePerImpression, minimumClicks => $adSpace->get('minimumClicks'), minimumImpressions => $adSpace->get('minimumImpressions'), clickDiscount => $self->getClickDiscountText, @@ -573,7 +552,7 @@ sub www_addToCart { push @errors, $i18n->get('form error no link'); } my $adSpace = $self->getAdSpace; - my $adId = $self->get('adId'); + my $adId = $self->adId; my $clicks = $form->process('formClicks','integer'); if($clicks < $adSpace->get('minimumClicks') ) { push @errors, sprintf($i18n->get('form error min clicks'), $adSpace->get('minimumClicks')); diff --git a/lib/WebGUI/Asset/Sku/Donation.pm b/lib/WebGUI/Asset/Sku/Donation.pm index 1f7df220b..0bda495ef 100644 --- a/lib/WebGUI/Asset/Sku/Donation.pm +++ b/lib/WebGUI/Asset/Sku/Donation.pm @@ -16,7 +16,43 @@ package WebGUI::Asset::Sku::Donation; use strict; use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['assetName', 'Asset_Donation']; +aspect icon => 'Donation.gif'; +aspect tableName => 'donation'; +property templateId => ( + tab => "display", + fieldType => "template", + namespace => "Donation", + default => "vrKXEtluIhbmAS9xmPukDA", + label => ["donate template", 'Asset_Donation'], + hoverHelp => ["donate template help", 'Asset_Donation'], + ); +property thankYouMessage => ( + tab => "properties", + builder => '_thankYouMessage_default', + lazy => 1, + fieldType => "HTMLArea", + label => ["thank you message", 'Asset_Donation'], + hoverHelp => ["thank you message help", 'Asset_Donation'], + ); +sub _thankYouMessage_default { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, "Asset_Donation"); + return $i18n->get("default thank you message"); +} +property defaultPrice => ( + tab => "shop", + fieldType => "float", + default => 100.00, + label => ["default price", 'Asset_Donation'], + hoverHelp => ["default price help", 'Asset_Donation'], + ); + + + use WebGUI::Asset::Template; use WebGUI::Form; @@ -41,57 +77,6 @@ These methods are available from this class: -#------------------------------------------------------------------- - -=head2 definition - -Adds templateId, thankYouMessage, and defaultPrice fields. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_Donation"); - %properties = ( - templateId => { - tab => "display", - fieldType => "template", - namespace => "Donation", - defaultValue => "vrKXEtluIhbmAS9xmPukDA", - label => $i18n->get("donate template"), - hoverHelp => $i18n->get("donate template help"), - }, - thankYouMessage => { - tab => "properties", - defaultValue => $i18n->get("default thank you message"), - fieldType => "HTMLArea", - label => $i18n->get("thank you message"), - hoverHelp => $i18n->get("thank you message help"), - }, - defaultPrice => { - tab => "shop", - fieldType => "float", - defaultValue => 100.00, - label => $i18n->get("default price"), - hoverHelp => $i18n->get("default price help"), - }, - ); - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'Donation.gif', - autoGenerateForms => 1, - tableName => 'donation', - className => 'WebGUI::Asset::Sku::Donation', - properties => \%properties - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 getAddToCartForm ( ) @@ -138,7 +123,7 @@ Returns configured price, or default price, or 100 if neither of those are avail sub getPrice { my $self = shift; - return $self->getOptions->{price} || $self->get("defaultPrice") || 100.00; + return $self->getOptions->{price} || $self->defaultPrice || 100.00; } #------------------------------------------------------------------- @@ -152,7 +137,7 @@ Prepares the template. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get("templateId"); + my $templateId = $self->templateId; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; diff --git a/lib/WebGUI/Asset/Sku/EMSBadge.pm b/lib/WebGUI/Asset/Sku/EMSBadge.pm index bb196c730..981c8336a 100644 --- a/lib/WebGUI/Asset/Sku/EMSBadge.pm +++ b/lib/WebGUI/Asset/Sku/EMSBadge.pm @@ -15,8 +15,71 @@ package WebGUI::Asset::Sku::EMSBadge; =cut use strict; -use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['ems badge', 'Asset_EMSBadge']; +aspect icon => 'EMSBadge.gif'; +aspect tableName => 'EMSBadge'; +property price => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["price", 'Asset_EMSBadge'], + hoverHelp => ["price help", 'Asset_EMSBadge'], + ); +property earlyBirdPrice => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["early bird price", 'Asset_EMSBadge'], + hoverHelp => ["early bird price help", 'Asset_EMSBadge'], + ); +property earlyBirdPriceEndDate => ( + tab => "shop", + fieldType => "date", + default => undef, + label => ["early bird price end date", 'Asset_EMSBadge'], + hoverHelp => ["early bird price end date help", 'Asset_EMSBadge'], + ); +property preRegistrationPrice => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["pre registration price", 'Asset_EMSBadge'], + hoverHelp => ["pre registration price help", 'Asset_EMSBadge'], + ); +property preRegistrationPriceEndDate => ( + tab => "shop", + fieldType => "date", + default => undef, + label => ["pre registration price end date", 'Asset_EMSBadge'], + hoverHelp => ["pre registration price end date help", 'Asset_EMSBadge'], + ); +property seatsAvailable => ( + tab => "shop", + fieldType => "integer", + default => 100, + label => ["seats available", 'Asset_EMSBadge'], + hoverHelp => ["seats available help", 'Asset_EMSBadge'], + ); +property relatedBadgeGroups => ( + tab => "properties", + fieldType => "checkList", + customDrawMethod=> 'drawRelatedBadgeGroupsField', + label => ["related badge groups", 'Asset_EMSBadge'], + hoverHelp => ["related badge groups badge help", 'Asset_EMSBadge'], + ); +property templateId => ( + tab => "display", + fieldType => "template", + label => ["view badge template", 'Asset_EMSBadge'], + hoverHelp => ["view badge template help", 'Asset_EMSBadge'], + default => 'PBEmsBadgeTemplate0000', + namespace => 'EMSBadge', + ); + + + use JSON; use WebGUI::HTMLForm; use WebGUI::International; @@ -63,91 +126,6 @@ sub addToCart { #------------------------------------------------------------------- -=head2 definition - -Adds price, seatsAvailable fields. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_EventManagementSystem"); - %properties = ( - price => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("price"), - hoverHelp => $i18n->get("price help"), - }, - earlyBirdPrice => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("early bird price"), - hoverHelp => $i18n->get("early bird price help"), - }, - earlyBirdPriceEndDate => { - tab => "shop", - fieldType => "date", - defaultValue => undef, - label => $i18n->get("early bird price end date"), - hoverHelp => $i18n->get("early bird price end date help"), - }, - preRegistrationPrice => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("pre registration price"), - hoverHelp => $i18n->get("pre registration price help"), - }, - preRegistrationPriceEndDate => { - tab => "shop", - fieldType => "date", - defaultValue => undef, - label => $i18n->get("pre registration price end date"), - hoverHelp => $i18n->get("pre registration price end date help"), - }, - seatsAvailable => { - tab => "shop", - fieldType => "integer", - defaultValue => 100, - label => $i18n->get("seats available"), - hoverHelp => $i18n->get("seats available help"), - }, - relatedBadgeGroups => { - tab => "properties", - fieldType => "checkList", - customDrawMethod=> 'drawRelatedBadgeGroupsField', - label => $i18n->get("related badge groups"), - hoverHelp => $i18n->get("related badge groups badge help"), - }, - templateId => { - tab => "display", - fieldType => "template", - label => $i18n->get("view badge template"), - hoverHelp => $i18n->get("view badge template help"), - defaultValue => 'PBEmsBadgeTemplate0000', - namespace => 'EMSBadge', - }, - ); - push(@{$definition}, { - assetName => $i18n->get('ems badge'), - icon => 'EMSBadge.gif', - autoGenerateForms => 1, - tableName => 'EMSBadge', - className => 'WebGUI::Asset::Sku::EMSBadge', - properties => \%properties - }); - return $class->SUPER::definition($session, $definition); -} - -#------------------------------------------------------------------- - =head2 drawRelatedBadgeGroupsField () Draws the field for the relatedBadgeGroups property. @@ -222,13 +200,13 @@ Returns the price field value. sub getPrice { my $self = shift; - if ($self->get('earlyBirdPriceEndDate') < time) { - return $self->get('price'); + if ($self->earlyBirdPriceEndDate < time) { + return $self->price; } - elsif ($self->get('preRegistrationPriceEndDate') < time) { - return $self->get('earlyBirdPrice'); + elsif ($self->preRegistrationPriceEndDate < time) { + return $self->earlyBirdPrice; } - return $self->get('preRegistrationPrice'); + return $self->preRegistrationPrice; } #------------------------------------------------------------------- @@ -242,7 +220,7 @@ Returns seatsAvailable - the count from the EMSRegistrant table. sub getQuantityAvailable { my $self = shift; my $seatsTaken = $self->session->db->quickScalar("select count(*) from EMSRegistrant where badgeAssetId=?",[$self->getId]); - return $self->get("seatsAvailable") - $seatsTaken; + return $self->seatsAvailable - $seatsTaken; } #------------------------------------------------------------------- @@ -350,7 +328,7 @@ See WebGUI::Asset, prepareView for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get('templateId'); + my $templateId = $self->templateId; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $self->{_viewTemplate} = $template; } @@ -458,7 +436,7 @@ sub view { $vars{submitAddress} = WebGUI::Form::submit($session, {value => $i18n->get('add to cart'),}); } $vars{title} = $self->getTitle; - $vars{description} = $self->get('description'); + $vars{description} = $self->description; # render the page; return $self->processTemplate(\%vars, undef, $self->{_viewTemplate}); diff --git a/lib/WebGUI/Asset/Sku/EMSRibbon.pm b/lib/WebGUI/Asset/Sku/EMSRibbon.pm index ccabe2406..94cf3681f 100644 --- a/lib/WebGUI/Asset/Sku/EMSRibbon.pm +++ b/lib/WebGUI/Asset/Sku/EMSRibbon.pm @@ -15,8 +15,26 @@ package WebGUI::Asset::Sku::EMSRibbon; =cut use strict; -use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['ems ribbon', 'Asset_EMSRibbon']; +aspect icon => 'EMSRibbon.gif'; +aspect tableName => 'EMSRibbon'; +property price => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["price", 'Asset_EMSRibbon'], + hoverHelp => ["price help", 'Asset_EMSRibbon'], + ); +property percentageDiscount => ( + tab => "shop", + fieldType => "float", + default => 10.0, + label => ["percentage discount", 'Asset_EMSRibbon'], + hoverHelp => ["percentage discount help", 'Asset_EMSRibbon'], + ); + use WebGUI::HTMLForm; use WebGUI::Utility; @@ -39,50 +57,6 @@ These methods are available from this class: =cut -#------------------------------------------------------------------- - -=head2 definition - -Add price field to the definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_EventManagementSystem"); - my $date = WebGUI::DateTime->new($session, time()); - %properties = ( - price => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("price"), - hoverHelp => $i18n->get("price help"), - }, - percentageDiscount => { - tab => "shop", - fieldType => "float", - defaultValue => 10.0, - label => $i18n->get("percentage discount"), - hoverHelp => $i18n->get("percentage discount help"), - }, - ); - push(@{$definition}, { - assetName => $i18n->get('ems ribbon'), - icon => 'EMSRibbon.gif', - autoGenerateForms => 1, - tableName => 'EMSRibbon', - className => 'WebGUI::Asset::Sku::EMSRibbon', - properties => \%properties - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 getAddToCartForm @@ -139,7 +113,7 @@ Returns the price from the definition. sub getPrice { my $self = shift; - return $self->get("price"); + return $self->price; } #------------------------------------------------------------------- @@ -215,10 +189,10 @@ sub view { # render the page; my $output = '

    '.$self->getTitle.'

    ' - .'

    '.$self->get('description').'

    '; + .'

    '.$self->description.'

    '; # build the add to cart form - if ($form->get('badgeId') ne '') { + if ($form->badgeId ne '') { my $addToCart = WebGUI::HTMLForm->new($self->session, action=>$self->getUrl); $addToCart->hidden(name=>"func", value=>"addToCart"); $addToCart->hidden(name=>"badgeId", value=>$form->get('badgeId')); @@ -256,7 +230,7 @@ Override to return to appropriate page. sub www_delete { my ($self) = @_; return $self->session->privilege->insufficient() unless ($self->canEdit && $self->canEditIfLocked); - return $self->session->privilege->vitalComponent() if $self->get('isSystem'); + return $self->session->privilege->vitalComponent() if $self->isSystem; return $self->session->privilege->vitalComponent() if (isIn($self->getId, $self->session->setting->get("defaultPage"), $self->session->setting->get("notFoundPage"))); $self->trash; diff --git a/lib/WebGUI/Asset/Sku/EMSTicket.pm b/lib/WebGUI/Asset/Sku/EMSTicket.pm index c6c9b2d38..aaa7098de 100644 --- a/lib/WebGUI/Asset/Sku/EMSTicket.pm +++ b/lib/WebGUI/Asset/Sku/EMSTicket.pm @@ -15,8 +15,81 @@ package WebGUI::Asset::Sku::EMSTicket; =cut use strict; -use base 'WebGUI::Asset::Sku'; -use Tie::IxHash; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['ems ticket', 'Asset_EMSTicket']; +aspect icon => 'EMSTicket.gif'; +aspect tableName => 'EMSTicket'; +property price => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["price", 'Asset_EMSTicket'], + hoverHelp => ["price help", 'Asset_EMSTicket'], + ); +property seatsAvailable => ( + tab => "shop", + fieldType => "integer", + default => 25, + label => ["seats available", 'Asset_EMSTicket'], + hoverHelp => ["seats available help", 'Asset_EMSTicket'], + ); +property eventNumber => ( + tab => "properties", + fieldType => "integer", + customDrawMethod=> 'drawEventNumberField', + label => ["event number", 'Asset_EMSTicket'], + hoverHelp => ["event number help", 'Asset_EMSTicket'], + ); +property startDate => ( + noFormPost => 1, + fieldType => "hidden", + builder => '_startDate_builder', + lazy => 1, + label => ["add/edit event start date", 'Asset_EMSTicket'], + hoverHelp => ["add/edit event start date help", 'Asset_EMSTicket'], + autoGenerate => 0, + ); +sub _startDate_builder { + my $session = shift->session; + my $date = WebGUI::DateTime->new($session, time()); + return $date->toDatabase, +} +property duration => ( + tab => "properties", + fieldType => "float", + default => 1.0, + subtext => ['hours', 'Asset_EMSTicket'], + label => ["duration", 'Asset_EMSTicket'], + hoverHelp => ["duration help", 'Asset_EMSTicket'], + ); +property location => ( + fieldType => "combo", + tab => "properties", + customDrawMethod=> 'drawLocationField', + label => ["location", 'Asset_EMSTicket'], + hoverHelp => ["location help", 'Asset_EMSTicket'], + ); +property relatedBadgeGroups => ( + tab => "properties", + fieldType => "checkList", + customDrawMethod=> 'drawRelatedBadgeGroupsField', + label => ["related badge groups", 'Asset_EMSTicket'], + hoverHelp => ["related badge groups ticket help", 'Asset_EMSTicket'], + ); +property relatedRibbons => ( + tab => "properties", + fieldType => "checkList", + customDrawMethod=> 'drawRelatedRibbonsField', + label => ["related ribbons", 'Asset_EMSTicket'], + hoverHelp => ["related ribbons help", 'Asset_EMSTicket'], + ); +property eventMetaData => ( + noFormPost => 1, + fieldType => "hidden", + default => '{}', + ); + use JSON (); use WebGUI::Utility; @@ -59,98 +132,6 @@ sub addToCart { #------------------------------------------------------------------- -=head2 definition - -Adds price, seatsAvailable, eventNumber, startDate, endDate and relatedBadges fields. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_EventManagementSystem"); - my $date = WebGUI::DateTime->new($session, time()); - %properties = ( - price => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("price"), - hoverHelp => $i18n->get("price help"), - }, - seatsAvailable => { - tab => "shop", - fieldType => "integer", - defaultValue => 25, - label => $i18n->get("seats available"), - hoverHelp => $i18n->get("seats available help"), - }, - eventNumber => { - tab => "properties", - fieldType => "integer", - customDrawMethod=> 'drawEventNumberField', - label => $i18n->get("event number"), - hoverHelp => $i18n->get("event number help"), - }, - startDate => { - noFormPost => 1, - fieldType => "hidden", - defaultValue => $date->toDatabase, - label => $i18n->get("add/edit event start date"), - hoverHelp => $i18n->get("add/edit event start date help"), - autoGenerate => 0, - }, - duration => { - tab => "properties", - fieldType => "float", - defaultValue => 1.0, - subtext => $i18n->get('hours'), - label => $i18n->get("duration"), - hoverHelp => $i18n->get("duration help"), - }, - location => { - fieldType => "combo", - tab => "properties", - customDrawMethod=> 'drawLocationField', - label => $i18n->get("location"), - hoverHelp => $i18n->get("location help"), - }, - relatedBadgeGroups => { - tab => "properties", - fieldType => "checkList", - customDrawMethod=> 'drawRelatedBadgeGroupsField', - label => $i18n->get("related badge groups"), - hoverHelp => $i18n->get("related badge groups ticket help"), - }, - relatedRibbons => { - tab => "properties", - fieldType => "checkList", - customDrawMethod=> 'drawRelatedRibbonsField', - label => $i18n->get("related ribbons"), - hoverHelp => $i18n->get("related ribbons help"), - }, - eventMetaData => { - noFormPost => 1, - fieldType => "hidden", - defaultValue => '{}', - }, - ); - push(@{$definition}, { - assetName => $i18n->get('ems ticket'), - icon => 'EMSTicket.gif', - autoGenerateForms => 1, - tableName => 'EMSTicket', - className => 'WebGUI::Asset::Sku::EMSTicket', - properties => \%properties - }); - return $class->SUPER::definition($session, $definition); -} - -#------------------------------------------------------------------- - =head2 drawEventNumberField () Draws the field for the eventNumber property. @@ -160,7 +141,7 @@ Draws the field for the eventNumber property. sub drawEventNumberField { my ($self, $params) = @_; my $default = $self->session->db->quickScalar("select max(eventNumber)+1 from EMSTicket left join asset using (assetId) - where parentId=?",[$self->get('parentId')]); + where parentId=?",[$self->parentId]); return WebGUI::Form::integer($self->session, { name => $params->{name}, value => $self->get($params->{name}), @@ -179,10 +160,10 @@ Draws the field for the location property. sub drawLocationField { my ($self, $params) = @_; my $options = $self->session->db->buildHashRef("select distinct(location) from EMSTicket left join asset using (assetId) - where parentId=? order by location",[$self->get('parentId')]); + where parentId=? order by location",[$self->parentId]); return WebGUI::Form::combo($self->session, { name => 'location', - value => $self->get('location'), + value => $self->location, options => $options, }); } @@ -291,7 +272,7 @@ sub getEditForm { hoverHelp => $i18n->get("add/edit event start date help"), timeZone => $self->getParent->get("timezone"), defaultValue => $date->toDatabase, - value => $self->get("startDate"), + value => $self->startDate, ); return $form; } @@ -312,7 +293,7 @@ If specified, returns a single value for the key specified. sub getEventMetaData { my $self = shift; my $key = shift; - my $metadata = JSON->new->decode($self->get("eventMetaData") || '{}'); + my $metadata = JSON->new->decode($self->eventMetaData || '{}'); if (defined $key) { return $metadata->{$key}; } @@ -341,20 +322,20 @@ Returns the value of the price field, after applying ribbon discounts. sub getPrice { my $self = shift; - my @ribbonIds = split("\n", $self->get('relatedRibbons')); - my $price = $self->get("price"); + my @ribbonIds = split("\n", $self->relatedRibbons); + my $price = $self->price; my $discount = 0; my $badgeId = $self->getOptions->{badgeId}; my $ribbonId = $self->session->db->quickScalar("select ribbonAssetId from EMSRegistrantRibbon where badgeId=? limit 1",[$badgeId]); if (defined $ribbonId && isIn($ribbonId, @ribbonIds)) { my $ribbon = WebGUI::Asset->new($self->session,$ribbonId,'WebGUI::Asset::Sku::EMSRibbon'); - $discount = $ribbon->get('percentageDiscount'); + $discount = $ribbon->percentageDiscount; } else { foreach my $item (@{$self->getCart->getItemsByAssetId(\@ribbonIds)}) { if ($item->get('options')->{badgeId} eq $badgeId) { my $ribbon = $item->getSku; - $discount = $ribbon->get('percentageDiscount'); + $discount = $ribbon->percentageDiscount; last; } } @@ -374,7 +355,7 @@ Returns seatsAvailable minus the count from the EMSRegistrantTicket table. sub getQuantityAvailable { my $self = shift; my $seatsTaken = $self->session->db->quickScalar("select count(*) from EMSRegistrantTicket where ticketAssetId=?",[$self->getId]); - return $self->get("seatsAvailable") - $seatsTaken; + return $self->seatsAvailable - $seatsTaken; } #------------------------------------------------------------------- @@ -388,7 +369,7 @@ Adding location and eventNumber as a keyword. See WebGUI::Asset::indexContent() sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get('location').' '.$self->get('eventNumber')); + $indexer->addKeywords($self->location.' '.$self->eventNumber); return $indexer; } @@ -456,7 +437,7 @@ sub processPropertiesFromFormPost { } my $date = WebGUI::DateTime->new($self->session, time())->toDatabase; my $startDate = $form->process('startDate', "dateTime", $date, - { defaultValue => $date, timeZone => $self->getParent->get("timezone")}); + { defaultValue => $date, timeZone => $self->getParent->timezone}); $self->update({eventMetaData => JSON->new->encode(\%metadata), startDate => $startDate}); } @@ -509,9 +490,9 @@ sub view { # render the page; - my $output = '

    '.$self->getTitle.' ('.$self->get('eventNumber').')

    ' - .'

    '.$self->get('description').'

    ' - .'

    '.$self->get('startDate').'

    '; + my $output = '

    '.$self->getTitle.' ('.$self->eventNumber.')

    ' + .'

    '.$self->description.'

    ' + .'

    '.$self->startDate.'

    '; # build the add to cart form if ($form->get('badgeId') ne '') { @@ -552,7 +533,7 @@ Override to return to appropriate page. sub www_delete { my ($self) = @_; return $self->session->privilege->insufficient() unless ($self->canEdit && $self->canEditIfLocked); - return $self->session->privilege->vitalComponent() if $self->get('isSystem'); + return $self->session->privilege->vitalComponent() if $self->isSystem; return $self->session->privilege->vitalComponent() if (isIn($self->getId, $self->session->setting->get("defaultPage"), $self->session->setting->get("notFoundPage"))); $self->trash; return $self->getParent->www_buildBadge(undef,'tickets'); diff --git a/lib/WebGUI/Asset/Sku/EMSToken.pm b/lib/WebGUI/Asset/Sku/EMSToken.pm index 28bec87b4..82ce21b64 100644 --- a/lib/WebGUI/Asset/Sku/EMSToken.pm +++ b/lib/WebGUI/Asset/Sku/EMSToken.pm @@ -15,8 +15,19 @@ package WebGUI::Asset::Sku::EMSToken; =cut use strict; -use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['ems token', 'Asset_EMSToken']; +aspect icon => 'EMSToken.gif'; +aspect tableName => 'EMSToken'; +property price => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["price", 'Asset_EMSToken'], + hoverHelp => ["price help", 'Asset_EMSToken'], + ); + use WebGUI::Utility; @@ -39,43 +50,6 @@ These methods are available from this class: =cut -#------------------------------------------------------------------- - -=head2 definition - -Adds price field. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_EventManagementSystem"); - my $date = WebGUI::DateTime->new($session, time()); - %properties = ( - price => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("price"), - hoverHelp => $i18n->get("price help"), - }, - ); - push(@{$definition}, { - assetName => $i18n->get('ems token'), - icon => 'EMSToken.gif', - autoGenerateForms => 1, - tableName => 'EMSToken', - className => 'WebGUI::Asset::Sku::EMSToken', - properties => \%properties - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 getAddToCartForm @@ -120,7 +94,7 @@ Returns the value of the price field. sub getPrice { my $self = shift; - return $self->get("price"); + return $self->price; } #------------------------------------------------------------------- @@ -208,7 +182,7 @@ sub view { # render the page; my $output = '

    '.$self->getTitle.'

    ' - .'

    '.$self->get('description').'

    '; + .'

    '.$self->description.'

    '; # build the add to cart form if ($form->get('badgeId') ne '') { @@ -250,7 +224,7 @@ Override to return to appropriate page. sub www_delete { my ($self) = @_; return $self->session->privilege->insufficient() unless ($self->canEdit && $self->canEditIfLocked); - return $self->session->privilege->vitalComponent() if $self->get('isSystem'); + return $self->session->privilege->vitalComponent() if $self->isSystem; return $self->session->privilege->vitalComponent() if (isIn($self->getId, $self->session->setting->get("defaultPage"), $self->session->setting->get("notFoundPage"))); $self->trash; diff --git a/lib/WebGUI/Asset/Sku/FlatDiscount.pm b/lib/WebGUI/Asset/Sku/FlatDiscount.pm index 708eeec4a..90a9c4d97 100644 --- a/lib/WebGUI/Asset/Sku/FlatDiscount.pm +++ b/lib/WebGUI/Asset/Sku/FlatDiscount.pm @@ -16,7 +16,55 @@ package WebGUI::Asset::Sku::FlatDiscount; use strict; use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['assetName', 'Asset_FlatDiscount']; +aspect icon => 'FlatDiscount.gif'; +aspect tableName => 'FlatDiscount'; +property templateId => ( + tab => "display", + fieldType => "template", + namespace => "FlatDiscount", + default => "63ix2-hU0FchXGIWkG3tow", + label => ["template", 'Asset_FlatDiscount'], + hoverHelp => ["template help", 'Asset_FlatDiscount'], + ); +property mustSpend => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["must spend", 'Asset_FlatDiscount'], + hoverHelp => ["must spend help", 'Asset_FlatDiscount'], + ); +property percentageDiscount => ( + tab => "shop", + fieldType => "integer", + default => 0, + label => ["percentage discount", 'Asset_FlatDiscount'], + hoverHelp => ["percentage discount help", 'Asset_FlatDiscount'], + ); +property priceDiscount => ( + tab => "shop", + fieldType => "float", + default => 0.00, + label => ["price discount", 'Asset_FlatDiscount'], + hoverHelp => ["price discount help", 'Asset_FlatDiscount'], + ); +property thankYouMessage => ( + tab => "properties", + builder => '_thankYouMessage_default', + lazy => 1, + fieldType => "HTMLArea", + label => ["thank you message", 'Asset_FlatDiscount'], + hoverHelp => ["thank you message help", 'Asset_FlatDiscount'], + ); +sub _thankYouMessage_default { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, "Asset_FlatDiscount"); + return $i18n->get("default thank you message"); +} + + use WebGUI::Asset::Template; use WebGUI::Form; @@ -59,69 +107,6 @@ sub addToCart { } } -#------------------------------------------------------------------- - -=head2 definition - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_FlatDiscount"); - %properties = ( - templateId => { - tab => "display", - fieldType => "template", - namespace => "FlatDiscount", - defaultValue => "63ix2-hU0FchXGIWkG3tow", - label => $i18n->get("template"), - hoverHelp => $i18n->get("template help"), - }, - mustSpend => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("must spend"), - hoverHelp => $i18n->get("must spend help"), - }, - percentageDiscount => { - tab => "shop", - fieldType => "integer", - defaultValue => 0, - label => $i18n->get("percentage discount"), - hoverHelp => $i18n->get("percentage discount help"), - }, - priceDiscount => { - tab => "shop", - fieldType => "float", - defaultValue => 0.00, - label => $i18n->get("price discount"), - hoverHelp => $i18n->get("price discount help"), - }, - thankYouMessage => { - tab => "properties", - defaultValue => $i18n->get("default thank you message"), - fieldType => "HTMLArea", - label => $i18n->get("thank you message"), - hoverHelp => $i18n->get("thank you message help"), - }, - ); - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'FlatDiscount.gif', - autoGenerateForms => 1, - tableName => 'FlatDiscount', - className => 'WebGUI::Asset::Sku::FlatDiscount', - properties => \%properties - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 getMaxAllowedInCart ( ) @@ -147,15 +132,15 @@ sub getPrice { my $self = shift; my $subtotal = 0; foreach my $item (@{$self->getCart->getItems()}) { - next if ($item->get('assetId') eq $self->getId); # avoid an infinite loop - $subtotal += $item->getSku->getPrice * $item->get('quantity'); + next if ($item->assetId eq $self->getId); # avoid an infinite loop + $subtotal += $item->getSku->getPrice * $item->quantity; } - if ($subtotal >= $self->get('mustSpend')) { - if ($self->get('percentageDiscount') > 0) { - return $subtotal * $self->get('percentageDiscount') / -100; + if ($subtotal >= $self->mustSpend) { + if ($self->percentageDiscount > 0) { + return $subtotal * $self->percentageDiscount / -100; } else { - return $self->get('priceDiscount'); + return $self->priceDiscount; } } return 0; @@ -207,7 +192,7 @@ Prepares the template. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get("templateId"); + my $templateId = $self->templateId; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; diff --git a/lib/WebGUI/Asset/Sku/Product.pm b/lib/WebGUI/Asset/Sku/Product.pm index 599f47435..71c5e89bb 100644 --- a/lib/WebGUI/Asset/Sku/Product.pm +++ b/lib/WebGUI/Asset/Sku/Product.pm @@ -19,7 +19,143 @@ use WebGUI::SQL; use WebGUI::Utility; use JSON; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; + +aspect assetName => ['assetName', 'Asset_Product']; +aspect icon => 'product.gif'; +aspect tableName => 'Product'; + +property cacheTimeout => ( + tab => "display", + fieldType => "interval", + default => 3600, + uiLevel => 8, + label => ["cache timeout"], + hoverHelp => ["cache timeout help"], + ); +property templateId => ( + fieldType => "template", + tab => "display", + namespace => "Product", + label => ['62', 'Asset_Product'], + hoverHelp => ['62 description', 'Asset_Product'], + default => 'PBtmpl0000000000000056' + ); +property thankYouMessage => ( + tab => "properties", + default => '_default_thankYouMessage', + fieldType => "HTMLArea", + label => ["thank you message", 'Asset_Product'], + hoverHelp => ["thank you message help", 'Asset_Product'], + lazy => 1, + ); +sub _default_thankYouMessage { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_Product'); + return $i18n->get("default thank you message"); +} +property image1 => ( + tab => "properties", + fieldType => "image", + default => undef, + maxAttachments => 1, + label => ['7', 'Asset_Product'], + deleteFileUrl => \&_product_delete_file_url, + persist => 1, + ); +sub _product_delete_file_url { + my ($self, $property) = @_; + return $self->session->url->page(sprintf "func=deleteFileConfirm;file=%s;filename=", $property->name); +} +property image2 => ( + tab => "properties", + fieldType => "image", + maxAttachments => 1, + label => ['8', 'Asset_Product'], + deleteFileUrl => \&_product_delete_file_url, + default => undef, + persist => 1, + ); +property image3 => ( + tab => "properties", + fieldType => "image", + maxAttachments => 1, + label => ['9', 'Asset_Product'], + deleteFileUrl => \&_product_delete_file_url, + default => undef, + persist => 1, + ); +property brochure => ( + tab => "properties", + fieldType => "file", + maxAttachments => 1, + label => ['13', 'Asset_Product'], + deleteFileUrl => \&_product_delete_file_url, + default => undef, + persist => 1, + ); +property manual => ( + tab => "properties", + fieldType => "file", + maxAttachments => 1, + label => ['14', 'Asset_Product'], + deleteFileUrl => \&_product_delete_file_url, + default => undef, + persist => 1, + ); +property isShippingRequired => ( + tab => "shop", + fieldType => "yesNo", + label => ['isShippingRequired', 'Asset_Product'], + hoverHelp => ['isShippingRequired help', 'Asset_Product'], + default => 0, + ); +property warranty => ( + tab => "properties", + fieldType => "file", + maxAttachments => 1, + label => ['15', 'Asset_Product'], + deleteFileUrl => \&_product_delete_file_url, + default => undef, + persist => 1, + ); +property variantsJSON => ( + ##Collateral data is stored as JSON in here + noFormPost => 0, + default => '[]', + fieldType => "textarea", + ); +property accessoryJSON => ( + ##Collateral data is stored as JSON in here + noFormPost => 0, + default => '[]', + fieldType => "textarea", + ); +property relatedJSON => ( + ##Collateral data is stored as JSON in here + noFormPost => 0, + default => '[]', + fieldType => "textarea", + ); +property specificationJSON => ( + ##Collateral data is stored as JSON in here + noFormPost => 0, + default => '[]', + fieldType => "textarea", + ); +property featureJSON => ( + ##Collateral data is stored as JSON in here + noFormPost => 0, + default => '[]', + fieldType => "textarea", + ); +property benefitJSON => ( + ##Collateral data is stored as JSON in here + noFormPost => 0, + default => '[]', + fieldType => "textarea", + ); #------------------------------------------------------------------- sub _duplicateFile { @@ -55,148 +191,6 @@ sub addRevision { return $newSelf; } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Product"); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - cacheTimeout => { - tab => "display", - fieldType => "interval", - defaultValue => 3600, - uiLevel => 8, - label => $i18n->get("cache timeout"), - hoverHelp => $i18n->get("cache timeout help") - }, - templateId =>{ - fieldType=>"template", - tab => "display", - namespace=>"Product", - label=>$i18n->get(62), - hoverHelp=>$i18n->get('62 description'), - defaultValue=>'PBtmpl0000000000000056' - }, - thankYouMessage => { - tab => "properties", - defaultValue => $i18n->get("default thank you message"), - fieldType => "HTMLArea", - label => $i18n->get("thank you message"), - hoverHelp => $i18n->get("thank you message help"), - }, - image1=>{ - tab => "properties", - fieldType=>"image", - defaultValue=>undef, - maxAttachments=>1, - label=>$i18n->get(7), - deleteFileUrl=>$session->url->page("func=deleteFileConfirm;file=image1;filename="), - persist => 1, - }, - image2=>{ - tab => "properties", - fieldType=>"image", - maxAttachments=>1, - label=>$i18n->get(8), - deleteFileUrl=>$session->url->page("func=deleteFileConfirm;file=image2;filename="), - defaultValue=>undef, - persist => 1, - }, - image3=>{ - tab => "properties", - fieldType=>"image", - maxAttachments=>1, - label=>$i18n->get(9), - deleteFileUrl=>$session->url->page("func=deleteFileConfirm;file=image3;filename="), - defaultValue=>undef, - persist => 1, - }, - brochure=>{ - tab => "properties", - fieldType=>"file", - maxAttachments=>1, - label=>$i18n->get(13), - deleteFileUrl=>$session->url->page("func=deleteFileConfirm;file=brochure;filename="), - defaultValue=>undef, - persist => 1, - }, - manual=>{ - tab => "properties", - fieldType=>"file", - maxAttachments=>1, - label=>$i18n->get(14), - deleteFileUrl=>$session->url->page("func=deleteFileConfirm;file=manual;filename="), - defaultValue=>undef, - persist => 1, - }, - isShippingRequired => { - tab => "shop", - fieldType => "yesNo", - label => $i18n->get('isShippingRequired'), - hoverHelp => $i18n->get('isShippingRequired help'), - defaultValue => 0, - }, - warranty=>{ - tab => "properties", - fieldType=>"file", - maxAttachments=>1, - label=>$i18n->get(15), - deleteFileUrl=>$session->url->page("func=deleteFileConfirm;file=warranty;filename="), - defaultValue=>undef, - persist => 1, - }, - variantsJSON => { - ##Collateral data is stored as JSON in here - autoGenerate => 0, - defaultValue => '[]', - fieldType=>"textarea", - }, - accessoryJSON => { - ##Collateral data is stored as JSON in here - autoGenerate => 0, - defaultValue => '[]', - fieldType=>"textarea", - }, - relatedJSON => { - ##Collateral data is stored as JSON in here - autoGenerate => 0, - defaultValue => '[]', - fieldType=>"textarea", - }, - specificationJSON => { - ##Collateral data is stored as JSON in here - autoGenerate => 0, - defaultValue => '[]', - fieldType=>"textarea", - }, - featureJSON => { - ##Collateral data is stored as JSON in here - autoGenerate => 0, - defaultValue => '[]', - fieldType=>"textarea", - }, - benefitJSON => { - ##Collateral data is stored as JSON in here - autoGenerate => 0, - defaultValue => '[]', - fieldType=>"textarea", - }, - ); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - autoGenerateForms=>1, - icon=>'product.gif', - tableName=>'Product', - className=>'WebGUI::Asset::Sku::Product', - properties=>\%properties - } - ); - return $class->SUPER::definition($session, $definition); -} - #------------------------------------------------------------------- =head2 deleteCollateral ( tableName, keyName, keyValue ) @@ -561,20 +555,6 @@ sub getWeight { return $self->getOptions->{weight}; } -#------------------------------------------------------------------- - -=head2 isShippingRequired - -Overriding the method from Sku so that the user can configure it. - -=cut - -sub isShippingRequired { - my $self = shift; - return $self->get('isShippingRequired'); -} - - #------------------------------------------------------------------- =head2 moveCollateralDown ( tableName, keyName, keyValue ) @@ -1794,7 +1774,7 @@ sub view { $segment = $self->session->icon->delete('func=deleteAccessoryConfirm&aid='.$id,$self->get('url'),$i18n->get(2)) . $self->session->icon->moveUp('func=moveAccessoryUp&aid='.$id,$self->get('url')) . $self->session->icon->moveDown('func=moveAccessoryDown&aid='.$id,$self->get('url')); - my $accessory = WebGUI::Asset->newByDynamicClass($session, $collateral->{accessoryAssetId}); + my $accessory = WebGUI::Asset->newById($session, $collateral->{accessoryAssetId}); push(@accessoryloop,{ 'accessory_URL' => $accessory->getUrl, 'accessory_title' => $accessory->getTitle, @@ -1811,7 +1791,7 @@ sub view { $segment = $self->session->icon->delete('func=deleteRelatedConfirm&rid='.$id, $self->get('url'),$i18n->get(4)) . $self->session->icon->moveUp('func=moveRelatedUp&rid='.$id, $self->get('url')) . $self->session->icon->moveDown('func=moveRelatedDown&rid='.$id, $self->get('url')); - my $related = WebGUI::Asset->newByDynamicClass($session, $collateral->{relatedAssetId}); + my $related = WebGUI::Asset->newById($session, $collateral->{relatedAssetId}); push(@relatedloop,{ 'relatedproduct_URL' => $related->getUrl, 'relatedproduct_title' => $related->getTitle, @@ -1877,8 +1857,8 @@ sub view { $var{continueShoppingUrl} = $self->getUrl; my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10 && $self->{_hasAddedToCart} != 1){ - $cache->set("view_".$self->getId, $out, $self->get("cacheTimeout")); + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10 && $self->{_hasAddedToCart} != 1){ + $cache->set("view_".$self->getId, $out, $self->cacheTimeout); } return $out; } @@ -1893,7 +1873,7 @@ Extend the base method to handle caching. sub www_view { my $self = shift; - $self->session->http->setCacheControl($self->get("cacheTimeout")); + $self->session->http->setCacheControl($self->cacheTimeout); $self->SUPER::www_view(@_); } diff --git a/lib/WebGUI/Asset/Sku/Subscription.pm b/lib/WebGUI/Asset/Sku/Subscription.pm index 82c52996d..0708c4230 100644 --- a/lib/WebGUI/Asset/Sku/Subscription.pm +++ b/lib/WebGUI/Asset/Sku/Subscription.pm @@ -16,7 +16,89 @@ package WebGUI::Asset::Sku::Subscription; use strict; use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['assetName', 'Asset_Subscription']; +aspect icon => 'subscription.gif'; +aspect tableName => 'Subscription'; +property templateId => ( + tab => "display", + fieldType => "template", + namespace => "Subscription", + default => 'eqb9sWjFEVq0yHunGV8IGw', + label => ["template", 'Asset_Subscription'], + hoverHelp => ["template help", 'Asset_Subscription'], + ); +property redeemSubscriptionCodeTemplateId => ( + tab => "display", + fieldType => "template", + namespace => "Operation/RedeemSubscription", + default => 'PBtmpl0000000000000053', + label => ["redeem subscription code template", 'Asset_Subscription'], + hoverHelp => ["redeem subscription code template help", 'Asset_Subscription'], + ); +property thankYouMessage => ( + tab => "properties", + builder => '_thankYouMessage_default', + lazy => 1, + fieldType => "HTMLArea", + label => ["thank you message", 'Asset_Subscription'], + hoverHelp => ["thank you message help", 'Asset_Subscription'], + ); +sub _thankYouMessage_default { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, "Asset_Subscription"); + return $i18n->get("default thank you message"); +} +property price => ( + fieldType => 'float', + label => ['subscription price', 'Asset_Subscription'], + hoverHelp => ['subscription price description', 'Asset_Subscription'], + default => '0.00', + ); +property subscriptionGroup => ( + fieldType => 'group', + label => ['subscription group', 'Asset_Subscription'], + hoverHelp => ['subscription group description', 'Asset_Subscription'], + defaultvalue => [ 2 ] + ); +property recurringSubscription => ( + fieldType => 'yesNo', + label => ['recurring subscription', 'Asset_Subscription'], + hoverHelp => ['recurring subscription description', 'Asset_Subscription'], + default => 1, + ); +property duration => ( + fieldType => 'selectBox', + label => ['subscription duration', 'Asset_Subscription'], + hoverHelp => ['subscription duration description', 'Asset_Subscription'], + default => 'Monthly', + options => \&_duration_options, + ); +sub _duration_options { + my $session = shift->session; + return WebGUI::Shop::Pay->new( $session )->getRecurringPeriodValues, +} +property executeOnSubscription => ( + fieldType => 'text', + label => ['execute on subscription', 'Asset_Subscription'], + hoverHelp => ['execute on subscription description', 'Asset_Subscription'], + default => '', + ); +property karma => ( + fieldType => 'integer', + noFormPost => \&_karma_noFormPost, + label => ['subscription karma', 'Asset_Subscription'], + hoverHelp => ['subscription karma description', 'Asset_Subscription'], + defaultvalue => 0, +); +sub _karma_noFormPost { + my $session = shift->session; + return ! $session->setting->get('useKarma'); +} + + + use WebGUI::Asset::Template; use WebGUI::Form; use WebGUI::Shop::Pay; @@ -60,7 +142,7 @@ sub apply { my $self = shift; my $session = $self->session; my $userId = shift || $session->user->userId; - my $groupId = $self->get('subscriptionGroup'); + my $groupId = $self->subscriptionGroup; # Make user part of the right group and adjust the expiration date my $group = WebGUI::Group->new($session, $groupId); @@ -75,109 +157,17 @@ sub apply { } # Add karma to the user's account - if ($session->setting->get('userKarma')) { - WebGUI::User->new($session,$userId)->karma($self->get('karma'), 'Subscription', 'Added for purchasing subscription '.$self->get('title')); + if ($session->setting->get('useKarma')) { + WebGUI::User->new($session,$userId)->karma($self->karma, 'Subscription', 'Added for purchasing subscription '.$self->title); } # Process the executeOnPurchase field - my $command = $self->get('executeOnSubscription'); + my $command = $self->executeOnSubscription; WebGUI::Macro::process($session,\$command); - system($command) if ($self->get('executeOnSubscription') ne ""); + system($command) if ($self->executeOnSubscription ne ""); } -#------------------------------------------------------------------- - -=head2 definition - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, "Asset_Subscription"); - %properties = ( - templateId => { - tab => "display", - fieldType => "template", - namespace => "Subscription", - defaultValue => 'eqb9sWjFEVq0yHunGV8IGw', - label => $i18n->get("template"), - hoverHelp => $i18n->get("template help"), - }, - redeemSubscriptionCodeTemplateId => { - tab => "display", - fieldType => "template", - namespace => "Operation/RedeemSubscription", - defaultValue => 'PBtmpl0000000000000053', - label => $i18n->get("redeem subscription code template"), - hoverHelp => $i18n->get("redeem subscription code template help"), - }, - thankYouMessage => { - tab => "properties", - defaultValue => $i18n->get("default thank you message"), - fieldType => "HTMLArea", - label => $i18n->get("thank you message"), - hoverHelp => $i18n->get("thank you message help"), - }, - - price => { - fieldType => 'float', - label => $i18n->get('subscription price'), - hoverHelp => $i18n->get('subscription price description'), - defaultValue => '0.00', - }, - subscriptionGroup => { - fieldType => 'group', - label => $i18n->get('subscription group'), - hoverHelp => $i18n->get('subscription group description'), - defaultvalue => [ 2 ] - }, - recurringSubscription => { - fieldType => 'yesNo', - label => $i18n->get('recurring subscription'), - hoverHelp => $i18n->get('recurring subscription description'), - defaultValue => 1, - }, - duration => { - fieldType => 'selectBox', - label => $i18n->get('subscription duration'), - hoverHelp => $i18n->get('subscription duration description'), - defaultValue => 'Monthly', - options => WebGUI::Shop::Pay->new( $session )->getRecurringPeriodValues, - }, - executeOnSubscription => { - fieldType => 'text', - label => $i18n->get('execute on subscription'), - hoverHelp => $i18n->get('execute on subscription description'), - defaultValue => '', - }, - ); - - # Show the karma field only if karma is enabled - if ($session->setting->get("useKarma")) { - $properties{ karma } = { - type => 'integer', - label => $i18n->get('subscription karma'), - hoverHelp => $i18n->get('subscription karma description'), - defaultvalue => 0, - }; - } - - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'subscription.gif', - autoGenerateForms => 1, - tableName => 'Subscription', - className => 'WebGUI::Asset::Sku::Subscription', - properties => \%properties, - }); - return $class->SUPER::definition($session, $definition); -} - #------------------------------------------------------------------- =head2 generateSubscriptionCode ( length ) @@ -409,7 +399,7 @@ The identifier of the interval. Can be either 'Weekly', 'BiWeekly', 'FourWeekly' sub getExpirationOffset { my $self = shift; - my $duration = shift || $self->get('duration'); + my $duration = shift || $self->duration; # y, m, d return $self->session->datetime->addToDate( 1, 0, 0, 7 ) - 1 if $duration eq 'Weekly'; @@ -433,7 +423,7 @@ Returns configured price, 0.00 if neither of those are available. sub getPrice { my $self = shift; - return $self->get('price') || 0.00; + return $self->price || 0.00; } #------------------------------------------------------------------- @@ -447,7 +437,7 @@ Returns the duration of this subscription in a format used by the commerce syste sub getRecurInterval { my $self = shift; - return $self->get('duration'); + return $self->duration; } #------------------------------------------------------------------- @@ -461,7 +451,7 @@ Tells the commerce system this Sku is recurring. sub isRecurring { my $self = shift; - return $self->getValue('recurringSubscription'); + return $self->recurringSubscription; } #------------------------------------------------------------------- @@ -489,7 +479,7 @@ Prepares the template. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get("templateId"); + my $templateId = $self->templateId; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; @@ -1018,7 +1008,7 @@ sub www_redeemSubscriptionCode { $f->submit; $var->{ codeForm } = $f->print; - return $self->processStyle($self->processTemplate($var, $self->get('redeemSubscriptionCodeTemplateId'))); + return $self->processStyle($self->processTemplate($var, $self->redeemSubscriptionCodeTemplateId)); } 1; diff --git a/lib/WebGUI/Asset/Sku/ThingyRecord.pm b/lib/WebGUI/Asset/Sku/ThingyRecord.pm index 391759182..dd4d2508c 100644 --- a/lib/WebGUI/Asset/Sku/ThingyRecord.pm +++ b/lib/WebGUI/Asset/Sku/ThingyRecord.pm @@ -16,7 +16,70 @@ package WebGUI::Asset::Sku::ThingyRecord; use strict; use Tie::IxHash; -use base 'WebGUI::Asset::Sku'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Sku'; +aspect assetName => ['assetName', 'Asset_ThingyRecord']; +aspect icon => 'thingyRecord.gif'; +aspect tableName => 'ThingyRecord'; +property templateIdView => ( + tab => "display", + fieldType => "template", + namespace => "ThingyRecord/View", + label => ['templateIdView label', 'Asset_ThingyRecord'], + hoverHelp => ['templateIdView description', 'Asset_ThingyRecord'], + ); +property thingId => ( + tab => "properties", + fieldType => "selectBox", + options => \&_thingId_options, + label => ['thingId label', 'Asset_ThingyRecord'], + hoverHelp => ['thingId description', 'Asset_ThingyRecord'], + ); +sub _thingId_options { + my $self = shift; + return $self->getThingOptions($self->session); +} +property thingFields => ( + tab => "properties", + fieldType => "selectList", + options => {}, # populated by ajax call + label => ['thingFields label', 'Asset_ThingyRecord'], + hoverHelp => ['thingFields description', 'Asset_ThingyRecord'], + ); +property thankYouText => ( + tab => "properties", + fieldType => "HTMLArea", + builder => '_thankYouMessage_default', + lazy => 1, + label => [ "thank you message", 'Asset_Product' , 'Asset_ThingyRecord'], + hoverHelp => [ "thank you message help", 'Asset_Product' , 'Asset_ThingyRecord'], + ); +sub _thankYouMessage_default { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, "Asset_Product"); + return $i18n->get( 'default thank you message', 'Asset_Product' ) . " ^ViewCart;"; +} +property price => ( + tab => "properties", + fieldType => "float", + label => [ '10', "Asset_Product" , 'Asset_ThingyRecord'], #Price + hoverHelp => [ 'price', 'Asset_Product' , 'Asset_ThingyRecord'], + ); +property fieldPrice => ( + tab => "properties", + fieldType => "textarea", + customDrawMethod => 'drawEditFieldPrice', + label => [ 'fieldPrice label' , 'Asset_ThingyRecord'], + hoverHelp => [ 'fieldPrice description', 'Asset_ThingyRecord'], + ); +property duration => ( + tab => "properties", + fieldType => "interval", + default => 60 * 60 * 24 * 7, # One week + label => ['duration label', 'Asset_ThingyRecord'], + hoverHelp => ['duration description', 'Asset_ThingyRecord'], + ); + use WebGUI::Utility; use HTML::Entities qw( encode_entities ); @@ -42,84 +105,6 @@ These methods are available from this class: =cut -#------------------------------------------------------------------- - -=head2 definition ( session, definition ) - -=head3 session - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new( $session, "Asset_ThingyRecord" ); - tie my %properties, 'Tie::IxHash', ( - templateIdView => { - tab => "display", - fieldType => "template", - namespace => "ThingyRecord/View", - label => $i18n->get('templateIdView label'), - hoverHelp => $i18n->get('templateIdView description'), - }, - thingId => { - tab => "properties", - fieldType => "selectBox", - options => $class->getThingOptions($session), - label => $i18n->get('thingId label'), - hoverHelp => $i18n->get('thingId description'), - }, - thingFields => { - tab => "properties", - fieldType => "selectList", - options => {}, # populated by ajax call - label => $i18n->get('thingFields label'), - hoverHelp => $i18n->get('thingFields description'), - }, - thankYouText => { - tab => "properties", - fieldType => "HTMLArea", - defaultValue => $i18n->get( 'default thank you message', 'Asset_Product' ) . " ^ViewCart;", - label => $i18n->get( "thank you message", 'Asset_Product' ), - hoverHelp => $i18n->get( "thank you message help", 'Asset_Product' ), - }, - price => { - tab => "properties", - fieldType => "float", - label => $i18n->get( '10', "Asset_Product" ), #Price - hoverHelp => $i18n->get( 'price', 'Asset_Product' ), - }, - fieldPrice => { - tab => "properties", - fieldType => "textarea", - customDrawMethod => 'drawEditFieldPrice', - label => $i18n->get( 'fieldPrice label' ), - hoverHelp => $i18n->get( 'fieldPrice description'), - }, - duration => { - tab => "properties", - fieldType => "interval", - defaultValue => 60 * 60 * 24 * 7, # One week - label => $i18n->get('duration label'), - hoverHelp => $i18n->get('duration description'), - }, - ); - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'thingyRecord.gif', - autoGenerateForms => 1, - tableName => 'ThingyRecord', - className => __PACKAGE__, - properties => \%properties, - }; - return $class->SUPER::definition( $session, $definition ); -} ## end sub definition - #---------------------------------------------------------------------------- =head2 appendVarsEditRecord ( var, recordId ) @@ -133,19 +118,19 @@ sub appendVarsEditRecord { my ( $self, $var, $recordId ) = @_; my $session = $self->session; my $thingy = $self->getThingy; - my $fieldPrice = JSON->new->decode( $self->get('fieldPrice') || '{}' ); + my $fieldPrice = JSON->new->decode( $self->fieldPrice || '{}' ); my $record = {}; if ($recordId) { # Get an existing record - $record = $self->getThingRecord( $self->get('thingId'), $recordId ); + $record = $self->getThingRecord( $self->thingId, $recordId ); if ( !%$record ) { # Record is hidden $record = JSON->new->decode( $RECORD_CLASS->new( $session, $recordId )->get('fields') ); } } - my $fields = $self->getThingFields( $self->get('thingId') ); - my @allowed = split "\n", $self->get('thingFields'); + my $fields = $self->getThingFields( $self->thingId ); + my @allowed = split "\n", $self->thingFields; for my $field ( @{$fields} ) { next unless grep { $_ eq $field->{fieldId} } @allowed; @@ -205,7 +190,7 @@ Draw the field to edit field prices. Add appropriate javascript. sub drawEditFieldPrice { my ( $self ) = @_; - my $fieldHtml = sprintf <<'ENDHTML', encode_entities( $self->get('fieldPrice') ); + my $fieldHtml = sprintf <<'ENDHTML', encode_entities( $self->fieldPrice );
    ENDHTML @@ -292,8 +277,8 @@ Get the price sub getPrice { my ($self) = @_; - my $price = $self->get('price'); - my $fieldPrice = JSON->new->decode( $self->get('fieldPrice') || '{}' ); + my $price = $self->price; + my $fieldPrice = JSON->new->decode( $self->fieldPrice || '{}' ); my $option = $self->getOptions; my $record = $RECORD_CLASS->new( $self->session, $option->{recordId} ); my $fields = JSON->new->decode( $record->get('fields') ); @@ -359,7 +344,7 @@ sub getThingOptions { while ( my $thingy = $thingyIter->() ) { tie my %things, 'Tie::IxHash', ( $session->db->buildHash( "SELECT thingId, label FROM Thingy_things WHERE assetId=?", [ $thingy->getId ] ) ); - $options{ $thingy->get('title') } = \%things; + $options{ $thingy->title } = \%things; } return \%options; @@ -391,9 +376,9 @@ sub getThingy { my ($self) = @_; my $thingyId = $self->session->db->quickScalar( "SELECT assetId FROM Thingy_things WHERE thingId=?", - [ $self->get('thingId') ], + [ $self->thingId ], ); - return WebGUI::Asset->newByDynamicClass( $self->session, $thingyId ); + return WebGUI::Asset->newById( $self->session, $thingyId ); } #------------------------------------------------------------------- @@ -415,7 +400,7 @@ sub onCompletePurchase { # Update record $record->update( { - expires => $now + $self->get('duration'), + expires => $now + $self->duration, transactionId => $item->transaction->getId, isHidden => 0, } @@ -423,26 +408,26 @@ sub onCompletePurchase { # Add to thingy data my $data = JSON->new->decode( $record->get('fields') ); - $self->updateThingRecord( $self->get('thingId'), $record->getId, $data ); + $self->updateThingRecord( $self->thingId, $record->getId, $data ); } elsif ( $option->{action} eq "renew" ) { # Renew a currently active record if ( $record->get('expires') > $now ) { - $record->update( { expires => $record->get('expires') + $self->get('duration'), } ); + $record->update( { expires => $record->get('expires') + $self->duration, } ); } # Renew an expired but not deleted record else { $record->update( { - expires => $now + $self->get('duration'), + expires => $now + $self->duration, isHidden => 0, } ); # Add to thingy data my $data = JSON->new->decode( $record->get('fields') ); - $self->updateThingRecord( $self->get('thingId'), $record->getId, $data ); + $self->updateThingRecord( $self->thingId, $record->getId, $data ); } } ## end elsif ( $option->{action}...) } ## end sub onCompletePurchase @@ -479,7 +464,7 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new( $self->session, $self->get("templateIdView") ); + my $template = WebGUI::Asset::Template->new( $self->session, $self->templateIdView ); $template->prepare( $self->getMetaDataAsTemplateVariables ); $self->{_viewTemplate} = $template; } @@ -495,9 +480,9 @@ Process the edit record form and return the record sub processEditRecordForm { my ($self) = @_; my $var = {}; - my $fieldPrice = JSON->new->decode( $self->get('fieldPrice') ); + my $fieldPrice = JSON->new->decode( $self->fieldPrice ); - my $fields = $self->getThingFields( $self->get('thingId') ); + my $fields = $self->getThingFields( $self->thingId ); for my $field ( @{$fields} ) { my $fieldName = 'field_' . $field->{fieldId}; my $fieldType = $field->{fieldType}; @@ -575,7 +560,7 @@ sub view { $var->{isNew} = 1; $var->{message} = $options->{addedToCart} - ? $self->get('thankYouText') + ? $self->thankYouText : $options->{message}; if ( $options->{addedToCart} ) { $var->{addedToCart} = 1; @@ -672,7 +657,7 @@ sub www_editRecord { ); } - return $self->processStyle( $self->processTemplate( $var, $self->get('templateIdView') ) ); + return $self->processStyle( $self->processTemplate( $var, $self->templateIdView ) ); } ## end sub www_editRecord #---------------------------------------------------------------------------- @@ -701,10 +686,10 @@ sub www_editRecordSave { ); if ($hide) { - $self->deleteThingRecord( $self->get('thingId'), $recordId ); + $self->deleteThingRecord( $self->thingId, $recordId ); } else { - $self->updateThingRecord( $self->get('thingId'), $recordId, $recordData ); + $self->updateThingRecord( $self->thingId, $recordId, $recordData ); } return $self->www_editRecord( { message => $i18n->get('saved') } ); diff --git a/lib/WebGUI/Asset/Snippet.pm b/lib/WebGUI/Asset/Snippet.pm index e6c4124b0..4ad1bc288 100644 --- a/lib/WebGUI/Asset/Snippet.pm +++ b/lib/WebGUI/Asset/Snippet.pm @@ -15,14 +15,88 @@ package WebGUI::Asset::Snippet; =cut use strict; -use WebGUI::Asset; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; use WebGUI::Asset::Template; use WebGUI::Macro; use HTML::Packer; use JavaScript::Packer; use CSS::Packer; -our @ISA = qw(WebGUI::Asset); +aspect assetName => ['assetName','Asset_Snippet']; +aspect uiLevel => 5; +aspect icon => 'snippet.gif'; +aspect tableName => 'snippet'; + +property snippet => ( + fieldType => 'codearea', + tab => "properties", + label => ['assetName','Asset_Snippet'], + hoverHelp => ['snippet description','Asset_Snippet'], + default => undef, +); +around snippet => sub { + my $orig = shift; + my $self = shift; + if (@_ > 1) { + my $packed = $_[0]; + if ( $self->mimeType eq "text/html" ) { + HTML::Packer::minify( \$packed, { + remove_comments => 1, + remove_newlines => 1, + do_javascript => "shrink", + do_stylesheet => "minify", + } ); + } + elsif ( $self->mimeType eq "text/css" ) { + CSS::Packer::minify( \$packed, { + compress => 'minify', + }); + } + elsif ( $self->mimeType eq 'text/javascript' ) { + JavaScript::Packer::minify( \$packed, { + compress => "shrink", + }); + } + $self->snippetPacked($packed); + } + $self->$orig(@_); +}; + +property snippetPacked => ( + fieldType => "hidden", + default => undef, + noFormPost => 1, +); +property usePacked => ( + tab => 'properties', + fieldType => 'yesNo', + label => ['usePacked label','Asset_Snippet'], + hoverHelp => ['usePacked description','Asset_Snippet'], + default => 0, +); +property cacheTimeout => ( + tab => "display", + fieldType => "interval", + default => 3600, + uiLevel => 8, + label => ["cache timeout",'Asset_Snippet'], + hoverHelp => ["cache timeout help",'Asset_Snippet'], +); +property processAsTemplate => ( + fieldType => 'yesNo', + label => ['process as template','Asset_Snippet'], + hoverHelp => ['process as template description','Asset_Snippet'], + tab => "properties", + default => 0, +); +property mimeType => ( + tab => "properties", + hoverHelp => ['mimeType description','Asset_Snippet'], + label => ['mimeType','Asset_Snippet'], + fieldType => 'mimeType', + default => 'text/html', +); =head1 NAME @@ -31,13 +105,16 @@ Package WebGUI::Asset::Snippet =head1 DESCRIPTION -Provides a mechanism to publish arbitrary code snippets to WebGUI for reuse in other pages. Can be used for things like HTML segments, javascript, and cascading style sheets. You can also specify the MIME type of the snippet, allowing you to serve XML, CSS and other text files directly from the WebGUI asset system and have browsers recognize them correctly. +Provides a mechanism to publish arbitrary code snippets to WebGUI for reuse +in other pages. Can be used for things like HTML segments, javascript, and +cascading style sheets. You can also specify the MIME type of the snippet, +allowing you to serve XML, CSS and other text files directly from the WebGUI +asset system and have browsers recognize them correctly. =head1 SYNOPSIS use WebGUI::Asset::Snippet; - =head1 METHODS These methods are available from this class: @@ -46,82 +123,6 @@ These methods are available from this class: -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Snippet"); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - snippet=>{ - fieldType=>'codearea', - tab=>"properties", - label=>$i18n->get('assetName'), - hoverHelp=>$i18n->get('snippet description'), - defaultValue=>undef, - filter => "packSnippet", - }, - snippetPacked => { - fieldType => "hidden", - defaultValue => undef, - noFormPost => 1, - }, - usePacked => { - tab => 'properties', - fieldType => 'yesNo', - label => $i18n->get('usePacked label'), - hoverHelp => $i18n->get('usePacked description'), - defaultValue => 0, - }, - cacheTimeout => { - tab => "display", - fieldType => "interval", - defaultValue => 3600, - uiLevel => 8, - label => $i18n->get("cache timeout"), - hoverHelp => $i18n->get("cache timeout help") - }, - processAsTemplate=>{ - fieldType=>'yesNo', - label=>$i18n->get('process as template'), - hoverHelp=>$i18n->get('process as template description'), - tab=>"properties", - defaultValue=>0 - }, - mimeType=>{ - tab=>"properties", - hoverHelp=>$i18n->get('mimeType description'), - label=>$i18n->get('mimeType'), - fieldType=>'mimeType', - defaultValue=>'text/html' - } - - ); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - uiLevel => 5, - icon=>'snippet.gif', - autoGenerateForms=>1, - tableName=>'snippet', - className=>'WebGUI::Asset::Snippet', - properties=>\%properties - }); - return $class->SUPER::definition($session,$definition); -} - #------------------------------------------------------------------- =head2 addRevision ( properties, ... ) @@ -199,49 +200,12 @@ Indexing the content of the snippet. See WebGUI::Asset::indexContent() for addit sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get("snippet")); + $indexer->addKeywords($self->snippet); $indexer->setIsPublic(0); } #------------------------------------------------------------------- -=head2 packSnippet ( unpacked ) - -Pack the snippet if possible. We can pack HTML, CSS, and JS snippets. - -=cut - -sub packSnippet { - my ( $self, $unpacked ) = @_; - return $unpacked if !$unpacked; - my $packed = $unpacked; - - if ( $self->get('mimeType') eq "text/html" ) { - HTML::Packer::minify( \$packed, { - remove_comments => 1, - remove_newlines => 1, - do_javascript => "shrink", - do_stylesheet => "minify", - } ); - } - elsif ( $self->get('mimeType') eq "text/css" ) { - CSS::Packer::minify( \$packed, { - compress => 'minify', - }); - } - elsif ( $self->get('mimeType') eq 'text/javascript' ) { - JavaScript::Packer::minify( \$packed, { - compress => "shrink", - }); - } - - $self->update({ snippetPacked => $packed }); - - return $unpacked; -} - -#------------------------------------------------------------------- - =head2 purgeCache ( ) Extending purgeCache to handle caching of the rendered snippet @@ -260,6 +224,18 @@ sub purgeCache { #------------------------------------------------------------------- +=head2 snippet ( value ) + +Returns the snippet's content. + +=head3 value + +If specified, sets the value, and also packs the content and inserts it into packedSnippet. + +=cut + +#------------------------------------------------------------------- + =head2 view ( $calledAsWebMethod ) Override the base class to implement caching, template and macro processing. @@ -278,23 +254,23 @@ sub view { my $versionTag = WebGUI::VersionTag->getWorking($session, 1); my $noCache = $session->var->isAdminOn - || $self->get("cacheTimeout") <= 10 - || ($versionTag && $versionTag->getId eq $self->get("tagId")); + || $self->cacheTimeout <= 10 + || ($versionTag && $versionTag->getId eq $self->tagId); unless ($noCache) { my $out = eval{$session->cache->get("view_".$calledAsWebMethod."_".$self->getId)}; return $out if $out; } - my $output = $self->get('usePacked') - ? $self->get("snippetPacked") - : $self->get('snippet') - ; + my $output = $self->usePacked + ? $self->snippetPacked + : $self->snippet + ; $output = $self->getToolbar.$output if ($session->var->isAdminOn && !$calledAsWebMethod); - if ($self->getValue("processAsTemplate")) { + if ($self->processAsTemplate) { $output = WebGUI::Asset::Template->processRaw($session, $output, $self->get); } WebGUI::Macro::process($session,\$output); unless ($noCache) { - eval{$session->cache->set("view_".$calledAsWebMethod."_".$self->getId, $output, $self->get("cacheTimeout"))}; + eval{$session->cache->set("view_".$calledAsWebMethod."_".$self->getId, $output, $self->cacheTimeout)}; } return $output; } @@ -310,9 +286,9 @@ A web accessible version of the view method. sub www_view { my $self = shift; return $self->session->privilege->insufficient() unless $self->canView; - my $mimeType=$self->getValue('mimeType'); + my $mimeType=$self->mimeType; $self->session->http->setMimeType($mimeType || 'text/html'); - $self->session->http->setCacheControl($self->get("cacheTimeout")); + $self->session->http->setCacheControl($self->cacheTimeout); my $output = $self->view(1); if (!defined $output) { $output = 'empty'; diff --git a/lib/WebGUI/Asset/Story.pm b/lib/WebGUI/Asset/Story.pm index f76e12656..8c8193b24 100644 --- a/lib/WebGUI/Asset/Story.pm +++ b/lib/WebGUI/Asset/Story.pm @@ -15,9 +15,60 @@ package WebGUI::Asset::Story; =cut use strict; -use Class::C3; -use base 'WebGUI::Asset'; -use Tie::IxHash; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect assetName => ['assetName', 'Asset_Story']; +aspect icon => 'story.gif'; +aspect tableName => 'Story'; +property headline => ( + fieldType => 'text', + label => ['headline', 'Asset_Story'], + hoverHelp => ['headline help', 'Asset_Story'], + default => '', + ); +property subtitle => ( + fieldType => 'text', + label => ['subtitle', 'Asset_Story'], + hoverHelp => ['subtitle help', 'Asset_Story'], + default => '', + ); +property byline => ( + fieldType => 'text', + label => ['byline', 'Asset_Story'], + hoverHelp => ['byline help', 'Asset_Story'], + default => '', + ); +property location => ( + fieldType => 'text', + label => ['location', 'Asset_Story'], + hoverHelp => ['location help', 'Asset_Story'], + default => '', + ); +property highlights => ( + fieldType => 'textarea', + label => ['highlights', 'Asset_Story'], + hoverHelp => ['highlights help', 'Asset_Story'], + default => '', + ); +property story => ( + fieldType => 'HTMLArea', + label => ['highlights', 'Asset_Story'], + hoverHelp => ['highlights help', 'Asset_Story'], + richEditId => \&_story_richEditId, + default => '', + ); +sub _story_richEditId { + my $self = shift; + return $self->parent->getStoryRichEdit; +} +property photo => ( + fieldType => 'textarea', + default => '[]', + noFormPost => 1, + ); + +with 'WebGUI::Role::Asset::AlwaysHidden'; + use WebGUI::Utility; use WebGUI::International; use JSON qw/from_json to_json/; @@ -94,7 +145,7 @@ You can't add children to a Story. sub canEdit { my $self = shift; my $userId = shift || $self->session->user->userId; - if ($userId eq $self->get("ownerUserId")) { + if ($userId eq $self->ownerUserId) { return 1; } my $user = WebGUI::User->new($self->session, $userId); @@ -102,84 +153,6 @@ sub canEdit { || $self->getArchive->canPostStories($userId); } -#------------------------------------------------------------------- - -=head2 definition ( session, definition ) - -defines asset properties for New Asset instances. You absolutely need -this method in your new Assets. - -=head3 session - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session, 'Asset_Story'); - %properties = ( - headline => { - fieldType => 'text', - #label => $i18n->get('headline'), - #hoverHelp => $i18n->get('headline help'), - defaultValue => '', - }, - subtitle => { - fieldType => 'text', - #label => $i18n->get('subtitle'), - #hoverHelp => $i18n->get('subtitle help'), - defaultValue => '', - }, - byline => { - fieldType => 'text', - #label => $i18n->get('byline'), - #hoverHelp => $i18n->get('byline help'), - defaultValue => '', - }, - location => { - fieldType => 'text', - #label => $i18n->get('location'), - #hoverHelp => $i18n->get('location help'), - defaultValue => '', - }, - highlights => { - fieldType => 'textarea', - #label => $i18n->get('highlights'), - #hoverHelp => $i18n->get('highlights help'), - defaultValue => '', - }, - story => { - fieldType => 'HTMLArea', - #label => $i18n->get('highlights'), - #hoverHelp => $i18n->get('highlights help'), - #richEditId => $self->parent->getStoryRichEdit, - defaultValue => '', - }, - photo => { - fieldType => 'textarea', - defaultValue => '[]', - noFormPost => 1, - }, - ); - push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'story.gif', - tableName => 'Story', - className => 'WebGUI::Asset::Story', - properties => \%properties, - autoGenerateForms => 0, - }); - return $class->next::method($session, $definition); -} - - #------------------------------------------------------------------- =head2 duplicate ( ) @@ -252,7 +225,7 @@ The date this was last updated. If left blank, it uses the revisionDate. sub formatDuration { my ($self, $lastUpdated) = @_; - $lastUpdated = defined $lastUpdated ? $lastUpdated : $self->get('revisionDate'); + $lastUpdated = defined $lastUpdated ? $lastUpdated : $self->revisionDate; my $session = $self->session; my $datetime = $session->datetime; my $duration = time() - $lastUpdated; @@ -305,7 +278,7 @@ sub getAutoCommitWorkflowId { my $self = shift; my $archive = $self->getArchive; if ($archive->hasBeenCommitted) { - return $archive->get('approvalWorkflowId') + return $archive->approvalWorkflowId || $self->session->setting->get('defaultVersionTagWorkflow'); } return undef; @@ -383,23 +356,23 @@ sub getEditForm { : $i18n->get('editing','Asset_WikiPage').' '.$title, headlineForm => WebGUI::Form::text($session, { name => 'headline', - value => $form->get('headline') || $self->get('headline'), + value => $form->get('headline') || $self->headline, } ), titleForm => WebGUI::Form::text($session, { name => 'title', - value => $form->get('title') || $self->get('title'), + value => $form->get('title') || $self->title, } ), subtitleForm => WebGUI::Form::text($session, { name => 'subtitle', - value => $form->get('subtitle') || $self->get('subtitle') + value => $form->get('subtitle') || $self->subtitle } ), bylineForm => WebGUI::Form::text($session, { name => 'byline', - value => $form->get('byline') || $self->get('byline') + value => $form->get('byline') || $self->byline } ), locationForm => WebGUI::Form::text($session, { name => 'location', - value => $form->get('location') || $self->get('location') + value => $form->get('location') || $self->location } ), keywordsForm => WebGUI::Form::keywords($session, { name => 'keywords', @@ -407,12 +380,12 @@ sub getEditForm { } ), highlightsForm => WebGUI::Form::textarea($session, { name => 'highlights', - value => $form->get('highlights') || $self->get('highlights') + value => $form->get('highlights') || $self->highlights } ), storyForm => WebGUI::Form::HTMLArea($session, { name => 'story', - value => $form->get('story') || $self->get('story'), - richEditId => $archive->get('richEditorId') + value => $form->get('story') || $self->story, + richEditId => $archive->richEditorId }), saveButton => WebGUI::Form::submit($session, { name => 'saveStory', @@ -501,7 +474,7 @@ sub getEditForm { else { $var->{formHeader} .= WebGUI::Form::hidden($session, { name => 'url', value => $url}); } - return $self->processTemplate($var, $archive->get('editStoryTemplateId')); + return $self->processTemplate($var, $archive->editStoryTemplateId); } @@ -516,7 +489,7 @@ Returns the photo hash formatted as perl data. See also L. sub getPhotoData { my $self = shift; if (!exists $self->{_photoData}) { - my $json = $self->get('photo'); + my $json = $self->photo; $json ||= '[]'; $self->{_photoData} = from_json($json); } @@ -535,11 +508,11 @@ property of the Asset. sub getRssData { my $self = shift; my $data = { - title => $self->get('headline') || $self->getTitle, - description => $self->get('subtitle'), + title => $self->headline || $self->getTitle, + description => $self->subtitle, 'link' => $self->getUrl, - author => $self->get('byline'), - date => $self->get('lastModified'), + author => $self->byline, + date => $self->lastModified, }; return $data; } @@ -555,7 +528,7 @@ Extend the base class to index Story properties like headline, byline, etc. sub indexContent { my $self = shift; my $indexer = $self->next::method(); - $indexer->addKeywords($self->get('headline'), $self->get('subtitle'), $self->get('location'), $self->get('highlights'), $self->get('byline'), $self->get('story'), ); + $indexer->addKeywords($self->headline, $self->subtitle, $self->location, $self->highlights, $self->byline, $self->story, ); } #------------------------------------------------------------------- @@ -573,10 +546,10 @@ sub prepareView { my $templateId; my $topic = $self->topic; if ($topic) { - $templateId = $topic->get('storyTemplateId'); + $templateId = $topic->storyTemplateId; } else { - $templateId = $self->getArchive->get('storyTemplateId'); + $templateId = $self->getArchive->storyTemplateId; } my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare; @@ -621,8 +594,8 @@ sub processPropertiesFromFormPost { my $filename = $upload->getFiles->[0]; $storage->addFileFromFilesystem($upload->getPath($filename)); my ($width, $height) = $storage->getSizeInPixels($filename); - if ($width > $self->getArchive->get('photoWidth')) { - $storage->resize($filename, $self->getArchive->get('photoWidth')); + if ($width > $self->getArchive->photoWidth) { + $storage->resize($filename, $self->getArchive->photoWidth); } $upload->delete; } @@ -641,8 +614,8 @@ sub processPropertiesFromFormPost { my $newStorage = WebGUI::Storage->get($session, $newStorageId); my $photoName = $newStorage->getFiles->[0]; my ($width, $height) = $newStorage->getSizeInPixels($photoName); - if ($width > $self->getArchive->get('photoWidth')) { - $newStorage->resize($photoName, $self->getArchive->get('photoWidth')); + if ($width > $self->getArchive->photoWidth) { + $newStorage->resize($photoName, $self->getArchive->photoWidth); } push @{ $photoData }, { caption => $form->process('newImgCaption', 'text'), @@ -805,21 +778,6 @@ sub topic { #------------------------------------------------------------------- -=head2 update - -Extend the superclass to make sure that the asset always stays hidden from navigation. - -=cut - -sub update { - my $self = shift; - my $properties = shift; - #$self->session->log->warn('story update'); - return $self->next::method({%$properties, isHidden => 1}); -} - -#------------------------------------------------------------------- - =head2 validParent Make sure that the current session asset is a StoryArchive for pasting and adding checks. @@ -889,7 +847,7 @@ sub viewTemplateVariables { }; } $var->{updatedTime} = $self->formatDuration(); - $var->{updatedTimeEpoch} = $self->get('revisionDate'); + $var->{updatedTimeEpoch} = $self->revisionDate; $var->{crumb_loop} = $self->getCrumbTrail(); my $photoData = $self->getPhotoData; @@ -914,7 +872,7 @@ sub viewTemplateVariables { $var->{hasPhotos} = $photoCounter; $var->{singlePhoto} = $photoCounter == 1; $var->{canEdit} = $self->canEdit; - $var->{photoWidth} = $archive->get('photoWidth'); + $var->{photoWidth} = $archive->photoWidth; return $var; } diff --git a/lib/WebGUI/Asset/Template.pm b/lib/WebGUI/Asset/Template.pm index d9330cf0d..a418ace2d 100644 --- a/lib/WebGUI/Asset/Template.pm +++ b/lib/WebGUI/Asset/Template.pm @@ -15,7 +15,79 @@ package WebGUI::Asset::Template; =cut use strict; -use base 'WebGUI::Asset'; + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; + +aspect assetName => ['assetName', 'Asset_Template']; +aspect icon => 'template.gif'; +aspect tableName => 'template'; + +property template => ( + fieldType => 'codearea', + syntax => "html", + default => undef, + trigger => \&_template_autopack, + label => ['assetName', 'Asset_Template'], + hoverHelp => ['template description', 'Asset_Template'], + ); +sub _template_autopack { + my ($self, $new, $old) = @_; + return if $new eq $old; + my $packed = $new; + HTML::Packer::minify( \$packed, { + remove_comments => 1, + remove_newlines => 1, + do_javascript => "shrink", + do_stylesheet => "minify", + } ); + $self->templatePacked($packed); +} +property isEditable => ( + noFormPost => 1, + fieldType => 'hidden', + default => 1, + ); +property isDefault => ( + noFormPost => 1, + fieldType => 'hidden', + default => 0, + ); +property showInForms => ( + fieldType => 'yesNo', + default => 1, + label => ['show in forms', 'Asset_Template'], + hoverHelp => ['show in forms description', 'Asset_Template'], + ); +property parser => ( + noFormPost => 1, + fieldType => 'selectBox', + lazy => 1, + builder => '_default_parser', + lazy => 1, + ); +sub _default_parser { + my $self = shift; + return $self->session->config->get('defaultTemplateParser'); +} +property namespace => ( + fieldType => 'combo', + default => undef, + label => ['namespace', 'Asset_Template'], + hoverHelp => ['namespace description', 'Asset_Template'], + ); +property templatePacked => ( + fieldType => 'hidden', + default => undef, + noFormPost => 1, + ); +property usePacked => ( + fieldType => 'yesNo', + default => 0, + label => ['usePacked label', 'Asset_Template'], + hoverHelp => ['usePacked description', 'Asset_Template'], + ); + use WebGUI::International; use WebGUI::Asset::Template::HTMLTemplate; use WebGUI::Utility; @@ -47,75 +119,6 @@ These methods are available from this class: #------------------------------------------------------------------- -=head2 definition ( session, definition ) - -Defines the properties of this asset. - -=head3 session - -A reference to an existing session. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Template"); - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'template.gif', - tableName => 'template', - className => 'WebGUI::Asset::Template', - properties => { - template => { - fieldType => 'codearea', - syntax => "html", - defaultValue => undef, - filter => 'packTemplate', - }, - isEditable => { - noFormPost => 1, - fieldType => 'hidden', - defaultValue => 1, - }, - isDefault => { - fieldType => 'hidden', - defaultValue => 0, - }, - showInForms => { - fieldType => 'yesNo', - defaultValue => 1, - }, - parser => { - noFormPost => 1, - fieldType => 'selectBox', - defaultValue => [$session->config->get("defaultTemplateParser")], - }, - namespace => { - fieldType => 'combo', - defaultValue => undef, - }, - templatePacked => { - fieldType => 'hidden', - defaultValue => undef, - noFormPost => 1, - }, - usePacked => { - fieldType => 'yesNo', - defaultValue => 0, - }, - }, - }; - return $class->SUPER::definition($session,$definition); -} - -#------------------------------------------------------------------- - =head2 addAttachments ( attachments ) Adds attachments to this template. Attachments is an arrayref of hashrefs, @@ -138,7 +141,7 @@ sub addAttachments { foreach my $a (@$attachments) { my @params = ( $self->getId, - $self->get('revisionDate'), + $self->revisionDate, @{$a}{qw(url type sequence)} ); $db->write($sql, \@params); @@ -172,7 +175,7 @@ Extra Head Tags. sub drawExtraHeadTags { my ($self, $params) = @_; - if ($self->get('namespace') eq 'style') { + if ($self->namespace eq 'style') { my $i18n = WebGUI::International->new($self->session); return $i18n->get(881); } @@ -227,7 +230,7 @@ If defined, will limit the attachments to this type; e.g., passing sub getAttachments { my ( $self, $type ) = @_; - my @params = ($self->getId, $self->get('revisionDate')); + my @params = ($self->getId, $self->revisionDate); my $typeString; if ($type) { @@ -266,7 +269,7 @@ sub getEditForm { name=>"returnUrl", value=>$self->session->form->get("returnUrl") }); - if ($self->getValue("namespace") eq "") { + if ($self->namespace eq "") { my $namespaces = $self->session->dbSlave->buildHashRef("select distinct(namespace) from template order by namespace"); $tabform->getTab("properties")->combo( -name=>"namespace", @@ -279,16 +282,16 @@ sub getEditForm { $tabform->getTab("meta")->readOnly( -label=>$i18n->get('namespace'), -hoverHelp=>$i18n->get('namespace description'), - -value=>$self->getValue("namespace") + -value=>$self->namespace ); $tabform->getTab("meta")->hidden( -name=>"namespace", - -value=>$self->getValue("namespace") + -value=>$self->namespace ); } $tabform->getTab("display")->yesNo( -name=>"showInForms", - -value=>$self->getValue("showInForms"), + -value=>$self->showInForms, -label=>$i18n->get('show in forms'), -hoverHelp=>$i18n->get('show in forms description'), ); @@ -297,13 +300,13 @@ sub getEditForm { -label=>$i18n->get('assetName'), -hoverHelp=>$i18n->get('template description'), -syntax => "html", - -value=>$self->getValue("template") + -value=>$self->template ); $tabform->getTab('properties')->yesNo( name => "usePacked", label => $i18n->get('usePacked label'), hoverHelp => $i18n->get('usePacked description'), - value => $self->getValue("usePacked"), + value => $self->usePacked, ); if($self->session->config->get("templateParsers")){ my @temparray = @{$self->session->config->get("templateParsers")}; @@ -312,7 +315,7 @@ sub getEditForm { $parsers{$a} = $self->getParser($self->session, $a)->getName(); } my $value = [$self->getValue("parser")]; - $value = \[$self->session->config->get("defaultTemplateParser")] if(!$self->getValue("parser")); + $value = \[$self->session->config->get("defaultTemplateParser")] if(!$self->parser); $tabform->getTab("properties")->selectBox( -name=>"parser", -options=>\%parsers, @@ -429,8 +432,10 @@ sub getList { my $sth = $session->dbSlave->read($sql, [$namespace, $session->scratch->get("versionTag")]); my %templates; tie %templates, 'Tie::IxHash'; - while (my ($id, $version) = $sth->array) { - $templates{$id} = WebGUI::Asset::Template->new($session,$id,undef,$version)->getTitle; + TEMPLATE: while (my ($id, $version) = $sth->array) { + my $template = eval { WebGUI::Asset::Template->new($session,$id,$version); }; + next TEMPLATE if Exception::Class->caught(); + $templates{$id} = $template->getTitle; } $sth->finish; return \%templates; @@ -493,33 +498,12 @@ Making private. See WebGUI::Asset::indexContent() for additonal details. sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get("namespace")); + $indexer->addKeywords($self->namespace); $indexer->setIsPublic(0); } #------------------------------------------------------------------- -=head2 packTemplate ( template ) - -Pack the template into a minified version for faster downloads. - -=cut - -sub packTemplate { - my ( $self, $template ) = @_; - my $packed = $template; - HTML::Packer::minify( \$packed, { - remove_comments => 1, - remove_newlines => 1, - do_javascript => "shrink", - do_stylesheet => "minify", - } ); - $self->update({ templatePacked => $packed }); - return $template; -} - -#------------------------------------------------------------------- - =head2 prepare ( headerTemplateVariables ) This method sets the tags from the head block parameter of the template into the HTML head block in the style. You only need to call this method if you're using the HTML streaming features of WebGUI, like is done in the prepareView()/view()/www_view() methods of WebGUI assets. @@ -546,7 +530,7 @@ sub prepare { my $session = $self->session; my ($db, $style) = $session->quick(qw(db style)); - my $parser = $self->getParser($session, $self->get('parser')); + my $parser = $self->getParser($session, $self->parser); my $headBlock = $parser->process($self->getExtraHeadTags, $vars); $style->setRawHeadTags($headBlock); @@ -590,16 +574,16 @@ sub process { my $vars = shift; my $session = $self->session; - if ($self->get('state') =~ /^trash/) { + if ($self->state =~ /^trash/) { my $i18n = WebGUI::International->new($session, 'Asset_Template'); $session->errorHandler->warn('process called on template in trash: '.$self->getId - .'. The template was called through this url: '.$session->asset->get('url')); + .'. The template was called through this url: '.$session->asset->url); return $session->var->isAdminOn ? $i18n->get('template in trash') : ''; } - elsif ($self->get('state') =~ /^clipboard/) { + elsif ($self->state =~ /^clipboard/) { my $i18n = WebGUI::International->new($session, 'Asset_Template'); $session->errorHandler->warn('process called on template in clipboard: '.$self->getId - .'. The template was called through this url: '.$session->asset->get('url')); + .'. The template was called through this url: '.$session->asset->url); return $session->var->isAdminOn ? $i18n->get('template in clipboard') : ''; } @@ -610,10 +594,10 @@ sub process { } $self->prepare unless ($self->{_prepared}); - my $parser = $self->getParser($session, $self->get("parser")); - my $template = $self->get('usePacked') - ? $self->get('templatePacked') - : $self->get('template') + my $parser = $self->getParser($session, $self->parser); + my $template = $self->usePacked + ? $self->templatePacked + : $self->template ; my $output; eval { $output = $parser->process($template, $vars); }; @@ -640,7 +624,7 @@ sub processPropertiesFromFormPost { # TODO: Perhaps add a way to check template syntax before it blows stuff up? my %data; my $needsUpdate = 0; - if ($self->getValue("parser") ne $self->session->form->process("parser","className") && ($self->session->form->process("parser","className") ne "")) { + if ($self->parser ne $self->session->form->process("parser","className") && ($self->session->form->process("parser","className") ne "")) { $needsUpdate = 1; if (isIn($self->session->form->process("parser","className"),@{$self->session->config->get("templateParsers")})) { %data = ( parser => $self->session->form->process("parser","className") ); @@ -767,30 +751,6 @@ sub removeAttachments { $db->write($rmsql, \@params); } -#------------------------------------------------------------------- - -=head2 update - -Override update from Asset.pm to handle backwards compatibility with the old -packages that contain headBlocks. This will be removed in the future. Don't plan -on this being here. - -=cut - -sub update { - my $self = shift; - my $requestedProperties = shift; - my $properties = clone($requestedProperties); - - if (exists $properties->{headBlock}) { - $properties->{extraHeadTags} .= $properties->{headBlock}; - delete $properties->{headBlock}; - } - - $self->SUPER::update($properties); -} - - #------------------------------------------------------------------- =head2 www_edit diff --git a/lib/WebGUI/Asset/WikiPage.pm b/lib/WebGUI/Asset/WikiPage.pm index d2e8ef30b..458e2f292 100644 --- a/lib/WebGUI/Asset/WikiPage.pm +++ b/lib/WebGUI/Asset/WikiPage.pm @@ -11,15 +11,55 @@ package WebGUI::Asset::WikiPage; # ------------------------------------------------------------------- use strict; -use Class::C3; -use base qw( - WebGUI::AssetAspect::Subscribable - WebGUI::AssetAspect::Comments - WebGUI::Asset -); -use Tie::IxHash; +#use Class::C3; +#use base qw( +# WebGUI::AssetAspect::Subscribable +# WebGUI::AssetAspect::Comments +# WebGUI::Asset +#); + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; + +apsect assetName => ['assetName', 'Asset_WikiPage']; +apsect icon => 'wikiPage.gif'; +apsect tableName => 'WikiPage'; + +property content => ( + fieldType => "HTMLArea", + default => undef + ); +property views => ( + fieldType => "integer", + default => 0, + noFormPost => 1 + ); +property isProtected => ( + fieldType => "yesNo", + default => 0, + noFormPost => 1 + ); +property actionTaken => ( + fieldType => "text", + default => '', + noFormPost => 1, + ); +property actionTakenBy => ( + fieldType => "user", + default => '', + noFormPost => 1, + ); +property isFeatured => ( + fieldType => "yesNo", + default => 0, + noFormPost => 1, + ); + +with 'WebGUI::Role::Asset::AlwaysHidden'; + use WebGUI::International; use WebGUI::Utility; + use WebGUI::VersionTag; @@ -92,60 +132,6 @@ sub canEdit { || ( $wiki->canEditPages && ( $addNew || $editSave || !$self->isProtected) ); } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session, "Asset_WikiPage"); - - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = - ( - content => { fieldType => "HTMLArea", - defaultValue => undef }, - views => { - fieldType => "integer", - defaultValue => 0, - noFormPost => 1 - }, - isProtected => { - fieldType => "yesNo", - defaultValue => 0, - noFormPost => 1 - }, - actionTaken => { - fieldType => "text", - defaultValue => '', - noFormPost => 1, - }, - actionTakenBy => { - fieldType => "user", - defaultValue => '', - noFormPost => 1, - }, - isFeatured => { - fieldType => "yesNo", - defaultValue => 0, - noFormPost => 1, - }, - ); - - push @$definition, - { - assetName => $i18n->get('assetName'), - icon => 'wikiPage.gif', - autoGenerateForms => 1, - tableName => 'WikiPage', - className => 'WebGUI::Asset::WikiPage', - properties => \%properties, - }; - - return $class->next::method($session, $definition); -} - - #------------------------------------------------------------------- =head2 getAutoCommitWorkflowId @@ -167,8 +153,8 @@ sub getAutoCommitWorkflowId { if (ref $spamStopWords eq 'ARRAY') { my $spamRegex = join('|',@{$spamStopWords}); $spamRegex =~ s/\s/\\ /g; - if ($self->get('content') =~ m{$spamRegex}xmsi) { - my $tag = WebGUI::VersionTag->new($self->session, $self->get('tagId')); + if ($self->content =~ m{$spamRegex}xmsi) { + my $tag = WebGUI::VersionTag->new($self->session, $self->assetId); $self->purgeRevision; if ($tag->getAssetCount == 0) { $tag->rollback; @@ -177,7 +163,7 @@ sub getAutoCommitWorkflowId { } } - return $wiki->get('approvalWorkflow') + return $wiki->approvalWorkflow || $self->session->setting->get('defaultVersionTagWorkflow'); } return undef; @@ -201,21 +187,21 @@ sub getEditForm { my $wiki = $self->getWiki; my $url = ($self->getId eq "new") ? $wiki->getUrl : $self->getUrl; my $var = { - title=> $i18n->get("editing")." ".(defined($self->get('title'))? $self->get('title') : $i18n->get("assetName")), + title=> $i18n->get("editing")." ".(defined($self->title)? $self->title : $i18n->get("assetName")), formHeader => WebGUI::Form::formHeader($session, { action => $url}) .WebGUI::Form::hidden($session, { name => 'func', value => 'editSave' }) .WebGUI::Form::hidden($session, { name=>"proceed", value=>"showConfirmation" }), formTitle => WebGUI::Form::text($session, { name => 'title', maxlength => 255, size => 40, - value => $self->get('title'), defaultValue=>$form->get("title","text") }), - formContent => WebGUI::Form::HTMLArea($session, { name => 'content', richEditId => $wiki->get('richEditor'), value => $self->get('content') }) , + value => $self->title, defaultValue=>$form->get("title","text") }), + formContent => WebGUI::Form::HTMLArea($session, { name => 'content', richEditId => $wiki->richEditor, value => $self->content }) , formSubmit => WebGUI::Form::submit($session, { value => 'Save' }), - formProtect => WebGUI::Form::yesNo($session, { name => "isProtected", value=>$self->getValue("isProtected")}), - formFeatured => WebGUI::Form::yesNo( $session, { name => 'isFeatured', value=>$self->getValue('isFeatured')}), + formProtect => WebGUI::Form::yesNo($session, { name => "isProtected", value=>$self->isProtected}), + formFeatured => WebGUI::Form::yesNo( $session, { name => 'isFeatured', value=>$self->isFeatured}), formKeywords => WebGUI::Form::keywords($session, { name => "keywords", value => WebGUI::Keyword->new($session)->getKeywordsForAsset({asset=>$self}), }), - allowsAttachments => $wiki->get("allowAttachments"), + allowsAttachments => $wiki->allowAttachments, formFooter => WebGUI::Form::formFooter($session), isNew => ($self->getId eq "new"), canAdminister => $wiki->canAdminister, @@ -237,11 +223,11 @@ sub getEditForm { } $var->{formAttachment} = WebGUI::Form::Attachments($session, { value => $children, - maxAttachments => $wiki->get("allowAttachments"), - maxImageSize => $wiki->get("maxImageSize"), - thumbnailSize => $wiki->get("thumbnailSize"), + maxAttachments => $wiki->allowAttachments, + maxImageSize => $wiki->maxImageSize, + thumbnailSize => $wiki->thumbnailSize, }); - return $self->processTemplate($var, $wiki->getValue('pageEditTemplateId')); + return $self->processTemplate($var, $wiki->pageEditTemplateId); } #------------------------------------------------------------------- @@ -267,7 +253,7 @@ sub getTemplateVars { my ( $self ) = @_; my $i18n = WebGUI::International->new($self->session, "Asset_WikiPage"); my $wiki = $self->getWiki; - my $owner = WebGUI::User->new( $self->session, $self->get('ownerUserId') ); + my $owner = WebGUI::User->new( $self->session, $self->ownerUserId ); my $keywords = WebGUI::Keyword->new($self->session)->getKeywordsForAsset({ asset => $self, asArrayRef => 1, @@ -296,13 +282,13 @@ sub getTemplateVars { wikiHomeUrl => $wiki->getUrl, historyUrl => $self->getUrl("func=getHistory"), editContent => $self->getEditForm, - allowsAttachments => $wiki->get("allowAttachments"), + allowsAttachments => $wiki->allowAttachments, comments => $self->getFormattedComments(), canEdit => $self->canEdit, isProtected => $self->isProtected, content => $wiki->autolinkHtml( $self->scrubContent, - {skipTitles => [$self->get('title')]}, + {skipTitles => [$self->title]}, ), isSubscribed => $self->isSubscribed, subscribeUrl => $self->getSubscribeUrl, @@ -339,7 +325,7 @@ Extends the master class to handle indexing the wiki content. sub indexContent { my $self = shift; my $indexer = $self->next::method; - $indexer->addKeywords($self->get('content')); + $indexer->addKeywords($self->content); return $indexer; } @@ -353,7 +339,7 @@ Returns a boolean indicating whether or not this WikiPage is protected. sub isProtected { my $self = shift; - return $self->get("isProtected"); + return $self->isProtected; } #------------------------------------------------------------------- @@ -369,7 +355,7 @@ sub preparePageTemplate { my $self = shift; return $self->{_pageTemplate} if $self->{_pageTemplate}; $self->{_pageTemplate} = - WebGUI::Asset::Template->new($self->session, $self->getWiki->get('pageTemplateId')); + WebGUI::Asset::Template->new($self->session, $self->getWiki->pageTemplateId); $self->{_pageTemplate}->prepare; return $self->{_pageTemplate}; } @@ -403,8 +389,8 @@ sub processPropertiesFromFormPost { my $actionTaken = ($self->session->form->process("assetId") eq "new") ? "Created" : "Edited"; my $wiki = $self->getWiki; my $properties = { - groupIdView => $wiki->get('groupIdView'), - groupIdEdit => $wiki->get('groupToAdminister'), + groupIdView => $wiki->groupIdView, + groupIdEdit => $wiki->groupToAdminister, actionTakenBy => $self->session->user->userId, actionTaken => $actionTaken, }; @@ -418,25 +404,25 @@ sub processPropertiesFromFormPost { # deal with attachments from the attachments form control my $options = { - maxImageSize => $wiki->get('maxImageSize'), - thumbnailSize => $wiki->get('thumbnailSize'), + maxImageSize => $wiki->maxImageSize, + thumbnailSize => $wiki->thumbnailSize, }; my @attachments = $self->session->form->param("attachments"); my @tags = (); foreach my $assetId (@attachments) { - my $asset = WebGUI::Asset->newByDynamicClass($self->session, $assetId); + my $asset = WebGUI::Asset->newById($self->session, $assetId); if (defined $asset) { - unless ($asset->get("parentId") eq $self->getId) { + unless ($asset->parentId eq $self->getId) { $asset->setParent($self); $asset->update({ - ownerUserId => $self->get("ownerUserId"), - groupIdEdit => $self->get("groupIdEdit"), - groupIdView => $self->get("groupIdView"), + ownerUserId => $self->ownerUserId, + groupIdEdit => $self->groupIdEdit, + groupIdView => $self->groupIdView, }); } $asset->applyConstraints($options); - push(@tags, $asset->get("tagId")); - $asset->setVersionTag($self->get("tagId")); + push(@tags, $asset->tagId); + $asset->setVersionTag($self->tagId); } } @@ -465,11 +451,11 @@ Optionally pass the ontent that we want to run the filters on. Otherwise we get sub scrubContent { my $self = shift; - my $content = shift || $self->get("content"); + my $content = shift || $self->content; - my $scrubbedContent = WebGUI::HTML::filter($content, $self->getWiki->get("filterCode")); + my $scrubbedContent = WebGUI::HTML::filter($content, $self->getWiki->filterCode); - if ($self->getWiki->get("useContentFilter")) { + if ($self->getWiki->useContentFilter) { $scrubbedContent = WebGUI::HTML::processReplacements($self->session, $scrubbedContent); } @@ -478,21 +464,6 @@ sub scrubContent { #------------------------------------------------------------------- -=head2 update - -Wrap update to force isHidden to be on, all the time. - -=cut - -sub update { - my $self = shift; - my $properties = shift; - $properties->{isHidden} = 1; - return $self->next::method($properties); -} - -#------------------------------------------------------------------- - =head2 validParent Make sure that the current session asset is a WikiMaster for pasting and adding checks. @@ -517,7 +488,7 @@ Renders this asset. sub view { my $self = shift; - return $self->processTemplate($self->getTemplateVars, $self->getWiki->get("pageTemplateId")); + return $self->processTemplate($self->getTemplateVars, $self->getWiki->pageTemplateId); } #------------------------------------------------------------------- @@ -569,16 +540,16 @@ sub www_getHistory { foreach my $revision (@{$self->getRevisions}) { my $user = WebGUI::User->new($self->session, $revision->get("actionTakenBy")); push(@{$var->{pageHistoryEntries}}, { - toolbar => $icon->delete("func=purgeRevision;revisionDate=".$revision->get("revisionDate"), $revision->get("url"), $i18n->get("delete confirmation")) - .$icon->edit('func=edit;revision='.$revision->get("revisionDate"), $revision->get("url")) - .$icon->view('func=view;revision='.$revision->get("revisionDate"), $revision->get("url")), - date => $date->epochToHuman($revision->get("revisionDate")), + toolbar => $icon->delete("func=purgeRevision;revisionDate=".$revision->revisionDate, $revision->url, $i18n->get("delete confirmation")) + .$icon->edit('func=edit;revision='.$revision->revisionDate, $revision->url) + .$icon->view('func=view;revision='.$revision->revisionDate, $revision->url), + date => $date->epochToHuman($revision->revisionDate), username => $user->profileField('alias') || $user->username, - actionTaken => $revision->get("actionTaken"), - interval => join(" ", $date->secondsToInterval(time() - $revision->get("revisionDate"))) + actionTaken => $revision->actionTaken, + interval => join(" ", $date->secondsToInterval(time() - $revision->revisionDate)) }); } - return $self->processTemplate($var, $self->getWiki->get('pageHistoryTemplateId')); + return $self->processTemplate($var, $self->getWiki->pageHistoryTemplateId); } #------------------------------------------------------------------- @@ -623,7 +594,7 @@ and to render it with the parent's style. sub www_view { my $self = shift; return $self->session->privilege->noAccess unless $self->canView; - $self->update({ views => $self->get('views')+1 }); + $self->update({ views => $self->views+1 }); # TODO: This should probably exist, as the CS has one. # $self->session->http->setCacheControl($self->getWiki->get('visitorCacheTimeout')) # if ($self->session->user->isVisitor); diff --git a/lib/WebGUI/Asset/Wobject.pm b/lib/WebGUI/Asset/Wobject.pm index cbcc54ddd..1dfc4cc49 100644 --- a/lib/WebGUI/Asset/Wobject.pm +++ b/lib/WebGUI/Asset/Wobject.pm @@ -23,8 +23,50 @@ use WebGUI::International; use WebGUI::Macro; use WebGUI::SQL; use WebGUI::Utility; - -our @ISA = qw(WebGUI::Asset); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; +aspect tableName => 'wobject'; +aspect assetName => 'Wobject'; +property description => ( + fieldType => 'HTMLArea', + default => undef, + tab => "properties", + label => [85,'Asset_Wobject'], + hoverHelp => ['85 description','Asset_Wobject'], + ); +property displayTitle => ( + fieldType => 'yesNo', + default => 1, + tab => "display", + label => [174,'Asset_Wobject'], + hoverHelp => ['174 description','Asset_Wobject'], + uiLevel => 5 + ); +property styleTemplateId => ( + fieldType => 'template', + default => 'PBtmpl0000000000000060', + tab => "display", + label => [1073,'Asset_Wobject'], + hoverHelp => ['1073 description','Asset_Wobject'], + namespace => 'style' + ); +property printableStyleTemplateId => ( + fieldType => 'template', + default => 'PBtmpl0000000000000060', + tab => "display", + label => [1079,'Asset_Wobject'], + hoverHelp => ['1079 description','Asset_Wobject'], + namespace => 'style' + ); +property mobileStyleTemplateId => ( + fieldType => 'template', + noFormPost => sub { return !$_[0]->session->setting->get('useMobileStyle'); }, + default => 'PBtmpl0000000000000060', + tab => 'display', + label => ['mobileStyleTemplateId label','Asset_Wobject'], + hoverHelp => ['mobileStyleTemplateId description','Asset_Wobject'], + namespace => 'style', + ); =head1 NAME @@ -49,78 +91,6 @@ These methods are available from this class: #------------------------------------------------------------------- -=head2 definition ( session, [definition] ) - -Returns an array reference of definitions. Adds tableName, className, properties to array definition. - -=head3 definition - -An array of hashes to prepend to the list - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,'Asset_Wobject'); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - description=>{ - fieldType=>'HTMLArea', - defaultValue=>undef, - tab=>"properties", - label=>$i18n->get(85), - hoverHelp=>$i18n->get('85 description') - }, - displayTitle=>{ - fieldType=>'yesNo', - defaultValue=>1, - tab=>"display", - label=>$i18n->get(174), - hoverHelp=>$i18n->get('174 description'), - uiLevel=>5 - }, - styleTemplateId=>{ - fieldType=>'template', - defaultValue=>'PBtmpl0000000000000060', - tab=>"display", - label=>$i18n->get(1073), - hoverHelp=>$i18n->get('1073 description'), - filter=>'fixId', - namespace=>'style' - }, - printableStyleTemplateId=>{ - fieldType=>'template', - defaultValue=>'PBtmpl0000000000000060', - tab=>"display", - label=>$i18n->get(1079), - hoverHelp=>$i18n->get('1079 description'), - filter=>'fixId', - namespace=>'style' - }, - mobileStyleTemplateId => { - fieldType => ( $session->setting->get('useMobileStyle') ? 'template' : 'hidden' ), - defaultValue => 'PBtmpl0000000000000060', - tab => 'display', - label => $i18n->get('mobileStyleTemplateId label'), - hoverHelp => $i18n->get('mobileStyleTemplateId description'), - filter => 'fixId', - namespace => 'style', - }, - ); - push(@{$definition}, { - tableName=>'wobject', - className=>'WebGUI::Asset::Wobject', - autoGenerateForms=>1, - properties => \%properties - }); - return $class->SUPER::definition($session,$definition); -} - -#------------------------------------------------------------------- - =head2 copyCollateral ( tableName, keyName, keyValue ) Copies a row of collateral data where keyName=keyValue. Generates a new key for keyName. diff --git a/lib/WebGUI/Asset/Wobject/Article.pm b/lib/WebGUI/Asset/Wobject/Article.pm index cc02a5558..282c7ed32 100644 --- a/lib/WebGUI/Asset/Wobject/Article.pm +++ b/lib/WebGUI/Asset/Wobject/Article.pm @@ -14,7 +14,67 @@ use strict; use Tie::IxHash; use WebGUI::International; use WebGUI::Paginator; -use WebGUI::Asset::Wobject; + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_Article']; +aspect icon => 'article.gif'; +aspect tableName => 'Article'; +property cacheTimeout => ( + tab => "display", + fieldType => "interval", + default => 3600, + uiLevel => 8, + label => ["cache timeout", 'Asset_Article'], + hoverHelp => ["cache timeout help", 'Asset_Article'], + ); +property templateId => ( + tab => "display", + fieldType => "template", + default => 'PBtmpl0000000000000002', + namespace => "Article", + hoverHelp => ['article template description', 'Asset_Article'], + label => ['72', 'Asset_Article'], + ); +property linkTitle => ( + tab => "properties", + fieldType => 'text', + default => undef, + label => ['7', 'Asset_Article'], + hoverHelp => ['link title description', 'Asset_Article'], + uiLevel => 3 + ); +property linkURL => ( + tab => "properties", + fieldType => 'url', + default => undef, + label => ['8', 'Asset_Article'], + hoverHelp => ['link url description', 'Asset_Article'], + uiLevel => 3 + ); +property storageId => ( + tab => "properties", + fieldType => "image", + deleteFileUrl => \&_storageId_deleteFileUrl, + maxAttachments => 2, + persist => 1, + default => undef, + label => ["attachments", 'Asset_Article'], + hoverHelp => ["attachments help", 'Asset_Article'], + trigger => \&_set_storageId, + ); +sub _set_storageId { + my ($self, $new, $old) = @_; + if ($new ne $old) { + delete $self->{_storageLocation}; + } +} +sub _storageid_deleteFileUrl { + return shift->session->url->page("func=deleteFile;filename="); +} + +with 'WebGUI::Role::Asset::SetStoragePermissions'; + use WebGUI::Storage; use WebGUI::HTML; @@ -72,77 +132,13 @@ Override the default method in order to deal with attachments. sub addRevision { my $self = shift; my $newSelf = $self->SUPER::addRevision(@_); - if ($newSelf->get("storageId") && $newSelf->get("storageId") eq $self->get('storageId')) { - my $newStorage = WebGUI::Storage->get($self->session,$self->get("storageId"))->copy; + if ($newSelf->storageId && $newSelf->storageId eq $self->storageId) { + my $newStorage = WebGUI::Storage->get($self->session,$self->storageId)->copy; $newSelf->update({storageId => $newStorage->getId}); } return $newSelf; } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,'Asset_Article'); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - cacheTimeout => { - tab => "display", - fieldType => "interval", - defaultValue => 3600, - uiLevel => 8, - label => $i18n->get("cache timeout"), - hoverHelp => $i18n->get("cache timeout help") - }, - templateId =>{ - fieldType=>"template", - defaultValue=>'PBtmpl0000000000000002', - tab=>"display", - namespace=>"Article", - hoverHelp=>$i18n->get('article template description'), - label=>$i18n->get(72) - }, - linkTitle=>{ - tab=>"properties", - fieldType=>'text', - defaultValue=>undef, - label=>$i18n->get(7), - hoverHelp=>$i18n->get('link title description'), - uiLevel=>3 - }, - linkURL=>{ - tab=>"properties", - fieldType=>'url', - defaultValue=>undef, - label=>$i18n->get(8), - hoverHelp=>$i18n->get('link url description'), - uiLevel=>3 - }, - storageId=>{ - tab=>"properties", - fieldType=>"image", - deleteFileUrl=>$session->url->page("func=deleteFile;filename="), - maxAttachments=>2, - persist => 1, - defaultValue=>undef, - label=>$i18n->get("attachments"), - hoverHelp=>$i18n->get("attachments help") - } - ); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'article.gif', - autoGenerateForms=>1, - tableName=>'Article', - className=>'WebGUI::Asset::Wobject::Article', - properties=>\%properties - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 duplicate ( ) @@ -153,7 +149,7 @@ Extend the super class to duplicate the storage location. sub duplicate { my $self = shift; - my $newAsset = $self->SUPER::duplicate(@_); + my $newAsset = $self->SUPER::duplicate(@_); my $newStorage = $self->getStorageLocation->copy; $newAsset->update({storageId=>$newStorage->getId}); return $newAsset; @@ -170,7 +166,7 @@ See WebGUI::AssetPackage::exportAssetData() for details. sub exportAssetData { my $self = shift; my $data = $self->SUPER::exportAssetData; - push(@{$data->{storage}}, $self->get("storageId")) if ($self->get("storageId") ne ""); + push(@{$data->{storage}}, $self->storageId) if ($self->storageId ne ""); return $data; } @@ -187,11 +183,11 @@ then make one. Build an internal cache of the storage object. sub getStorageLocation { my $self = shift; unless (exists $self->{_storageLocation}) { - if ($self->get("storageId") eq "") { + if ($self->storageId eq "") { $self->{_storageLocation} = WebGUI::Storage->create($self->session); $self->update({storageId=>$self->{_storageLocation}->getId}); } else { - $self->{_storageLocation} = WebGUI::Storage->get($self->session,$self->get("storageId")); + $self->{_storageLocation} = WebGUI::Storage->get($self->session,$self->storageId); } } return $self->{_storageLocation}; @@ -208,8 +204,8 @@ Indexing the content of attachments and user defined fields. See WebGUI::Asset:: sub indexContent { my $self = shift; my $indexer = $self->SUPER::indexContent; - $indexer->addKeywords($self->get("linkTitle")); - $indexer->addKeywords($self->get("linkUrl")); + $indexer->addKeywords($self->linkTitle); + $indexer->addKeywords($self->linkUrl); my $storage = $self->getStorageLocation; foreach my $file (@{$storage->getFiles}) { $indexer->addFile($storage->getPath($file)); @@ -227,7 +223,7 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $templateId = $self->get("templateId"); + my $templateId = $self->templateId; if ($self->session->form->process("overrideTemplateId") ne "") { $templateId = $self->session->form->process("overrideTemplateId"); } @@ -263,32 +259,6 @@ sub processPropertiesFromFormPost { $self->setSize($size); } -#------------------------------------------------------------------- - -=head2 update ( ) - -Extend the super class to handle the storage location. Sets -the correct privileges and deletes the internally cached -Storage object. - -=cut - -sub update { - my $self = shift; - my $previousStorageId = $self->get('storageId'); - $self->SUPER::update(@_); - ##update may have entered a new storageId. Reset the cached one just in case. - if ($self->get("storageId") ne $previousStorageId) { - delete $self->{_storageLocation}; - } - $self->getStorageLocation->setPrivileges( - $self->get("ownerUserId"), - $self->get("groupIdView"), - $self->get("groupIdEdit"), - ); -} - - #------------------------------------------------------------------- =head2 purge ( ) @@ -348,13 +318,13 @@ returns the output. sub view { my $self = shift; my $cache = $self->session->cache; - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10 && !$self->session->form->process("overrideTemplateId") && + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10 && !$self->session->form->process("overrideTemplateId") && !$self->session->form->process($self->paginateVar) && !$self->session->form->process("makePrintable")) { my $out = eval{$cache->get("view_".$self->getId)}; return $out if $out; } my %var; - if ($self->get("storageId")) { + if ($self->storageId) { my $storage = $self->getStorageLocation; my @loop = (); foreach my $file (@{$storage->getFiles}) { @@ -375,7 +345,7 @@ sub view { }); } } - $var{description} = $self->get("description"); + $var{description} = $self->description; $var{"new.template"} = $self->getUrl("func=view").";overrideTemplateId="; $var{"description.full"} = $var{description}; $var{"description.full"} =~ s/\^\-\;//g; @@ -412,9 +382,9 @@ sub view { } $p->appendTemplateVars(\%var); my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); - if (!$self->session->var->isAdminOn && $self->get("cacheTimeout") > 10 && !$self->session->form->process("overrideTemplateId") && + if (!$self->session->var->isAdminOn && $self->cacheTimeout > 10 && !$self->session->form->process("overrideTemplateId") && !$self->session->form->process($self->paginateVar) && !$self->session->form->process("makePrintable")) { - eval{$cache->set("view_".$self->getId, $out, $self->get("cacheTimeout"))}; + eval{$cache->set("view_".$self->getId, $out, $self->cacheTimeout)}; } return $out; } @@ -444,7 +414,7 @@ Deletes and attached file. sub www_deleteFile { my $self = shift; return $self->session->privilege->insufficient unless $self->canEdit; - if ($self->get("storageId") ne "") { + if ($self->storageId ne "") { my $storage = $self->getStorageLocation; $storage->deleteFile($self->session->form->param("filename")); } @@ -461,7 +431,7 @@ See WebGUI::Asset::Wobject::www_view() for details. sub www_view { my $self = shift; - $self->session->http->setCacheControl($self->get("cacheTimeout")); + $self->session->http->setCacheControl($self->cacheTimeout); $self->SUPER::www_view(@_); } diff --git a/lib/WebGUI/Asset/Wobject/Calendar.pm b/lib/WebGUI/Asset/Wobject/Calendar.pm index 10af735a1..9ec8de37c 100644 --- a/lib/WebGUI/Asset/Wobject/Calendar.pm +++ b/lib/WebGUI/Asset/Wobject/Calendar.pm @@ -12,7 +12,267 @@ use strict; # http://www.plainblack.com info@plainblack.com #---------------------------------------------------------------------------- -use Tie::IxHash; +#use base qw/WebGUI::Asset::Wobject WebGUI::JSONCollateral/; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; + +aspect assetName => ['assetName', 'Asset_Calendar']; +aspect icon => 'calendar.gif'; +aspect tableName => 'Calendar'; +property defaultView => ( + fieldType => "SelectBox", + default => "month", + options => \&_defaultView_options, + tab => "display", + label => ["defaultView label", 'Asset_Calendar'], + hoverHelp => ["defaultView description", 'Asset_Calendar'], + ); +sub _defaultView_options { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_Calendar'); + tie my %optionsDefaultView, 'Tie::IxHash', ( + month => $i18n->get("defaultView value month"), + week => $i18n->get("defaultView value week"), + day => $i18n->get("defaultView value day"), + list => $i18n->get('defaultView value list'), + ); + return %optionsDefaultView; +} + +property defaultDate => ( + fieldType => "SelectBox", + default => 'current', + options => \&_defaultDate_options, + tab => "display", + label => ["defaultDate label", 'Asset_Calendar'], + hoverHelp => ["defaultDate description", 'Asset_Calendar'], + ); +sub _defaultDate_options { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_Calendar'); + tie my %optionsDefaultDate, 'Tie::IxHash', ( + current => $i18n->get("defaultDate value current"), + first => $i18n->get("defaultDate value first"), + last => $i18n->get("defaultDate value last"), + ); + return %optionsDefaultDate; +} + + ##### GROUPS / ACCESS ##### + # Edit events +property groupIdEventEdit => ( + fieldType => "group", + default => "3", + tab => "security", + label => ["groupIdEventEdit label", 'Asset_Calendar'], + hoverHelp => ["groupIdEventEdit description", 'Asset_Calendar'], + ); + +property groupIdSubscribed => ( + noFormPost => 1, + fieldType => 'hidden', + ); + + + ##### TEMPLATES - DISPLAY ##### + # Month +property templateIdMonth => ( + fieldType => "template", + default => 'CalendarMonth000000001', + tab => "display", + namespace => "Calendar/Month", + hoverHelp => ['templateIdMonth description', 'Asset_Calendar'], + label => ['templateIdMonth label', 'Asset_Calendar'], + ); + + # Week +property templateIdWeek => ( + fieldType => "template", + default => 'CalendarWeek0000000001', + tab => "display", + namespace => "Calendar/Week", + hoverHelp => ['templateIdWeek description', 'Asset_Calendar'], + label => ['templateIdWeek label', 'Asset_Calendar'], + ); + + # Day +property templateIdDay => ( + fieldType => "template", + default => 'CalendarDay00000000001', + tab => "display", + namespace => "Calendar/Day", + hoverHelp => ['templateIdDay description', 'Asset_Calendar'], + label => ['templateIdDay label', 'Asset_Calendar'], + ); + + # List +property templateIdList => ( + fieldType => "template", + default => 'kj3b-X3i6zRKnhLb4ZiCLw', + tab => "display", + namespace => "Calendar/List", + hoverHelp => ['editForm templateIdList description', 'Asset_Calendar'], + label => ['editForm templateIdList label', 'Asset_Calendar'], + ); + + # Event Details +property templateIdEvent => ( + fieldType => "template", + default => 'CalendarEvent000000001', + tab => "display", + namespace => "Calendar/Event", + hoverHelp => ['templateIdEvent description', 'Asset_Calendar'], + label => ['templateIdEvent label', 'Asset_Calendar'], + ); + + # Event Edit +property templateIdEventEdit => ( + fieldType => "template", + default => 'CalendarEventEdit00001', + tab => "display", + namespace => "Calendar/EventEdit", + hoverHelp => ['templateIdEventEdit description', 'Asset_Calendar'], + label => ['templateIdEventEdit label', 'Asset_Calendar'], + ); + + # Search +property templateIdSearch => ( + fieldType => "template", + default => 'CalendarSearch00000001', + tab => "display", + namespace => "Calendar/Search", + hoverHelp => ['templateIdSearch description', 'Asset_Calendar'], + label => ['templateIdSearch label', 'Asset_Calendar'], + ); + + + ##### TEMPLATES - PRINT ##### + # Month +property templateIdPrintMonth => ( + fieldType => "template", + default => 'CalendarPrintMonth0001', + tab => "display", + namespace => "Calendar/Print/Month", + hoverHelp => ['templateIdPrintMonth description', 'Asset_Calendar'], + label => ['templateIdPrintMonth label', 'Asset_Calendar'], + ); + + # Week +property templateIdPrintWeek => ( + fieldType => "template", + default => 'CalendarPrintWeek00001', + tab => "display", + namespace => "Calendar/Print/Week", + hoverHelp => ['templateIdPrintWeek description', 'Asset_Calendar'], + label => ['templateIdPrintWeek label', 'Asset_Calendar'], + ); + + # Day +property templateIdPrintDay => ( + fieldType => "template", + default => 'CalendarPrintDay000001', + tab => "display", + namespace => "Calendar/Print/Day", + hoverHelp => ['templateIdPrintDay description', 'Asset_Calendar'], + label => ['templateIdPrintDay label', 'Asset_Calendar'], + ); + + # List +property templateIdPrintList => ( + fieldType => "template", + default => '', + tab => "display", + namespace => "Calendar/Print/List", + hoverHelp => ['editForm templateIdPrintList description', 'Asset_Calendar'], + label => ['editForm templateIdPrintList label', 'Asset_Calendar'], + ); + + # Event Details +property templateIdPrintEvent => ( + fieldType => "template", + default => 'CalendarPrintEvent0001', + tab => "display", + namespace => "Calendar/Print/Event", + hoverHelp => ['templateIdPrintEvent description', 'Asset_Calendar'], + label => ['templateIdPrintEvent label', 'Asset_Calendar'], + ); + + + ##### Miscellany ##### +property visitorCacheTimeout => ( + fieldType => "integer", + default => "60", + tab => "display", + hoverHelp => ['visitorCacheTimeout description', 'Asset_Calendar'], + label => ['visitorCacheTimeout label', 'Asset_Calendar'], + ); +property sortEventsBy => ( + fieldType => "SelectBox", + default => "time", + options => \&_sortEventsBy_options, + tab => "display", + label => ["sortEventsBy label", 'Asset_Calendar'], + hoverHelp => ["sortEventsBy description", 'Asset_Calendar'], + ); +sub _sortEventsBy_options { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_Calendar'); + tie my %optionsEventSort, 'Tie::IxHash', ( + time => $i18n->get("sortEventsBy value time"), + sequencenumber => $i18n->get("sortEventsBy value sequencenumber"), + ); + return %optionsEventSort; +} + + +property listViewPageInterval => ( + fieldType => "interval", + builder => '_listViewPageInterval_builder', + tab => "display", + label => ['editForm listViewPageInterval label', 'Asset_Calendar'], + hoverHelp => ['editForm listViewPageInterval description', 'Asset_Calendar'], + unitsAvailable => [ qw( days weeks months years ) ], + lazy => 1, + ); +sub _listViewPageInterval_builder { + my $self = shift; + return $self->session->datetime->intervalToSeconds( 3, 'months' ); +} + +property icalFeeds => ( + fieldType => "textarea", + default => sub { return []; }, + serialize => 1, + noFormPost => 1, + autoGenerate => 0, + tab => "display", + ); + +property icalInterval => ( + fieldType => "interval", + builder => '_icalInterval_builder', + lazy => 1, + tab => "display", + label => ['editForm icalInterval label', 'Asset_Calendar'], + hoverHelp => ['editForm icalInterval description', 'Asset_Calendar'], + unitsAvailable => [ qw( days weeks months years ) ], + ); +sub _icalInterval_builder { + return shift->session->datetime->intervalToSeconds( 3, 'months' ); +} + +property workflowIdCommit => ( + fieldType => "workflow", + builder => '_workflowIdCommit_builder', + lazy => 1, + tab => 'security', + label => ['editForm workflowIdCommit label', 'Asset_Calendar'], + hoverHelp => ['editForm workflowIdCommit description', 'Asset_Calendar'], + type => 'WebGUI::VersionTag', + ); +sub _workflowIdCommit_builder { + return shift->session->setting->get('defaultVersionTagWorkflow'), +} use WebGUI::Utility; use WebGUI::International; @@ -20,13 +280,11 @@ use WebGUI::Search; use WebGUI::Form; use WebGUI::HTML; use WebGUI::DateTime; -use Class::C3; - -use base qw/WebGUI::Asset::Wobject WebGUI::JSONCollateral/; use DateTime; use JSON; use Text::Wrap; +use Tie::IxHash; =head1 NAME @@ -43,261 +301,6 @@ use Text::Wrap; #---------------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift || []; - - my $i18n = WebGUI::International->new($session, 'Asset_Calendar'); - - ### Set up list options ### - tie my %optionsDefaultView, 'Tie::IxHash', ( - month => $i18n->get("defaultView value month"), - week => $i18n->get("defaultView value week"), - day => $i18n->get("defaultView value day"), - list => $i18n->get('defaultView value list'), - ); - - tie my %optionsDefaultDate, 'Tie::IxHash', ( - current => $i18n->get("defaultDate value current"), - first => $i18n->get("defaultDate value first"), - last => $i18n->get("defaultDate value last"), - ); - - tie my %optionsEventSort, 'Tie::IxHash', ( - time => $i18n->get("sortEventsBy value time"), - sequencenumber => $i18n->get("sortEventsBy value sequencenumber"), - ); - - - ### Build properties hash ### - tie my %properties, 'Tie::IxHash', ( - ##### DEFAULTS ##### - defaultView => { - fieldType => "SelectBox", - defaultValue => "month", - options => \%optionsDefaultView, - tab => "display", - label => $i18n->get("defaultView label"), - hoverHelp => $i18n->get("defaultView description"), - }, - - defaultDate => { - fieldType => "SelectBox", - defaultValue => 'current', - options => \%optionsDefaultDate, - tab => "display", - label => $i18n->get("defaultDate label"), - hoverHelp => $i18n->get("defaultDate description"), - }, - - ##### GROUPS / ACCESS ##### - # Edit events - groupIdEventEdit => { - fieldType => "group", - defaultValue => "3", - tab => "security", - label => $i18n->get("groupIdEventEdit label"), - hoverHelp => $i18n->get("groupIdEventEdit description"), - }, - - groupIdSubscribed => { - fieldType => 'hidden', - }, - - - ##### TEMPLATES - DISPLAY ##### - # Month - templateIdMonth => { - fieldType => "template", - defaultValue => 'CalendarMonth000000001', - tab => "display", - namespace => "Calendar/Month", - hoverHelp => $i18n->get('templateIdMonth description'), - label => $i18n->get('templateIdMonth label'), - }, - - # Week - templateIdWeek => { - fieldType => "template", - defaultValue => 'CalendarWeek0000000001', - tab => "display", - namespace => "Calendar/Week", - hoverHelp => $i18n->get('templateIdWeek description'), - label => $i18n->get('templateIdWeek label'), - }, - - # Day - templateIdDay => { - fieldType => "template", - defaultValue => 'CalendarDay00000000001', - tab => "display", - namespace => "Calendar/Day", - hoverHelp => $i18n->get('templateIdDay description'), - label => $i18n->get('templateIdDay label'), - }, - - # List - templateIdList => { - fieldType => "template", - defaultValue => 'kj3b-X3i6zRKnhLb4ZiCLw', - tab => "display", - namespace => "Calendar/List", - hoverHelp => $i18n->get('editForm templateIdList description'), - label => $i18n->get('editForm templateIdList label'), - }, - - # Event Details - templateIdEvent => { - fieldType => "template", - defaultValue => 'CalendarEvent000000001', - tab => "display", - namespace => "Calendar/Event", - hoverHelp => $i18n->get('templateIdEvent description'), - label => $i18n->get('templateIdEvent label'), - }, - - # Event Edit - templateIdEventEdit => { - fieldType => "template", - defaultValue => 'CalendarEventEdit00001', - tab => "display", - namespace => "Calendar/EventEdit", - hoverHelp => $i18n->get('templateIdEventEdit description'), - label => $i18n->get('templateIdEventEdit label'), - }, - - # Search - templateIdSearch => { - fieldType => "template", - defaultValue => 'CalendarSearch00000001', - tab => "display", - namespace => "Calendar/Search", - hoverHelp => $i18n->get('templateIdSearch description'), - label => $i18n->get('templateIdSearch label'), - }, - - - ##### TEMPLATES - PRINT ##### - # Month - templateIdPrintMonth => { - fieldType => "template", - defaultValue => 'CalendarPrintMonth0001', - tab => "display", - namespace => "Calendar/Print/Month", - hoverHelp => $i18n->get('templateIdPrintMonth description'), - label => $i18n->get('templateIdPrintMonth label'), - }, - - # Week - templateIdPrintWeek => { - fieldType => "template", - defaultValue => 'CalendarPrintWeek00001', - tab => "display", - namespace => "Calendar/Print/Week", - hoverHelp => $i18n->get('templateIdPrintWeek description'), - label => $i18n->get('templateIdPrintWeek label'), - }, - - # Day - templateIdPrintDay => { - fieldType => "template", - defaultValue => 'CalendarPrintDay000001', - tab => "display", - namespace => "Calendar/Print/Day", - hoverHelp => $i18n->get('templateIdPrintDay description'), - label => $i18n->get('templateIdPrintDay label'), - }, - - # List - templateIdPrintList => { - fieldType => "template", - defaultValue => '', - tab => "display", - namespace => "Calendar/Print/List", - hoverHelp => $i18n->get('editForm templateIdPrintList description'), - label => $i18n->get('editForm templateIdPrintList label'), - }, - - # Event Details - templateIdPrintEvent => { - fieldType => "template", - defaultValue => 'CalendarPrintEvent0001', - tab => "display", - namespace => "Calendar/Print/Event", - hoverHelp => $i18n->get('templateIdPrintEvent description'), - label => $i18n->get('templateIdPrintEvent label'), - }, - - - ##### Miscellany ##### - visitorCacheTimeout => { - fieldType => "integer", - defaultValue => "60", - tab => "display", - hoverHelp => $i18n->get('visitorCacheTimeout description'), - label => $i18n->get('visitorCacheTimeout label'), - }, - sortEventsBy => { - fieldType => "SelectBox", - defaultValue => "time", - options => \%optionsEventSort, - tab => "display", - label => $i18n->get("sortEventsBy label"), - hoverHelp => $i18n->get("sortEventsBy description"), - }, - - listViewPageInterval => { - fieldType => "interval", - defaultValue => $session->datetime->intervalToSeconds( 3, 'months' ), - tab => "display", - label => $i18n->get('editForm listViewPageInterval label'), - hoverHelp => $i18n->get('editForm listViewPageInterval description'), - unitsAvailable => [ qw( days weeks months years ) ], - }, - - icalFeeds => { - fieldType => "textarea", - defaultValue => [], - serialize => 1, - noFormPost => 1, - autoGenerate => 0, - tab => "display", - }, - - icalInterval => { - fieldType => "interval", - defaultValue => $session->datetime->intervalToSeconds( 3, 'months' ), - tab => "display", - label => $i18n->get('editForm icalInterval label'), - hoverHelp => $i18n->get('editForm icalInterval description'), - unitsAvailable => [ qw( days weeks months years ) ], - }, - - workflowIdCommit => { - fieldType => "workflow", - defaultValue => $session->setting->get('defaultVersionTagWorkflow'), - tab => 'security', - label => $i18n->get('editForm workflowIdCommit label'), - hoverHelp => $i18n->get('editForm workflowIdCommit description'), - type => 'WebGUI::VersionTag', - }, - ); - - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'calendar.gif', - tableName => 'Calendar', - className => 'WebGUI::Asset::Wobject::Calendar', - properties => \%properties, - autoGenerateForms => 1, - }; - - return $class->SUPER::definition($session, $definition); -} - -#---------------------------------------------------------------------------- - =head2 addChild ( properties [, more ] ) Only allows Events to be added as a child of this asset. @@ -308,7 +311,7 @@ sub addChild { my $self = shift; my $properties = shift; my @other = @_; - + if ($properties->{className} ne "WebGUI::Asset::Event") { $self->session->errorHandler->security("add a ".$properties->{className}." to a ".$self->get("className")); return undef; @@ -401,7 +404,7 @@ sub appendTemplateVarsDateTime { $var->{ $name } = $dt->can( $fields{ $name } )->( $dt ); } } - + # Special fields if ( $prefix ) { $var->{ $prefix . "Second" } = sprintf "%02d", $dt->second; @@ -414,7 +417,7 @@ sub appendTemplateVarsDateTime { $var->{ "minute" } = sprintf "%02d", $dt->minute; $var->{ "meridiem" } = ( $dt->hour < 12 ? "AM" : "PM" ); } - + return $var; } @@ -433,7 +436,7 @@ sub canEdit { my $self = shift; my $userId = shift || $self->session->user->userId; my $form = $self->session->form; - + # Account for new events return 1 if ( $self->canAddEvent( $userId ) @@ -476,7 +479,7 @@ sub canAddEvent { ; return 1 if ( - $user->isInGroup( $self->get("groupIdEventEdit") ) + $user->isInGroup( $self->groupIdEventEdit ) || $self->SUPER::canEdit( $userId ) ); } @@ -492,14 +495,14 @@ Creates the group for users that are subscribed to the Calendar. # Copied from WebGUI::Asset::Wobject::Collaboration. sub createSubscriptionGroup { my $self = shift; - + my $group = WebGUI::Group->new($self->session, "new"); $group->name($self->getId); $group->description("The group to store subscriptions for the calendar ".$self->getId); $group->isEditable(0); $group->showInForms(0); $group->deleteGroups([3]); # admins don't want to be auto subscribed to this thing - + $self->update({ groupIdSubscription => $group->getId }); @@ -542,35 +545,35 @@ sub getEditForm { my $session = $self->session; my $form = $self->SUPER::getEditForm; my $i18n = WebGUI::International->new($session,"Asset_Calendar"); - + my $tab = $form->addTab("feeds",$i18n->get("feeds"), 6); $tab->raw(""); - + $tab->raw(<<'ENDJS'); ENDJS @@ -664,7 +667,7 @@ ENDJS - + @@ -708,18 +711,18 @@ sub getEvent { # Warn and return undef if no assetId $self->session->errorHandler->warn("WebGUI::Asset::Wobject::Calendar->getEvent :: No asset ID."), return unless $assetId; - + # ? Perhaps use Stow to cache events ? - - my $event = WebGUI::Asset->newByDynamicClass($self->session, $assetId); - + + my $event = WebGUI::Asset->newById($self->session, $assetId); + unless ( $event ) { $self->session->errorHandler->warn("Event '$assetId' doesn't exist!"); return undef; } $self->session->errorHandler->warn("WebGUI::Asset::Wobject::Calendar->getEvent :: Event '$assetId' not a child of calendar '".$self->getId."'"), return - unless $event->get("parentId") eq $self->getId; + unless $event->parentId eq $self->getId; return $event; } @@ -766,16 +769,16 @@ sub getEventsIn { my $params = shift; $params->{order} = '' if $params->{order} !~ /^(?:time|sequencenumber)/i; - my $order_by_type = $params->{order} ? lc($params->{order}) : $self->get('sortEventsBy'); + my $order_by_type = $params->{order} ? lc($params->{order}) : $self->sortEventsBy; # Warn and return undef if no startDate or endDate unless ($start && $end) { $self->session->errorHandler->warn("WebGUI::Asset::Wobject::Calendar->getEventsIn() called with not enough arguments at ".join('::',(caller)[1,2])); return undef; } - + # Create objects and adjust for timezone - + my ($startDate) = split / /, $start; my ($endDate) = split / /, $end; @@ -836,7 +839,7 @@ week, month and or day views. sub getEventVars { my $self = shift; my $event = shift; - + my %eventVar = %{$event->get}; %eventVar = (map { "event".ucfirst($_) => delete $eventVar{$_} } keys %eventVar); my %eventDates = $event->getTemplateVars; @@ -876,7 +879,7 @@ TODO: Format lastUpdated into the user's time zone sub getFeeds { my $self = shift; - return $self->get('icalFeeds'); + return $self->icalFeeds; } #---------------------------------------------------------------------------- @@ -889,7 +892,7 @@ Gets the first event in this calendar. Returns the Event object. sub getFirstEvent { my $self = shift; - my $lineage = $self->get("lineage"); + my $lineage = $self->lineage; my ($assetId) = $self->session->db->quickArray(<get("lineage"); - + my $lineage = $self->lineage; + my ($assetId) = $self->session->db->quickArray(<getEvent($assetId); } @@ -943,7 +946,7 @@ sub getTemplateVars { my $self = shift; my $var = $self->get; - + return $var; } @@ -974,18 +977,18 @@ parameters. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - + my $view = ucfirst lc $self->session->form->param("type") - || ucfirst $self->get("defaultView") + || ucfirst $self->defaultView || "Month"; - + if ($self->session->form->param("print")){ $view = "Print".$view; $self->session->style->makePrintable(1); } - + #$self->session->errorHandler->warn("Prepare view ".$view." with template ".$self->get("templateId".$view)); - + my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId".$view)); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( @@ -995,7 +998,7 @@ sub prepareView { ); } $template->prepare($self->getMetaDataAsTemplateVariables); - + $self->{_viewTemplate} = $template; } @@ -1016,13 +1019,13 @@ sub processPropertiesFromFormPost { my $session = $self->session; my $form = $self->session->form; $self->SUPER::processPropertiesFromFormPost; - - unless ($self->get("groupIdSubscribed")) { + + unless ($self->groupIdSubscribed) { $self->createSubscriptionGroup(); } - - $self->session->errorHandler->info( "DEFAULT VIEW:" . $self->get('defaultView') ); - + + $self->session->errorHandler->info( "DEFAULT VIEW:" . $self->defaultView ); + ### Get feeds from the form # Workaround WebGUI::Session::Form->param bug that returns duplicate # names. @@ -1098,21 +1101,21 @@ sub view { my $self = shift; my $session = $self->session; my $form = $session->form; - + ## INTERRUPT: If user is only a Visitor and we have a cached version # and is not expired, use it. - + # Get the form parameters my $params = {}; - $params->{type} = $form->param("type") || $self->get( 'defaultView' ); + $params->{type} = $form->param("type") || $self->defaultView; $params->{start} = $form->param("start"); - + # Validate type passed, or recover from session scratchpad if ($params->{type} =~ /^(?:month|week|day|list)$/i) { $session->scratch->set('cal_view_type', $params->{'type'}); } else { - $params->{type} = $session->scratch->get('cal_view_type') || $self->get( 'defaultView' ) || 'month'; + $params->{type} = $session->scratch->get('cal_view_type') || $self->defaultView || 'month'; $session->scratch->set('cal_view_type', $params->{'type'}); } @@ -1127,16 +1130,16 @@ sub view { # Set defaults if necessary if (!$params->{start}) { $params->{start} - = $self->get("defaultDate") eq "first" && $self->getFirstEvent + = $self->defaultDate eq "first" && $self->getFirstEvent ? $self->getFirstEvent->getDateTimeStart - : $self->get("defaultDate") eq "last" && $self->getLastEvent + : $self->defaultDate eq "last" && $self->getLastEvent ? $self->getLastEvent->getDateTimeStart : WebGUI::DateTime->new($session, time)->toUserTimeZone ; $session->scratch->set('cal_view_start', $params->{'start'}); } - + # Get the template from the appropriate view* method # TODO: This should be abstracted my $var = lc $params->{type} eq "month" ? $self->viewMonth( $params ) @@ -1145,7 +1148,7 @@ sub view { : lc $params->{type} eq "list" ? $self->viewList( $params ) : return $self->errorHandler->error("Calendar invalid 'type=' url parameter") ; - + ##### Process the template # Add any global variables # Admin @@ -1153,13 +1156,13 @@ sub view { $var->{'admin'} = 1; $var->{'adminControls'} = $self->getToolbar; } - + # Event editor if ($self->canAddEvent) { $var->{'editor'} = 1; $var->{"urlAdd"} = $self->getUrl("func=add;class=WebGUI::Asset::Event;type=".$params->{type}.";start=$params->{start}"); } - + # URLs $var->{ url } = $self->getUrl; $var->{"urlDay"} = $self->getUrl("type=day;start=".$params->{start}); @@ -1168,13 +1171,13 @@ sub view { $var->{"urlSearch"} = $self->getSearchUrl; $var->{"urlPrint"} = $self->getUrl("type=".$params->{type}.";start=".$params->{start}.";print=1"); $var->{"urlIcal"} = $self->getUrl("func=ical"); - + $var->{"extrasUrl"} = $self->session->url->extras(); $var->{ paramStart } = $params->{ start }; $var->{ paramType } = $params->{ type }; # TODO: If user is only a Visitor and we've gotten this far, update the cache - + # Return the processed template to be displayed for the user return $self->processTemplate($var, undef, $self->{_viewTemplate}); } @@ -1291,10 +1294,10 @@ sub viewList { my $session = $self->session; my $i18n = WebGUI::International->new($session,"Asset_Calendar"); my $var = $self->getTemplateVars; - + ### Get the events my $dtStart = WebGUI::DateTime->new( $session, $params->{start} )->truncate( to => "day" ); - my $dtEnd = $dtStart->clone->add( seconds => $self->get('listViewPageInterval') ); + my $dtEnd = $dtStart->clone->add( seconds => $self->listViewPageInterval ); my @events = $self->getEventsIn( @@ -1320,7 +1323,7 @@ sub viewList { if ( $dt->day > $dtLast->day ) { $eventVar{ new_day } = 1; } - + push @{ $var->{events} }, { %eventVar, %eventDate }; $dtLast = $dt; } @@ -1329,11 +1332,11 @@ sub viewList { # Date span $self->appendTemplateVarsDateTime( $var, $dtStart, "start" ); $self->appendTemplateVarsDateTime( $var, $dtEnd, "end" ); - + # Previous and next pages if ( $self->getFirstEvent && $self->getFirstEvent->getDateTimeStart < $dtStart ) { my $dtPrevious - = $dtStart->clone->add( seconds => 0 - $self->get('listViewPageInterval') ); + = $dtStart->clone->add( seconds => 0 - $self->listViewPageInterval ); $var->{ url_previousPage } = $self->getUrl( 'type=list;start=' . $dtPrevious->toDatabase ); } @@ -1373,7 +1376,7 @@ sub viewMonth { my $tz = $session->datetime->getTimeZone; my $today = WebGUI::DateTime->new($self->session, time) ->set_time_zone($tz)->toMysqlDate; - + #### Get all the events in this time period # Get the range of the epoch of this month my $dt = WebGUI::DateTime->new($self->session, $params->{start}); @@ -1383,11 +1386,11 @@ sub viewMonth { my $dtEnd = $dt->clone->add(months => 1); my $end = $dtEnd->toMysql; $dtEnd->add(seconds => -1); - + my @events = $self->getEventsIn($start,$end); - - + + #### Create the template parameters ## The grid my $first_dow = $session->user->profileField("firstDayOfWeek") || 0; @@ -1398,15 +1401,15 @@ sub viewMonth { my $days_in_month = $dt->clone->add(months=>1)->subtract(seconds=>1)->day_of_month; # Adjustment for first day of week my $adjust = ( $dt->day_of_week_0 - $first_dow + 1) % 7; - + # First create the days that are in this month for my $day (0..$days_in_month-1) { my $dt_day = $dt->clone->add(days=>$day); - + # Calculate what position this day should be in my $week = int(($adjust + $dt_day->day_of_month_0) / 7); my $position = ($adjust + $dt_day->day_of_month_0) % 7; - + # Add the day in the appropriate position $var->{weeks}->[$week]->{days}->[$position] = { "dayMonth" => $dt_day->day_of_month, @@ -1414,18 +1417,18 @@ sub viewMonth { "dayCurrent" => ($today eq $dt_day->toMysqlDate ? 1 : 0 ), }; } - + # Add any remaning trailing empty spaces push @{$var->{weeks}->[-1]->{days}},undef until @{$var->{weeks}->[-1]->{days}} >= 7; - + ## The events EVENT: for my $event (@events) { next EVENT unless $event->canView(); # Get the WebGUI::DateTime objects my $dt_event_start = $event->getDateTimeStart; my $dt_event_end = $event->getDateTimeEndNI; - + # Prepare the template variables my %eventTemplateVariables = $self->getEventVars($event); @@ -1442,16 +1445,16 @@ sub viewMonth { for my $mday ($dt_event_start->day_of_month_0..$dt_event_end->day_of_month_0) { my $week = int(($adjust + $mday) / 7); my $position = ($adjust + $mday) % 7; - + push @{$var->{weeks}->[$week]->{days}->[$position]->{events}}, \%eventTemplateVariables; } } - + # Make the navigation bars my $dt_year = $dt->clone->truncate(to => "year"); for my $m (0..11) { my $dt_month = $dt_year->clone->add(months=>$m); - + push @{$var->{months}}, { "monthName" => $dt_month->month_name, "monthAbbr" => $dt_month->month_abbr, @@ -1460,21 +1463,21 @@ sub viewMonth { "monthCurrent" => ($dt_month->month eq $dt->month ? 1 : 0), }; } - + # Day names my @dayNames = @{$dt->locale->day_names}[6,0..5]; # Put sunday first my @dayAbbrs = @{$dt->locale->day_abbreviations}[6,0..5]; # Take from FirstDOW to the end and put it on the beginning unshift @dayNames,splice(@dayNames,$first_dow); unshift @dayAbbrs,splice(@dayAbbrs,$first_dow); - + for my $dayIndex (0..$#dayNames) { push @{$var->{dayNames}}, { "dayName" => $dayNames[$dayIndex], "dayAbbr" => $dayAbbrs[$dayIndex], }; } - + $var->{"pageNextYear" } = $dt->year + 1; $var->{"pageNextUrl" } = $self->getUrl("type=month;start=" . $dt->clone->add(years=>1)->toMysql); $var->{"pagePrevYear" } = $dt->year - 1; @@ -1482,7 +1485,7 @@ sub viewMonth { $var->{"monthName" } = $dt->month_name; $var->{"monthAbbr" } = $dt->month_abbr; $var->{"year" } = $dt->year; - + # Return the template return $var; } @@ -1514,14 +1517,14 @@ sub viewWeek { my $tz = $session->datetime->getTimeZone; my $today = WebGUI::DateTime->new($self->session, time)->set_time_zone($tz) ->toMysqlDate; - - + + #### Get all the events in this time period # Get the range of the epoch of this week my $dt = WebGUI::DateTime->new($self->session, $params->{start}); $dt->set_time_zone($tz); $dt->truncate( to => "day"); - + # Apply First Day of Week settings my $first_dow = $session->user->profileField("firstDayOfWeek") || 0; # 0 - sunday @@ -1529,12 +1532,12 @@ sub viewWeek { # 2 - tuesday, etc... # subtract because we want to include the day that was passed $dt->subtract(days => $dt->day_of_week % 7 - $first_dow); - + my $start = $dt->toMysql; my $dtEnd = $dt->clone->add(days => 7)->add( seconds => -1); my $end = $dtEnd->toMysql; # Clone to prevent saving change - - my $sort_by_sequence++ if $self->get('sortEventsBy') eq 'sequencenumber'; + + my $sort_by_sequence++ if $self->sortEventsBy eq 'sequencenumber'; my $can_edit_order++ if $self->canEdit && $sort_by_sequence; my $reorder_request++ if $can_edit_order && $session->form->param( 'eventMove' ) =~ /^(?:UP|DOWN)$/; @@ -1545,12 +1548,12 @@ sub viewWeek { my @events = $self->getEventsIn( $start, $end ); my (%event_asset_of, %seq_key_of, %week_day_of, @event_days); - + # The events for my $event ( @events ) { next unless $event->canView(); - - my $event_asset_id = $event->get( 'assetId' ); + + my $event_asset_id = $event->getId; # Add Event object use by assetId $event_asset_of{ $event_asset_id }{ object } = $event; @@ -1559,16 +1562,16 @@ sub viewWeek { # the template variables my $dt_event_start = $event->getDateTimeStart; my $dt_event_end = $event->getDateTimeEndNI; - + #Handle events that start before this week or end after this week. if ($dt_event_start < $dt) { $dt_event_start = $dt; } - + if ($dt_event_end > $dtEnd) { $dt_event_end = $dtEnd; } - + my $start_dow = ($dt_event_start->day_of_week - $first_dow) % 7; my $end_dow = ($dt_event_end->day_of_week - $first_dow) % 7; @@ -1577,13 +1580,13 @@ sub viewWeek { {},$event_asset_id)->[0]; foreach my $weekDay ($start_dow .. $end_dow) { - + push @{ $event_days[ $weekDay ] }, $event; my $event_day_pos = $#{ $event_days[ $weekDay ]}; # Monitor duplicates in sequence list; push @{ $seq_key_of{ $sequence_number } }, $event_asset_id; - + # Add find assetId by day/order pos $week_day_of{ $weekDay }{ $event_day_pos } = $event_asset_id; @@ -1591,7 +1594,7 @@ sub viewWeek { $event_asset_of{ $event_asset_id }{ $weekDay } = $event_day_pos; } } - + # Process the event sequence change request # # Based upon binary values beginning at 16384 sequence @@ -1652,11 +1655,11 @@ sub viewWeek { } } - + $session->db->dbh->do ("UPDATE Event SET sequenceNumber = ? WHERE assetId = ? AND revisionDate = ?",{}, - $prev_seq_num-$incr, $event_asset_id, $event_object->get( 'revisionDate' ) + $prev_seq_num-$incr, $event_asset_id, $event_object->revisionDate ); # warn "Moved Asset New Seq Num: ".($prev_seq_num - $incr)." by $incr\n"; @@ -1666,7 +1669,7 @@ sub viewWeek { my $next_day_pos = $event_asset_of{ $next_asset_id }{ $event_day }; my $next_event_object = $event_asset_of{ $next_asset_id }{ object }; my $next_seq_num = $session->db->dbh->selectcol_arrayref("SELECT sequenceNumber FROM Event WHERE assetId = ? ORDER BY revisionDate desc LIMIT 1",{},$next_asset_id)->[0]; - + # warn "After Asset: $next_asset_id, seqNum: $next_seq_num, day: $event_day.$next_day_pos\n"; my $seq_idx; @@ -1685,19 +1688,19 @@ sub viewWeek { $session->db->dbh->do ("UPDATE Event SET sequenceNumber = ? WHERE assetId = ? AND revisionDate = ?",{}, - $next_seq_num + $incr, $event_asset_id, $event_object->get( 'revisionDate' ) + $next_seq_num + $incr, $event_asset_id, $event_object->revisionDate ); # warn "Moved Asset New Seq Num: ".($next_seq_num + $incr)." by $incr\n"; } } - - + + #### Create the template parameters # Some friendly dates for my $i (0..6) { my $day = {}; my $dt_day = $dt->clone->add(days=>$i); - + $day->{"dayName" } = $dt_day->day_name; $day->{"dayAbbr" } = $dt_day->day_abbr; $day->{"dayOfMonth" } = $dt_day->day_of_month; @@ -1709,14 +1712,14 @@ sub viewWeek { $day->{"mdy" } = $dt_day->mdy; $day->{"dmy" } = $dt_day->dmy; $day->{"epoch" } = $dt_day->epoch; - + if ($dt_day->toMysqlDate eq $today) { $day->{"dayCurrent"} = 1; } - + push @{$var->{days}}, $day; } - + # The events my @events = $self->getEventsIn( $start, $end ); for my $event ( @events ) { @@ -1741,7 +1744,7 @@ sub viewWeek { my %eventTemplateVariables = $self->getEventVars($event); foreach my $weekDay ($start_dow .. $end_dow) { - my $eventAssetId = $event->get( 'assetId' ); + my $eventAssetId = $event->getId; my %hash = %eventTemplateVariables; @@ -1761,13 +1764,13 @@ sub viewWeek { } } - + # Make the navigation bars $var->{"pageNextUrl"} = $self->getUrl("type=week;start=" . $dt->clone->add(weeks=>1)->toMysql); $var->{"pagePrevUrl"} = $self->getUrl("type=week;start=" . $dt->clone->subtract(weeks=>1)->toMysql); - + $var->{"startMonth" } = $dt->month; $var->{"startMonthName" } = $dt->month_name; $var->{"startMonthAbbr" } = $dt->month_abbr; @@ -1775,7 +1778,7 @@ sub viewWeek { $var->{"startDayName" } = $dt->day_name; $var->{"startDayAbbr" } = $dt->day_abbr; $var->{"startYear" } = $dt->year; - + $var->{"endMonth" } = $dtEnd->month; $var->{"endMonthName" } = $dtEnd->month_name; $var->{"endMonthAbbr" } = $dtEnd->month_abbr; @@ -1783,8 +1786,8 @@ sub viewWeek { $var->{"endDayName" } = $dtEnd->day_name; $var->{"endDayAbbr" } = $dtEnd->day_abbr; $var->{"endYear" } = $dtEnd->year; - - + + # Return the template return $var; } @@ -1803,9 +1806,9 @@ sub unwrapIcal { my $self = shift; my $text = shift; - - - + + + } #---------------------------------------------------------------------------- @@ -1845,10 +1848,10 @@ sub www_edit { my $self = shift; my $session = $self->session; my $i18n = WebGUI::International->new($session, 'Asset_Calendar'); - + return $session->privilege->insufficient() unless $self->canEdit; - - + + return $self->getAdminConsole->render( $self->getEditForm->print, $i18n->get("assetName") @@ -1868,7 +1871,7 @@ sub www_ical { my $session = $self->session; my $user = $self->session->user; my $form = $self->session->form; - + #!!! KLUDGE: # An "adminId" may be passed as a parameter in order to facilitate # calls between calendars on the same server getting administrator @@ -1882,15 +1885,15 @@ sub www_ical { my ($spectreTest) = $self->session->db->quickArray( "SELECT value FROM userSessionScratch WHERE sessionId=? and name=?", - [$adminId,$self->get("assetId")] + [$adminId,$self->getId] ); - + if ($spectreTest eq "SPECTRE") { $self->session->user({userId => 3}); } } #/KLUDGE - + my $dt_start; my $start = $form->param("start"); if ($start) { @@ -1904,7 +1907,7 @@ sub www_ical { $dt_start = WebGUI::DateTime->new($self->session, time); $dt_start->set_time_zone( $session->datetime->getTimeZone ); } - + my $dt_end; my $end = $form->param("end"); if ($end) { @@ -1915,53 +1918,53 @@ sub www_ical { ); } else { - $dt_end = $dt_start->clone->add( seconds => $self->get('icalInterval') ); + $dt_end = $dt_start->clone->add( seconds => $self->icalInterval ); } - - - + + + # Get all the events we're going to display my @events = $self->getEventsIn($dt_start->toMysql,$dt_end->toMysql); - - + + my $ical = qq{BEGIN:VCALENDAR\r\n} . qq{PRODID:WebGUI }.$WebGUI::VERSION."-".$WebGUI::STATUS.qq{\r\n} . qq{VERSION:2.0\r\n}; - + # VEVENT: EVENT: for my $event (@events) { next EVENT unless $event->canView(); $ical .= qq{BEGIN:VEVENT\r\n}; - + ### UID # Use feed's UID to prevent over-propagation - if ($event->get("feedUid")) { - $ical .= qq{UID:}.$event->get("feedUid")."\r\n"; + if ($event->feedUid) { + $ical .= qq{UID:}.$event->feedUid."\r\n"; } # Create a UID for feeds native to this calendar else { my $domain = $session->config->get("sitename")->[0]; - $ical .= qq{UID:}.$event->get("assetId").'@'.$domain."\r\n"; + $ical .= qq{UID:}.$event->assetId.'@'.$domain."\r\n"; } - + # LAST-MODIFIED (revisionDate) $ical .= qq{LAST-MODIFIED:} - . WebGUI::DateTime->new($self->session, $event->get("revisionDate"))->toIcal + . WebGUI::DateTime->new($self->session, $event->revisionDate)->toIcal . "\r\n"; - + # CREATED (creationDate) $ical .= qq{CREATED:} - . WebGUI::DateTime->new($self->session, $event->get("creationDate"))->toIcal + . WebGUI::DateTime->new($self->session, $event->creationDate)->toIcal . "\r\n"; - + # SEQUENCE - my $sequenceNumber = $event->get("iCalSequenceNumber"); + my $sequenceNumber = $event->iCalSequenceNumber; if (defined $sequenceNumber) { $ical .= qq{SEQUENCE:} - . $event->get("iCalSequenceNumber") + . $event->iCalSequenceNumber . "\r\n"; } - + # DTSTART my $eventStart = $event->getIcalStart; $ical .= 'DTSTART'; @@ -1969,7 +1972,7 @@ sub www_ical { $ical .= ';VALUE=DATE'; } $ical .= ":$eventStart\r\n"; - + # DTEND my $eventEnd = $event->getIcalEnd; $ical .= 'DTEND'; @@ -1977,36 +1980,36 @@ sub www_ical { $ical .= ';VALUE=DATE'; } $ical .= ":$eventEnd\r\n"; - + # Summary (the title) # Wrapped at 75 columns - $ical .= $self->wrapIcal("SUMMARY:".$event->get("title"))."\r\n"; + $ical .= $self->wrapIcal("SUMMARY:".$event->title)."\r\n"; # Description (the text) # Wrapped at 75 columns - $ical .= $self->wrapIcal("DESCRIPTION:".$event->get("description"))."\r\n"; + $ical .= $self->wrapIcal("DESCRIPTION:".$event->description)."\r\n"; # Location (the text) # Wrapped at 75 columns - $ical .= $self->wrapIcal("LOCATION:".$event->get("location"))."\r\n"; + $ical .= $self->wrapIcal("LOCATION:".$event->location)."\r\n"; # X-WEBGUI lines - if ($event->get("groupIdView")) { - $ical .= "X-WEBGUI-GROUPIDVIEW:".$event->get("groupIdView")."\r\n"; + if ($event->groupIdView) { + $ical .= "X-WEBGUI-GROUPIDVIEW:".$event->groupIdView."\r\n"; } if ($event->get("groupIdEdit")) { - $ical .= "X-WEBGUI-GROUPIDEDIT:".$event->get("groupIdEdit")."\r\n"; + $ical .= "X-WEBGUI-GROUPIDEDIT:".$event->groupIdEdit."\r\n"; } $ical .= "X-WEBGUI-URL:".$event->get("url")."\r\n"; - $ical .= "X-WEBGUI-MENUTITLE:".$event->get("menuTitle")."\r\n"; + $ical .= "X-WEBGUI-MENUTITLE:".$event->menuTitle."\r\n"; $ical .= qq{END:VEVENT\r\n}; } # ENDVEVENT $ical .= qq{END:VCALENDAR\r\n}; - - + + # Set mime of text/icalendar #$self->session->http->setMimeType("text/plain"); $self->session->http->setFilename("feed.ics","text/calendar"); @@ -2025,7 +2028,7 @@ Import an iCalendar file into the Events Calendar. sub www_importIcal { ### TODO: Everything - + return $_[0]->session->privilege->noAccess; } @@ -2048,21 +2051,21 @@ sub www_search { my $startDate = $form->process("startdate"); my $endDate = $form->process("enddate"); my $perpage = $form->param("perpage"); - + my $var = $self->getTemplateVars; $var->{url} = $self->getUrl; - + # If there is a search to perform if ($keywords || $startDate || $endDate) { my $search = new WebGUI::Search($session); my %rules = ( keywords => $keywords, classes => ['WebGUI::Asset::Event'], - lineage => [$self->get("lineage")], + lineage => [$self->lineage], join => "join Event on assetIndex.assetId=Event.assetId and assetIndex.revisionDate=Event.revisionDate", columns => ['Event.startDate','Event.startTime'], ); - + # If the start and/or end dates are not filled in, do not limit # to a certain time period $rules{where} .= "Event.startDate >= '$startDate'" @@ -2070,8 +2073,8 @@ sub www_search { $rules{where} .= " && " if ($startDate && $endDate); $rules{where} .= "Event.endDate <= '$endDate'" if ($endDate); - - + + # Prepare the paginator my @results = (); $search->search(\%rules); @@ -2085,7 +2088,7 @@ sub www_search { my $dt = WebGUI::DateTime->new($self->session, $data->{startDate}." ".($data->{startTime}?$data->{startTime}:"00:00:00")); $dt->set_time_zone( $self->session->datetime->getTimeZone ) if ($data->{startTime}); - + push(@results, { url => $self->session->url->gateway($data->{url}), title => $data->{title}, @@ -2094,7 +2097,7 @@ sub www_search { }); } } - + my $urlParams = 'func=search;' . 'keywords=' . $self->session->url->escape($keywords) . ';' . 'startdate=' . $startDate . ';' @@ -2111,12 +2114,12 @@ sub www_search { $p->appendTemplateVars($var); $var->{results} = $p->getPageData; } - + # Prepare the form my $default_dt = WebGUI::DateTime->new($self->session, time); my $default_start = $default_dt->toMysqlDate; my $default_end = $default_dt->add(years => 1)->toMysqlDate; - + $var->{"form.header"} = WebGUI::Form::formHeader($session, { action => $self->getUrl, @@ -2125,9 +2128,9 @@ sub www_search { name => "func", value => "search", }); - + $var->{"form.footer"} = WebGUI::Form::formFooter($session); - + $var->{"form.keywords"} = WebGUI::Form::text($session, { name => "keywords", @@ -2153,7 +2156,7 @@ sub www_search { value => $endDate, defaultValue => $default_end, }); - + my $i18n = WebGUI::International->new($session, 'Asset_Calendar'); $var->{"form.submit"} @@ -2164,7 +2167,7 @@ sub www_search { # This is very bad! It should be $self->processStyle or whatnot. return $self->processStyle( - $self->processTemplate( $var, $self->get('templateIdSearch') ) + $self->processTemplate( $var, $self->templateIdSearch ) ); } diff --git a/lib/WebGUI/Asset/Wobject/Carousel.pm b/lib/WebGUI/Asset/Wobject/Carousel.pm index 22a06f79a..0bec2c1d6 100644 --- a/lib/WebGUI/Asset/Wobject/Carousel.pm +++ b/lib/WebGUI/Asset/Wobject/Carousel.pm @@ -15,78 +15,33 @@ $VERSION = "1.0.0"; use strict; use warnings; use JSON; -use Tie::IxHash; use WebGUI::International; use WebGUI::Utility; -use base 'WebGUI::Asset::Wobject'; - -#------------------------------------------------------------------- - -=head2 definition ( ) - -defines wobject properties for New Wobject instances. You absolutely need -this method in your new Wobjects. If you choose to "autoGenerateForms", the -getEditForm method is unnecessary/redundant/useless. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session, 'Asset_Carousel'); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - templateId =>{ - fieldType =>"template", - defaultValue =>'CarouselTmpl0000000001', - tab =>"display", - noFormPost =>0, - namespace =>"Carousel", - hoverHelp =>$i18n->get('carousel template description'), - label =>$i18n->get('carousel template label'), - }, - slideWidth =>{ - fieldType => "integer", - defaultValue => 0, - tab => "display", - hoverHelp => $i18n->get('carousel slideWidth description'), - label => $i18n->get('carousel slideWidth label'), - }, - items =>{ - noFormPost =>1, - fieldType =>'text', - autoGenerate =>0, - }, - ); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'Carousel.png', - autoGenerateForms=>1, - tableName=>'Carousel', - className=>'WebGUI::Asset::Wobject::Carousel', - properties=>\%properties - }); - return $class->SUPER::definition($session, $definition); -} - - -#------------------------------------------------------------------- - -=head2 duplicate ( ) - -duplicates a New Wobject. This method is unnecessary, but if you have -auxiliary, ancillary, or "collateral" data or files related to your -wobject instances, you will need to duplicate them here. - -=cut - -sub duplicate { - my $self = shift; - my $newAsset = $self->SUPER::duplicate(@_); - return $newAsset; -} +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => [ 'assetName', 'Asset_Carousel' ]; +aspect icon => 'Carousel.png'; +aspect tableName => 'Carousel'; +property templateId => ( + fieldType => "template", + default => 'CarouselTmpl0000000001', + tab => "display", + noFormPost => 0, + namespace => "Carousel", + hoverHelp => [ 'carousel template description', 'Asset_Carousel' ], + label => [ 'carousel template label', 'Asset_Carousel' ], +); +property slideWidth => ( + fieldType => "integer", + default => 0, + tab => "display", + hoverHelp => [ 'carousel slideWidth description', 'Asset_Carousel' ], + label => [ 'carousel slideWidth label', 'Asset_Carousel' ], +); +property items => ( + noFormPost => 1, + fieldType => 'text', +); #------------------------------------------------------------------- @@ -119,8 +74,8 @@ sub getEditForm { $tabform->getTab("properties")->raw($tableRowStart); - if($self->getValue('items')){ - my @items = @{JSON->new->decode($self->getValue('items'))->{items}}; + if($self->items){ + my @items = @{JSON->new->decode($self->items)->{items}}; foreach my $item (@items){ my $itemNr = $item->{sequenceNumber}; @@ -184,11 +139,11 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("templateId"), + templateId => $self->templateId, assetId => $self->getId, ); } @@ -238,24 +193,6 @@ sub processPropertiesFromFormPost { #------------------------------------------------------------------- -=head2 purge ( ) - -removes collateral data associated with a Carousel when the system -purges it's data. This method is unnecessary, but if you have -auxiliary, ancillary, or "collateral" data or files related to your -wobject instances, you will need to purge them here. - -=cut - -sub purge { - my $self = shift; - #purge your wobject-specific data here. This does not include fields - # you create for your Carousel asset/wobject table. - return $self->SUPER::purge; -} - -#------------------------------------------------------------------- - =head2 view ( ) method called by the www_view method. Returns a processed template @@ -271,8 +208,8 @@ sub view { #This automatically creates template variables for all of your wobject's properties. my $var = $self->get; - if($self->getValue('items')){ - $var->{item_loop} = JSON->new->decode($self->getValue('items'))->{items}; + if($self->items){ + $var->{item_loop} = JSON->new->decode($self->items)->{items}; } #This is an example of debugging code to help you diagnose problems. diff --git a/lib/WebGUI/Asset/Wobject/Collaboration.pm b/lib/WebGUI/Asset/Wobject/Collaboration.pm index 867b58478..9371fb072 100644 --- a/lib/WebGUI/Asset/Wobject/Collaboration.pm +++ b/lib/WebGUI/Asset/Wobject/Collaboration.pm @@ -11,7 +11,447 @@ package WebGUI::Asset::Wobject::Collaboration; #------------------------------------------------------------------- use strict; -use Tie::IxHash; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_Collaboration']; +aspect icon => 'collaboration.gif'; +aspect tableName => 'Collaboration'; +property visitorCacheTimeout => ( + tab => "display", + fieldType => "interval", + default => 3600, + uiLevel => 8, + label => [ "visitor cache timeout", 'Asset_Collaboration' ], + hoverHelp => [ "visitor cache timeout help", 'Asset_Collaboration' ] +); +property autoSubscribeToThread => ( + fieldType => "yesNo", + default => 1, + tab => 'mail', + label => [ "auto subscribe to thread", 'Asset_Collaboration' ], + hoverHelp => [ "auto subscribe to thread help", 'Asset_Collaboration' ], +); +property requireSubscriptionForEmailPosting => ( + fieldType => "yesNo", + default => 1, + tab => 'mail', + label => [ "require subscription for email posting", 'Asset_Collaboration' ], + hoverHelp => [ "require subscription for email posting help", 'Asset_Collaboration' ], +); +property approvalWorkflow => ( + fieldType => "workflow", + default => "pbworkflow000000000003", + type => 'WebGUI::VersionTag', + tab => 'security', + label => [ 'approval workflow', 'Asset_Collaboration' ], + hoverHelp => [ 'approval workflow description', 'Asset_Collaboration' ], +); +property threadApprovalWorkflow => ( + fieldType => "workflow", + default => "pbworkflow000000000003", + type => 'WebGUI::VersionTag', + tab => 'security', + label => [ 'thread approval workflow', 'Asset_Collaboration' ], + hoverHelp => [ 'thread approval workflow description', 'Asset_Collaboration' ], +); +property thumbnailSize => ( + fieldType => "integer", + default => 0, + tab => "display", + label => [ "thumbnail size", 'Asset_Collaboration' ], + hoverHelp => [ "thumbnail size help", 'Asset_Collaboration' ] +); +property maxImageSize => ( + fieldType => "integer", + default => 0, + tab => "display", + label => [ "max image size", 'Asset_Collaboration' ], + hoverHelp => [ "max image size help", 'Asset_Collaboration' ] +); +property mailServer => ( + fieldType => "text", + default => undef, + tab => 'mail', + label => [ "mail server", 'Asset_Collaboration' ], + hoverHelp => [ "mail server help", 'Asset_Collaboration' ], +); +property mailAccount => ( + fieldType => "text", + default => undef, + tab => 'mail', + label => [ "mail account", 'Asset_Collaboration' ], + hoverHelp => [ "mail account help", 'Asset_Collaboration' ], +); +property mailPassword => ( + fieldType => "password", + default => undef, + tab => 'mail', + label => [ "mail password", 'Asset_Collaboration' ], + hoverHelp => [ "mail password help", 'Asset_Collaboration' ], +); +property mailAddress => ( + fieldType => "email", + default => undef, + tab => 'mail', + label => [ "mail address", 'Asset_Collaboration' ], + hoverHelp => [ "mail address help", 'Asset_Collaboration' ], +); +property mailPrefix => ( + fieldType => "text", + default => undef, + tab => 'mail', + label => [ "mail prefix", 'Asset_Collaboration' ], + hoverHelp => [ "mail prefix help", 'Asset_Collaboration' ], +); +property getMailCronId => ( + fieldType => "hidden", + default => undef, + noFormPost => 1 +); +property getMail => ( + fieldType => "yesNo", + default => 0, + tab => 'mail', + label => [ "get mail", 'Asset_Collaboration' ], + hoverHelp => [ "get mail help", 'Asset_Collaboration' ], +); +property getMailInterval => ( + fieldType => "interval", + default => 300, + tab => 'mail', + label => [ "get mail interval", 'Asset_Collaboration' ], + hoverHelp => [ "get mail interval help", 'Asset_Collaboration' ], +); +property displayLastReply => ( + fieldType => "yesNo", + default => 0, + tab => 'display', + label => [ 'display last reply', 'Asset_Collaboration' ], + hoverHelp => [ 'display last reply description', 'Asset_Collaboration' ], +); +property allowReplies => ( + fieldType => "yesNo", + default => 1, + tab => 'security', + label => [ 'allow replies', 'Asset_Collaboration' ], + hoverHelp => [ 'allow replies description', 'Asset_Collaboration' ], +); +property threadsPerPage => ( + fieldType => "integer", + default => 30, + tab => 'display', + label => [ 'threads/page', 'Asset_Collaboration' ], + hoverHelp => [ 'threads/page description', 'Asset_Collaboration' ], +); +property postsPerPage => ( + fieldType => "integer", + default => 10, + tab => 'display', + label => [ 'posts/page', 'Asset_Collaboration' ], + hoverHelp => [ 'posts/page description', 'Asset_Collaboration' ], +); +property archiveEnabled => ( + fieldType => "yesNo", + default => 1, + tab => 'properties', + label => [ 'editForm archiveEnabled label', 'Asset_Collaboration' ], + hoverHelp => [ 'editForm archiveEnabled description', 'Asset_Collaboration' ], +); +property archiveAfter => ( + fieldType => "interval", + default => 31536000, + tab => 'properties', + label => [ 'archive after', 'Asset_Collaboration' ], + hoverHelp => [ 'archive after description', 'Asset_Collaboration' ], +); +property lastPostDate => ( + noFormPost => 1, + fieldType => "hidden", + default => undef +); +property lastPostId => ( + noFormPost => 1, + fieldType => "hidden", + default => undef +); +property rating => ( + noFormPost => 1, + fieldType => "hidden", + default => undef +); +property replies => ( + noFormPost => 1, + fieldType => "hidden", + default => undef +); +property views => ( + noFormPost => 1, + fieldType => "hidden", + default => undef +); +property threads => ( + noFormPost => 1, + fieldType => "hidden", + default => undef +); +property useContentFilter => ( + fieldType => "yesNo", + default => 1, + tab => 'display', + label => [ 'content filter', 'Asset_Collaboration' ], + hoverHelp => [ 'content filter description', 'Asset_Collaboration' ], +); +property filterCode => ( + fieldType => "filterContent", + default => 'most', + tab => 'security', + label => [ 'filter code', 'Asset_Collaboration' ], + hoverHelp => [ 'filter code description', 'Asset_Collaboration' ], +); +property replyFilterCode => ( + fieldType => "filterContent", + default => 'most', + tab => 'security', + label => [ 'reply filter code', 'Asset_Collaboration' ], + hoverHelp => [ 'reply filter code description', 'Asset_Collaboration' ], +); +property richEditor => ( + fieldType => "selectRichEditor", + default => "PBrichedit000000000002", + tab => 'display', + label => [ 'rich editor', 'Asset_Collaboration' ], + hoverHelp => [ 'rich editor description', 'Asset_Collaboration' ], +); +property replyRichEditor => ( + fieldType => "selectRichEditor", + default => "PBrichedit000000000002", + tab => 'display', + label => [ 'reply rich editor', 'Asset_Collaboration' ], + hoverHelp => [ 'reply rich editor description', 'Asset_Collaboration' ], +); +property attachmentsPerPost => ( + fieldType => "integer", + default => 0, + tab => 'properties', + label => [ 'attachments/post', 'Asset_Collaboration' ], + hoverHelp => [ 'attachments/post description', 'Asset_Collaboration' ], +); +property editTimeout => ( + fieldType => "interval", + default => 3600, + tab => 'security', + label => [ 'edit timeout', 'Asset_Collaboration' ], + hoverHelp => [ 'edit timeout description', 'Asset_Collaboration' ], +); +property addEditStampToPosts => ( + fieldType => "yesNo", + default => 0, + tab => 'security', + label => [ 'edit stamp', 'Asset_Collaboration' ], + hoverHelp => [ 'edit stamp description', 'Asset_Collaboration' ], +); +property usePreview => ( + fieldType => "yesNo", + default => 1, + tab => 'properties', + label => [ 'use preview', 'Asset_Collaboration' ], + hoverHelp => [ 'use preview description', 'Asset_Collaboration' ], +); +property sortOrder => ( + fieldType => "selectBox", + default => 'desc', + tab => 'display', + options => \&_sortOrder_options, + label => [ 'sort order', 'Asset_Collaboration' ], + hoverHelp => [ 'sort order description', 'Asset_Collaboration' ], +); +sub _sortOrder_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session,"Asset_Collaboration"); + return { + asc => $i18n->get('ascending'), + desc => $i18n->get('descending'), + }; +} +property sortBy => ( + fieldType => "selectBox", + default => 'assetData.revisionDate', + tab => 'display', + options => \&_sortBy_options, + label => [ 'sort by', 'Asset_Collaboration' ], + hoverHelp => [ 'sort by description', 'Asset_Collaboration' ], +); +sub _sortBy_options { + my $self = shift; + my $session = $self->session; + my $i18n = WebGUI::International->new($session,"Asset_Collaboration"); + tie my %sortByOptions, 'Tie::IxHash'; + %sortByOptions = ( + lineage => $i18n->get('sequence'), + "assetData.revisionDate" => $i18n->get('date updated'), + creationDate => $i18n->get('date submitted'), + title => $i18n->get('title'), + userDefined1 => $i18n->get('user defined 1'), + userDefined2 => $i18n->get('user defined 2'), + userDefined3 => $i18n->get('user defined 3'), + userDefined4 => $i18n->get('user defined 4'), + userDefined5 => $i18n->get('user defined 5'), + ); + if ($self->_useKarma) { + $sortByOptions{karmaRank} = $i18n->get('karma rank'); + } + return \%sortByOptions; +} +property notificationTemplateId => ( + fieldType => "template", + namespace => "Collaboration/Notification", + default => 'PBtmpl0000000000000027', + tab => 'mail', + label => [ 'notification template', 'Asset_Collaboration' ], + hoverHelp => [ 'notification template description', 'Asset_Collaboration' ], +); +property searchTemplateId => ( + fieldType => "template", + namespace => "Collaboration/Search", + default => 'PBtmpl0000000000000031', + tab => 'display', + label => [ 'search template', 'Asset_Collaboration' ], + hoverHelp => [ 'search template description', 'Asset_Collaboration' ], +); +property postFormTemplateId => ( + fieldType => "template", + namespace => "Collaboration/PostForm", + default => 'PBtmpl0000000000000029', + tab => 'display', + label => [ 'post template', 'Asset_Collaboration' ], + hoverHelp => [ 'post template description', 'Asset_Collaboration' ], +); +property threadTemplateId => ( + fieldType => "template", + namespace => "Collaboration/Thread", + default => 'PBtmpl0000000000000032', + tab => 'display', + label => [ 'thread template', 'Asset_Collaboration' ], + hoverHelp => [ 'thread template description', 'Asset_Collaboration' ], +); +property collaborationTemplateId => ( + fieldType => "template", + namespace => 'Collaboration', + default => 'PBtmpl0000000000000026', + tab => 'display', + label => [ 'system template', 'Asset_Collaboration' ], + hoverHelp => [ 'system template description', 'Asset_Collaboration' ], +); +property karmaPerPost => ( + fieldType => "integer", + default => 0, + tab => 'properties', + noFormPost => \&_disableForKarma, + label => [ 'karma/post', 'Asset_Collaboration' ], + hoverHelp => [ 'karma/post description', 'Asset_Collaboration' ], +); +sub _disableForKarma { + my $self = shift; + return ! $self->_useKarma; +} +property karmaSpentToRate => ( + fieldType => "integer", + default => 0, + tab => 'properties', + noFormPost => \&_disableForKarma, + label => [ 'karma spent to rate', 'Asset_Collaboration' ], + hoverHelp => [ 'karma spent to rate description', 'Asset_Collaboration' ], +); +property karmaRatingMultiplier => ( + fieldType => "integer", + default => 1, + tab => 'properties', + noFormPost => \&_disableForKarma, + label => [ 'karma rating multiplier', 'Asset_Collaboration' ], + hoverHelp => [ 'karma rating multiplier description', 'Asset_Collaboration' ], +); +property avatarsEnabled => ( + fieldType => "yesNo", + default => 0, + tab => 'properties', + label => [ 'enable avatars', 'Asset_Collaboration' ], + hoverHelp => [ 'enable avatars description', 'Asset_Collaboration' ], +); +property enablePostMetaData => ( + fieldType => "yesNo", + default => 0, + tab => 'meta', + label => [ 'enable metadata', 'Asset_Collaboration' ], + hoverHelp => [ 'enable metadata description', 'Asset_Collaboration' ], +); +property postGroupId => ( + fieldType => "group", + default => '2', + tab => 'security', + label => [ 'who posts', 'Asset_Collaboration' ], + hoverHelp => [ 'who posts description', 'Asset_Collaboration' ], +); +property canStartThreadGroupId => ( + fieldType => "group", + default => '2', + tab => 'security', + label => [ 'who threads', 'Asset_Collaboration' ], + hoverHelp => [ 'who threads description', 'Asset_Collaboration' ], +); +property defaultKarmaScale => ( + fieldType => "integer", + default => 1, + tab => 'properties', + noFormPost => \&_disableForKarma, + label => [ "default karma scale", 'Asset_Collaboration' ], + hoverHelp => [ 'default karma scale help', 'Asset_Collaboration' ], +); +property useCaptcha => ( + fieldType => "yesNo", + default => '0', + tab => 'security', + label => [ 'use captcha label', 'Asset_Collaboration' ], + hoverHelp => [ 'use captcha hover help', 'Asset_Collaboration' ], +); +property subscriptionGroupId => ( + fieldType => "subscriptionGroup", + tab => 'security', + label => [ "subscription group label", 'Asset_Collaboration' ], + hoverHelp => [ "subscription group hoverHelp", 'Asset_Collaboration' ], + noFormPost => 1, + default => undef, +); +property groupToEditPost => ( + tab => "security", + label => [ 'group to edit label', 'Asset_Collaboration' ], + excludeGroups => [ 1, 7 ], + hoverHelp => [ 'group to edit hoverhelp', 'Asset_Collaboration' ], + uiLevel => 6, + fieldType => 'group', + builder => '_groupToEditPost_builder', # groupToEditPost should default to groupIdEdit + lazy => 1, +); +sub _groupToEditPost_builder { + my $session = shift->session; + my $groupIdEdit; + if($session->asset) { + $groupIdEdit = $session->asset->groupIdEdit; + } + else { + $groupIdEdit = '4'; + } + return $groupIdEdit; +} +property postReceivedTemplateId => ( + fieldType => 'template', + namespace => 'Collaboration/PostReceived', + tab => 'display', + label => [ 'post received template', 'Asset_Collaboration' ], + hoverHelp => [ 'post received template hoverHelp', 'Asset_Collaboration' ], + default => 'default_post_received1', +); + + use WebGUI::Group; use WebGUI::HTML; use WebGUI::International; @@ -19,9 +459,8 @@ use WebGUI::Paginator; use WebGUI::Utility; use WebGUI::Asset::Wobject; use WebGUI::Workflow::Cron; -use Class::C3; -use base qw(WebGUI::AssetAspect::RssFeed WebGUI::Asset::Wobject); - +#use Class::C3; +#use base qw(WebGUI::AssetAspect::RssFeed WebGUI::Asset::Wobject); #------------------------------------------------------------------- sub _computePostCount { @@ -47,6 +486,19 @@ sub _get_rfc822_date { $mday, $month, $year, $hour, $min, $sec); } + +#------------------------------------------------------------------- + +=head2 _useKarma + +Internal method for determining if the karma is enabled in settings. + +=cut + +sub _useKarma { + my $self = shift; + return $self->session->setting->get('useKarma'); +} #------------------------------------------------------------------- sub _visitorCacheKey { my $self = shift; @@ -74,7 +526,7 @@ sub addChild { my $properties = shift; my @other = @_; if ($properties->{className} ne "WebGUI::Asset::Post::Thread") { - $self->session->errorHandler->security("add a ".$properties->{className}." to a ".$self->get("className")); + $self->session->errorHandler->security("add a ".$properties->{className}." to a ".$self->className); return undef; } return $self->next::method($properties, @other); @@ -108,39 +560,39 @@ sub appendPostListTemplateVars { foreach my $row (@$page) { my $post = WebGUI::Asset->new($self->session,$row->{assetId}, $row->{className}, $row->{revisionDate}); $post->{_parent} = $self; # caching parent for efficiency - my $controls = $icon->delete('func=delete',$post->get("url"),"Delete") . $icon->edit('func=edit',$post->get("url")); - if ($self->get("sortBy") eq "lineage") { - if ($self->get("sortOrder") eq "desc") { - $controls .= $icon->moveUp('func=demote',$post->get("url")).$icon->moveDown('func=promote',$post->get("url")); + my $controls = $icon->delete('func=delete',$post->url,"Delete") . $icon->edit('func=edit',$post->url); + if ($self->sortBy eq "lineage") { + if ($self->sortOrder eq "desc") { + $controls .= $icon->moveUp('func=demote',$post->url).$icon->moveDown('func=promote',$post->url); } else { - $controls .= $icon->moveUp('func=promote',$post->get("url")).$icon->moveDown('func=demote',$post->get("url")); + $controls .= $icon->moveUp('func=promote',$post->url).$icon->moveDown('func=demote',$post->url); } } my @rating_loop; - for (my $i=0;$i<=$post->get("rating");$i++) { + for (my $i=0;$i<=$post->rating;$i++) { push(@rating_loop,{'rating_loop.count'=>$i}); } my %lastReply; my $hasRead = 0; - if ($post->get("className") =~ /Thread/) { - if ($self->get("displayLastReply")) { + if ($post->isa('WebGUI::Asset::Post::Thread')) { + if ($self->displayLastReply) { my $lastPost = $post->getLastPost(); %lastReply = ( "lastReply.url" => $lastPost->getUrl.'#'.$lastPost->getId, - "lastReply.title" => $lastPost->get("title"), - "lastReply.user.isVisitor" => $lastPost->get("ownerUserId") eq "1", - "lastReply.username" => $lastPost->get("username"), + "lastReply.title" => $lastPost->title, + "lastReply.user.isVisitor" => $lastPost->ownerUserId eq "1", + "lastReply.username" => $lastPost->username, "lastReply.userProfile.url" => $lastPost->getPosterProfileUrl(), - "lastReply.dateSubmitted.human" => $datetime->epochToHuman($lastPost->get("creationDate"),"%z"), - "lastReply.timeSubmitted.human" => $datetime->epochToHuman($lastPost->get("creationDate"),"%Z"), + "lastReply.dateSubmitted.human" => $datetime->epochToHuman($lastPost->creationDate,"%z"), + "lastReply.timeSubmitted.human" => $datetime->epochToHuman($lastPost->creationDate,"%Z"), ); } $hasRead = $post->isMarkedRead; } my $url; - if ($post->get("status") eq "pending") { - $url = $post->getUrl("revision=".$post->get("revisionDate"))."#".$post->getId; + if ($post->status eq "pending") { + $url = $post->getUrl("revision=".$post->revisionDate)."#".$post->getId; } else { $url = $post->getUrl."#".$post->getId; } @@ -153,12 +605,12 @@ sub appendPostListTemplateVars { "status" => $post->getStatus, "thumbnail" => $post->getThumbnailUrl, "image.url" => $post->getImageUrl, - "dateSubmitted.human" => $datetime->epochToHuman($post->get("creationDate"),"%z"), - "dateUpdated.human" => $datetime->epochToHuman($post->get("revisionDate"),"%z"), - "timeSubmitted.human" => $datetime->epochToHuman($post->get("creationDate"),"%Z"), - "timeUpdated.human" => $datetime->epochToHuman($post->get("revisionDate"),"%Z"), + "dateSubmitted.human" => $datetime->epochToHuman($post->creationDate,"%z"), + "dateUpdated.human" => $datetime->epochToHuman($post->revisionDate,"%z"), + "timeSubmitted.human" => $datetime->epochToHuman($post->creationDate,"%Z"), + "timeUpdated.human" => $datetime->epochToHuman($post->revisionDate,"%Z"), "userProfile.url" => $post->getPosterProfileUrl, - "user.isVisitor" => $post->get("ownerUserId") eq "1", + "user.isVisitor" => $post->ownerUserId eq "1", "edit.url" => $post->getEditUrl, 'controls' => $controls, "isSecond" => (($i+1)%2==0), @@ -172,7 +624,7 @@ sub appendPostListTemplateVars { ); $post->getTemplateMetadataVars(\%postVars); if ($row->{className} =~ m/^WebGUI::Asset::Post::Thread/) { - $postVars{'rating'} = $post->get('threadRating'); + $postVars{'rating'} = $post->threadRating; } push(@{$var->{post_loop}}, \%postVars ); $i++; @@ -344,11 +796,11 @@ sub canPost { ; # checks to make sure that the cs has been committed at least once - if ( $self->get("status") ne "approved" && $self->getTagCount <= 1 ) { + if ( $self->status ne "approved" && $self->getTagCount <= 1 ) { return 0; } # Users in the postGroupId can post - elsif ( $user->isInGroup( $self->get("postGroupId") ) ) { + elsif ( $user->isInGroup( $self->postGroupId ) ) { return 1; } # Users who can edit the collab can post @@ -406,7 +858,7 @@ sub canStartThread { : $self->session->user ; return ( - $user->isInGroup($self->get("canStartThreadGroupId")) + $user->isInGroup($self->canStartThreadGroupId) || $self->WebGUI::Asset::canEdit( $userId ) ); } @@ -445,14 +897,14 @@ sub commit { my $self = shift; $self->next::method; my $cron = undef; - if ($self->get("getMailCronId")) { - $cron = WebGUI::Workflow::Cron->new($self->session, $self->get("getMailCronId")); + if ($self->getMailCronId) { + $cron = WebGUI::Workflow::Cron->new($self->session, $self->getMailCronId); } my $i18n = WebGUI::International->new($self->session, "Asset_Collaboration"); unless (defined $cron) { $cron = WebGUI::Workflow::Cron->create($self->session, { title=>$self->getTitle." ".$i18n->get("mail"), - minuteOfHour=>"*/".($self->get("getMailInterval")/60), + minuteOfHour=>"*/".($self->getMailInterval/60), className=>(ref $self), methodName=>"new", parameters=>$self->getId, @@ -460,10 +912,10 @@ sub commit { }); $self->update({getMailCronId=>$cron->getId}); } - if ($self->get("getMail")) { - $cron->set({enabled=>1,title=>$self->getTitle." ".$i18n->get("mail"), minuteOfHour=>"*/".($self->get("getMailInterval")/60)}); + if ($self->getMail) { + $cron->set({enabled=>1,title=>$self->getTitle." ".$i18n->get("mail"), minuteOfHour=>"*/".($self->getMailInterval/60)}); } else { - $cron->set({enabled=>0,title=>$self->getTitle." ".$i18n->get("mail"), minuteOfHour=>"*/".($self->get("getMailInterval")/60)}); + $cron->set({enabled=>0,title=>$self->getTitle." ".$i18n->get("mail"), minuteOfHour=>"*/".($self->getMailInterval/60)}); } } @@ -488,447 +940,6 @@ sub createSubscriptionGroup { }); } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Collaboration"); - my $useKarma = $session->setting->get('useKarma'); - - # obtain the groupIdEdit default value. Try to get it from the parent asset - # if it exists. If not, default to the value specified in WebGUI::Asset's - # definition. - my $groupIdEdit; - if($session->asset) { - $groupIdEdit = $session->asset->get('groupIdEdit'); - } - else { - $groupIdEdit = '4'; - } - - - my %sortByOptions; - tie %sortByOptions, 'Tie::IxHash'; - %sortByOptions = (lineage=>$i18n->get('sequence'), - "assetData.revisionDate"=>$i18n->get('date updated'), - creationDate=>$i18n->get('date submitted'), - title=>$i18n->get('title'), - userDefined1=>$i18n->get('user defined 1'), - userDefined2=>$i18n->get('user defined 2'), - userDefined3=>$i18n->get('user defined 3'), - userDefined4=>$i18n->get('user defined 4'), - userDefined5=>$i18n->get('user defined 5'), - ($useKarma? (karmaRank=>$i18n->get('karma rank')) : ()), - ); - - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - visitorCacheTimeout => { - tab => "display", - fieldType => "interval", - defaultValue => 3600, - uiLevel => 8, - label => $i18n->get("visitor cache timeout"), - hoverHelp => $i18n->get("visitor cache timeout help") - }, - autoSubscribeToThread => { - fieldType=>"yesNo", - defaultValue=>1, - tab=>'mail', - label=>$i18n->get("auto subscribe to thread"), - hoverHelp=>$i18n->get("auto subscribe to thread help"), - }, - requireSubscriptionForEmailPosting => { - fieldType=>"yesNo", - defaultValue=>1, - tab=>'mail', - label=>$i18n->get("require subscription for email posting"), - hoverHelp=>$i18n->get("require subscription for email posting help"), - }, - approvalWorkflow =>{ - fieldType=>"workflow", - defaultValue=>"pbworkflow000000000003", - type=>'WebGUI::VersionTag', - tab=>'security', - label=>$i18n->get('approval workflow'), - hoverHelp=>$i18n->get('approval workflow description'), - }, - threadApprovalWorkflow =>{ - fieldType=>"workflow", - defaultValue=>"pbworkflow000000000003", - type=>'WebGUI::VersionTag', - tab=>'security', - label=>$i18n->get('thread approval workflow'), - hoverHelp=>$i18n->get('thread approval workflow description'), - }, - thumbnailSize => { - fieldType => "integer", - defaultValue => 0, - tab => "display", - label => $i18n->get("thumbnail size"), - hoverHelp => $i18n->get("thumbnail size help") - }, - maxImageSize => { - fieldType => "integer", - defaultValue => 0, - tab => "display", - label => $i18n->get("max image size"), - hoverHelp => $i18n->get("max image size help") - }, - mailServer=>{ - fieldType=>"text", - defaultValue=>undef, - tab=>'mail', - label=>$i18n->get("mail server"), - hoverHelp=>$i18n->get("mail server help"), - }, - mailAccount=>{ - fieldType=>"text", - defaultValue=>undef, - tab=>'mail', - label=>$i18n->get("mail account"), - hoverHelp=>$i18n->get("mail account help"), - }, - mailPassword=>{ - fieldType=>"password", - defaultValue=>undef, - tab=>'mail', - label=>$i18n->get("mail password"), - hoverHelp=>$i18n->get("mail password help"), - }, - mailAddress=>{ - fieldType=>"email", - defaultValue=>undef, - tab=>'mail', - label=>$i18n->get("mail address"), - hoverHelp=>$i18n->get("mail address help"), - }, - mailPrefix=>{ - fieldType=>"text", - defaultValue=>undef, - tab=>'mail', - label=>$i18n->get("mail prefix"), - hoverHelp=>$i18n->get("mail prefix help"), - }, - getMailCronId=>{ - fieldType=>"hidden", - defaultValue=>undef, - noFormPost=>1 - }, - getMail=>{ - fieldType=>"yesNo", - defaultValue=>0, - tab=>'mail', - label=>$i18n->get("get mail"), - hoverHelp=>$i18n->get("get mail help"), - }, - getMailInterval=>{ - fieldType=>"interval", - defaultValue=>300, - tab=>'mail', - label=>$i18n->get("get mail interval"), - hoverHelp=>$i18n->get("get mail interval help"), - }, - displayLastReply =>{ - fieldType=>"yesNo", - defaultValue=>0, - tab=>'display', - label=>$i18n->get('display last reply'), - hoverHelp=>$i18n->get('display last reply description'), - }, - allowReplies =>{ - fieldType=>"yesNo", - defaultValue=>1, - tab=>'security', - label=>$i18n->get('allow replies'), - hoverHelp=>$i18n->get('allow replies description'), - }, - threadsPerPage =>{ - fieldType=>"integer", - defaultValue=>30, - tab=>'display', - label=>$i18n->get('threads/page'), - hoverHelp=>$i18n->get('threads/page description'), - }, - postsPerPage =>{ - fieldType=>"integer", - defaultValue=>10, - tab=>'display', - label=>$i18n->get('posts/page'), - hoverHelp=>$i18n->get('posts/page description'), - }, - archiveEnabled => { - fieldType => "yesNo", - defaultValue => 1, - tab => 'properties', - label => $i18n->get('editForm archiveEnabled label'), - hoverHelp => $i18n->get('editForm archiveEnabled description'), - }, - archiveAfter =>{ - fieldType=>"interval", - defaultValue=>31536000, - tab=>'properties', - label=>$i18n->get('archive after'), - hoverHelp=>$i18n->get('archive after description'), - }, - lastPostDate =>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - lastPostId =>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - rating =>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - replies =>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - views =>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - threads =>{ - noFormPost=>1, - fieldType=>"hidden", - defaultValue=>undef - }, - useContentFilter =>{ - fieldType=>"yesNo", - defaultValue=>1, - tab=>'display', - label=>$i18n->get('content filter'), - hoverHelp=>$i18n->get('content filter description'), - }, - filterCode =>{ - fieldType=>"filterContent", - defaultValue=>'most', - tab=>'security', - label=>$i18n->get('filter code'), - hoverHelp=>$i18n->get('filter code description'), - }, - replyFilterCode =>{ - fieldType=>"filterContent", - defaultValue=>'most', - tab=>'security', - label=>$i18n->get('reply filter code'), - hoverHelp=>$i18n->get('reply filter code description'), - }, - richEditor =>{ - fieldType=>"selectRichEditor", - defaultValue=>"PBrichedit000000000002", - tab=>'display', - label=>$i18n->get('rich editor'), - hoverHelp=>$i18n->get('rich editor description'), - }, - replyRichEditor =>{ - fieldType=>"selectRichEditor", - defaultValue=>"PBrichedit000000000002", - tab=>'display', - label=>$i18n->get('reply rich editor'), - hoverHelp=>$i18n->get('reply rich editor description'), - }, - attachmentsPerPost =>{ - fieldType=>"integer", - defaultValue=>0, - tab=>'properties', - label=>$i18n->get('attachments/post'), - hoverHelp=>$i18n->get('attachments/post description'), - }, - editTimeout =>{ - fieldType=>"interval", - defaultValue=>3600, - tab=>'security', - label=>$i18n->get('edit timeout'), - hoverHelp=>$i18n->get('edit timeout description'), - }, - addEditStampToPosts =>{ - fieldType=>"yesNo", - defaultValue=>0, - tab=>'security', - label=>$i18n->get('edit stamp'), - hoverHelp=>$i18n->get('edit stamp description'), - }, - usePreview =>{ - fieldType=>"yesNo", - defaultValue=>1, - tab=>'properties', - label=>$i18n->get('use preview'), - hoverHelp=>$i18n->get('use preview description'), - }, - sortOrder =>{ - fieldType=>"selectBox", - defaultValue=>'desc', - tab=>'display', - options=>{ asc => $i18n->get('ascending'), - desc => $i18n->get('descending') }, - label=>$i18n->get('sort order'), - hoverHelp=>$i18n->get('sort order description'), - }, - sortBy =>{ - fieldType=>"selectBox", - defaultValue=>'assetData.revisionDate', - tab=>'display', - options=>\%sortByOptions, - label=>$i18n->get('sort by'), - hoverHelp=>$i18n->get('sort by description'), - }, - notificationTemplateId =>{ - fieldType=>"template", - namespace=>"Collaboration/Notification", - defaultValue=>'PBtmpl0000000000000027', - tab=>'mail', - label=>$i18n->get('notification template'), - hoverHelp=>$i18n->get('notification template description'), - }, - searchTemplateId =>{ - fieldType=>"template", - namespace=>"Collaboration/Search", - defaultValue=>'PBtmpl0000000000000031', - tab=>'display', - label=>$i18n->get('search template'), - hoverHelp=>$i18n->get('search template description'), - }, - postFormTemplateId =>{ - fieldType=>"template", - namespace=>"Collaboration/PostForm", - defaultValue=>'PBtmpl0000000000000029', - tab=>'display', - label=>$i18n->get('post template'), - hoverHelp=>$i18n->get('post template description'), - }, - threadTemplateId =>{ - fieldType=>"template", - namespace=>"Collaboration/Thread", - defaultValue=>'PBtmpl0000000000000032', - tab=>'display', - label=>$i18n->get('thread template'), - hoverHelp=>$i18n->get('thread template description'), - }, - collaborationTemplateId =>{ - fieldType=>"template", - namespace=>'Collaboration', - defaultValue=>'PBtmpl0000000000000026', - tab=>'display', - label=>$i18n->get('system template'), - hoverHelp=>$i18n->get('system template description'), - }, - karmaPerPost =>{ - fieldType=>"integer", - defaultValue=>0, - tab=>'properties', - visible=>$useKarma, - label=>$i18n->get('karma/post'), - hoverHelp=>$i18n->get('karma/post description'), - }, - karmaSpentToRate => { - fieldType => "integer", - defaultValue=> 0, - tab=>'properties', - visible => $useKarma, - label => $i18n->get('karma spent to rate'), - hoverHelp => $i18n->get('karma spent to rate description'), - }, - karmaRatingMultiplier => { - fieldType => "integer", - defaultValue=> 1, - tab=>'properties', - visible => $useKarma, - label=>$i18n->get('karma rating multiplier'), - hoverHelp=>$i18n->get('karma rating multiplier description'), - }, - avatarsEnabled =>{ - fieldType=>"yesNo", - defaultValue=>0, - tab=>'properties', - label=>$i18n->get('enable avatars'), - hoverHelp=>$i18n->get('enable avatars description'), - }, - enablePostMetaData =>{ - fieldType=>"yesNo", - defaultValue=>0, - tab=>'meta', - label=>$i18n->get('enable metadata'), - hoverHelp=>$i18n->get('enable metadata description'), - }, - postGroupId =>{ - fieldType=>"group", - defaultValue=>'2', - tab=>'security', - label=>$i18n->get('who posts'), - hoverHelp=>$i18n->get('who posts description'), - }, - canStartThreadGroupId =>{ - fieldType=>"group", - defaultValue=>'2', - tab=>'security', - label=>$i18n->get('who threads'), - hoverHelp=>$i18n->get('who threads description'), - }, - defaultKarmaScale => { - fieldType=>"integer", - defaultValue=>1, - tab=>'properties', - visible=>$useKarma, - label=>$i18n->get("default karma scale"), - hoverHelp=>$i18n->get('default karma scale help'), - }, - useCaptcha => { - fieldType=>"yesNo", - defaultValue=>'0', - tab=>'security', - label=>$i18n->get('use captcha label'), - hoverHelp=>$i18n->get('use captcha hover help'), - }, - subscriptionGroupId =>{ - fieldType=>"subscriptionGroup", - tab=>'security', - label=>$i18n->get("subscription group label"), - hoverHelp=>$i18n->get("subscription group hoverHelp"), - noFormPost=>1, - defaultValue=>undef, - }, - groupToEditPost=>{ - tab=>"security", - label=>$i18n->get('group to edit label'), - excludeGroups=>[1,7], - hoverHelp=>$i18n->get('group to edit hoverhelp'), - uiLevel=>6, - fieldType=>'group', - filter=>'fixId', - defaultValue=>$groupIdEdit, # groupToEditPost should default to groupIdEdit - }, - postReceivedTemplateId =>{ - fieldType=>'template', - namespace=>'Collaboration/PostReceived', - tab=>'display', - label=>$i18n->get('post received template'), - hoverHelp=>$i18n->get('post received template hoverHelp'), - defaultValue=>'default_post_received1', - }, - ); - - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - autoGenerateForms=>1, - icon=>'collaboration.gif', - tableName=>'Collaboration', - className=>'WebGUI::Asset::Wobject::Collaboration', - properties=>\%properties, - }); - return $class->next::method($session, $definition); -} - #------------------------------------------------------------------- =head2 duplicate @@ -984,7 +995,7 @@ sub getRssFeedItems { # XXX copied and reformatted this query from www_viewRSS, but why is it constructed like this? # And it's duplicated inside view, too! Eeeagh! And it uses the versionTag scratch var... - my ($sortBy, $sortOrder) = ($self->getValue('sortBy'), $self->getValue('sortOrder')); + my ($sortBy, $sortOrder) = ($self->sortBy, $self->sortOrder); my @postIds = $self->session->db->buildArray(<<"SQL", [$self->getId, $self->session->scratch->get('versionTag')]); SELECT asset.assetId @@ -1002,7 +1013,7 @@ SQL my $datetime = $self->session->datetime; my @posts; - my $rssLimit = $self->get('itemsPerFeed'); + my $rssLimit = $self->itemsPerFeed; for my $postId (@postIds) { my $post = WebGUI::Asset->new($self->session, $postId, 'WebGUI::Asset::Post::Thread'); my $postUrl = $siteUrl . $post->getUrl; @@ -1012,7 +1023,7 @@ SQL # Create the attachment template loop my $storage = $post->getStorageLocation; my $attachmentLoop = []; - if ($post->get('storageId')) { + if ($post->storageId) { for my $file (@{$storage->getFiles}) { push @{$attachmentLoop}, { 'attachment.url' => $storage->getUrl($file), @@ -1024,19 +1035,19 @@ SQL } push @posts, { - author => $post->get('username'), - title => $post->get('title'), + author => $post->username, + title => $post->title, 'link' => $postUrl, guid => $postUrl, - description => $post->get('synopsis'), - epochDate => $post->get('creationDate'), - pubDate => $datetime->epochToMail($post->get('creationDate')), + description => $post->synopsis, + epochDate => $post->creationDate, + pubDate => $datetime->epochToMail($post->creationDate), attachmentLoop => $attachmentLoop, - userDefined1 => $post->get("userDefined1"), - userDefined2 => $post->get("userDefined2"), - userDefined3 => $post->get("userDefined3"), - userDefined4 => $post->get("userDefined4"), - userDefined5 => $post->get("userDefined5"), + userDefined1 => $post->userDefined1, + userDefined2 => $post->userDefined2, + userDefined3 => $post->userDefined3, + userDefined4 => $post->userDefined4, + userDefined5 => $post->userDefined5, }; last if $rssLimit <= scalar(@posts); @@ -1087,7 +1098,7 @@ Retrieves the field to sort by sub getSortBy { my $self = shift; my $scratchSortBy = $self->getId."_sortBy"; - my $sortBy = $self->session->scratch->get($scratchSortBy) || $self->getValue("sortBy"); + my $sortBy = $self->session->scratch->get($scratchSortBy) || $self->sortBy; # XXX: This should be fixed in an upgrade and in the definition, NOT HERE if ( $sortBy eq "rating" ) { $sortBy = "threadRating"; @@ -1106,7 +1117,7 @@ Retrieves the direction to sort in sub getSortOrder { my $self = shift; my $scratchSortOrder = $self->getId."_sortDir"; - my $sortOrder = $self->session->scratch->get($scratchSortOrder) || $self->getValue("sortOrder"); + my $sortOrder = $self->session->scratch->get($scratchSortOrder) || $self->sortOrder; return $sortOrder; } @@ -1137,8 +1148,8 @@ sub getThreadsPaginator { my $scratchSortBy = $self->getId."_sortBy"; my $scratchSortOrder = $self->getId."_sortDir"; - my $sortBy = $self->session->form->process("sortBy") || $self->session->scratch->get($scratchSortBy) || $self->get("sortBy"); - my $sortOrder = $self->session->scratch->get($scratchSortOrder) || $self->get("sortOrder"); + my $sortBy = $self->session->form->process("sortBy") || $self->session->scratch->get($scratchSortBy) || $self->sortBy; + my $sortOrder = $self->session->scratch->get($scratchSortOrder) || $self->sortOrder; if ($sortBy ne $self->session->scratch->get($scratchSortBy) && $self->session->form->process("func") ne "editSave") { $self->session->scratch->set($scratchSortBy,$self->session->form->process("sortBy")); $self->session->scratch->set($scratchSortOrder, $sortOrder); @@ -1187,7 +1198,7 @@ sub getThreadsPaginator { Thread.isSticky desc, ".$sortBy." ".$sortOrder; - my $p = WebGUI::Paginator->new($self->session,$self->getUrl,$self->get("threadsPerPage")); + my $p = WebGUI::Paginator->new($self->session,$self->getUrl,$self->threadsPerPage); $p->setDataByQuery($sql); return $p; @@ -1302,7 +1313,7 @@ Increments the views counter on this forum. sub incrementViews { my ($self) = @_; - $self->update({views=>$self->get("views")+1}); + $self->update({views=>$self->views+1}); } #------------------------------------------------------------------- @@ -1315,7 +1326,7 @@ Returns a boolean indicating whether the user is subscribed to the forum. sub isSubscribed { my $self = shift; - return $self->session->user->isInGroup($self->get("subscriptionGroupId")); + return $self->session->user->isInGroup($self->subscriptionGroupId); } #------------------------------------------------------------------- @@ -1329,11 +1340,11 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->next::method; - my $template = WebGUI::Asset::Template->new($self->session, $self->get("collaborationTemplateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->collaborationTemplateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("collaborationTemplateId"), + templateId => $self->collaborationTemplateId, assetId => $self->getId, ); } @@ -1354,16 +1365,16 @@ and direction. sub processPropertiesFromFormPost { my $self = shift; - my $updatePrivs = ($self->session->form->process("groupIdView") ne $self->get("groupIdView") || $self->session->form->process("groupIdEdit") ne $self->get("groupIdEdit")); + my $updatePrivs = ($self->session->form->process("groupIdView") ne $self->groupIdView || $self->session->form->process("groupIdEdit") ne $self->groupIdEdit); $self->next::method; - if ($self->get("subscriptionGroupId") eq "") { + if ($self->subscriptionGroupId eq "") { $self->createSubscriptionGroup; } if ($updatePrivs) { foreach my $descendant (@{$self->getLineage(["descendants"],{returnObjects=>1})}) { $descendant->update({ - groupIdView=>$self->get("groupIdView"), - groupIdEdit=>$self->get("groupIdEdit") + groupIdView=>$self->groupIdView, + groupIdEdit=>$self->groupIdEdit }); } } @@ -1382,12 +1393,12 @@ Extend the base method to delete the subscription group and cron job for emails. sub purge { my $self = shift; - my $group = WebGUI::Group->new($self->session, $self->get("subscriptionGroupId")); + my $group = WebGUI::Group->new($self->session, $self->subscriptionGroupId); if ($group) { $group->delete; } - if ($self->get("getMailCronId")) { - my $cron = WebGUI::Workflow::Cron->new($self->session, $self->get("getMailCronId")); + if ($self->getMailCronId) { + my $cron = WebGUI::Workflow::Cron->new($self->session, $self->getMailCronId); $cron->delete if defined $cron; } $self->next::method; @@ -1513,13 +1524,13 @@ Subscribes a user to this collaboration system. sub subscribe { my $self = shift; my $group; - my $subscriptionGroup = $self->get('subscriptionGroupId'); + my $subscriptionGroup = $self->subscriptionGroupId; if ($subscriptionGroup) { $group = WebGUI::Group->new($self->session,$subscriptionGroup); } if (!$group) { $self->createSubscriptionGroup; - $group = WebGUI::Group->new($self->session,$self->get('subscriptionGroupId')); + $group = WebGUI::Group->new($self->session,$self->subscriptionGroupId); } $group->addUsers([$self->session->user->userId]); } @@ -1534,10 +1545,10 @@ Unsubscribes a user from this collaboration system sub unsubscribe { my $self = shift; - my $group = WebGUI::Group->new($self->session,$self->get("subscriptionGroupId")); + my $group = WebGUI::Group->new($self->session,$self->subscriptionGroupId); return unless $group; - $group->deleteUsers([$self->session->user->userId],[$self->get("subscriptionGroupId")]); + $group->deleteUsers([$self->session->user->userId],[$self->subscriptionGroupId]); } @@ -1564,7 +1575,7 @@ sub view { $self->prepareView unless ($self->{_viewTemplate}); my $out = $self->processTemplate($self->getViewTemplateVars,undef,$self->{_viewTemplate}); if ($self->_visitorCacheOk) { - eval{$cache->set($self->_visitorCacheKey, $out, $self->get("visitorCacheTimeout"))}; + eval{$cache->set($self->_visitorCacheKey, $out, $self->visitorCacheTimeout)}; } return $out; } @@ -1603,13 +1614,13 @@ sub www_search { my $search = WebGUI::Search->new($self->session); $search->search({ keywords=>$query, - lineage=>[$self->get("lineage")], + lineage=>[$self->lineage], classes=>["WebGUI::Asset::Post", "WebGUI::Asset::Post::Thread"] }); - my $p = $search->getPaginatorResultSet($self->getUrl("func=search;doit=1;query=".$query), $self->get("threadsPerPage")); + my $p = $search->getPaginatorResultSet($self->getUrl("func=search;doit=1;query=".$query), $self->threadsPerPage); $self->appendPostListTemplateVars($var, $p); } - return $self->processStyle($self->processTemplate($var, $self->get("searchTemplateId"))); + return $self->processStyle($self->processTemplate($var, $self->searchTemplateId)); } #------------------------------------------------------------------- @@ -1655,7 +1666,7 @@ Extend the base method to handle the visitor cache timeout. sub www_view { my $self = shift; my $disableCache = ($self->session->form->process("sortBy") ne ""); - $self->session->http->setCacheControl($self->get("visitorCacheTimeout")) if ($self->session->user->isVisitor && !$disableCache); + $self->session->http->setCacheControl($self->visitorCacheTimeout) if ($self->session->user->isVisitor && !$disableCache); return $self->next::method(@_); } diff --git a/lib/WebGUI/Asset/Wobject/Collaboration/Newsletter.pm b/lib/WebGUI/Asset/Wobject/Collaboration/Newsletter.pm index d098ce819..b795ea304 100644 --- a/lib/WebGUI/Asset/Wobject/Collaboration/Newsletter.pm +++ b/lib/WebGUI/Asset/Wobject/Collaboration/Newsletter.pm @@ -11,90 +11,58 @@ package WebGUI::Asset::Wobject::Collaboration::Newsletter; #------------------------------------------------------------------- use strict; -use Tie::IxHash; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject::Collaboration'; +aspect assetName => ['assetName', 'Asset_Newsletter']; +aspect icon => 'newsletter.gif'; +aspect tableName => 'Newsletter'; +property newsletterHeader => ( + default => undef, + fieldType => "HTMLArea", + tab => "mail", + label => [ "newsletter header", 'Asset_Newsletter' ], + hoverHelp => [ "newsletter header help", 'Asset_Newsletter' ], +); +property newsletterFooter => ( + default => undef, + fieldType => "HTMLArea", + tab => "mail", + label => [ "newsletter footer", 'Asset_Newsletter' ], + hoverHelp => [ "newsletter footer help", 'Asset_Newsletter' ], +); +property newsletterTemplateId => ( + default => 'newsletter000000000001', + fieldType => "template", + namespace => "newsletter", + tab => "mail", + label => [ "newsletter template", 'Asset_Newsletter' ], + hoverHelp => [ "newsletter template help", 'Asset_Newsletter' ], +); +property mySubscriptionsTemplateId => ( + default => 'newslettersubscrip0001', + fieldType => "template", + namespace => "newsletter/mysubscriptions", + tab => "display", + label => [ "my subscriptions template", 'Asset_Newsletter' ], + hoverHelp => [ "my subscriptions template help", 'Asset_Newsletter' ], +); +property newsletterCategories => ( + default => undef, + fieldType => "checkList", + tab => "properties", + options => \&_newsletterCategories_options, + label => [ "newsletter categories", 'Asset_Newsletter' ], + hoverHelp => [ "newsletter categories help", 'Asset_Newsletter' ], + vertical => 1, +); +sub _newsletterCategories_options { + my $session = shift->session; + return $session->db->buildHashRef("select fieldId, fieldName from metaData_properties where fieldType in ('selectBox', 'checkList', 'radioList') order by fieldName"); +} + use WebGUI::Form; use WebGUI::International; use WebGUI::Utility; -use base 'WebGUI::Asset::Wobject::Collaboration'; - -#------------------------------------------------------------------- - -=head2 definition ( ) - -defines wobject properties for Newsletter instances. You absolutely need -this method in your new Wobjects. If you choose to "autoGenerateForms", the -getEditForm method is unnecessary/redundant/useless. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session, 'Asset_Newsletter'); - my %properties; - tie %properties, 'Tie::IxHash'; - %properties = ( - newsletterHeader => { - defaultValue=>undef, - fieldType=>"HTMLArea", - tab=>"mail", - label=>$i18n->get("newsletter header"), - hoverHelp=>$i18n->get("newsletter header help"), - }, - newsletterFooter => { - defaultValue=>undef, - fieldType=>"HTMLArea", - tab=>"mail", - label=>$i18n->get("newsletter footer"), - hoverHelp=>$i18n->get("newsletter footer help"), - }, - newsletterTemplateId => { - defaultValue=>'newsletter000000000001', - fieldType=>"template", - namespace=>"newsletter", - tab=>"mail", - label=>$i18n->get("newsletter template"), - hoverHelp=>$i18n->get("newsletter template help"), - }, - mySubscriptionsTemplateId => { - defaultValue=>'newslettersubscrip0001', - fieldType=>"template", - namespace=>"newsletter/mysubscriptions", - tab=>"display", - label=>$i18n->get("my subscriptions template"), - hoverHelp=>$i18n->get("my subscriptions template help"), - }, - ); - if ($session->setting->get("metaDataEnabled")) { - $properties{newsletterCategories} = { - defaultValue=>undef, - fieldType=>"checkList", - tab=>"properties", - options=>$session->db->buildHashRef("select fieldId, fieldName from metaData_properties where - fieldType in ('selectBox', 'checkList', 'radioList') order by fieldName"), - label=>$i18n->get("newsletter categories"), - hoverHelp=>$i18n->get("newsletter categories help"), - vertical=>1, - }; - } - else { - $properties{newsletterCategories} = { - fieldType=>"readOnly", - value=>''.$i18n->get("content profiling needed").'', - }; - } - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'newsletter.gif', - autoGenerateForms=>1, - tableName=>'Newsletter', - className=>'WebGUI::Asset::Wobject::Collaboration::Newsletter', - properties=>\%properties - }); - return $class->SUPER::definition($session, $definition); -} - #------------------------------------------------------------------- @@ -215,7 +183,7 @@ sub www_mySubscriptions { my @userPrefs = $self->getUserSubscriptions; foreach my $id (keys %{$meta}) { my @options = (); - if (isIn($id, split("\n", $self->get("newsletterCategories")))) { + if (isIn($id, split("\n", $self->newsletterCategories))) { foreach my $option (split("\n", $meta->{$id}{possibleValues})) { $option =~ s/\s+$//; # remove trailing spaces next if $option eq ""; # skip blank values @@ -242,7 +210,7 @@ sub www_mySubscriptions { $var{formFooter} = WebGUI::Form::formFooter($self->session); $var{formSubmit} = WebGUI::Form::submit($self->session); } - return $self->processStyle($self->processTemplate(\%var, $self->get("mySubscriptionsTemplateId"))); + return $self->processStyle($self->processTemplate(\%var, $self->mySubscriptionsTemplateId)); } #------------------------------------------------------------------- diff --git a/lib/WebGUI/Asset/Wobject/Dashboard.pm b/lib/WebGUI/Asset/Wobject/Dashboard.pm index 0590e4b64..b9dc58998 100644 --- a/lib/WebGUI/Asset/Wobject/Dashboard.pm +++ b/lib/WebGUI/Asset/Wobject/Dashboard.pm @@ -11,14 +11,71 @@ package WebGUI::Asset::Wobject::Dashboard; #------------------------------------------------------------------- use strict; -use Tie::IxHash; use WebGUI::International; use WebGUI::Utility; use WebGUI::ProfileField; use Time::HiRes; use WebGUI::Asset::Wobject; -our @ISA = qw(WebGUI::Asset::Wobject); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => [ 'assetName', 'Asset_Dashboard' ]; +aspect icon => 'dashboard.gif'; +aspect tableName => 'Dashboard'; +property templateId => ( + fieldType => "template", + default => 'DashboardViewTmpl00001', + namespace => "Dashboard", + tab => 'display', + label => [ 'dashboard template field label', 'Asset_Dashboard' ], + hoverHelp => [ 'dashboard template description', 'Asset_Dashboard' ], +); + +property adminsGroupId => ( + fieldType => "group", + default => '4', + tab => 'security', + label => [ 'dashboard adminsGroupId field label', 'Asset_Dashboard' ], + hoverHelp => [ 'dashboard adminsGroupId description', 'Asset_Dashboard' ], +); + +property usersGroupId => ( + fieldType => "group", + default => '2', + label => [ 'dashboard usersGroupId field label', 'Asset_Dashboard' ], + hoverHelp => [ 'dashboard usersGroupId description', 'Asset_Dashboard' ], +); + +property isInitialized => ( + fieldType => "yesNo", + default => 0, + noFormPost => 1, +); + +property assetsToHide => ( + default => undef, + fieldType => "checkList", + noFormPost => \&_assetsToHide_noFormPost, + label => [ 'assets to hide', 'Asset_Dashboard' ], + hoverHelp => [ 'assets to hide description', 'Asset_Dashboard' ], + vertical => 1, + uiLevel => 9, + options => \&_assetsToHide_options, +); +sub _assetsToHide_noFormPost { + my $self = shift; + return $self->session->form->process("func") eq "add" ? 1 : 0; +} +sub _assetsToHide_options { + my $self = shift; + my $session = $self->session; + my $children = $self->getLineage(["children"],{"returnObjects"=>1, excludeClasses=>["WebGUI::Asset::Wobject::Layout"]}); + my %childIds; + foreach my $child (@{$children}) { + $childIds{$child->getId} = $child->getTitle.' ['.ref($child).']'; + } + return \%childIds; +} #------------------------------------------------------------------- @@ -34,7 +91,7 @@ in the dashboard's adminsGroup. sub canManage { my $self = shift; return 0 if $self->session->user->isVisitor; - return $self->session->user->isInGroup($self->get("adminsGroupId")); + return $self->session->user->isInGroup($self->adminsGroupId); } #------------------------------------------------------------------- @@ -50,7 +107,7 @@ in this dashboard's userGroup. sub canPersonalize { my $self = shift; return 0 if $self->session->user->isVisitor; - return $self->session->user->isInGroup($self->get("usersGroupId")); + return $self->session->user->isInGroup($self->usersGroupId); } #------------------------------------------------------------------- @@ -61,50 +118,10 @@ sub definition { my $i18n = WebGUI::International->new($session,"Asset_Dashboard"); my %properties; - tie %properties, 'Tie::IxHash'; %properties = ( - templateId => { - fieldType => "template", - defaultValue => 'DashboardViewTmpl00001', - namespace => "Dashboard", - tab => 'display', - label => $i18n->get('dashboard template field label'), - hoverHelp => $i18n->get('dashboard template description'), - }, - - adminsGroupId => { - fieldType => "group", - defaultValue => '4', - tab => 'security', - label => $i18n->get('dashboard adminsGroupId field label'), - hoverHelp=>$i18n->get('dashboard adminsGroupId description'), - }, - - usersGroupId => { - fieldType => "group", - defaultValue => '2', - label => $i18n->get('dashboard usersGroupId field label'), - hoverHelp => $i18n->get('dashboard usersGroupId description'), - }, - - isInitialized => { - fieldType => "yesNo", - defaultValue => 0, - noFormPost => 1, - autoGenerate => 0, - }, - - assetsToHide => { - defaultValue => undef, - fieldType => "checkList", - autoGenerate => 0, - }, ); push(@{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'dashboard.gif', - tableName => 'Dashboard', className => 'WebGUI::Asset::Wobject::Dashboard', properties => \%properties, autoGenerateForms => 1, @@ -138,7 +155,7 @@ then return default locations. sub getContentPositions { my $self = shift; - my $dummy = $self->initialize unless $self->get("isInitialized"); + my $dummy = $self->initialize unless $self->isInitialized; my $u = WebGUI::User->new($self->session, $self->discernUserId); return $u->profileField($self->getContentPositionsId) || $self->getContentPositionsDefault; @@ -169,7 +186,7 @@ Returns the default content positions for this Dashboard. sub getContentPositionsDefault { my $self = shift; - my $dummy = $self->initialize unless $self->get("isInitialized"); + my $dummy = $self->initialize unless $self->isInitialized; # The default positions are saved under the "Visitor" user my $u = WebGUI::User->new($self->session, 1); return $u->profileField($self->getContentPositionsId); @@ -177,38 +194,6 @@ sub getContentPositionsDefault { #------------------------------------------------------------------- -=head2 getEditForm - -Extend the base method to display lists of assets to hide or show. - -=cut - -sub getEditForm { - my $self = shift; - my $tabform = $self->SUPER::getEditForm; - my $i18n = WebGUI::International->new($self->session, "Asset_Dashboard"); - if ($self->session->form->process("func") ne "add") { - my @assetsToHide = split("\n",$self->getValue("assetsToHide")); - my $children = $self->getLineage(["children"],{"returnObjects"=>1, excludeClasses=>["WebGUI::Asset::Wobject::Layout"]}); - my %childIds; - foreach my $child (@{$children}) { - $childIds{$child->getId} = $child->getTitle.' ['.ref($child).']'; - } - $tabform->getTab("display")->checkList( - -name=>"assetsToHide", - -value=>\@assetsToHide, - -options=>\%childIds, - -label=>$i18n->get('assets to hide'), - -hoverHelp=>$i18n->get('assets to hide description'), - -vertical=>1, - -uiLevel=>9 - ); - } - return $tabform; -} - -#------------------------------------------------------------------- - =head2 initialize Add the unique profile field that holds content positions for this dashboard. @@ -256,7 +241,7 @@ sub prepareView { my $self = shift; $self->SUPER::prepareView; my $children = $self->getLineage( ["children"], { returnObjects=>1, excludeClasses=>["WebGUI::Asset::Wobject::Layout","WebGUI::Asset::Wobject::Dashboard"] }); - my @hidden = split("\n",$self->get("assetsToHide")); + my @hidden = split("\n",$self->assetsToHide); foreach my $child (@{$children}) { unless (isIn($child->getId, @hidden) || !($child->canView)) { $self->session->style->setRawHeadTags($child->getExtraHeadTags); @@ -280,7 +265,7 @@ sub processPropertiesFromFormPost { if ($self->session->form->process("assetId") eq "new" && $self->session->form->process("class") eq 'WebGUI::Asset::Wobject::Dashboard') { $self->initialize; if (ref $self->getParent eq 'WebGUI::Asset::Wobject::Layout') { - $self->getParent->update({assetsToHide=>$self->getParent->get("assetsToHide")."\n".$self->getId}); + $self->getParent->update({assetsToHide=>$self->getParent->assetsToHide."\n".$self->getId}); } $self->update({styleTemplateId=>'PBtmplBlankStyle000001'}); } @@ -322,24 +307,24 @@ sub view { { type=>'text/javascript' } ); - my $templateId = $self->get("templateId"); + my $templateId = $self->templateId; my $children = $self->getLineage( ["children"], { returnObjects=>1, excludeClasses=>["WebGUI::Asset::Wobject::Layout","WebGUI::Asset::Wobject::Dashboard"] }); # I'm sure there's a more efficient way to do this. We'll figure it out someday. my @positions = split(/\./,$self->getContentPositions); - my @hidden = split("\n",$self->get("assetsToHide")); + my @hidden = split("\n",$self->assetsToHide); foreach my $child (@{$children}) { - push(@hidden,$child->get('shortcutToAssetId')) if ref $child eq 'WebGUI::Asset::Shortcut'; + push(@hidden,$child->shortcutToAssetId) if ref $child eq 'WebGUI::Asset::Shortcut'; #the following loop will initially place just-dashletted assets. for (my $i = 0; $i < scalar(@positions); $i++) { - next unless isIn($child->get('shortcutToAssetId'),@hidden); + next unless isIn($child->shortcutToAssetId,@hidden); my $newChildId = $child->getId; - my $oldChildId = $child->get('shortcutToAssetId'); + my $oldChildId = $child->shortcutToAssetId; $positions[$i] =~ s/${oldChildId}/${newChildId}/g; } } my $i = 1; - my $templateAsset = WebGUI::Asset->newByDynamicClass($self->session, $templateId) || WebGUI::Asset->getImportNode($self->session); - my $template = $templateAsset->get("template"); + my $templateAsset = WebGUI::Asset->newById($self->session, $templateId) || WebGUI::Asset->getImportNode($self->session); + my $template = $templateAsset->template; my $numPositions = 1; foreach my $j (2..15) { $numPositions = $j if $template =~ m/position${j}\_loop/; @@ -393,7 +378,7 @@ sub view { foreach my $child (@{$children}) { unless (isIn($child->getId, @found)||isIn($child->getId,@hidden)) { if ($child->canView) { - $child->{_properties}{title} = $child->getShortcut->get("title") if (ref $child eq 'WebGUI::Asset::Shortcut'); + $child->{_properties}{title} = $child->getShortcut->title if (ref $child eq 'WebGUI::Asset::Shortcut'); push(@{$vars{"position1_loop"}},{ id=>$child->getId, content=>'', @@ -430,8 +415,8 @@ sub www_setContentPositions { my $self = shift; return 'Visitors cannot save settings' if($self->session->user->isVisitor); return $self->session->privilege->insufficient() unless ($self->canPersonalize); - return 'empty' unless $self->get("isInitialized"); - my $dummy = $self->initialize unless $self->get("isInitialized"); + return 'empty' unless $self->isInitialized; + my $dummy = $self->initialize unless $self->isInitialized; my $u = WebGUI::User->new($self->session, $self->discernUserId); my $success = $u->profileField($self->getContentPositionsId,$self->session->form->process("map")) eq $self->session->form->process("map"); return "Map set: ".$self->session->form->process("map") if $success; @@ -449,12 +434,12 @@ Renders self->view based upon current style, subject to timeouts. Returns Privil sub www_view { my $self = shift; unless ($self->canView) { - if ($self->get("state") eq "published") { # no privileges, make em log in + if ($self->state eq "published") { # no privileges, make em log in return $self->session->privilege->noAccess(); - } elsif ($self->session->var->isAdminOn && $self->get("state") =~ /^trash/) { # show em trash + } elsif ($self->session->var->isAdminOn && $self->state =~ /^trash/) { # show em trash $self->session->http->setRedirect($self->getUrl("func=manageTrash")); return undef; - } elsif ($self->session->var->isAdminOn && $self->get("state") =~ /^clipboard/) { # show em clipboard + } elsif ($self->session->var->isAdminOn && $self->state =~ /^clipboard/) { # show em clipboard $self->session->http->setRedirect($self->getUrl("func=manageClipboard")); return undef; } else { # tell em it doesn't exist anymore diff --git a/lib/WebGUI/Asset/Wobject/DataForm.pm b/lib/WebGUI/Asset/Wobject/DataForm.pm index 79aeffdf6..42e3f13a3 100644 --- a/lib/WebGUI/Asset/Wobject/DataForm.pm +++ b/lib/WebGUI/Asset/Wobject/DataForm.pm @@ -23,16 +23,205 @@ use WebGUI::Mail::Send; use WebGUI::Macro; use WebGUI::Inbox; use WebGUI::SQL; -use WebGUI::Asset::Wobject; +use JSON (); + +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; + +aspect assetName => ['assetName', 'Asset_DataForm']; +aspect uiLevel => 5; +aspect tableName => 'DataForm'; +aspect icon => 'dataForm.gif'; +property templateId => ( + fieldType => 'template', + default => 'PBtmpl0000000000000141', + namespace => 'DataForm', + tab => 'display', + label => [82, 'Asset_DataForm'], + hoverHelp => ['82 description', 'Asset_DataForm'], + afterEdit => 'func=edit', + ); +property htmlAreaRichEditor => ( + fieldType => "selectBox", + default => 0, + options => \&_htmlAreaRichEditor_options, + tab => 'display', + label => ['htmlAreaRichEditor', 'Asset_DataForm'], + hoverHelp => ['htmlAreaRichEditor description', 'Asset_DataForm'], + ); +sub _htmlAreaRichEditor_options { + my $self = shift; + my $session = $self->session; + my $i18n = WebGUI::International->new($session, 'Asset_DataForm'); + my $selectRichEditor = WebGUI::Form::SelectRichEditor->new($session,{}); + my $richEditorOptions = $selectRichEditor->getOptions(); + $richEditorOptions->{'**Use_Default_Editor**'} = $i18n->get("Use Default Rich Editor"); + return $richEditorOptions; +} + # populate hash of Rich Editors and add an entry to the list to use the default +property emailTemplateId => ( + fieldType => "template", + default => 'PBtmpl0000000000000085', + namespace => 'DataForm', + tab => 'display', + label => ['80', 'Asset_DataForm'], + hoverHelp => ['80 description', 'Asset_DataForm'], + afterEdit => 'func=edit', + ); +property acknowlegementTemplateId => ( + fieldType => "template", + default => 'PBtmpl0000000000000104', + namespace => 'DataForm', + tab => 'display', + label => ['81', 'Asset_DataForm'], + hoverHelp => ['81 description', 'Asset_DataForm'], + afterEdit => 'func=edit', + ); +property listTemplateId => ( + fieldType => "template", + default => 'PBtmpl0000000000000021', + namespace => 'DataForm/List', + tab => 'display', + label => ['87', 'Asset_DataForm'], + hoverHelp => ['87 description', 'Asset_DataForm'], + afterEdit => 'func=edit', + ); +property defaultView => ( + fieldType => "radioList", + default => 0, + options => \&_defaultView_options, + label => ['defaultView', 'Asset_DataForm'], + hoverHelp => ['defaultView description', 'Asset_DataForm'], + tab => 'display', + ); +sub _defaultView_options { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_DataForm'); + return { + 0 => $i18n->get('data form'), + 1 => $i18n->get('data list'), + }; +} +property acknowledgement => ( + fieldType => "HTMLArea", + default => undef, + tab => 'properties', + label => ['16', 'Asset_DataForm'], + hoverHelp => ['16 description', 'Asset_DataForm'], + ); +property mailData => ( + fieldType => "yesNo", + default => 0, + tab => 'display', + label => ['74', 'Asset_DataForm'], + hoverHelp => ['74 description', 'Asset_DataForm'], + ); +property storeData => ( + fieldType => "yesNo", + default => 1, + tab => 'display', + label => ['store data', 'Asset_DataForm'], + hoverHelp => ['store data description', 'Asset_DataForm'], + ); +property mailAttachments => ( + fieldType => 'yesNo', + default => 0, + tab => 'properties', + label => ["mail attachments", 'Asset_DataForm'], + hoverHelp => ["mail attachments description", 'Asset_DataForm'], + ); +property groupToViewEntries => ( + fieldType => "group", + default => 7, + tab => 'security', + label => ['group to view entries', 'Asset_DataForm'], + hoverHelp => ['group to view entries description', 'Asset_DataForm'], + ); +property useCaptcha => ( + tab => 'properties', + fieldType => "yesNo", + default => 0, + label => ['editForm useCaptcha label', 'Asset_DataForm'], + hoverHelp => ['editForm useCaptcha description', 'Asset_DataForm'], + ); +property workflowIdAddEntry => ( + tab => "properties", + fieldType => "workflow", + default => undef, + type => "WebGUI::AssetCollateral::DataForm::Entry", + none => 1, + label => ['editForm workflowIdAddEntry label', 'Asset_DataForm'], + hoverHelp => ['editForm workflowIdAddEntry description', 'Asset_DataForm'], + ); +property fieldConfiguration => ( + fieldType => 'hidden', + noFormPost => 1, + builder => '_fieldConfiguration_builder', + lazy => 1, + ); +sub _fieldConfiguration_builder { + my $self = shift; + my $session = $self->session; + my $i18n = WebGUI::International->new($session,"Asset_DataForm"); + my @defFieldConfig = ( + { + name=>"from", + label=>$i18n->get(10), + status=>"editable", + isMailField=>1, + width=>0, + type=>"email", + }, + { + name=>"to", + label=>$i18n->get(11), + status=>"hidden", + isMailField=>1, + width=>0, + type=>"email", + defaultValue=>$session->setting->get("companyEmail"), + }, + { + name=>"cc", + label=>$i18n->get(12), + status=>"hidden", + isMailField=>1, + width=>0, + type=>"email", + }, + { + name=>"bcc", + label=>$i18n->get(13), + status=>"hidden", + isMailField=>1, + width=>0, + type=>"email", + }, + { + name=>"subject", + label=>$i18n->get(14), + status=>"editable", + isMailField=>1, + width=>0, + type=>"text", + defaultValue=>$i18n->get(2), + }, + ); + my $json = JSON::to_json(\@defFieldConfig); + return $json; +} +property tabConfiguration => ( + fieldType => 'hidden', + noFormPost => 1, + ); + use WebGUI::Pluggable; use WebGUI::DateTime; use WebGUI::User; use WebGUI::Group; use WebGUI::AssetCollateral::DataForm::Entry; use WebGUI::Form::SelectRichEditor; -use JSON (); -our @ISA = qw(WebGUI::Asset::Wobject); =head1 NAME @@ -87,11 +276,11 @@ sub _fieldAdminIcons { my $fieldName = shift; my $i18n = WebGUI::International->new($self->session,"Asset_DataForm"); my $output; - $output = $self->session->icon->delete('func=deleteFieldConfirm;fieldName='.$fieldName,$self->get("url"),$i18n->get(19)) + $output = $self->session->icon->delete('func=deleteFieldConfirm;fieldName='.$fieldName,$self->url,$i18n->get(19)) unless $self->getFieldConfig($fieldName)->{isMailField}; - $output .= $self->session->icon->edit('func=editField;fieldName='.$fieldName,$self->get("url")) - . $self->session->icon->moveUp('func=moveFieldUp;fieldName='.$fieldName,$self->get("url")) - . $self->session->icon->moveDown('func=moveFieldDown;fieldName='.$fieldName,$self->get("url")); + $output .= $self->session->icon->edit('func=editField;fieldName='.$fieldName,$self->url) + . $self->session->icon->moveUp('func=moveFieldUp;fieldName='.$fieldName,$self->url) + . $self->session->icon->moveDown('func=moveFieldDown;fieldName='.$fieldName,$self->url); return $output; } #------------------------------------------------------------------- @@ -100,10 +289,10 @@ sub _tabAdminIcons { my $tabId = shift; my $i18n = WebGUI::International->new($self->session,"Asset_DataForm"); my $output - = $self->session->icon->delete('func=deleteTabConfirm;tabId='.$tabId,$self->get("url"),$i18n->get(100)) - . $self->session->icon->edit('func=editTab;tabId='.$tabId,$self->get("url")) - . $self->session->icon->moveLeft('func=moveTabLeft;tabId='.$tabId,$self->get("url")) - . $self->session->icon->moveRight('func=moveTabRight;tabId='.$tabId,$self->get("url")); + = $self->session->icon->delete('func=deleteTabConfirm;tabId='.$tabId,$self->url,$i18n->get(100)) + . $self->session->icon->edit('func=editTab;tabId='.$tabId,$self->url) + . $self->session->icon->moveLeft('func=moveTabLeft;tabId='.$tabId,$self->url) + . $self->session->icon->moveRight('func=moveTabRight;tabId='.$tabId,$self->url); return $output; } @@ -125,7 +314,7 @@ Returns true if defaultView is set to 0. sub defaultViewForm { my $self = shift; - return ($self->get("defaultView") == 0); + return ($self->defaultView == 0); } #------------------------------------------------------------------- @@ -137,9 +326,9 @@ it returns 'list'. =cut -sub defaultView { +sub defaultViewName { my $self = shift; - return ($self->get("defaultView") == 0 ? 'form' : 'list'); + return ($self->defaultViewForm ? 'form' : 'list'); } #------------------------------------------------------------------- @@ -153,7 +342,7 @@ cached mode, then it checks for a C form parameter, then it resorts to def sub currentView { my $self = shift; - my $view = $self->{_mode} || $self->session->form->param('mode') || $self->defaultView; + my $view = $self->{_mode} || $self->session->form->param('mode') || $self->defaultViewName; return $view; } @@ -287,206 +476,10 @@ sub _saveTabConfig { #------------------------------------------------------------------- -=head2 definition ( session, [definition] ) - -Returns an array reference of definitions. Adds tableName, className, properties to array definition. - -=head3 definition - -An array of hashes to prepend to the list - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_DataForm"); - my %properties; - - # populate hash of Rich Editors and add an entry to the list to use the default - my $selectRichEditor = WebGUI::Form::SelectRichEditor->new($session,{}) ; - my $richEditorOptions = $selectRichEditor->getOptions() ; - $richEditorOptions->{'**Use_Default_Editor**'} = $i18n->get("Use Default Rich Editor"); - - tie %properties, 'Tie::IxHash'; - %properties = ( - templateId => { - fieldType => 'template', - defaultValue => 'PBtmpl0000000000000141', - namespace => 'DataForm', - tab => 'display', - label => $i18n->get(82), - hoverHelp => $i18n->get('82 description'), - afterEdit => 'func=edit', - }, - htmlAreaRichEditor =>{ - fieldType=>"selectBox", - defaultValue=>0, - options=>$richEditorOptions, - tab=>'display', - label=>$i18n->get('htmlAreaRichEditor'), - hoverHelp=>$i18n->get('htmlAreaRichEditor description'), - }, - emailTemplateId => { - fieldType => "template", - defaultValue => 'PBtmpl0000000000000085', - namespace => 'DataForm', - tab => 'display', - label => $i18n->get(80), - hoverHelp => $i18n->get('80 description'), - afterEdit => 'func=edit', - }, - acknowlegementTemplateId => { - fieldType => "template", - defaultValue => 'PBtmpl0000000000000104', - namespace => 'DataForm', - tab => 'display', - label => $i18n->get(81), - hoverHelp => $i18n->get('81 description'), - afterEdit => 'func=edit', - }, - listTemplateId => { - fieldType => "template", - defaultValue => 'PBtmpl0000000000000021', - namespace => 'DataForm/List', - tab => 'display', - label => $i18n->get(87), - hoverHelp => $i18n->get('87 description'), - afterEdit => 'func=edit', - }, - defaultView => { - fieldType => "radioList", - defaultValue => 0, - options => { - 0 => $i18n->get('data form'), - 1 => $i18n->get('data list'), - }, - label => $i18n->get('defaultView'), - hoverHelp => $i18n->get('defaultView description'), - tab => 'display', - }, - acknowledgement => { - fieldType => "HTMLArea", - defaultValue => undef, - tab => 'properties', - label => $i18n->get(16), - hoverHelp => $i18n->get('16 description'), - }, - mailData => { - fieldType => "yesNo", - defaultValue => 0, - tab => 'display', - label => $i18n->get(74), - hoverHelp => $i18n->get('74 description'), - }, - storeData => { - fieldType => "yesNo", - defaultValue => 1, - tab => 'display', - label => $i18n->get('store data'), - hoverHelp => $i18n->get('store data description'), - }, - mailAttachments => { - fieldType => 'yesNo', - defaultValue => 0, - tab => 'properties', - label => $i18n->get("mail attachments"), - hoverHelp => $i18n->get("mail attachments description"), - }, - groupToViewEntries => { - fieldType => "group", - defaultValue => 7, - tab => 'security', - label => $i18n->get('group to view entries'), - hoverHelp => $i18n->get('group to view entries description'), - }, - useCaptcha => { - tab => 'properties', - fieldType => "yesNo", - defaultValue => 0, - label => $i18n->get('editForm useCaptcha label'), - hoverHelp => $i18n->get('editForm useCaptcha description'), - }, - workflowIdAddEntry => { - tab => "properties", - fieldType => "workflow", - defaultValue => undef, - type => "WebGUI::AssetCollateral::DataForm::Entry", - none => 1, - label => $i18n->get('editForm workflowIdAddEntry label'), - hoverHelp => $i18n->get('editForm workflowIdAddEntry description'), - }, - fieldConfiguration => { - fieldType => 'hidden', - }, - tabConfiguration => { - fieldType => 'hidden', - }, - ); - my @defFieldConfig = ( - { - name=>"from", - label=>$i18n->get(10), - status=>"editable", - isMailField=>1, - width=>0, - type=>"email", - }, - { - name=>"to", - label=>$i18n->get(11), - status=>"hidden", - isMailField=>1, - width=>0, - type=>"email", - defaultValue=>$session->setting->get("companyEmail"), - }, - { - name=>"cc", - label=>$i18n->get(12), - status=>"hidden", - isMailField=>1, - width=>0, - type=>"email", - }, - { - name=>"bcc", - label=>$i18n->get(13), - status=>"hidden", - isMailField=>1, - width=>0, - type=>"email", - }, - { - name=>"subject", - label=>$i18n->get(14), - status=>"editable", - isMailField=>1, - width=>0, - type=>"text", - defaultValue=>$i18n->get(2), - }, - ); - $properties{fieldConfiguration}{defaultValue} = JSON::to_json(\@defFieldConfig); - push @$definition, { - assetName => $i18n->get('assetName'), - uiLevel => 5, - tableName => 'DataForm', - icon => 'dataForm.gif', - className => __PACKAGE__, - properties => \%properties, - autoGenerateForms => 1, - }; - return $class->SUPER::definition($session, $definition); -} - -#------------------------------------------------------------------- - sub _cacheFieldConfig { my $self = shift; if (!$self->{_fieldConfig}) { - my $jsonData = $self->get("fieldConfiguration"); + my $jsonData = $self->fieldConfiguration; my $fieldData; if ($jsonData && eval { $jsonData = JSON::from_json($jsonData) ; 1 }) { # jsonData is an array in the order the fields should be @@ -511,7 +504,7 @@ sub _cacheFieldConfig { sub _cacheTabConfig { my $self = shift; if (!$self->{_tabConfig}) { - my $jsonData = $self->get("tabConfiguration"); + my $jsonData = $self->tabConfiguration; my $fieldData; if ($jsonData && eval { $jsonData = JSON::from_json($jsonData) ; 1 }) { # jsonData is an array in the order the fields should be @@ -732,9 +725,9 @@ sub getListTemplateVars { %dataVars, "record.ipAddress" => $entry->ipAddress, "record.edit.url" => $self->getFormUrl("func=view;entryId=".$entry->getId), - "record.edit.icon" => $self->session->icon->edit("func=view;entryId=".$entry->getId, $self->get('url')), + "record.edit.icon" => $self->session->icon->edit("func=view;entryId=".$entry->getId, $self->url), "record.delete.url" => $self->getUrl("func=deleteEntry;entryId=".$entry->getId), - "record.delete.icon" => $self->session->icon->delete("func=deleteEntry;entryId=".$entry->getId, $self->get('url'), $i18n->get('Delete entry confirmation')), + "record.delete.icon" => $self->session->icon->delete("func=deleteEntry;entryId=".$entry->getId, $self->url, $i18n->get('Delete entry confirmation')), "record.username" => $entry->username, "record.userId" => $entry->userId, "record.submissionDate.epoch" => $entry->submissionDate->epoch, @@ -882,11 +875,11 @@ sub getRecordTemplateVars { } my $hidden = ($field->{status} eq 'hidden' && !$session->var->isAdminOn) - || ($field->{isMailField} && !$self->get('mailData')); - + || ($field->{isMailField} && !$self->mailData); + # populate Rich Editor field if the field is an HTMLArea if ($field->{type} eq "HTMLArea") { - $field->{htmlAreaRichEditor} = $self->get("htmlAreaRichEditor") ; + $field->{htmlAreaRichEditor} = $self->htmlAreaRichEditor ; } my $form = $self->_createForm($field, $value); $value = $form->getValueAsHtml; @@ -923,7 +916,7 @@ sub getRecordTemplateVars { $var->{'form.send'} = WebGUI::Form::submit($session, { value => $i18n->get(73) }); $var->{'form.save'} = WebGUI::Form::submit($session); # Create CAPTCHA if configured and user is not a Registered User - if ( $self->useCaptcha ) { + if ( $self->shouldUseCaptcha ) { # Create one captcha we can use multiple times $var->{ 'form_captcha' } = WebGUI::Form::Captcha( $session, { name => 'captcha', @@ -951,9 +944,9 @@ sub getTemplateVars { my $var = $self->get; my $i18n = WebGUI::International->new($self->session,"Asset_DataForm"); - $var->{'useCaptcha' } = ( $self->useCaptcha ? 1 : 0 ); + $var->{'useCaptcha' } = ( $self->shouldUseCaptcha ? 1 : 0 ); $var->{'canEdit' } = ($self->canEdit); - $var->{'canViewEntries' } = ($self->session->user->isInGroup($self->get("groupToViewEntries"))); + $var->{'canViewEntries' } = ($self->session->user->isInGroup($self->groupToViewEntries)); $var->{'hasEntries' } = $self->hasEntries; $var->{'entryList.url' } = $self->getListUrl; $var->{'entryList.label' } = $i18n->get(86); @@ -1049,9 +1042,9 @@ sub sendEmail { my $from = $entry->field('from'); my $bcc = $entry->field('bcc'); my $cc = $entry->field('cc'); - my $message = $self->processTemplate($var, $self->get("emailTemplateId")); + my $message = $self->processTemplate($var, $self->emailTemplateId); WebGUI::Macro::process($self->session,\$message); - my @attachments = $self->get('mailAttachments') + my @attachments = $self->mailAttachments ? @{ $self->getAttachedFiles($entry) } : (); if ($to =~ /\@/) { @@ -1108,7 +1101,7 @@ sub sendEmail { #---------------------------------------------------------------------------- -=head2 useCaptcha ( ) +=head2 shouldUseCaptcha ( ) Returns true if we should use and process the CAPTCHA. @@ -1117,10 +1110,10 @@ user is not a Registered User. =cut -sub useCaptcha { +sub shouldUseCaptcha { my $self = shift; - if ( $self->get('useCaptcha') && $self->session->user->isVisitor ) { + if ( $self->useCaptcha && $self->session->user->isVisitor ) { return 1; } @@ -1163,7 +1156,7 @@ sub canView { return 1 if $self->canEdit; return 1 - if $self->session->user->isInGroup($self->get('groupToViewEntries')); + if $self->session->user->isInGroup($self->groupToViewEntries); return 0; } return 1; @@ -1179,7 +1172,7 @@ Like prepareView, but for the list view of the template. sub prepareViewList { my $self = shift; - my $templateId = $self->get('listTemplateId'); + my $templateId = $self->listTemplateId; my $template = WebGUI::Asset::Template->new($self->session, $templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( @@ -1218,7 +1211,7 @@ sub prepareViewForm { my $self = shift; $self->session->style->setLink($self->session->url->extras('tabs/tabs.css'), {"type"=>"text/css"}); $self->session->style->setScript($self->session->url->extras('tabs/tabs.js'), {"type"=>"text/javascript"}); - my $templateId = $self->get('templateId'); + my $templateId = $self->templateId; my $template = WebGUI::Asset::Template->new($self->session, $templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( @@ -1653,7 +1646,7 @@ sub setField { my $self = shift; my $fieldName = shift; my $field = shift; - + $field->{ name } = $fieldName; my $fieldConfig = $self->getFieldConfig; @@ -1777,7 +1770,7 @@ sub www_exportTab { my @exportFields; for my $field ( map { $self->getFieldConfig($_) } @{$self->getFieldOrder} ) { next - if $field->{isMailField} && !$self->get('mailData'); + if $field->{isMailField} && !$self->mailData; push @exportFields, $field->{name}; } my $tsv = Text::CSV_XS->new({sep_char => "\t", eol => "\n", binary => 1}); @@ -1790,7 +1783,7 @@ sub www_exportTab { @exportFields, ); - $session->http->setFilename($self->get("url").".tab","text/plain"); + $session->http->setFilename($self->url.".tab","text/plain"); $session->http->sendHeader; $session->output->print($tsv->string, 1); @@ -2093,7 +2086,7 @@ sub www_process { } # Process CAPTCHA - if ( $self->useCaptcha && !$session->form->process( 'captcha', 'captcha' ) ) { + if ( $self->shouldUseCaptcha && !$session->form->process( 'captcha', 'captcha' ) ) { push @errors, { "error.message" => $i18n->get( 'error captcha' ), }; @@ -2110,24 +2103,24 @@ sub www_process { } # Send email - if ($self->get("mailData") && !$entryId) { + if ($self->mailData && !$entryId) { $self->sendEmail($var, $entry); } # Save entry to database - if ($self->get('storeData')) { + if ($self->storeData) { $entry->save; } - + # Run the workflow - if ( $self->get("workflowIdAddEntry") ) { + if ( $self->workflowIdAddEntry ) { my $instanceVar = { - workflowId => $self->get( "workflowIdAddEntry" ), + workflowId => $self->workflowIdAddEntry, className => "WebGUI::AssetCollateral::DataForm::Entry", }; # If we've saved the entry, we only need the ID - if ( $self->get( 'storeData' ) ) { + if ( $self->storeData ) { $instanceVar->{ methodName } = "new"; $instanceVar->{ parameters } = $entry->getId; } @@ -2140,7 +2133,7 @@ sub www_process { WebGUI::Workflow::Instance->create( $self->session, $instanceVar )->start; } - return $self->processStyle($self->processTemplate($var,$self->get("acknowlegementTemplateId"))) + return $self->processStyle($self->processTemplate($var,$self->acknowlegementTemplateId)) if $self->defaultViewForm; return ''; } diff --git a/lib/WebGUI/Asset/Wobject/DataTable.pm b/lib/WebGUI/Asset/Wobject/DataTable.pm index 3d6b964f6..593faf5bc 100644 --- a/lib/WebGUI/Asset/Wobject/DataTable.pm +++ b/lib/WebGUI/Asset/Wobject/DataTable.pm @@ -13,51 +13,28 @@ $VERSION = "1.0.0"; #------------------------------------------------------------------- use strict; -use Tie::IxHash; -use WebGUI::International; -use WebGUI::Utility; -use WebGUI::Form::DataTable; -use base 'WebGUI::Asset::Wobject'; - -#------------------------------------------------------------------- - -=head2 definition ( session, definition ) - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new( $session, 'Asset_DataTable' ); - - tie my %properties, 'Tie::IxHash', ( - data => { +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_EMSRibbon']; +aspect icon => 'DataTable.gif'; +aspect tableName => 'DataTable'; +property data => ( fieldType => 'DataTable', - defaultValue => undef, - autoGenerate => 0, - }, - templateId => { + default => undef, + label => '', + ); +property templateId => ( tab => "display", fieldType => "template", namespace => "DataTable", - defaultValue => "3rjnBVJRO6ZSkxlFkYh_ug", - label => $i18n->get("editForm templateId label"), - hoverHelp => $i18n->get("editForm templateId description"), - }, - ); + default => "3rjnBVJRO6ZSkxlFkYh_ug", + label => ["editForm templateId label", 'Asset_DataTable'], + hoverHelp => ["editForm templateId description", 'Asset_DataTable'], + ); - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'DataTable.gif', - autoGenerateForms => 1, - tableName => 'DataTable', - className => 'WebGUI::Asset::Wobject::DataTable', - properties => \%properties, - }; - - return $class->SUPER::definition( $session, $definition ); -} ## end sub definition +use WebGUI::International; +use WebGUI::Utility; +use WebGUI::Form::DataTable; #---------------------------------------------------------------------------- @@ -87,7 +64,7 @@ Get the data as a JSON object with the following structure: sub getDataJson { my $self = shift; - return $self->get("data"); + return $self->data; } #---------------------------------------------------------------------------- @@ -157,7 +134,7 @@ sub getEditForm { WebGUI::Form::DataTable->new( $self->session, { name => "data", - value => $self->get("data"), + value => $self->data, defaultValue => undef, showEdit => 1, } @@ -221,7 +198,7 @@ sub prepareView { my $dt = WebGUI::Form::DataTable->new( $session, { name => $self->getId, - value => $self->get('data'), + value => $self->data, defaultValue => undef, } ); @@ -229,11 +206,11 @@ sub prepareView { $self->{_datatable} = $dt; # Prepare the template - my $template = WebGUI::Asset::Template->new( $session, $self->get("templateId") ); + my $template = WebGUI::Asset::Template->new( $session, $self->templateId ); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("templateId"), + templateId => $self->templateId, assetId => $self->getId, ); } @@ -293,7 +270,7 @@ sub www_ajaxUpdateData { $self->update( { data => $data } ); } - $data ||= $self->get("data"); + $data ||= $self->data; $self->session->http->setMimeType("application/json"); return $data; diff --git a/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm b/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm index b8f1424e4..d0b3ad96c 100644 --- a/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm +++ b/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm @@ -15,7 +15,134 @@ package WebGUI::Asset::Wobject::EventManagementSystem; =cut use strict; -use base 'WebGUI::Asset::Wobject'; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_EventManagementSystem']; +aspect icon => 'ems.gif'; +aspect tableName => 'EventManagementSystem'; +property timezone => ( + fieldType => 'TimeZone', + default => 'America/Chicago', + tab => 'properties', + label => ['time zone', 'Asset_EventManagementSystem'], + hoverHelp => ['time zone help', 'Asset_EventManagementSystem'], + ); +property templateId => ( + fieldType => 'template', + default => '2rC4ErZ3c77OJzJm7O5s3w', + tab => 'display', + label => ['main template', 'Asset_EventManagementSystem'], + hoverHelp => ['main template help', 'Asset_EventManagementSystem'], + namespace => 'EMS', + ); +property scheduleTemplateId => ( + fieldType => 'template', + default => 'S2_LsvVa95OSqc66ITAoig', + tab => 'display', + label => ['schedule template', 'Asset_EventManagementSystem'], + hoverHelp => ['schedule template help', 'Asset_EventManagementSystem'], + namespace => 'EMS', + ); +property scheduleColumnsPerPage => ( + fieldType => 'Integer', + default => '5', + tab => 'display', + label => ['schedule number of columns', 'Asset_EventManagementSystem'], + hoverHelp => ['schedule number of columns help', 'Asset_EventManagementSystem'], + ); +property badgeBuilderTemplateId => ( + fieldType => 'template', + default => 'BMybD3cEnmXVk2wQ_qEsRQ', + tab => 'display', + label => ['badge builder template', 'Asset_EventManagementSystem'], + hoverHelp => ['badge builder template help', 'Asset_EventManagementSystem'], + namespace => 'EMS/BadgeBuilder', + ); +property lookupRegistrantTemplateId => ( + fieldType => 'template', + default => 'OOyMH33plAy6oCj_QWrxtg', + tab => 'display', + label => ['lookup registrant template', 'Asset_EventManagementSystem'], + hoverHelp => ['lookup registrant template help', 'Asset_EventManagementSystem'], + namespace => 'EMS/LookupRegistrant', + ); +property printBadgeTemplateId => ( + fieldType => 'template', + default => 'PsFn7dJt4wMwBa8hiE3hOA', + tab => 'display', + label => ['print badge template', 'Asset_EventManagementSystem'], + hoverHelp => ['print badge template help', 'Asset_EventManagementSystem'], + namespace => 'EMS/PrintBadge', + ); +property printTicketTemplateId => ( + fieldType => 'template', + default => 'yBwydfooiLvhEFawJb0VTQ', + tab => 'display', + label => ['print ticket template', 'Asset_EventManagementSystem'], + hoverHelp => ['print ticket template help', 'Asset_EventManagementSystem'], + namespace => 'EMS/PrintTicket', + ); +property badgeInstructions => ( + fieldType => 'HTMLArea', + builder => '_badgeInstructions_builder', + lazy => 1, + tab => 'properties', + label => ['badge instructions', 'Asset_EventManagementSystem'], + hoverHelp => ['badge instructions help', 'Asset_EventManagementSystem'], + ); +sub _badgeInstructions_builder { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_EventMangementSystem'); + return $i18n->get('default badge instructions'); +} +property ticketInstructions => ( + fieldType => 'HTMLArea', + builder => '_ticketInstructions_builder', + lazy => 1, + tab => 'properties', + label => ['ticket instructions', 'Asset_EventManagementSystem'], + hoverHelp => ['ticket instructions help', 'Asset_EventManagementSystem'], + ); +sub _ticketInstructions_builder { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_EventMangementSystem'); + return $i18n->get('default ticket instructions'); +} +property ribbonInstructions => ( + fieldType => 'HTMLArea', + builder => '_ribbonInstructions_builder', + lazy => 1, + tab => 'properties', + label => ['ribbon instructions', 'Asset_EventManagementSystem'], + hoverHelp => ['ribbon instructions help', 'Asset_EventManagementSystem'], + ); +sub _ribbonInstructions_builder { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_EventMangementSystem'); + return $i18n->get('default ribbon instructions'); +} +property tokenInstructions => ( + fieldType => 'HTMLArea', + builder => '_tokenInstructions_builder', + lazy => 1, + tab => 'properties', + label => ['token instructions', 'Asset_EventManagementSystem'], + hoverHelp => ['token instructions help', 'Asset_EventManagementSystem'], + ); +sub _tokenInstructions_builder { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_EventMangementSystem'); + return $i18n->get('default token instructions'); +} +property registrationStaffGroupId => ( + fieldType => 'group', + default => 3, + tab => 'security', + label => ['registration staff group', 'Asset_EventManagementSystem'], + hoverHelp => ['registration staff group help', 'Asset_EventManagementSystem'], + ); + + use Digest::MD5; use JSON; use Text::CSV_XS; @@ -31,128 +158,9 @@ use WebGUI::HTMLForm; use WebGUI::International; use WebGUI::Utility; use WebGUI::Workflow::Instance; -use Tie::IxHash; use Data::Dumper; -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my %properties; - tie %properties, 'Tie::IxHash'; - my $i18n = WebGUI::International->new($session,'Asset_EventManagementSystem'); - %properties = ( - timezone => { - fieldType => 'TimeZone', - defaultValue => 'America/Chicago', - tab => 'properties', - label => $i18n->get('time zone'), - hoverHelp => $i18n->get('time zone help'), - }, - templateId => { - fieldType => 'template', - defaultValue => '2rC4ErZ3c77OJzJm7O5s3w', - tab => 'display', - label => $i18n->get('main template'), - hoverHelp => $i18n->get('main template help'), - namespace => 'EMS', - }, - scheduleTemplateId => { - fieldType => 'template', - defaultValue => 'S2_LsvVa95OSqc66ITAoig', - tab => 'display', - label => $i18n->get('schedule template'), - hoverHelp => $i18n->get('schedule template help'), - namespace => 'EMS', - }, - scheduleColumnsPerPage => { - fieldType => 'Integer', - defaultValue => '5', - tab => 'display', - label => $i18n->get('schedule number of columns'), - hoverHelp => $i18n->get('schedule number of columns help'), - }, - badgeBuilderTemplateId => { - fieldType => 'template', - defaultValue => 'BMybD3cEnmXVk2wQ_qEsRQ', - tab => 'display', - label => $i18n->get('badge builder template'), - hoverHelp => $i18n->get('badge builder template help'), - namespace => 'EMS/BadgeBuilder', - }, - lookupRegistrantTemplateId => { - fieldType => 'template', - defaultValue => 'OOyMH33plAy6oCj_QWrxtg', - tab => 'display', - label => $i18n->get('lookup registrant template'), - hoverHelp => $i18n->get('lookup registrant template help'), - namespace => 'EMS/LookupRegistrant', - }, - printBadgeTemplateId => { - fieldType => 'template', - defaultValue => 'PsFn7dJt4wMwBa8hiE3hOA', - tab => 'display', - label => $i18n->get('print badge template'), - hoverHelp => $i18n->get('print badge template help'), - namespace => 'EMS/PrintBadge', - }, - printTicketTemplateId => { - fieldType => 'template', - defaultValue => 'yBwydfooiLvhEFawJb0VTQ', - tab => 'display', - label => $i18n->get('print ticket template'), - hoverHelp => $i18n->get('print ticket template help'), - namespace => 'EMS/PrintTicket', - }, - badgeInstructions => { - fieldType => 'HTMLArea', - defaultValue => $i18n->get('default badge instructions'), - tab => 'properties', - label => $i18n->get('badge instructions'), - hoverHelp => $i18n->get('badge instructions help'), - }, - ticketInstructions => { - fieldType => 'HTMLArea', - defaultValue => $i18n->get('default ticket instructions'), - tab => 'properties', - label => $i18n->get('ticket instructions'), - hoverHelp => $i18n->get('ticket instructions help'), - }, - ribbonInstructions => { - fieldType => 'HTMLArea', - defaultValue => $i18n->get('default ribbon instructions'), - tab => 'properties', - label => $i18n->get('ribbon instructions'), - hoverHelp => $i18n->get('ribbon instructions help'), - }, - tokenInstructions => { - fieldType => 'HTMLArea', - defaultValue => $i18n->get('default token instructions'), - tab => 'properties', - label => $i18n->get('token instructions'), - hoverHelp => $i18n->get('token instructions help'), - }, - registrationStaffGroupId => { - fieldType => 'group', - defaultValue => [3], - tab => 'security', - label => $i18n->get('registration staff group'), - hoverHelp => $i18n->get('registration staff group help'), - }, - ); - push(@{$definition}, { - assetName=>$i18n->get('assetName'), - icon=>'ems.gif', - autoGenerateForms=>1, - tableName=>'EventManagementSystem', - className=>'WebGUI::Asset::Wobject::EventManagementSystem', - properties=>\%properties - }); - return $class->SUPER::definition($session,$definition); -} - #------------------------------------------------------------------ =head2 deleteEventMetaField ( id ) @@ -289,8 +297,8 @@ sub getLocations { my %hashDate; my $tickets = $self->getTickets; for my $ticket ( @$tickets ) { - my $name = $ticket->get('location'); - my $date = $ticket->get('startDate'); + my $name = $ticket->location; + my $date = $ticket->startDate; $hash{$name} = 1 if defined $name; # cut off the time from the startDate. $date =~ s/\s*\d+:\d+(:\d+)?// if defined $date; @@ -388,7 +396,7 @@ A WebGUI::User object. Defaults to $session->user. sub isRegistrationStaff { my $self = shift; my $user = shift || $self->session->user; - $user->isInGroup($self->get('registrationStaffGroupId')); + $user->isInGroup($self->registrationStaffGroupId); } #------------------------------------------------------------------- @@ -402,11 +410,11 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("templateId"), + templateId => $self->templateId, assetId => $self->getId, ); } @@ -592,7 +600,7 @@ sub www_buildBadge { $var{otherBadgesInCart} = \@otherBadges; # render - return $self->processStyle($self->processTemplate(\%var,$self->get('badgeBuilderTemplateId'))); + return $self->processStyle($self->processTemplate(\%var,$self->badgeBuilderTemplateId)); } #------------------------------------------------------------------- @@ -894,7 +902,7 @@ sub www_getBadgesAsJson { next BADGE unless $badge->canView; push(@{$results{records}}, { title => $badge->getTitle, - description => $badge->get('description'), + description => $badge->description, price => $badge->getPrice+0, quantityAvailable => $badge->getQuantityAvailable, url => $badge->getUrl, @@ -935,7 +943,7 @@ sub www_getRegistrantAsJson { return "{}" unless (exists $badgeInfo->{badgeAssetId}); my $badge = WebGUI::Asset::Sku::EMSBadge->new($session, $badgeInfo->{badgeAssetId}); $badgeInfo->{title} = $badge->getTitle; - $badgeInfo->{sku} = $badge->get('sku'); + $badgeInfo->{sku} = $badge->sku; $badgeInfo->{assetId} = $badge->getId; $badgeInfo->{hasPurchased} = ($badgeInfo->{purchaseComplete}) ? 1 : 0; @@ -943,16 +951,16 @@ sub www_getRegistrantAsJson { my $existingTickets = $db->read("select ticketAssetId from EMSRegistrantTicket where badgeId=? and purchaseComplete=1",[$badgeId]); while (my ($id) = $existingTickets->array) { my $ticket = WebGUI::Asset::Sku::EMSTicket->new($session, $id); - my $startTime = WebGUI::DateTime->new($ticket->get('startDate'))->set_time_zone($self->get('timezone')); + my $startTime = WebGUI::DateTime->new($ticket->startDate)->set_time_zone($self->timezone); push(@tickets, { title => $ticket->getTitle, - eventNumber => $ticket->get('eventNumber'), + eventNumber => $ticket->eventNumber, hasPurchased => 1, startDate => $startTime->toMysqlTime, - endDate => $ticket->get('endDate'), - location => $ticket->get('location'), + endDate => $ticket->endDate, + location => $ticket->location, assetId => $ticket->getId, - sku => $ticket->get('sku'), + sku => $ticket->sku, }); } @@ -964,7 +972,7 @@ sub www_getRegistrantAsJson { title => $ribbon->getTitle, hasPurchased => 1, assetId => $ribbon->getId, - sku => $ribbon->get('sku'), + sku => $ribbon->sku, }); } @@ -977,7 +985,7 @@ sub www_getRegistrantAsJson { hasPurchased => 1, quantity => $quantity, assetId => $token->getId, - sku => $token->get('sku'), + sku => $token->sku, }); } @@ -990,16 +998,16 @@ sub www_getRegistrantAsJson { my $sku = $item->getSku; # it's a ticket if ($sku->isa('WebGUI::Asset::Sku::EMSTicket')) { - my $startTime = WebGUI::DateTime->new($sku->get('startDate'))->set_time_zone($self->get('timezone')); + my $startTime = WebGUI::DateTime->new($sku->startDate)->set_time_zone($self->timezone); push(@tickets, { title => $sku->getTitle, - eventNumber => $sku->get('eventNumber'), + eventNumber => $sku->eventNumber, itemId => $item->getId, startDate => $startTime->toMysqlTime, - endDate => $sku->get('endDate'), - location => $sku->get('location'), + endDate => $sku->endDate, + location => $sku->location, assetId => $sku->getId, - sku => $sku->get('sku'), + sku => $sku->sku, hasPurchased => 0, price => $sku->getPrice+0, }); @@ -1009,10 +1017,10 @@ sub www_getRegistrantAsJson { push(@tokens, { title => $sku->getTitle, itemId => $item->getId, - quantity => $item->get('quantity'), + quantity => $item->quantity, assetId => $sku->getId, hasPurchased => 0, - sku => $sku->get('sku'), + sku => $sku->sku, price => $sku->getPrice+0 * $item->get('quantity'), }); } @@ -1024,7 +1032,7 @@ sub www_getRegistrantAsJson { itemId => $item->getId, assetId => $sku->getId, hasPurchased => 0, - sku => $sku->get('sku'), + sku => $sku->sku, price => $sku->getPrice+0, }); } @@ -1091,7 +1099,7 @@ sub www_getRegistrantsAsJson { next; } $badgeInfo->{title} = $badge->getTitle; - $badgeInfo->{sku} = $badge->get('sku'); + $badgeInfo->{sku} = $badge->sku; $badgeInfo->{assetId} = $badge->getId; $badgeInfo->{manageUrl} = $self->getUrl('func=manageRegistrant;badgeId='.$badgeInfo->{badgeId}); $badgeInfo->{buildBadgeUrl} = $self->getUrl('func=buildBadge;badgeId='.$badgeInfo->{badgeId}); @@ -1126,7 +1134,7 @@ sub www_getRibbonsAsJson { foreach my $ribbon (@{$self->getRibbons}) { push(@{$results{records}}, { title => $ribbon->getTitle, - description => $ribbon->get('description'), + description => $ribbon->description, price => $ribbon->getPrice+0, url => $ribbon->getUrl, editUrl => $ribbon->getUrl('func=edit'), @@ -1163,7 +1171,7 @@ sub www_getScheduleDataJSON { }); return $emptyRecord unless $self->canView; # the following two are expected to be configurable... - my $locationsPerPage = $self->get('scheduleColumnsPerPage'); + my $locationsPerPage = $self->scheduleColumnsPerPage; my ($db, $form) = $session->quick(qw(db form)); my $locationPageNumber = $form->get('locationPage') || 1; @@ -1282,7 +1290,7 @@ sub www_getTicketsAsJson { elsif ($keywords ne "") { @ids = @{WebGUI::Search->new($session)->search({ keywords => $keywords, - lineage => [$self->get('lineage')], + lineage => [$self->lineage], classes => ['WebGUI::Asset::Sku::EMSTicket'], })->getAssetIds}; } @@ -1299,7 +1307,7 @@ className='WebGUI::Asset::Sku::EMSTicket' and state='published' and revisionDate if (defined $badgeId) { my $assetId = $db->quickScalar("select badgeAssetId from EMSRegistrant where badgeId=?",[$badgeId]); my $badge = WebGUI::Asset->new($session, $assetId, 'WebGUI::Asset::Sku::EMSBadge'); - @badgeGroups = split("\n",$badge->get('relatedBadgeGroups')) if (defined $badge); + @badgeGroups = split("\n",$badge->relatedBadgeGroups) if (defined $badge); } # get a list of tickets already associated with the badge @@ -1333,8 +1341,8 @@ className='WebGUI::Asset::Sku::EMSTicket' and state='published' and revisionDate } # skip tickets not in our badge's badge groups - if ($badgeId ne "" && scalar(@badgeGroups) > 0 && $ticket->get('relatedBadgeGroups') ne '') { # skip check if it has no badge groups - my @groups = split("\n",$ticket->get('relatedBadgeGroups')); + if ($badgeId ne "" && scalar(@badgeGroups) > 0 && $ticket->relatedBadgeGroups ne '') { # skip check if it has no badge groups + my @groups = split("\n",$ticket->relatedBadgeGroups); my $found = 0; BADGE: { foreach my $a (@badgeGroups) { @@ -1357,8 +1365,8 @@ className='WebGUI::Asset::Sku::EMSTicket' and state='published' and revisionDate next unless ($counter >= ($startIndex * $numberOfResults)); # publish the data for this ticket - my $description = $ticket->get('description'); - my $data = $ticket->get('eventMetaData'); + my $description = $ticket->description; + my $data = $ticket->eventMetaData; $data = '{}' if ($data eq ""); my $meta = JSON->new->decode($data); foreach my $field (@{$self->getEventMetaFields}) { @@ -1367,8 +1375,8 @@ className='WebGUI::Asset::Sku::EMSTicket' and state='published' and revisionDate $description .= '

    '.$label.': '.$meta->{$label}.'

    '; } } - my $date = WebGUI::DateTime->new($session, mysql => $ticket->get('startDate')) - ->set_time_zone($self->get("timezone")) + my $date = WebGUI::DateTime->new($session, mysql => $ticket->startDate) + ->set_time_zone($self->timezone) ->webguiDate("%W %z %Z"); push(@records, { title => $ticket->getTitle, @@ -1379,10 +1387,10 @@ className='WebGUI::Asset::Sku::EMSTicket' and state='published' and revisionDate editUrl => $ticket->getUrl('func=edit'), deleteUrl => $ticket->getUrl('func=delete'), assetId => $ticket->getId, - eventNumber => $ticket->get('eventNumber'), - location => $ticket->get('location'), + eventNumber => $ticket->eventNumber, + location => $ticket->location, startDate => $date, - duration => $ticket->get('duration'), + duration => $ticket->duration, }); last unless (scalar(@records) < $numberOfResults); } @@ -1426,7 +1434,7 @@ sub www_getTokensAsJson { foreach my $token (@{$self->getTokens}) { push(@{$results{records}}, { title => $token->getTitle, - description => $token->get('description'), + description => $token->description, price => $token->getPrice+0, url => $token->getUrl, editUrl => $token->getUrl('func=edit'), @@ -1608,7 +1616,7 @@ $|=1; } $out->print("\tUpdating properties\n",1); $properties{menuTitle} = $properties{title}; - $properties{url} = $self->get("url")."/".$properties{title}; + $properties{url} = $self->url."/".$properties{title}; $event->update(\%properties); $out->print("\tUpdating meta data\n",1); $event->setEventMetaData($metadata); @@ -1654,7 +1662,7 @@ sub www_lookupRegistrant { ); # render the page - return $self->processStyle($self->processTemplate(\%var, $self->get('lookupRegistrantTemplateId'))); + return $self->processStyle($self->processTemplate(\%var, $self->lookupRegistrantTemplateId)); } #------------------------------------------------------------------- @@ -1710,10 +1718,10 @@ sub www_manageEventMetaFields { my %row = %{$row1}; $count++; $output .= "
    ". - $self->session->icon->delete('func=deleteEventMetaField;fieldId='.$row{fieldId},$self->get('url'),$i18n->get('confirm delete event metadata')). - $self->session->icon->edit('func=editEventMetaField;fieldId='.$row{fieldId}, $self->get('url')). - $self->session->icon->moveUp('func=moveEventMetaFieldUp;fieldId='.$row{fieldId}, $self->get('url'),($count == 1)?1:0); - $output .= $self->session->icon->moveDown('func=moveEventMetaFieldDown;fieldId='.$row{fieldId}, $self->get('url'),($count == $number)?1:0). + $self->session->icon->delete('func=deleteEventMetaField;fieldId='.$row{fieldId},$self->url,$i18n->get('confirm delete event metadata')). + $self->session->icon->edit('func=editEventMetaField;fieldId='.$row{fieldId}, $self->url). + $self->session->icon->moveUp('func=moveEventMetaFieldUp;fieldId='.$row{fieldId}, $self->url,($count == 1)?1:0); + $output .= $self->session->icon->moveDown('func=moveEventMetaFieldDown;fieldId='.$row{fieldId}, $self->url,($count == $number)?1:0). " ".$row{label}."
    "; } } @@ -1955,7 +1963,7 @@ sub www_printBadge { my $registrant = $self->getRegistrant($form->get('badgeId')); my $badge = WebGUI::Asset::Sku::EMSBadge->new($session, $registrant->{badgeAssetId}); $registrant->{badgeTitle} = $badge->getTitle; - return $self->processTemplate($registrant,$self->get('printBadgeTemplateId')); + return $self->processTemplate($registrant,$self->printBadgeTemplateId); } #------------------------------------------------------------------- @@ -1974,12 +1982,12 @@ sub www_printTicket { my $registrant = $self->getRegistrant($form->get('badgeId')); my $ticket = WebGUI::Asset::Sku::EMSTicket->new($session, $form->get('ticketAssetId')); $registrant->{ticketTitle} = $ticket->getTitle; - my $startTime = WebGUI::DateTime->new($ticket->get('startDate'))->set_time_zone($self->get('timezone')); + my $startTime = WebGUI::DateTime->new($ticket->startDate)->set_time_zone($self->timezone); $registrant->{ticketStart} = $startTime->strftime('%F %R'); - $registrant->{ticketDuration} = $ticket->get('duration'); - $registrant->{ticketLocation} = $ticket->get('location'); - $registrant->{ticketEventNumber} = $ticket->get('eventNumber'); - return $self->processTemplate($registrant,$self->get('printTicketTemplateId')); + $registrant->{ticketDuration} = $ticket->duration; + $registrant->{ticketLocation} = $ticket->location; + $registrant->{ticketEventNumber} = $ticket->eventNumber; + return $self->processTemplate($registrant,$self->printTicketTemplateId); } @@ -2063,7 +2071,7 @@ sub www_viewSchedule { return $self->session->privilege->insufficient() unless $self->canView; my $db = $self->session->db; my $rowsPerPage = 25; - my $locationsPerPage = $self->get('scheduleColumnsPerPage'); + my $locationsPerPage = $self->scheduleColumnsPerPage; my @columnNames = map { "'col" . $_ . "'" } ( 1..$locationsPerPage ); my $fieldList = join ',', @columnNames; @@ -2078,7 +2086,7 @@ sub www_viewSchedule { dataColumns => $dataColumns, fieldList => $fieldList, dataSourceUrl => $self->getUrl('func=getScheduleDataJSON'), - },$self->get('scheduleTemplateId'))); + },$self->scheduleTemplateId)); } diff --git a/lib/WebGUI/Asset/Wobject/Folder.pm b/lib/WebGUI/Asset/Wobject/Folder.pm index d7d8b1018..9abf7b6fb 100644 --- a/lib/WebGUI/Asset/Wobject/Folder.pm +++ b/lib/WebGUI/Asset/Wobject/Folder.pm @@ -15,10 +15,59 @@ package WebGUI::Asset::Wobject::Folder; =cut use strict; -use WebGUI::Asset::Wobject; -use WebGUI::Utility; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; -our @ISA = qw(WebGUI::Asset::Wobject); +aspect assetName => ["assetName", 'Asset_Folder']; +aspect uiLevel => 5; +aspect icon => 'folder.gif'; +aspect tableName => 'Folder'; + +property visitorCacheTimeout => ( + tab => "display", + fieldType => "interval", + default => 3600, + uiLevel => 8, + label => ["visitor cache timeout", 'Asset_Folder'], + hoverHelp => ["visitor cache timeout help", 'Asset_Folder'], + ); + # TODO: This should probably be a proper "sortBy" with multiple possible fields +property sortAlphabetically => ( + fieldType => "yesNo", + default => 0, + tab => 'display', + label => ['sort alphabetically', 'Asset_Folder'], + hoverHelp => ['sort alphabetically help', 'Asset_Folder'], + ); + +property sortOrder => ( + tab => 'display', + fieldType => "selectBox", + options => \&_sortOrder_options, + default => "ASC", + label => [ "editForm sortOrder label" , 'Asset_Folder'], + hoverHelp => [ "editForm sortOrder description" , 'Asset_Folder'], + ); +sub _sortOrder_options { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_Folder'); + my $optionsSortOrder = { + ASC => $i18n->get( "editForm sortOrder ascending" ), + DESC => $i18n->get( "editForm sortOrder descending" ), + }; + return $optionsSortOrder; +} + +property templateId => ( + fieldType => "template", + default => 'PBtmpl0000000000000078', + namespace => 'Folder', + tab => 'display', + label => ['folder template title', 'Asset_Folder'], + hoverHelp => ['folder template description', 'Asset_Folder'], + ); + +use WebGUI::Utility; =head1 NAME @@ -41,75 +90,6 @@ These methods are available from this class: -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Folder"); - - my %optionsSortOrder = ( - ASC => $i18n->get( "editForm sortOrder ascending" ), - DESC => $i18n->get( "editForm sortOrder descending" ), - ); - - push @{ $definition }, { - assetName => $i18n->get("assetName"), - uiLevel => 5, - icon => 'folder.gif', - tableName => 'Folder', - className => 'WebGUI::Asset::Wobject::Folder', - autoGenerateForms => 1, - properties => { - visitorCacheTimeout => { - tab => "display", - fieldType => "interval", - defaultValue => 3600, - uiLevel => 8, - label => $i18n->get("visitor cache timeout"), - hoverHelp => $i18n->get("visitor cache timeout help"), - }, - # TODO: This should probably be a proper "sortBy" with multiple possible fields - sortAlphabetically => { - fieldType => "yesNo", - defaultValue => 0, - tab => 'display', - label => $i18n->get('sort alphabetically'), - hoverHelp => $i18n->get('sort alphabetically help'), - }, - sortOrder => { - tab => 'display', - fieldType => "selectBox", - options => \%optionsSortOrder, - defaultValue => "ASC", - label => $i18n->get( "editForm sortOrder label" ), - hoverHelp => $i18n->get( "editForm sortOrder description" ), - }, - templateId => { - fieldType => "template", - defaultValue => 'PBtmpl0000000000000078', - namespace => 'Folder', - tab => 'display', - label => $i18n->get('folder template title'), - hoverHelp => $i18n->get('folder template description'), - }, - }, - }; - - return $class->SUPER::definition($session, $definition); -} - #------------------------------------------------------------------- =head2 getContentLastModified @@ -120,7 +100,7 @@ Overridden to check the revision dates of children as well sub getContentLastModified { my $self = shift; - my $mtime = $self->get("revisionDate"); + my $mtime = $self->revisionDate; foreach my $child (@{ $self->getLineage(["children"],{returnObjects=>1}) }) { my $child_mtime = $child->getContentLastModified; $mtime = $child_mtime if ($child_mtime > $mtime); @@ -140,7 +120,7 @@ sub getEditForm { my $self = shift; my $tabform = $self->SUPER::getEditForm(); my $i18n = WebGUI::International->new($self->session,"Asset_Folder"); - if ($self->get("assetId") eq "new") { + if ($self->assetId eq "new") { $tabform->getTab("properties")->whatNext( -options=>{ view=>$i18n->get(823), @@ -184,11 +164,11 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("templateId"), + templateId => $self->templateId, assetId => $self->getId, ); } @@ -234,11 +214,11 @@ sub view { # TODO: Getting the children template vars should be a seperate method. my %rules = ( returnObjects => 1); - if ( $self->get( "sortAlphabetically" ) ) { - $rules{ orderByClause } = "assetData.title " . $self->get( "sortOrder" ); + if ( $self->sortAlphabetically ) { + $rules{ orderByClause } = "assetData.title " . $self->sortOrder; } else { - $rules{ orderByClause } = "asset.lineage " . $self->get( "sortOrder" ); + $rules{ orderByClause } = "asset.lineage " . $self->sortOrder; } my $children = $self->getLineage( ["children"], \%rules); @@ -248,9 +228,9 @@ sub view { push @{ $vars->{ "subfolder_loop" } }, { id => $child->getId, url => $child->getUrl, - title => $child->get("title"), - menuTitle => $child->get("menuTitle"), - synopsis => $child->get("synopsis") || '', + title => $child->title, + menuTitle => $child->menuTitle, + synopsis => $child->synopsis || '', canView => $child->canView(), "icon.small" => $child->getIcon(1), "icon.big" => $child->getIcon, @@ -260,11 +240,11 @@ sub view { my $childVars = { id => $child->getId, canView => $child->canView(), - title => $child->get("title"), - menuTitle => $child->get("menuTitle"), - synopsis => $child->get("synopsis") || '', - size => WebGUI::Utility::formatBytes($child->get("assetSize")), - "date.epoch" => $child->get("revisionDate"), + title => $child->title, + menuTitle => $child->menuTitle, + synopsis => $child->synopsis || '', + size => WebGUI::Utility::formatBytes($child->assetSize), + "date.epoch" => $child->revisionDate, "icon.small" => $child->getIcon(1), "icon.big" => $child->getIcon, type => $child->getName, @@ -291,7 +271,7 @@ sub view { # Update the cache if ($self->session->user->isVisitor) { - eval{$cache->set("view_".$self->getId, $out, $self->get("visitorCacheTimeout"))}; + eval{$cache->set("view_".$self->getId, $out, $self->visitorCacheTimeout)}; } return $out; @@ -308,7 +288,7 @@ See WebGUI::Asset::Wobject::www_view() for details. sub www_view { my $self = shift; - $self->session->http->setCacheControl($self->get("visitorCacheTimeout")) if ($self->session->user->isVisitor); + $self->session->http->setCacheControl($self->visitorCacheTimeout) if ($self->session->user->isVisitor); $self->SUPER::www_view(@_); } diff --git a/lib/WebGUI/Asset/Wobject/Gallery.pm b/lib/WebGUI/Asset/Wobject/Gallery.pm index 8b24fe7d8..36731a359 100644 --- a/lib/WebGUI/Asset/Wobject/Gallery.pm +++ b/lib/WebGUI/Asset/Wobject/Gallery.pm @@ -11,8 +11,319 @@ package WebGUI::Asset::Wobject::Gallery; #------------------------------------------------------------------- use strict; -use Class::C3; -use base qw(WebGUI::AssetAspect::RssFeed WebGUI::Asset::Wobject); +#use Class::C3; +#use base qw(WebGUI::AssetAspect::RssFeed WebGUI::Asset::Wobject); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_Gallery']; +aspect icon => 'photoGallery.gif'; +aspect tableName => 'Gallery', +property groupIdAddComment => ( + tab => "security", + fieldType => "group", + default => 2, # Registered Users + label => ["groupIdAddComment label", 'Asset_Gallery'], + hoverHelp => ["groupIdAddComment description", 'Asset_Gallery'], + ); +property groupIdAddFile => ( + tab => "security", + fieldType => "group", + default => 2, # Registered Users + label => ["groupIdAddFile label", 'Asset_Gallery'], + hoverHelp => ["groupIdAddFile description", 'Asset_Gallery'], + ); +property imageResolutions => ( + tab => "properties", + fieldType => "checkList", + builder => '_imageResolutions_builder', + lazy => 1, + options => \&_imageResolutions_options, + label => ["imageResolutions label", 'Asset_Gallery'], + hoverHelp => ["imageResolutions description", 'Asset_Gallery'], + ); +sub _imageResolutions_builder { + return join("\n", '800', '1024', '1200', '1600', '2880'); +} +sub _imageResolutions_options { + tie my %imageResolutionOptions, 'Tie::IxHash', map { $_ => $_ } qw(600 800 1024 1260 1440 1600 2880); + return \%imageResolutionOptions; +} +property imageViewSize => ( + tab => "properties", + fieldType => "integer", + default => 700, + label => ["imageViewSize label", 'Asset_Gallery'], + hoverHelp => ["imageViewSize description", 'Asset_Gallery'], + ); +property imageThumbnailSize => ( + tab => "properties", + fieldType => "integer", + default => 300, + label => ["imageThumbnailSize label", 'Asset_Gallery'], + hoverHelp => ["imageThumbnailSize description", 'Asset_Gallery'], + ); +property imageDensity => ( + tab => "properties", + fieldType => "selectBox", + options => \&_imageDensity_options, + default => 72, + label => [ "imageDensity label" , 'Asset_Gallery'], + hoverHelp => [ "imageDensity description" , 'Asset_Gallery'], + ); +sub _imageDensity_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_Gallery'); + + tie my %imageDensityOptions, 'Tie::IxHash', ( + 72 => $i18n->get( "imageDensity option web" ), + 300 => $i18n->get( "imageDensity option print" ), + ); + return \%imageDensityOptions; +} +property maxSpacePerUser => ( + tab => "properties", + fieldType => "integer", + default => 0, + label => ["maxSpacePerUser label", 'Asset_Gallery'], + hoverHelp => ["maxSpacePerUser description", 'Asset_Gallery'], + ); +property richEditIdAlbum => ( + tab => "properties", + fieldType => "selectRichEditor", + default => "PBrichedit000000000001", # Content Managers editor + label => ["richEditIdAlbum label", 'Asset_Gallery'], + hoverHelp => ["richEditIdAlbum description", 'Asset_Gallery'], + ); +property richEditIdFile => ( + tab => "properties", + fieldType => "selectRichEditor", + default => "PBrichedit000000000002", # Forum Rich editor + label => ["richEditIdFile label", 'Asset_Gallery'], + hoverHelp => ["richEditIdFile description", 'Asset_Gallery'], + ); +property richEditIdComment => ( + tab => "properties", + fieldType => "selectRichEditor", + default => "PBrichedit000000000002", # Forum Rich Editor + label => ["richEditIdFileComment label", 'Asset_Gallery'], + hoverHelp => ["richEditIdFileComment description", 'Asset_Gallery'], + ); +property templateIdAddArchive => ( + tab => "display", + fieldType => "template", + default => "i0X4Q3tBWUb_thsVbsYz9xQ", + namespace => "GalleryAlbum/AddArchive", + label => ["templateIdAddArchive label", 'Asset_Gallery'], + hoverHelp => ["templateIdAddArchive description", 'Asset_Gallery'], + ); +property templateIdDeleteAlbum => ( + tab => "display", + fieldType => "template", + default => "UTNFeV7B_aSCRmmaFCq4Vw", + namespace => "GalleryAlbum/Delete", + label => ["templateIdDeleteAlbum label", 'Asset_Gallery'], + hoverHelp => ["templateIdDeleteAlbum description", 'Asset_Gallery'], + ); +property templateIdDeleteFile => ( + tab => "display", + fieldType => "template", + default => "zcX-wIUct0S_np14xxOA-A", + namespace => "GalleryFile/Delete", + label => ["templateIdDeleteFile label", 'Asset_Gallery'], + hoverHelp => ["templateIdDeleteFile description", 'Asset_Gallery'], + ); +property templateIdEditAlbum => ( + tab => "display", + fieldType => "template", + default => "6X-7Twabn5KKO_AbgK3PEw", + namespace => "GalleryAlbum/Edit", + label => ["templateIdEditAlbum label", 'Asset_Gallery'], + hoverHelp => ["templateIdEditAlbum description", 'Asset_Gallery'], + ); +property templateIdEditComment => ( + tab => "display", + fieldType => "template", + default => "OxJWQgnGsgyGohP2L3zJPQ", + namespace => "GalleryFile/EditComment", + label => ["templateIdEditComment label", 'Asset_Gallery'], + hoverHelp => ["templateIdEditComment description", 'Asset_Gallery'], + ); +property templateIdEditFile => ( + tab => "display", + fieldType => "template", + default => "7JCTAiu1U_bT9ldr655Blw", + namespace => "GalleryFile/Edit", + label => ["templateIdEditFile label", 'Asset_Gallery'], + hoverHelp => ["templateIdEditFile description", 'Asset_Gallery'], + ); +property templateIdListAlbums => ( + tab => "display", + fieldType => "template", + default => "azCqD0IjdQSlM3ar29k5Sg", + namespace => "Gallery/ListAlbums", + label => ["templateIdListAlbums label", 'Asset_Gallery'], + hoverHelp => ["templateIdListAlbums description", 'Asset_Gallery'], + ); +property templateIdListAlbumsRss => ( + tab => "display", + fieldType => "template", + default => "ilu5BrM-VGaOsec9Lm7M6Q", + namespace => "Gallery/ListAlbumsRss", + label => ["templateIdListAlbumsRss label", 'Asset_Gallery'], + hoverHelp => ["templateIdListAlbumsRss description", 'Asset_Gallery'], + ); +property templateIdListFilesForUser => ( + tab => "display", + fieldType => "template", + default => "OkphOEdaSGTXnFGhK4GT5A", + namespace => "Gallery/ListFilesForUser", + label => ["templateIdListFilesForUser label", 'Asset_Gallery'], + hoverHelp => ["templateIdListFilesForUser description", 'Asset_Gallery'], + ); +property templateIdListFilesForUserRss => ( + tab => "display", + fieldType => "template", + default => "-ANLpoTEP-n4POAdRxCzRw", + namespace => "Gallery/ListFilesForUserRss", + label => ["templateIdListFilesForUserRss label", 'Asset_Gallery'], + hoverHelp => ["templateIdListFilesForUserRss description", 'Asset_Gallery'], + ); +property templateIdMakeShortcut => ( + tab => "display", + fieldType => "template", + default => "m3IbBavqzuKDd2PGGhKPlA", + namespace => "GalleryFile/MakeShortcut", + label => ["templateIdMakeShortcut label", 'Asset_Gallery'], + hoverHelp => ["templateIdMakeShortcut description", 'Asset_Gallery'], + ); +property templateIdSearch => ( + tab => "display", + fieldType => "template", + default => "jME5BEDYVDlBZ8jIQA9-jQ", + namespace => "Gallery/Search", + label => ["templateIdSearch label", 'Asset_Gallery'], + hoverHelp => ["templateIdSearch description", 'Asset_Gallery'], + ); +property templateIdViewSlideshow => ( + tab => "display", + fieldType => "template", + default => "KAMdiUdJykjN02CPHpyZOw", + namespace => "GalleryAlbum/ViewSlideshow", + label => ["templateIdViewSlideshow label", 'Asset_Gallery'], + hoverHelp => ["templateIdViewSlideshow description", 'Asset_Gallery'], + ); +property templateIdViewThumbnails => ( + tab => "display", + fieldType => "template", + default => "q5O62aH4pjUXsrQR3Pq4lw", + namespace => "GalleryAlbum/ViewThumbnails", + label => ["templateIdViewThumbnails label", 'Asset_Gallery'], + hoverHelp => ["templateIdViewThumbnails description", 'Asset_Gallery'], + ); +property templateIdViewAlbum => ( + tab => "display", + fieldType => "template", + default => "05FpjceLYhq4csF1Kww1KQ", + namespace => "GalleryAlbum/View", + label => ["templateIdViewAlbum label", 'Asset_Gallery'], + hoverHelp => ["templateIdViewAlbum description", 'Asset_Gallery'], + ); +property templateIdViewAlbumRss => ( + tab => "display", + fieldType => "template", + default => "mM3bjP_iG9sv5nQb4S17tQ", + namespace => "GalleryAlbum/ViewRss", + label => ["templateIdViewAlbumRss label", 'Asset_Gallery'], + hoverHelp => ["templateIdViewAlbumRss description", 'Asset_Gallery'], + ); +property templateIdViewFile => ( + tab => "display", + fieldType => "template", + default => "TEId5V-jEvUULsZA0wuRuA", + namespace => "GalleryFile/View", + label => ["templateIdViewFile label", 'Asset_Gallery'], + hoverHelp => ["templateIdViewFile description", 'Asset_Gallery'], + ); +property viewDefault => ( + tab => "display", + fieldType => "selectBox", + default => "list", + options => \&_viewDefault_options, + label => ["viewDefault label", 'Asset_Gallery'], + hoverHelp => ["viewDefault description", 'Asset_Gallery'], + ); +sub _viewDefault_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_Gallery'); + tie my %viewDefaultOptions, 'Tie::IxHash', ( + list => $i18n->get("viewDefault option list"), + album => $i18n->get("viewDefault option album"), + ); + return \%viewDefaultOptions; +} +property viewAlbumAssetId => ( + tab => "display", + fieldType => "asset", + class => "WebGUI::Asset::Wobject::GalleryAlbum", + label => ["viewAlbumAssetId label", 'Asset_Gallery'], + hoverHelp => ["viewAlbumAssetId description", 'Asset_Gallery'], + ); +property viewListOrderBy => ( + tab => "display", + fieldType => "selectBox", + default => "lineage", # "Sequence Number" + options => \&_viewListOrderBy_options, + label => ["viewListOrderBy label", 'Asset_Gallery'], + hoverHelp => ["viewListOrderBy description", 'Asset_Gallery'], + ); +sub _viewListOrderBy_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_Gallery'); + + tie my %viewListOrderByOptions, 'Tie::IxHash', ( + creationDate => $i18n->get("viewListOrderBy option creationDate"), + lineage => $i18n->get("viewListOrderBy option lineage"), + revisionDate => $i18n->get("viewListOrderBy option revisionDate"), + title => $i18n->get("viewListOrderBy option title"), + ); + return \%viewListOrderByOptions; + +} +property viewListOrderDirection => ( + tab => "display", + fieldType => "selectBox", + default => "ASC", + options => \&_viewListOrderDirection_options, + label => ["viewListOrderDirection label", 'Asset_Gallery'], + hoverHelp => ["viewListOrderDirection description", 'Asset_Gallery'], + ); +sub _viewListOrderDirection_options { + my $session = shift->session; + my $i18n = WebGUI::International->new($session, 'Asset_Gallery'); + tie my %viewListOrderDirectionOptions, 'Tie::IxHash', ( + ASC => $i18n->get("viewListOrderDirection option asc"), + DESC => $i18n->get("viewListOrderDirection option desc"), + ); + return \%viewListOrderDirectionOptions; +} +property workflowIdCommit => ( + tab => "security", + fieldType => "workflow", + default => "pbworkflow000000000003", # Commit without approval + type => 'WebGUI::VersionTag', + label => ["workflowIdCommit label", 'Asset_Gallery'], + hoverHelp => ["workflowIdCommit description", 'Asset_Gallery'], + ); +property defaultFilesPerPage => ( + tab => 'display', + fieldType => 'integer', + default => 24, + label => [ 'defaultFilesPerPage label' , 'Asset_Gallery'], + hoverHelp => [ 'defaultFilesPerPage description' , 'Asset_Gallery'], + ); + + + use JSON; use Tie::IxHash; use WebGUI::International; @@ -30,319 +341,6 @@ use WebGUI::HTML; =head1 METHODS -#------------------------------------------------------------------- - -=head2 definition ( ) - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session, 'Asset_Gallery'); - - tie my %imageResolutionOptions, 'Tie::IxHash', ( - '640' => '640', - '800' => '800', - '1024' => '1024', - '1260' => '1260', - '1440' => '1440', - '1600' => '1600', - '2880' => '2880', - ); - - tie my %viewDefaultOptions, 'Tie::IxHash', ( - list => $i18n->get("viewDefault option list"), - album => $i18n->get("viewDefault option album"), - ); - - tie my %viewListOrderByOptions, 'Tie::IxHash', ( - creationDate => $i18n->get("viewListOrderBy option creationDate"), - lineage => $i18n->get("viewListOrderBy option lineage"), - revisionDate => $i18n->get("viewListOrderBy option revisionDate"), - title => $i18n->get("viewListOrderBy option title"), - ); - - tie my %viewListOrderDirectionOptions, 'Tie::IxHash', ( - ASC => $i18n->get("viewListOrderDirection option asc"), - DESC => $i18n->get("viewListOrderDirection option desc"), - ); - - tie my %imageDensityOptions, 'Tie::IxHash', ( - 72 => $i18n->get( "imageDensity option web" ), - 300 => $i18n->get( "imageDensity option print" ), - ); - - tie my %properties, 'Tie::IxHash', ( - groupIdAddComment => { - tab => "security", - fieldType => "group", - defaultValue => 2, # Registered Users - label => $i18n->get("groupIdAddComment label"), - hoverHelp => $i18n->get("groupIdAddComment description"), - }, - groupIdAddFile => { - tab => "security", - fieldType => "group", - defaultValue => 2, # Registered Users - label => $i18n->get("groupIdAddFile label"), - hoverHelp => $i18n->get("groupIdAddFile description"), - }, - imageResolutions => { - tab => "properties", - fieldType => "checkList", - defaultValue => join("\n", '800', '1024', '1200', '1600', '2880'), - options => \%imageResolutionOptions, - label => $i18n->get("imageResolutions label"), - hoverHelp => $i18n->get("imageResolutions description"), - }, - imageViewSize => { - tab => "properties", - fieldType => "integer", - defaultValue => 700, - label => $i18n->get("imageViewSize label"), - hoverHelp => $i18n->get("imageViewSize description"), - }, - imageThumbnailSize => { - tab => "properties", - fieldType => "integer", - defaultValue => 300, - label => $i18n->get("imageThumbnailSize label"), - hoverHelp => $i18n->get("imageThumbnailSize description"), - }, - imageDensity => { - tab => "properties", - fieldType => "selectBox", - options => \%imageDensityOptions, - defaultValue => 72, - label => $i18n->get( "imageDensity label" ), - hoverHelp => $i18n->get( "imageDensity description" ), - }, - maxSpacePerUser => { - tab => "properties", - fieldType => "integer", - defaultValue => 0, - label => $i18n->get("maxSpacePerUser label"), - hoverHelp => $i18n->get("maxSpacePerUser description"), - }, - richEditIdAlbum => { - tab => "properties", - fieldType => "selectRichEditor", - defaultValue => "PBrichedit000000000001", # Content Managers editor - label => $i18n->get("richEditIdAlbum label"), - hoverHelp => $i18n->get("richEditIdAlbum description"), - }, - richEditIdFile => { - tab => "properties", - fieldType => "selectRichEditor", - defaultValue => "PBrichedit000000000002", # Forum Rich editor - label => $i18n->get("richEditIdFile label"), - hoverHelp => $i18n->get("richEditIdFile description"), - }, - richEditIdComment => { - tab => "properties", - fieldType => "selectRichEditor", - defaultValue => "PBrichedit000000000002", # Forum Rich Editor - label => $i18n->get("richEditIdFileComment label"), - hoverHelp => $i18n->get("richEditIdFileComment description"), - }, - templateIdAddArchive => { - tab => "display", - fieldType => "template", - defaultValue => "i0X4Q3tBWUb_thsVbsYz9xQ", - namespace => "GalleryAlbum/AddArchive", - label => $i18n->get("templateIdAddArchive label"), - hoverHelp => $i18n->get("templateIdAddArchive description"), - }, - templateIdDeleteAlbum => { - tab => "display", - fieldType => "template", - defaultValue => "UTNFeV7B_aSCRmmaFCq4Vw", - namespace => "GalleryAlbum/Delete", - label => $i18n->get("templateIdDeleteAlbum label"), - hoverHelp => $i18n->get("templateIdDeleteAlbum description"), - }, - templateIdDeleteFile => { - tab => "display", - fieldType => "template", - defaultValue => "zcX-wIUct0S_np14xxOA-A", - namespace => "GalleryFile/Delete", - label => $i18n->get("templateIdDeleteFile label"), - hoverHelp => $i18n->get("templateIdDeleteFile description"), - }, - templateIdEditAlbum => { - tab => "display", - fieldType => "template", - defaultValue => "6X-7Twabn5KKO_AbgK3PEw", - namespace => "GalleryAlbum/Edit", - label => $i18n->get("templateIdEditAlbum label"), - hoverHelp => $i18n->get("templateIdEditAlbum description"), - }, - templateIdEditComment => { - tab => "display", - fieldType => "template", - defaultValue => "OxJWQgnGsgyGohP2L3zJPQ", - namespace => "GalleryFile/EditComment", - label => $i18n->get("templateIdEditComment label"), - hoverHelp => $i18n->get("templateIdEditComment description"), - }, - templateIdEditFile => { - tab => "display", - fieldType => "template", - defaultValue => "7JCTAiu1U_bT9ldr655Blw", - namespace => "GalleryFile/Edit", - label => $i18n->get("templateIdEditFile label"), - hoverHelp => $i18n->get("templateIdEditFile description"), - }, - templateIdListAlbums => { - tab => "display", - fieldType => "template", - defaultValue => "azCqD0IjdQSlM3ar29k5Sg", - namespace => "Gallery/ListAlbums", - label => $i18n->get("templateIdListAlbums label"), - hoverHelp => $i18n->get("templateIdListAlbums description"), - }, - templateIdListAlbumsRss => { - tab => "display", - fieldType => "template", - defaultValue => "ilu5BrM-VGaOsec9Lm7M6Q", - namespace => "Gallery/ListAlbumsRss", - label => $i18n->get("templateIdListAlbumsRss label"), - hoverHelp => $i18n->get("templateIdListAlbumsRss description"), - }, - templateIdListFilesForUser => { - tab => "display", - fieldType => "template", - defaultValue => "OkphOEdaSGTXnFGhK4GT5A", - namespace => "Gallery/ListFilesForUser", - label => $i18n->get("templateIdListFilesForUser label"), - hoverHelp => $i18n->get("templateIdListFilesForUser description"), - }, - templateIdListFilesForUserRss => { - tab => "display", - fieldType => "template", - defaultValue => "-ANLpoTEP-n4POAdRxCzRw", - namespace => "Gallery/ListFilesForUserRss", - label => $i18n->get("templateIdListFilesForUserRss label"), - hoverHelp => $i18n->get("templateIdListFilesForUserRss description"), - }, - templateIdMakeShortcut => { - tab => "display", - fieldType => "template", - defaultValue => "m3IbBavqzuKDd2PGGhKPlA", - namespace => "GalleryFile/MakeShortcut", - label => $i18n->get("templateIdMakeShortcut label"), - hoverHelp => $i18n->get("templateIdMakeShortcut description"), - }, - templateIdSearch => { - tab => "display", - fieldType => "template", - defaultValue => "jME5BEDYVDlBZ8jIQA9-jQ", - namespace => "Gallery/Search", - label => $i18n->get("templateIdSearch label"), - hoverHelp => $i18n->get("templateIdSearch description"), - }, - templateIdViewSlideshow => { - tab => "display", - fieldType => "template", - defaultValue => "KAMdiUdJykjN02CPHpyZOw", - namespace => "GalleryAlbum/ViewSlideshow", - label => $i18n->get("templateIdViewSlideshow label"), - hoverHelp => $i18n->get("templateIdViewSlideshow description"), - }, - templateIdViewThumbnails => { - tab => "display", - fieldType => "template", - defaultValue => "q5O62aH4pjUXsrQR3Pq4lw", - namespace => "GalleryAlbum/ViewThumbnails", - label => $i18n->get("templateIdViewThumbnails label"), - hoverHelp => $i18n->get("templateIdViewThumbnails description"), - }, - templateIdViewAlbum => { - tab => "display", - fieldType => "template", - defaultValue => "05FpjceLYhq4csF1Kww1KQ", - namespace => "GalleryAlbum/View", - label => $i18n->get("templateIdViewAlbum label"), - hoverHelp => $i18n->get("templateIdViewAlbum description"), - }, - templateIdViewAlbumRss => { - tab => "display", - fieldType => "template", - defaultValue => "mM3bjP_iG9sv5nQb4S17tQ", - namespace => "GalleryAlbum/ViewRss", - label => $i18n->get("templateIdViewAlbumRss label"), - hoverHelp => $i18n->get("templateIdViewAlbumRss description"), - }, - templateIdViewFile => { - tab => "display", - fieldType => "template", - defaultValue => "TEId5V-jEvUULsZA0wuRuA", - namespace => "GalleryFile/View", - label => $i18n->get("templateIdViewFile label"), - hoverHelp => $i18n->get("templateIdViewFile description"), - }, - viewDefault => { - tab => "display", - fieldType => "selectBox", - defaultValue => "list", - options => \%viewDefaultOptions, - label => $i18n->get("viewDefault label"), - hoverHelp => $i18n->get("viewDefault description"), - }, - viewAlbumAssetId => { - tab => "display", - fieldType => "asset", - class => "WebGUI::Asset::Wobject::GalleryAlbum", - label => $i18n->get("viewAlbumAssetId label"), - hoverHelp => $i18n->get("viewAlbumAssetId description"), - }, - viewListOrderBy => { - tab => "display", - fieldType => "selectBox", - defaultValue => "lineage", # "Sequence Number" - options => \%viewListOrderByOptions, - label => $i18n->get("viewListOrderBy label"), - hoverHelp => $i18n->get("viewListOrderBy description"), - }, - viewListOrderDirection => { - tab => "display", - fieldType => "selectBox", - defaultValue => "ASC", - options => \%viewListOrderDirectionOptions, - label => $i18n->get("viewListOrderDirection label"), - hoverHelp => $i18n->get("viewListOrderDirection description"), - }, - workflowIdCommit => { - tab => "security", - fieldType => "workflow", - defaultValue => "pbworkflow000000000003", # Commit without approval - type => 'WebGUI::VersionTag', - label => $i18n->get("workflowIdCommit label"), - hoverHelp => $i18n->get("workflowIdCommit description"), - }, - defaultFilesPerPage => { - tab => 'display', - fieldType => 'integer', - defaultValue => 24, - label => $i18n->get( 'defaultFilesPerPage label' ), - hoverHelp => $i18n->get( 'defaultFilesPerPage description' ), - }, - ); - - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'photoGallery.gif', - autoGenerateForms => 1, - tableName => 'Gallery', - className => __PACKAGE__, - properties => \%properties, - }; - - return $class->next::method($session, $definition); -} - #---------------------------------------------------------------------------- =head2 addChild ( properties, [...] ) @@ -363,7 +361,7 @@ sub addChild { if ( !$properties->{className}->isa( $albumClass ) ) { $self->session->errorHandler->security( - "add a ".$properties->{className}." to a ".$self->get("className") + "add a ".$properties->{className}." to a ".$self->className ); return undef; } @@ -476,7 +474,7 @@ sub canAddFile { : $self->session->user ; - return $user->isInGroup( $self->get("groupIdAddFile") ); + return $user->isInGroup( $self->groupIdAddFile ); } #---------------------------------------------------------------------------- @@ -500,7 +498,7 @@ sub canComment { : $self->session->user ; - return $user->isInGroup( $self->get("groupIdAddComment") ); + return $user->isInGroup( $self->groupIdAddComment ); } #---------------------------------------------------------------------------- @@ -534,8 +532,8 @@ sub canEdit { ? WebGUI::User->new( $self->session, $userId ) : $self->session->user ; - - return $user->isInGroup( $self->get("groupIdEdit") ); + + return $user->isInGroup( $self->groupIdEdit ); } } @@ -559,7 +557,7 @@ sub canView { : $self->session->user ; - return $user->isInGroup( $self->get("groupIdView") ); + return $user->isInGroup( $self->groupIdView ); } #---------------------------------------------------------------------------- @@ -578,11 +576,11 @@ is a hash reference with the following keys. sub getAlbumIds { my $self = shift; my $options = shift; - + my $orderBy = $options->{ orderBy } ? $options->{ orderBy } - : $self->get( 'viewListOrderBy' ) - ? join( " ", $self->get( 'viewListOrderBy' ), $self->get( 'viewListOrderDirection' ) ) + : $self->viewListOrderBy + ? join( " ", $self->getviewListOrderBy, $self->viewListOrderDirection ) : "lineage ASC" ; @@ -599,7 +597,7 @@ sub getAlbumIds { ) }; } - + my $assets = $self->getLineage(['descendants'], { includeOnlyClasses => ['WebGUI::Asset::Wobject::GalleryAlbum'], @@ -626,7 +624,7 @@ For more C, see L. sub getAlbumPaginator { my $self = shift; my $options = shift; - + my $perpage = $options->{ perpage } || 20; delete $options->{ perpage }; @@ -687,7 +685,7 @@ assets in this gallery. sub getImageResolutions { my $self = shift; - return [ split /\n/, $self->get("imageResolutions") ]; + return [ split /\n/, $self->imageResolutions ]; } #---------------------------------------------------------------------------- @@ -758,9 +756,9 @@ sub getRssFeedItems { my $p = $self->getAlbumPaginator( { - perpage => $self->get('itemsPerFeed'), + perpage => $self->itemsPerFeed, } ); - + my $var = []; for my $assetId ( @{ $p->getPageData } ) { my $asset = WebGUI::Asset::Wobject::GalleryAlbum->newPending( $self->session, $assetId ); @@ -773,7 +771,7 @@ sub getRssFeedItems { 'author' => WebGUI::User->new($self->session, $asset->{_properties}->{ 'ownerUserId' })->username }; } - + return $var; } @@ -794,7 +792,7 @@ sub getSearchPaginator { my $self = shift; my $rules = shift; - $rules->{ lineage } = [ $self->get("lineage") ]; + $rules->{ lineage } = [ $self->lineage ]; my $search = WebGUI::Search->new( $self->session ); $search->search( $rules ); @@ -816,7 +814,7 @@ classes of files inside of a Gallery. sub getTemplateIdEditFile { my $self = shift; - return $self->get("templateIdEditFile"); + return $self->templateIdEditFile; } #---------------------------------------------------------------------------- @@ -830,7 +828,7 @@ Gets a hash reference of vars common to all templates. sub getTemplateVars { my $self = shift; my $var = $self->get; - + # Add the search form variables $self->appendTemplateVarsSearchForm( $var ); @@ -934,14 +932,14 @@ sub hasSpaceAvailable { my $self = shift; my $spaceWanted = shift; my $userId = shift || $self->session->user->userId; - + # If we don't care, just return - return 1 if ( $self->get( "maxSpacePerUser" ) == 0 ); + return 1 if ( $self->maxSpacePerUser == 0 ); my $db = $self->session->db; # Compile the amount of disk space used - my $maxSpace = $self->get( "maxSpacePerUser" ) * ( 1_024 ** 2 ); # maxSpacePerUser is in MB + my $maxSpace = $self->maxSpacePerUser * ( 1_024 ** 2 ); # maxSpacePerUser is in MB my $spaceUsed = 0; my $fileIds = $self->getLineage( [ 'descendants' ], { @@ -950,9 +948,9 @@ sub hasSpaceAvailable { } ); for my $assetId ( @{ $fileIds } ) { - my $asset = WebGUI::Asset->newByDynamicClass( $self->session, $assetId ); + my $asset = WebGUI::Asset->newById( $self->session, $assetId ); next unless $asset; - $spaceUsed += $asset->get( 'assetSize' ); + $spaceUsed += $asset->assetSize; return 0 if ( $spaceUsed + $spaceWanted >= $maxSpace ); } @@ -973,10 +971,9 @@ sub prepareView { my $self = shift; $self->next::method(); - if ( $self->get("viewDefault") eq "album" && $self->get("viewAlbumAssetId") && $self->get("viewAlbumAssetId") -ne 'PBasset000000000000001') { + if ( $self->viewDefault eq "album" && $self->viewAlbumAssetId && $self->viewAlbumAssetId ne 'PBasset000000000000001') { my $asset - = WebGUI::Asset->newByDynamicClass( $self->session, $self->get("viewAlbumAssetId") ); + = WebGUI::Asset->newById( $self->session, $self->viewAlbumAssetId ); if ($asset) { $asset->prepareView; $self->{_viewAsset} = $asset; @@ -1001,11 +998,11 @@ Prepare the template for listing multiple albums. sub prepareViewListAlbums { my $self = shift; my $template - = WebGUI::Asset::Template->new($self->session, $self->get("templateIdListAlbums")); + = WebGUI::Asset::Template->new($self->session, $self->templateIdListAlbums); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("templateIdListAlbums"), + templateId => $self->templateIdListAlbums, assetId => $self->getId, ); } @@ -1026,7 +1023,7 @@ sub view { my $session = $self->session; my $var = $self->get; - if ( $self->get("viewDefault") eq "album" && $self->{_viewAsset}) { + if ( $self->viewDefault eq "album" && $self->{_viewAsset}) { return $self->{_viewAsset}->view; } else { @@ -1059,7 +1056,7 @@ sub view_listAlbums { my $asset = WebGUI::Asset::Wobject::GalleryAlbum->newPending( $session, $assetId ); push @{ $var->{albums} }, $asset->getTemplateVars; } - + return $self->processTemplate( $var, undef, $self->{_viewTemplate} ); } @@ -1080,7 +1077,7 @@ instead of having to block things from being added. sub www_add { my $self = shift; - + unless ( $self->hasBeenCommitted ) { my $i18n = WebGUI::International->new($self->session, 'Asset_Gallery'); return $self->processStyle($i18n->get("error add uncommitted")); @@ -1138,10 +1135,10 @@ A 1 or a 0 depending on whether you want other people to be able to add images t sub www_addAlbumService { my $self = shift; my $session = $self->session; - + return $session->privilege->insufficient unless ($self->canAddFile); my $form = $session->form; - + my $album = $self->addChild({ className => "WebGUI::Asset::Wobject::GalleryAlbum", title => $form->get('title','text'), @@ -1150,7 +1147,7 @@ sub www_addAlbumService { othersCanAdd => $form->get('othersCanAdd','yesNo'), ownerUserId => $session->user->userId, }); - + $album->requestAutoCommit; my $siteUrl = $session->url->getSiteURL; @@ -1161,8 +1158,8 @@ sub www_addAlbumService { canAddFiles => $album->canAddFile, title => $album->getTitle, url => $siteUrl.$album->getUrl, - dateCreated => $date->epochToHuman($album->get('creationDate'), '%y-%m-%d %j:%n:%s'), - lastUpdated => $date->epochToHuman($album->get('revisionDate'), '%y-%m-%d %j:%n:%s'), + dateCreated => $date->epochToHuman($album->creationDate, '%y-%m-%d %j:%n:%s'), + lastUpdated => $date->epochToHuman($album->revisionDate, '%y-%m-%d %j:%n:%s'), }; if ($as eq "xml") { $session->http->setMimeType('text/xml'); @@ -1183,7 +1180,7 @@ Show a paginated list of the albums in this gallery. sub www_listAlbums { my $self = shift; - + # Perform the prepareView ourselves $self->prepareViewListAlbums; @@ -1227,7 +1224,7 @@ sub www_listAlbumsRss { } $self->session->http->setMimeType('text/xml'); - return $self->processTemplate( $var, $self->get("templateIdListAlbumsRss") ); + return $self->processTemplate( $var, $self->templateIdListAlbumsRss ); } #---------------------------------------------------------------------------- @@ -1315,9 +1312,9 @@ Defaults to 1. This represents the page number. It will return up to 100 albums sub www_listAlbumsService { my $self = shift; my $session = $self->session; - + return $session->privilege->insufficient unless ($self->canView); - + my $siteUrl = $session->url->getSiteURL; my @assets; my $date = $session->datetime; @@ -1340,8 +1337,8 @@ sub www_listAlbumsService { push @assets, { title => $asset->getTitle, url => $siteUrl.$asset->getUrl, - dateCreated => $date->epochToHuman($asset->get('creationDate'), '%y-%m-%d %j:%n:%s'), - lastUpdated => $date->epochToHuman($asset->get('revisionDate'), '%y-%m-%d %j:%n:%s'), + dateCreated => $date->epochToHuman($asset->creationDate, '%y-%m-%d %j:%n:%s'), + lastUpdated => $date->epochToHuman($asset->revisionDate, '%y-%m-%d %j:%n:%s'), thumbnailUrl => $siteUrl.$asset->getThumbnailUrl, canAddFiles => $asset->canAddFile, }; @@ -1355,11 +1352,11 @@ sub www_listAlbumsService { gallery => { canAddAlbums => $self->canAddFile, title => $self->getTitle, - menuTitle => $self->get('menuTitle'), - synopsis => $self->get('synopsis'), + menuTitle => $self->menuTitle, + synopsis => $self->synopsis, url => $siteUrl.$self->getUrl, - dateCreated => $date->epochToHuman($self->get('creationDate'), '%y-%m-%d %j:%n:%s'), - lastUpdated => $date->epochToHuman($self->get('revisionDate'), '%y-%m-%d %j:%n:%s'), + dateCreated => $date->epochToHuman($self->creationDate, '%y-%m-%d %j:%n:%s'), + lastUpdated => $date->epochToHuman($self->revisionDate, '%y-%m-%d %j:%n:%s'), }, albums => \@assets }; @@ -1447,7 +1444,7 @@ sub www_search { $joinClass = [ $form->get('className') ]; } $where .= q{ AND assetIndex.className IN ( } . $db->quoteAndJoin( $joinClass ) . q{ ) }; - + # Build a URL for the pagination my $url @@ -1473,12 +1470,12 @@ sub www_search { joinClass => $joinClass, creationDate => $creationDate, } ); - + $var->{ keywords } = $keywords; $p->appendTemplateVars( $var ); for my $result ( @{ $p->getPageData } ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $result->{assetId} ); + my $asset = WebGUI::Asset->newById( $session, $result->{assetId} ); push @{ $var->{search_results} }, { %{ $asset->getTemplateVars }, isAlbum => $asset->isa( 'WebGUI::Asset::Wobject::GalleryAlbum' ), @@ -1487,7 +1484,7 @@ sub www_search { } return $self->processStyle( - $self->processTemplate( $var, $self->get("templateIdSearch") ) + $self->processTemplate( $var, $self->templateIdSearch ) ); } @@ -1514,7 +1511,7 @@ sub www_listFilesForUser { # Get all the albums my $albumIds = $self->getUserAlbumIds( $userId ); for my $albumId ( @$albumIds ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $albumId ); + my $asset = WebGUI::Asset->newById( $session, $albumId ); push @{ $var->{user_albums} }, $asset->getTemplateVars; } @@ -1527,12 +1524,12 @@ sub www_listFilesForUser { $p->appendTemplateVars( $var ); for my $fileId ( @{ $p->getPageData } ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $fileId ); + my $asset = WebGUI::Asset->newById( $session, $fileId ); push @{ $var->{user_files} }, $asset->getTemplateVars; } return $self->processStyle( - $self->processTemplate( $var, $self->get("templateIdListFilesForUser") ) + $self->processTemplate( $var, $self->templateIdListFilesForUser ) ); } @@ -1556,7 +1553,7 @@ sub www_listFilesForUserRss { # Get all the albums my $albumIds = $self->getUserAlbumIds( $userId ); for my $albumId ( @$albumIds ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $albumId ); + my $asset = WebGUI::Asset->newById( $session, $albumId ); my $assetVar = $asset->getTemplateVars; for my $key ( qw( url ) ) { @@ -1569,7 +1566,7 @@ sub www_listFilesForUserRss { # Get all the files my $fileIds = $self->getUserFileIds( $userId ); for my $fileId ( @$fileIds ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $fileId ); + my $asset = WebGUI::Asset->newById( $session, $fileId ); my $assetVar = $asset->getTemplateVars; for my $key ( qw( url ) ) { @@ -1580,7 +1577,7 @@ sub www_listFilesForUserRss { } $self->session->http->setMimeType('text/xml'); - return $self->processTemplate( $var, $self->get("templateIdListFilesForUserRss") ); + return $self->processTemplate( $var, $self->templateIdListFilesForUserRss ); } 1; diff --git a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm index b8f8e90a3..f6ae132fc 100644 --- a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm +++ b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm @@ -11,13 +11,42 @@ package WebGUI::Asset::Wobject::GalleryAlbum; #------------------------------------------------------------------- use strict; -use Class::C3; -use base qw(WebGUI::AssetAspect::RssFeed WebGUI::Asset::Wobject); +#use Class::C3; +#use base qw(WebGUI::AssetAspect::RssFeed WebGUI::Asset::Wobject); +use WebGUI::Definition::Asset; +aspect assetName => ['assetName', 'Asset_GalleryAlbum']; +aspect icon => 'photoAlbum.gif'; +aspect tableName => 'GalleryAlbum'; + +property allowComments => ( ##Note, there's no UI for this feature. There's just the framework for it. + noFormPost => 1, + fieldType => "yesNo", + default => 1, + ); +property othersCanAdd => ( + label => ['editForm othersCanAdd label','Asset_GalleryAlbum'], + fieldType => "yesNo", + default => 0, + ); +property assetIdThumbnail => ( + label => ['editForm assetIdThumbnail label','Asset_GalleryAlbum'], + fieldType => "asset", + default => undef, + ); +for my $i ( 1 .. 5 ) { + property 'userDefined'.$i => ( + default => undef, + label => '', + fieldType => 'text', + ); +} + +with 'WebGUI::Role::Asset::AlwaysHidden'; + use Carp qw( croak ); use File::Find; use File::Spec; use File::Temp qw{ tempdir }; -use Tie::IxHash; use WebGUI::International; use WebGUI::Utility; use WebGUI::HTML; @@ -34,54 +63,6 @@ use Archive::Any; =head1 METHODS -#------------------------------------------------------------------- - -=head2 definition ( ) - -Define wobject properties for new GalleryAlbum wobjects. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session, 'Asset_GalleryAlbum'); - - tie my %properties, 'Tie::IxHash', ( - allowComments => { - fieldType => "yesNo", - defaultValue => 1, - }, - othersCanAdd => { - fieldType => "yesNo", - defaultValue => 0, - }, - assetIdThumbnail => { - fieldType => "asset", - defaultValue => undef, - }, - ); - - # UserDefined Fields - for my $i (1 .. 5) { - $properties{"userDefined".$i} = { - defaultValue => undef, - }; - } - - push @{$definition}, { - assetName => $i18n->get('assetName'), - autoGenerateForms => 0, - icon => 'photoAlbum.gif', - tableName => 'GalleryAlbum', - className => __PACKAGE__, - properties => \%properties, - }; - - return $class->next::method($session, $definition); -} - #---------------------------------------------------------------------------- =head2 addArchive ( filename, properties ) @@ -141,7 +122,7 @@ sub addArchive { my $versionTag = WebGUI::VersionTag->getWorking( $self->session ); $versionTag->set({ - "workflowId" => $self->getParent->get("workflowIdCommit"), + "workflowId" => $self->getParent->workflowIdCommit, }); $versionTag->requestCommit; @@ -171,7 +152,7 @@ sub addChild { && !$properties->{ className }->isa( "WebGUI::Asset::Shortcut" ) ) { $self->session->errorHandler->security( - "add a ".$properties->{className}." to a ".$self->get("className") + "add a ".$properties->{className}." to a ".$self->className ); return undef; } @@ -198,7 +179,7 @@ sub appendTemplateVarsFileLoop { my $session = $self->session; for my $assetId (@$assetIds) { - my $asset = WebGUI::Asset->newByDynamicClass($session, $assetId); + my $asset = WebGUI::Asset->newById($session, $assetId); # Set the parent $asset->{_parent} = $self; push @{$var->{file_loop}}, $asset->getTemplateVars; @@ -238,8 +219,8 @@ sub canAddFile { my $userId = shift || $self->session->user->userId; my $gallery = $self->getParent; - return 1 if $userId eq $self->get("ownerUserId"); - return 1 if $self->get("othersCanAdd") && $gallery->canAddFile( $userId ); + return 1 if $userId eq $self->ownerUserId; + return 1 if $self->othersCanAdd && $gallery->canAddFile( $userId ); return $gallery->canEdit( $userId ); } @@ -261,7 +242,7 @@ sub canComment { my $userId = shift || $self->session->user->userId; my $gallery = $self->getParent; - return 0 if !$self->get("allowComments"); + return 0 if !$self->allowComments; return $gallery->canComment( $userId ); } @@ -294,7 +275,7 @@ sub canEdit { return $self->canAddFile; } else { - return 1 if $userId eq $self->get("ownerUserId"); + return 1 if $userId eq $self->ownerUserId; return $gallery->canEdit($userId); } @@ -364,7 +345,7 @@ sub getAutoCommitWorkflowId { my $self = shift; my $gallery = $self->getParent; if ($gallery->hasBeenCommitted) { - return $gallery->get("workflowIdCommit") + return $gallery->workflowIdCommit || $self->session->setting->get('defaultVersionTagWorkflow'); } return undef; @@ -398,7 +379,7 @@ sub getCurrentRevisionDate { return undef unless $asset; - if ( $asset->get( 'status' ) eq "approved" || $asset->canEdit ) { + if ( $asset->status eq "approved" || $asset->canEdit ) { return $revisionDate; } else { @@ -455,7 +436,7 @@ url to the current page that will be given to the paginator. sub getFilePaginator { my $self = shift; my $url = shift || $self->getUrl; - my $perPage = $self->getParent->get( 'defaultFilesPerPage' ); + my $perPage = $self->getParent->defaultFilesPerPage; my $p = WebGUI::Paginator->new( $self->session, $url, $perPage ); $p->setDataByArrayRef( $self->getFileIds ); @@ -477,7 +458,7 @@ sub getNextAlbum { return $self->{_nextAlbum} if $self->{_nextAlbum}; my $nextId = $self->getParent->getNextAlbumId( $self->getId ); return undef unless $nextId; - $self->{_nextAlbum } = WebGUI::Asset->newByDynamicClass( $self->session, $nextId ); + $self->{_nextAlbum } = WebGUI::Asset->newById( $self->session, $nextId ); return $self->{_nextAlbum}; } @@ -495,7 +476,7 @@ sub getPreviousAlbum { return $self->{_previousAlbum} if $self->{_previousAlbum}; my $previousId = $self->getParent->getPreviousAlbumId( $self->getId ); return undef unless $previousId; - $self->{_previousAlbum} = WebGUI::Asset->newByDynamicClass( $self->session, $previousId ); + $self->{_previousAlbum} = WebGUI::Asset->newById( $self->session, $previousId ); return $self->{_previousAlbum}; } @@ -515,7 +496,7 @@ sub getRssFeedItems { my $p = $self->getFilePaginator( { - perpage => $self->get('itemsPerFeed'), + perpage => $self->itemsPerFeed, } ); my $var = []; @@ -547,7 +528,7 @@ sub getTemplateVars { my $session = $self->session; my $gallery = $self->getParent; my $var = $self->get; - my $owner = WebGUI::User->new( $session, $self->get("ownerUserId") ); + my $owner = WebGUI::User->new( $session, $self->ownerUserId ); # Fix 'undef' vars since HTML::Template does inheritence on them for my $key ( qw( description ) ) { @@ -557,7 +538,7 @@ sub getTemplateVars { } # Set a flag for pending files - if ( $self->get( "status" ) eq "pending" ) { + if ( $self->status eq "pending" ) { $var->{ 'isPending' } = 1; } @@ -592,12 +573,12 @@ sub getTemplateVars { if ( my $nextAlbum = $self->getNextAlbum ) { $var->{ nextAlbum_url } = $nextAlbum->getUrl; - $var->{ nextAlbum_title } = $nextAlbum->get( "title" ); + $var->{ nextAlbum_title } = $nextAlbum->title; $var->{ nextAlbum_thumbnailUrl } = $nextAlbum->getThumbnailUrl; } if ( my $prevAlbum = $self->getPreviousAlbum ) { $var->{ previousAlbum_url } = $prevAlbum->getUrl; - $var->{ previousAlbum_title } = $prevAlbum->get( "title" ); + $var->{ previousAlbum_title } = $prevAlbum->title; $var->{ previousAlbum_thumbnailUrl } = $prevAlbum->getThumbnailUrl; } @@ -625,8 +606,8 @@ sub getThumbnailUrl { my $asset = undef; # Try to get the asset - if ( $self->get("assetIdThumbnail") ) { - $asset = WebGUI::Asset->newByDynamicClass( $self->session, $self->get("assetIdThumbnail") ); + if ( $self->assetIdThumbnail ) { + $asset = WebGUI::Asset->newById( $self->session, $self->assetIdThumbnail ); } elsif ( $self->getFirstChild ) { $asset = $self->getFirstChild; @@ -663,7 +644,7 @@ Returns true if people other than the owner can add files to this album. sub othersCanAdd { my $self = shift; - return $self->get("othersCanAdd"); + return $self->othersCanAdd; } #---------------------------------------------------------------------------- @@ -678,7 +659,7 @@ sub prepareView { my $self = shift; $self->next::method(); - my $templateId = $self->getParent->get("templateIdViewAlbum"); + my $templateId = $self->getParent->templateIdViewAlbum; my $template = WebGUI::Asset::Template->new($self->session, $templateId); @@ -712,7 +693,7 @@ sub processFileSynopsis { my $oldVersionTag = WebGUI::VersionTag->getWorking( $session, "nocreate" ); my $newVersionTag = WebGUI::VersionTag->create( $session, { - workflowId => $self->getParent->get("workflowIdCommit"), + workflowId => $self->getParent->workflowIdCommit, } ); $newVersionTag->setWorking; @@ -720,8 +701,8 @@ sub processFileSynopsis { ( my $assetId ) = $key =~ /^fileSynopsis_(.+)$/; my $synopsis = $form->get( $key ); - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); - if ( $asset->get("synopsis") ne $synopsis ) { + my $asset = WebGUI::Asset->newById( $session, $assetId ); + if ( $asset->synopsis ne $synopsis ) { my $properties = $asset->get; $properties->{ synopsis } = $synopsis; @@ -799,20 +780,6 @@ sub sendChunkedContent { #---------------------------------------------------------------------------- -=head2 update ( ) - -Override update to force isHidden=1 on all albums. - -=cut - -sub update { - my $self = shift; - my $properties = shift; - return $self->next::method({ %{ $properties }, isHidden=>1 }); -} - -#---------------------------------------------------------------------------- - =head2 view ( ) method called by the www_view method. Returns a processed template @@ -847,7 +814,7 @@ sub view_slideshow { my $self = shift; my $session = $self->session; my $var = delete $self->{_templateVars}; - return $self->processTemplate($var, $self->getParent->get("templateIdViewSlideshow"), $self->{_preparedTemplate}); + return $self->processTemplate($var, $self->getParent->templateIdViewSlideshow, $self->{_preparedTemplate}); } #---------------------------------------------------------------------------- @@ -878,7 +845,7 @@ sub view_thumbnails { # Add direct vars for the requested file my $asset; if ($fileId) { - $asset = WebGUI::Asset->newByDynamicClass( $session, $fileId ); + $asset = WebGUI::Asset->newById( $session, $fileId ); } # If no fileId given or fileId does not exist if (!$asset) { @@ -892,7 +859,7 @@ sub view_thumbnails { } } - return $self->processTemplate($var, $self->getParent->get("templateIdViewThumbnails")); + return $self->processTemplate($var, $self->getParent->templateIdViewThumbnails); } #---------------------------------------------------------------------------- @@ -953,7 +920,7 @@ sub www_addArchive { }); return $self->processStyle( - $self->processTemplate($var, $self->getParent->get("templateIdAddArchive")) + $self->processTemplate($var, $self->getParent->templateIdAddArchive) ); } @@ -1082,8 +1049,8 @@ sub www_addFileService { title => $file->getTitle, url => $siteUrl.$file->getUrl, thumbnailUrl => $siteUrl.$file->getThumbnailUrl, - dateCreated => $date->epochToHuman($file->get('creationDate'), '%y-%m-%d %j:%n:%s'), - lastUpdated => $date->epochToHuman($file->get('revisionDate'), '%y-%m-%d %j:%n:%s'), + dateCreated => $date->epochToHuman($file->creationDate, '%y-%m-%d %j:%n:%s'), + lastUpdated => $date->epochToHuman($file->revisionDate, '%y-%m-%d %j:%n:%s'), }; if ($as eq "xml") { $session->http->setMimeType('text/xml'); @@ -1111,7 +1078,7 @@ sub www_delete { $var->{ url_yes } = $self->getUrl("func=deleteConfirm"); return $self->processStyle( - $self->processTemplate( $var, $self->getParent->get("templateIdDeleteAlbum") ) + $self->processTemplate( $var, $self->getParent->templateIdDeleteAlbum ) ); } @@ -1173,7 +1140,7 @@ sub www_edit { elsif ( grep { $_ =~ /^promote-(.{22})$/ } $form->param ) { my $assetId = ( grep { $_ =~ /^promote-(.{22})$/ } $form->param )[0]; $assetId =~ s/^promote-//; - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); + my $asset = WebGUI::Asset->newById( $session, $assetId ); if ( $asset ) { $asset->promote; } @@ -1185,7 +1152,7 @@ sub www_edit { elsif ( grep { $_ =~ /^demote-(.{22})$/ } $form->param ) { my $assetId = ( grep { $_ =~ /^demote-(.{22})$/ } $form->param )[0]; $assetId =~ s/^demote-//; - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); + my $asset = WebGUI::Asset->newById( $session, $assetId ); if ( $asset ) { $asset->demote; } @@ -1196,7 +1163,7 @@ sub www_edit { elsif ( grep { $_ =~ /^delete-(.{22})$/ } $form->param ) { my $assetId = ( grep { $_ =~ /^delete-(.{22})$/ } $form->param )[0]; $assetId =~ s/^delete-//; - my $asset = WebGUI::Asset->newByDynamicClass( $session, $assetId ); + my $asset = WebGUI::Asset->newById( $session, $assetId ); if ( $asset ) { $asset->purge; } @@ -1233,7 +1200,7 @@ sub www_edit { }) . WebGUI::Form::hidden( $session, { name => "ownerUserId", - value => $self->get("ownerUserId"), + value => $self->ownerUserId, }); # Put in the buttons that may ignore button handling code @@ -1263,24 +1230,24 @@ sub www_edit { $var->{ form_title } = WebGUI::Form::text( $session, { name => "title", - value => $form->get("title") || $self->get("title"), + value => $form->get("title") || $self->title, }); $var->{ form_description } = WebGUI::Form::HTMLArea( $session, { name => "description", - value => $form->get("description") || $self->get("description"), - richEditId => $self->getParent->get("richEditIdAlbum"), + value => $form->get("description") || $self->description, + richEditId => $self->getParent->richEditIdAlbum, }); $var->{ form_othersCanAdd } = WebGUI::Form::yesNo( $session, { name => "othersCanAdd", - value => $form->get( "othersCanAdd" ) || $self->get( "othersCanAdd" ), + value => $form->get( "othersCanAdd" ) || $self->othersCanAdd, } ); # Generate the file loop - my $assetIdThumbnail = $form->get("assetIdThumbnail") || $self->get("assetIdThumbnail"); + my $assetIdThumbnail = $form->get("assetIdThumbnail") || $self->assetIdThumbnail; $self->appendTemplateVarsFileLoop( $var, $self->getFileIds ); for my $file ( @{ $var->{file_loop} } ) { $file->{ form_assetIdThumbnail } @@ -1313,14 +1280,14 @@ sub www_edit { = WebGUI::Form::HTMLArea( $session, { name => "fileSynopsis_$file->{assetId}", value => $form->get( "fileSynopsis_$file->{assetId}" ) || $file->{ synopsis }, - richEditId => $self->getParent->get( 'richEditIdFile' ), + richEditId => $self->getParent->richEditIdFile, height => 150, width => 300, }); } return $self->processStyle( - $self->processTemplate( $var, $self->getParent->get("templateIdEditAlbum") ) + $self->processTemplate( $var, $self->getParent->templateIdEditAlbum ) ); } @@ -1368,7 +1335,7 @@ sub www_slideshow { $self->{_templateVars} = $self->getTemplateVars; $self->appendTemplateVarsFileLoop( $self->{_templateVars}, $self->getFileIds ); - my $templateId = $self->getParent->get('templateIdViewSlideshow'); + my $templateId = $self->getParent->templateIdViewSlideshow; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_preparedTemplate} = $template; @@ -1391,7 +1358,7 @@ sub www_thumbnails { $self->{_templateVars} = $self->getTemplateVars; $self->appendTemplateVarsFileLoop($self->{_templateVars}, $self->getFileIds); - my $templateId = $self->getParent->get('templateIdViewThumbnails'); + my $templateId = $self->getParent->templateIdViewThumbnails; my $template = WebGUI::Asset::Template->new($self->session, $templateId); $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_preparedTemplate} = $template; @@ -1441,7 +1408,7 @@ sub www_viewRss { } $self->session->http->setMimeType('text/xml'); - return $self->processTemplate( $var, $self->getParent->get('templateIdViewAlbumRss') ); + return $self->processTemplate( $var, $self->getParent->templateIdViewAlbumRss ); } 1; diff --git a/lib/WebGUI/Asset/Wobject/HttpProxy.pm b/lib/WebGUI/Asset/Wobject/HttpProxy.pm index a05e9806a..3be01c33d 100644 --- a/lib/WebGUI/Asset/Wobject/HttpProxy.pm +++ b/lib/WebGUI/Asset/Wobject/HttpProxy.pm @@ -18,12 +18,134 @@ use HTTP::Request::Common; use HTML::Entities; use WebGUI::International; use WebGUI::Storage; -use WebGUI::Asset::Wobject; use WebGUI::Asset::Wobject::HttpProxy::Parse; use WebGUI::Macro; use Apache2::Upload; -our @ISA = qw(WebGUI::Asset::Wobject); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_HttpProxy']; +aspect uiLevel => 5; +aspect icon => 'httpProxy.gif'; +aspect tableName => 'HttpProxy'; +property templateId => ( + fieldType => "template", + default => 'PBtmpl0000000000000033', + namespace => 'HttpProxy', + tab => 'display', + label => ['http proxy template title', 'Asset_HttpProxy'], + hoverHelp => ['http proxy template title description', 'Asset_HttpProxy'], + ); + +property proxiedUrl => ( + fieldType => "url", + default => 'http://', + tab => 'properties', + label => [1, 'Asset_HttpProxy'], + hoverHelp => ['1 description', 'Asset_HttpProxy'], + ); + +property useAmpersand => ( + fieldType => "yesNo", + default => 0, + tab => 'properties', + label => ["use ampersand", 'Asset_HttpProxy'], + hoverHelp => ["use ampersand help", 'Asset_HttpProxy'], + ); + +property timeout => ( + fieldType => "selectBox", + default => 30, + tab => 'properties', + options => \&_timeout_options, + label => [4, 'Asset_HttpProxy'], + hoverHelp => ['4 description', 'Asset_HttpProxy'], + ); +sub _timeout_options { + my %timeoutOptions; + tie %timeoutOptions, 'Tie::IxHash'; + %timeoutOptions = map{$_ => $_} (5, 10, 20, 30, 60); + return \%timeoutOptions; +} + +property removeStyle => ( + fieldType => "yesNo", + default => 1, + tab => 'display', + label => [6, 'Asset_HttpProxy'], + hoverHelp => ['6 description', 'Asset_HttpProxy'], + ); + +property cacheTimeout => ( + fieldType => "interval", + default => 0, + tab => 'display', + label => ['cache timeout', 'Asset_HttpProxy'], + hoverHelp => ['cache timeout description', 'Asset_HttpProxy'], + uiLevel => 8, + ); + +property filterHtml => ( + fieldType => "filterContent", + default => "javascript", + tab => 'display', + label => [418, 'WebGUI', 'Asset_HttpProxy'], + hoverHelp => ['418 description', 'WebGUI', 'Asset_HttpProxy'], + ); + +property urlPatternFilter => ( + fieldType => "textarea", + default => "", + tab => "display", + label => ["url pattern filter label", 'Asset_HttpProxy'], + hoverHelp => ["url pattern filter hover help", 'Asset_HttpProxy'], + ); + +property followExternal => ( + fieldType => "yesNo", + default => 1, + tab => 'security', + label => [5, 'Asset_HttpProxy'], + hoverHelp => ['5 description', 'Asset_HttpProxy'], + ); + +property rewriteUrls => ( + fieldType => "yesNo", + default => 1, + tab => 'properties', + label => [12, 'Asset_HttpProxy'], + hoverHelp => ['12 description', 'Asset_HttpProxy'], + ); + +property followRedirect => ( + fieldType => "yesNo", + default => 0, + tab => 'security', + label => [8, 'Asset_HttpProxy'], + hoverHelp => ['8 description', 'Asset_HttpProxy'], + ); + +property searchFor => ( + fieldType => "text", + default => undef, + tab => 'display', + label => [13, 'Asset_HttpProxy'], + hoverHelp => ['13 description', 'Asset_HttpProxy'], + ); + +property stopAt => ( + fieldType => "text", + default => undef, + tab => 'display', + label => [14, 'Asset_HttpProxy'], + hoverHelp => ['14 description', 'Asset_HttpProxy'], + ); + +property cookieJarStorageId => ( + noFormPost => 1, + fieldType => "hidden", + default => undef + ); #------------------------------------------------------------------- @@ -47,7 +169,7 @@ sub appendToUrl { my $self = shift; my $url = shift; my $paramSet = shift; - my $seperator = ($self->get("useAmpersand")) ? "&" : ";"; + my $seperator = ($self->useAmpersand) ? "&" : ";"; if (index($url, '?') == length($url)-1) { $url .= $paramSet; } elsif (index($url, '?') >= 0) { @@ -59,141 +181,6 @@ sub appendToUrl { } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_HttpProxy"); - my %timeoutOptions; - tie %timeoutOptions, 'Tie::IxHash'; - %timeoutOptions = map{$_ => $_} (5, 10, 20, 30, 60); - - push(@{$definition}, { - assetName => $i18n->get('assetName'), - uiLevel => 5, - icon => 'httpProxy.gif', - tableName => 'HttpProxy', - className => 'WebGUI::Asset::Wobject::HttpProxy', - autoGenerateForms => 1, - properties => { - templateId => { - fieldType => "template", - defaultValue => 'PBtmpl0000000000000033', - namespace => 'HttpProxy', - tab => 'display', - label => $i18n->get('http proxy template title'), - hoverHelp => $i18n->get('http proxy template title description'), - }, - - proxiedUrl => { - fieldType => "url", - defaultValue => 'http://', - tab => 'properties', - label => $i18n->get(1), - hoverHelp => $i18n->get('1 description'), - }, - - useAmpersand => { - fieldType => "yesNo", - defaultValue => 0, - tab => 'properties', - label => $i18n->get("use ampersand"), - hoverHelp => $i18n->get("use ampersand help") - }, - - timeout => { - fieldType => "selectBox", - defaultValue => 30, - tab => 'properties', - options => \%timeoutOptions, - label => $i18n->get(4), - hoverHelp => $i18n->get('4 description'), - }, - - removeStyle => { - fieldType => "yesNo", - defaultValue => 1, - tab => 'display', - label => $i18n->get(6), - hoverHelp => $i18n->get('6 description'), - }, - - cacheTimeout => { - fieldType => "interval", - defaultValue => 0, - tab => 'display', - label => $i18n->get('cache timeout'), - hoverHelp => $i18n->get('cache timeout description'), - uiLevel => 8, - }, - - filterHtml => { - fieldType => "filterContent", - defaultValue => "javascript", - tab => 'display', - label => $i18n->get(418, 'WebGUI'), - hoverHelp => $i18n->get('418 description', 'WebGUI'), - }, - - urlPatternFilter=>{ - fieldType => "textarea", - defaultValue => "", - tab => "display", - label => $i18n->get("url pattern filter label"), - hoverHelp => $i18n->get("url pattern filter hover help"), - }, - - followExternal => { - fieldType => "yesNo", - defaultValue => 1, - tab => 'security', - label => $i18n->get(5), - hoverHelp => $i18n->get('5 description'), - }, - - rewriteUrls => { - fieldType => "yesNo", - defaultValue => 1, - tab => 'properties', - label => $i18n->get(12), - hoverHelp => $i18n->get('12 description'), - }, - - followRedirect => { - fieldType => "yesNo", - defaultValue => 0, - tab => 'security', - label => $i18n->get(8), - hoverHelp => $i18n->get('8 description'), - }, - - searchFor => { - fieldType => "text", - defaultValue => undef, - tab => 'display', - label => $i18n->get(13), - hoverHelp => $i18n->get('13 description'), - }, - - stopAt => { - fieldType => "text", - defaultValue => undef, - tab => 'display', - label => $i18n->get(14), - hoverHelp => $i18n->get('14 description'), - }, - - cookieJarStorageId => { - noFormPost => 1, - fieldType => "hidden", - defaultValue => undef - } - } - }); - return $class->SUPER::definition($session, $definition); -} - #------------------------------------------------------------------- =head2 getContentLastModified @@ -218,11 +205,11 @@ Return a WebGUI::Storage object to hold cookie data. sub getCookieJar { my $self = shift; my $storage; - unless ($self->get("cookieJarStorageId")) { + unless ($self->cookieJarStorageId) { $storage = WebGUI::Storage->create($self->session); $self->update({cookieJarStorageId=>$storage->getId}); } else { - $storage = WebGUI::Storage->get($self->session,$self->get("cookieJarStorageId")); + $storage = WebGUI::Storage->get($self->session,$self->cookieJarStorageId); } return $storage; } @@ -238,11 +225,11 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->get("templateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->get("templateId"), + templateId => $self->templateId, assetId => $self->getId, ); } @@ -278,8 +265,8 @@ sub purgeCache { my $self = shift; my $cache = $self->session->cache; eval { - $cache->delete([$self->get("proxiedUrl"),"URL"]); - $cache->delete([$self->get("proxiedUrl"),"HEADER"]); + $cache->delete([$self->proxiedUrl,"URL"]); + $cache->delete([$self->proxiedUrl,"HEADER"]); }; $self->SUPER::purgeCache; } @@ -299,7 +286,7 @@ sub view { my $redirect = 0; my $response; my $header; - my $proxiedUrl = $self->get("proxiedUrl"); + my $proxiedUrl = $self->proxiedUrl; WebGUI::Macro::process($self->session,\$proxiedUrl); my $i18n = WebGUI::International->new($self->session, 'Asset_HttpProxy'); @@ -316,7 +303,7 @@ sub view { $proxiedUrl = $self->session->form->process("FormAction") || $self->session->form->process("proxiedUrl") || $proxiedUrl ; } - return $self->processTemplate({},$self->get("templateId")) + return $self->processTemplate({},$self->templateId) unless ($proxiedUrl ne ""); my $requestMethod = $self->session->env->get("REQUEST_METHOD") || "GET"; @@ -338,7 +325,7 @@ sub view { my $userAgent = new LWP::UserAgent; $userAgent->agent($self->session->env->get("HTTP_USER_AGENT")); - $userAgent->timeout($self->get("timeout")); + $userAgent->timeout($self->timeout); $userAgent->env_proxy; @@ -351,16 +338,16 @@ sub view { ## Make sure the user isn't leaving where we've allowed - if ($self->get("followExternal")==0 - && (URI->new($self->get('proxiedUrl'))->host) ne (URI->new($proxiedUrl)->host) ) { + if ($self->followExternal==0 + && (URI->new($self->proxiedUrl)->host) ne (URI->new($proxiedUrl)->host) ) { $var{header} = "text/html"; - $var{content} = sprintf $i18n->get('may not leave error message'), $self->get("proxiedUrl"); + $var{content} = sprintf $i18n->get('may not leave error message'), $self->proxiedUrl; last; } $header = new HTTP::Headers; - $header->referer($self->get("proxiedUrl")); # To get around referrer blocking + $header->referer($self->proxiedUrl); # To get around referrer blocking my $request; # Create the request @@ -428,7 +415,7 @@ sub view { last REDIRECT; } ##At least 1 time through the loop - last REDIRECT if (not $self->get("followRedirect")); # No redirection. Overruled by setting + last REDIRECT if (not $self->followRedirect); # No redirection. Overruled by setting } if($response->is_success) { @@ -437,8 +424,8 @@ sub view { if($response->content_type eq "text/html" || ($response->content_type eq "" && $var{content}=~/getValue("searchFor"); - $var{"stop.at"} = $self->getValue("stopAt"); + $var{"search.for"} = $self->searchFor; + $var{"stop.at"} = $self->stopAt; if ($var{"search.for"}) { $var{content} =~ /^(.*?)\Q$var{"search.for"}\E(.*)$/gis; $var{"content.leading"} = $1 || $var{content}; @@ -449,7 +436,7 @@ sub view { $var{content} = $1 || $var{content}; $var{"content.trailing"} = $2; } - my $p = WebGUI::Asset::Wobject::HttpProxy::Parse->new($self->session, $proxiedUrl, $var{content}, $self->getId,$self->get("rewriteUrls"),$self->getUrl,$self->get("urlPatternFilter")); + my $p = WebGUI::Asset::Wobject::HttpProxy::Parse->new($self->session, $proxiedUrl, $var{content}, $self->getId,$self->rewriteUrls,$self->getUrl,$self->urlPatternFilter); $var{content} = $p->filter; # Rewrite content. (let forms/links return to us). $p->DESTROY; @@ -457,19 +444,19 @@ sub view { $var{header} = "text/html"; $var{content} = sprintf $i18n->get('no frame error message'), $proxiedUrl; } else { - $var{content} =~ s/\//isg if ($self->get("removeStyle")); + $var{content} =~ s/\//isg if ($self->removeStyle); $var{content} = WebGUI::HTML::cleanSegment($var{content}, 1); - $var{content} = WebGUI::HTML::filter($var{content}, $self->get("filterHtml")); + $var{content} = WebGUI::HTML::filter($var{content}, $self->filterHtml); } } } else { # Fetching page failed... $var{header} = "text/html"; $var{content} = sprintf $i18n->get('fetch page error'), $proxiedUrl, $proxiedUrl, $response->status_line; } - unless ($self->get("cacheTimeout") <= 10) { + unless ($self->cacheTimeout <= 10) { eval{ - $cache->set([$proxiedUrl,'URL'], $var{content}, $self->get("cacheTimeout")); - $cache->set([$proxiedUrl,'HEADER'], $var{header}, $self->get("cacheTimeout")); + $cache->set([$proxiedUrl,'URL'], $var{content}, $self->cacheTimeout); + $cache->set([$proxiedUrl,'HEADER'], $var{header}, $self->cacheTimeout); }; } } diff --git a/lib/WebGUI/Asset/Wobject/InOutBoard.pm b/lib/WebGUI/Asset/Wobject/InOutBoard.pm index b58daab24..a42ac0809 100644 --- a/lib/WebGUI/Asset/Wobject/InOutBoard.pm +++ b/lib/WebGUI/Asset/Wobject/InOutBoard.pm @@ -6,9 +6,64 @@ use WebGUI::HTMLForm; use WebGUI::International; use WebGUI::Paginator; use WebGUI::SQL; -use WebGUI::Asset::Wobject; -our @ISA = qw(WebGUI::Asset::Wobject); +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect tableName => 'InOutBoard'; +aspect assetName => ['assetName', 'Asset_MapPoint']; +aspect icon => 'iob.gif'; +property statusList => ( + tab => 'properties', + fieldType => "textarea", + builder => '_statusList_builder', + lazy => 1, + label => [1, 'Asset_InOutBoard'], + hoverHelp => ['1 description', 'Asset_InOutBoard'], + subtext => [2, 'Asset_InOutBoard'], + ); +sub _statusList_builder { + my $self = shift; + my $session = $self->session; + my $i18n = WebGUI::International->new($session, 'Asset_InOutBoard'); + return $i18n->get(10)."\n".$i18n->get(11)."\n"; +} +property reportViewerGroup => ( + tab => 'security', + default => 3, + fieldType => "group", + label => [3, 'Asset_InOutBoard'], + hoverHelp => ["3 description", 'Asset_InOutBoard'], + ); +property inOutGroup => ( + tab => 'security', + default => 2, + fieldType => "group", + label => ['inOutGroup', 'Asset_InOutBoard'], + hoverHelp => ['inOutGroup description', 'Asset_InOutBoard'], + ); +property inOutTemplateId => ( + tab => 'display', + fieldType => "template", + namespace => "InOutBoard", + label => ["In Out Template", 'Asset_InOutBoard'], + hoverHelp => ["In Out Template description", 'Asset_InOutBoard'], + default => 'IOB0000000000000000001', + ); +property reportTemplateId => ( + tab => 'display', + fieldType => "template", + default => 'IOB0000000000000000002', + label => [13, 'Asset_InOutBoard'], + hoverHelp => ["13 description", 'Asset_InOutBoard'], + namespace => "InOutBoard/Report" + ); +property paginateAfter => ( + tab => 'display', + fieldType => "integer", + default => 50, + label => [12, 'Asset_InOutBoard'], + hoverHelp => ['12 description', 'Asset_InOutBoard'], + ); #See line 285 if you wish to change the users visible in the delegate select list @@ -50,69 +105,6 @@ sub _fetchDepartments { } -#------------------------------------------------------------------- -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_InOutBoard"); - push(@{$definition}, { - tableName => 'InOutBoard', - className => 'WebGUI::Asset::Wobject::InOutBoard', - assetName => $i18n->get('assetName'), - icon => 'iob.gif', - autoGenerateForms => 1, - properties => { - statusList => { - tab => 'properties', - defaultValue => $i18n->get(10)."\n".$i18n->get(11)."\n", - fieldType => "textarea", - label => $i18n->get(1), - hoverHelp => $i18n->get('1 description'), - subtext => $i18n->get(2), - }, - reportViewerGroup => { - tab => 'security', - defaultValue => 3, - fieldType => "group", - label => $i18n->get(3), - hoverHelp => $i18n->get("3 description"), - }, - inOutGroup => { - tab => 'security', - defaultValue => 2, - fieldType => "group", - label => $i18n->get('inOutGroup'), - hoverHelp => $i18n->get('inOutGroup description'), - }, - inOutTemplateId => { - tab => 'display', - fieldType => "template", - namespace => "InOutBoard", - label => $i18n->get("In Out Template"), - hoverHelp => $i18n->get("In Out Template description"), - defaultValue => 'IOB0000000000000000001', - }, - reportTemplateId => { - tab => 'display', - fieldType => "template", - defaultValue => 'IOB0000000000000000002', - label => $i18n->get(13), - hoverHelp => $i18n->get("13 description"), - namespace => "InOutBoard/Report" - }, - paginateAfter => { - tab => 'display', - fieldType => "integer", - defaultValue => 50, - label => $i18n->get(12), - hoverHelp => $i18n->get('12 description'), - }, - } - }); - return $class->SUPER::definition($session, $definition); -} - #------------------------------------------------------------------- =head2 prepareView ( ) @@ -124,11 +116,11 @@ See WebGUI::Asset::prepareView() for details. sub prepareView { my $self = shift; $self->SUPER::prepareView(); - my $template = WebGUI::Asset::Template->new($self->session, $self->getValue("inOutTemplateId")); + my $template = WebGUI::Asset::Template->new($self->session, $self->inOutTemplateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, - templateId => $self->getValue("inOutTemplateId"), + templateId => $self->inOutTemplateId, assetId => $self->getId, ); } @@ -170,7 +162,7 @@ sub view { my $url = $self->getUrl('func=view'); my $i18n = WebGUI::International->new($self->session, "Asset_InOutBoard"); - if ($session->user->isInGroup($self->getValue("reportViewerGroup"))) { + if ($session->user->isInGroup($self->reportViewerGroup)) { $var{'viewReportURL'} = $self->getUrl("func=viewReport"); $var{'viewReportLabel'} = $i18n->get('view report label'); $var{canViewReport} = 1; @@ -180,7 +172,7 @@ sub view { } my $statusUserId = $self->session->scratch->get("userId") || $self->session->user->userId; - my $statusListString = $self->getValue("statusList"); + my $statusListString = $self->statusList; my @statusListArray = split("\n",$statusListString); my $statusListHashRef; tie %$statusListHashRef, 'Tie::IxHash'; @@ -240,7 +232,7 @@ sub view { my ($isInGroup) = $session->db->quickArray( "select count(*) from groupings where userId=? and groupId=?", - [ $session->user->userId, $self->get("inOutGroup") ] + [ $session->user->userId, $self->inOutGroup ] ); if ($isInGroup) { $var{displayForm} = 1; @@ -254,7 +246,7 @@ sub view { my $lastDepartment = "_nothing_"; - my $p = WebGUI::Paginator->new($session, $url, $self->getValue("paginateAfter")); + my $p = WebGUI::Paginator->new($session, $url, $self->paginateAfter); my $sql = "select users.username, users.userId, @@ -274,7 +266,7 @@ where users.userId<>'1' and InOutBoard.inOutGroup=? group by userId order by department, lastName, firstName"; - $p->setDataByQuery($sql, undef, 0, [ $self->getId, $self->get('inOutGroup') ], ); + $p->setDataByQuery($sql, undef, 0, [ $self->getId, $self->inOutGroup ], ); my $rowdata = $p->getPageData(); my @rows; foreach my $data (@$rowdata) { @@ -335,7 +327,7 @@ sub www_selectDelegates { and users.userId <> ? and InOutBoard.inOutGroup=? group by userId - ",[$self->getId, $self->session->user->userId, $self->getValue("inOutGroup")]); + ",[$self->getId, $self->session->user->userId, $self->inOutGroup]); while (my $data = $sth->hashRef) { $userNames{ $data->{userId} } = _defineUsername($data); } @@ -439,7 +431,7 @@ the report. sub www_viewReport { my $self = shift; - return "" unless ($self->session->user->isInGroup($self->getValue("reportViewerGroup"))); + return "" unless ($self->session->user->isInGroup($self->reportViewerGroup)); my %var; my $i18n = WebGUI::International->new($self->session,'Asset_InOutBoard'); my $f = WebGUI::HTMLForm->new($self->session,-action=>$self->getUrl, -method=>"GET"); @@ -522,7 +514,7 @@ left join groupings on groupings.userId=users.userId left join userProfileData on users.userId=userProfileData.userId left join InOutBoard_statusLog on users.userId=InOutBoard_statusLog.userId and InOutBoard_statusLog.assetId=".$self->session->db->quote($self->getId())." where users.userId<>'1' and - groupings.groupId=".$self->session->db->quote($self->getValue("inOutGroup"))." and + groupings.groupId=".$self->session->db->quote($self->inOutGroup)." and groupings.userId=users.userId and InOutBoard_statusLog.dateStamp>=$startDate and InOutBoard_statusLog.dateStamp<=$endDate @@ -569,7 +561,7 @@ order by department, lastName, firstName, InOutBoard_statusLog.dateStamp"; $var{showReport} = 0; } - return $self->processStyle($self->processTemplate(\%var, $self->getValue("reportTemplateId"))); + return $self->processStyle($self->processTemplate(\%var, $self->reportTemplateId)); } 1; diff --git a/lib/WebGUI/Asset/Wobject/Layout.pm b/lib/WebGUI/Asset/Wobject/Layout.pm index 5ac97afdf..35889eefd 100644 --- a/lib/WebGUI/Asset/Wobject/Layout.pm +++ b/lib/WebGUI/Asset/Wobject/Layout.pm @@ -16,10 +16,45 @@ package WebGUI::Asset::Wobject::Layout; use strict; use WebGUI::AdSpace; -use WebGUI::Asset::Wobject; -use WebGUI::Utility; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; -our @ISA = qw(WebGUI::Asset::Wobject); +aspect assetName => ["assetName", 'Asset_Layout']; +aspect icon => 'layout.gif'; +aspect tableName => 'Layout'; + +property templateId => ( + fieldType => "template", + namespace => "Layout", + default => 'PBtmpl0000000000000054', + label => ['layout template title', 'Asset_Layout'], + hoverHelp => ['template description', 'Asset_Layout'], + ); +property mobileTemplateId => ( + #fieldType => ( $session->style->useMobileStyle ? 'template' : 'hidden' ), + fieldType => 'template', + namespace => 'Layout', + default => 'PBtmpl0000000000000054', + noFormPost => 1, + ); +property contentPositions => ( + noFormPost => 1, + default => undef, + fieldType => "hidden", + noFormPost => 1, + ); +property assetsToHide => ( + default => undef, + fieldType => "checkList", + noFormPost => 1, + ); +property assetOrder => ( + default => 'asc', + fieldType => 'selectBox', + noFormPost => 1, + ); + +use WebGUI::Utility; =head1 NAME @@ -42,59 +77,6 @@ These methods are available from this class: -#------------------------------------------------------------------- - -=head2 definition ( definition ) - -Defines the properties of this asset. - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new($session,"Asset_Layout"); - - push(@{$definition}, { - assetName=>$i18n->get("assetName"), - icon=>'layout.gif', - tableName=>'Layout', - className=>'WebGUI::Asset::Wobject::Layout', - properties=>{ - templateId =>{ - fieldType =>"template", - namespace => "Layout", - defaultValue =>'PBtmpl0000000000000054', - }, - mobileTemplateId => { - fieldType => ( $session->style->useMobileStyle ? 'template' : 'hidden' ), - namespace => 'Layout', - defaultValue => 'PBtmpl0000000000000054', - }, - contentPositions => { - noFormPost =>1, - defaultValue =>undef, - fieldType =>"hidden" - }, - assetsToHide => { - defaultValue =>undef, - fieldType =>"checkList" - }, - assetOrder => { - defaultValue =>'asc', - fieldType =>'selectBox', - } - } - }); - return $class->SUPER::definition($session, $definition); -} - - #------------------------------------------------------------------- =head2 getEditForm ( ) @@ -109,10 +91,11 @@ sub getEditForm { my $i18n = WebGUI::International->new($self->session,"Asset_Layout"); my ($templateId); - if (($self->get("assetId") eq "new") && ($self->getParent->get('className') eq 'WebGUI::Asset::Wobject::Layout')) { - $templateId = $self->getParent->getValue('templateId'); - } else { - $templateId = $self->getValue('templateId'); + if (($self->assetId eq "new") && ($self->getParent->isa('WebGUI::Asset::Wobject::Layout'))) { + $templateId = $self->getParent->templateId; + } + else { + $templateId = $self->templateId; } $tabform->getTab("display")->template( -value=>$templateId, @@ -124,7 +107,7 @@ sub getEditForm { if ( $self->session->setting->get('useMobileStyle') ) { $tabform->getTab("display")->template( name => 'mobileTemplateId', - value => $self->getValue('mobileTemplateId'), + value => $self->mobileTemplateId, label => $i18n->get('mobileTemplateId label'), hoverHelp => $i18n->get('mobileTemplateId description'), namespace => 'Layout', @@ -133,7 +116,7 @@ sub getEditForm { else { $tabform->getTab("display")->hidden( name => 'mobileTemplateId', - value => $self->getValue('mobileTemplateId'), + value => $self->mobileTemplateId, ); } @@ -146,7 +129,7 @@ sub getEditForm { -name => 'assetOrder', -label => $i18n->get('asset order label'), -hoverHelp => $i18n->get('asset order hoverHelp'), - -value => $self->getValue('assetOrder'), + -value => $self->assetOrder, -options => \%assetOrder ); if ($self->get("assetId") eq "new") { @@ -158,7 +141,7 @@ sub getEditForm { -value=>"view" ); } else { - my @assetsToHide = split("\n",$self->getValue("assetsToHide")); + my @assetsToHide = split("\n",$self->assetsToHide); my $children = $self->getLineage(["children"],{"returnObjects"=>1, excludeClasses=>["WebGUI::Asset::Wobject::Layout"]}); my %childIds; foreach my $child (@{$children}) { @@ -193,13 +176,13 @@ sub prepareView { my $templateId; if ($session->style->useMobileStyle) { - $templateId = $self->get('mobileTemplateId'); + $templateId = $self->mobileTemplateId; } else { - $templateId = $self->get('templateId'); + $templateId = $self->templateId; } - my $template = WebGUI::Asset->new($session,$templateId,"WebGUI::Asset::Template"); + my $template = WebGUI::Asset->newById($session, $templateId); if (!$template) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, @@ -210,7 +193,7 @@ sub prepareView { $template->prepare( $self->getMetaDataAsTemplateVariables ); $self->{_viewTemplate} = $template; - my $templateContent = $template->get("template"); + my $templateContent = $template->template; my $numPositions = 1; while ($templateContent =~ /position(\d+)_loop/g) { $numPositions = $1 @@ -223,7 +206,7 @@ sub prepareView { my $splitter = $self->{_viewSplitter} = $self->getSeparator; my %hidden = map { $_ => 1 } - split "\n", $self->get("assetsToHide"); + split "\n", $self->assetsToHide; my %placeHolder; my @children; @@ -239,7 +222,7 @@ sub prepareView { $placeHolder{$assetId} = $child; push @children, { id => $assetId, - isUncommitted => $child->get('status') eq 'pending', + isUncommitted => $child->status eq 'pending', content => $splitter . $assetId . '~~', }; if ($vars{showAdmin}) { @@ -247,7 +230,7 @@ sub prepareView { }; } - my @positions = split /\./, $self->get("contentPositions"); + my @positions = split /\./, $self->contentPositions; # cut positions off at the number we found in the template $#positions = $numPositions - 1 if $numPositions < scalar @positions; @@ -270,7 +253,7 @@ sub prepareView { } # deal with unplaced children # Add children to the top or bottom of the first content position based on assetOrder setting - if($self->getValue("assetOrder") eq "asc") { + if($self->assetOrder eq "asc") { push @{ $vars{"position1_loop"} }, @children; } else { diff --git a/lib/WebGUI/Asset/Wobject/Map.pm b/lib/WebGUI/Asset/Wobject/Map.pm index 2b590d662..ca9a93f03 100644 --- a/lib/WebGUI/Asset/Wobject/Map.pm +++ b/lib/WebGUI/Asset/Wobject/Map.pm @@ -17,121 +17,104 @@ use Tie::IxHash; use WebGUI::International; use WebGUI::Utility; use HTML::Entities qw(encode_entities); -use base 'WebGUI::Asset::Wobject'; - -# To get an installer for your wobject, add the Installable AssetAspect -# See WebGUI::AssetAspect::Installable and sbin/installClass.pl for more -# details - -#------------------------------------------------------------------- - -=head2 definition ( ) - -Define asset properties - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new( $session, 'Asset_Map' ); - +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset::Wobject'; +aspect assetName => ['assetName', 'Asset_Map']; +aspect icon => 'maps.png'; +aspect tableName => 'Map'; +property groupIdAddPoint => ( + tab => "security", + fieldType => "group", + label => ["groupIdAddPoint label", 'Asset_Map'], + hoverHelp => ["groupIdAddPoint description", 'Asset_Map'], + default => '2', # Registered users + ); +property mapApiKey => ( + tab => "properties", + fieldType => "text", + label => ["mapApiKey label", 'Asset_Map'], + hoverHelp => ["mapApiKey description", 'Asset_Map'], + builder => '_mapApiKey_builder', + lazy => 1, + subtext => + ); +sub _mapApiKey_builder { + my $self = shift; + return $self->getDefaultApiKey($self->session); +} +sub _mapApiKey_subtext { + my $self = shift; + my $session = $self->session; + my $i18n = WebGUI::International->new($session, 'Asset_Map'); my $googleApiKeyUrl = 'http://code.google.com/apis/maps/signup.html'; my $googleApiKeyLink = q{%s}; - - tie my %properties, 'Tie::IxHash', ( - groupIdAddPoint => { - tab => "security", - fieldType => "group", - label => $i18n->get("groupIdAddPoint label"), - hoverHelp => $i18n->get("groupIdAddPoint description"), - defaultValue=> '2', # Registered users - }, - mapApiKey => { - tab => "properties", - fieldType => "text", - label => $i18n->get("mapApiKey label"), - hoverHelp => $i18n->get("mapApiKey description"), - defaultValue=> $class->getDefaultApiKey($session), - subtext => sprintf($googleApiKeyLink, ($googleApiKeyUrl)x2, $i18n->get('mapApiKey link') ), - }, - mapHeight => { + return sprintf($googleApiKeyLink, ($googleApiKeyUrl)x2, $i18n->get('mapApiKey link') ); +} +property mapHeight => ( tab => "display", fieldType => "text", - label => $i18n->get("mapHeight label"), - hoverHelp => $i18n->get("mapHeight description"), - defaultValue => '400px', - }, - mapWidth => { + label => ["mapHeight label", 'Asset_Map'], + hoverHelp => ["mapHeight description", 'Asset_Map'], + default => '400px', + ); +property mapWidth => ( tab => "display", fieldType => "text", - label => $i18n->get("mapWidth label"), - hoverHelp => $i18n->get("mapWidth description"), - defaultValue => '100%', - }, - startLatitude => { + label => ["mapWidth label", 'Asset_Map'], + hoverHelp => ["mapWidth description", 'Asset_Map'], + default => '100%', + ); +property startLatitude => ( tab => "display", fieldType => "float", - label => $i18n->get("startLatitude label"), - hoverHelp => $i18n->get("startLatitude description"), - defaultValue => 43.074719, - }, - startLongitude => { + label => ["startLatitude label", 'Asset_Map'], + hoverHelp => ["startLatitude description", 'Asset_Map'], + default => 43.074719, + ); +property startLongitude => ( tab => "display", fieldType => "float", - label => $i18n->get("startLongitude label"), - hoverHelp => $i18n->get("startLongitude description"), - defaultValue => -89.384251, - }, - startZoom => { + label => ["startLongitude label", 'Asset_Map'], + hoverHelp => ["startLongitude description", 'Asset_Map'], + default => -89.384251, + ); +property startZoom => ( tab => "display", fieldType => "intSlider", minimum => 1, maximum => 19, - label => $i18n->get("startZoom label"), - hoverHelp => $i18n->get("startZoom description"), - }, - templateIdEditPoint => { + label => ["startZoom label", 'Asset_Map'], + hoverHelp => ["startZoom description", 'Asset_Map'], + ); +property templateIdEditPoint => ( tab => "display", fieldType => "template", namespace => "MapPoint/Edit", - label => $i18n->get("templateIdEditPoint label"), - hoverHelp => $i18n->get("templateIdEditPoint description"), - }, - templateIdView => { + label => ["templateIdEditPoint label", 'Asset_Map'], + hoverHelp => ["templateIdEditPoint description", 'Asset_Map'], + ); +property templateIdView => ( tab => "display", fieldType => "template", namespace => "Map/View", - label => $i18n->get("templateIdView label"), - hoverHelp => $i18n->get("templateIdView description"), - }, - templateIdViewPoint => { + label => ["templateIdView label", 'Asset_Map'], + hoverHelp => ["templateIdView description", 'Asset_Map'], + ); +property templateIdViewPoint => ( tab => "display", fieldType => "template", namespace => "MapPoint/View", - label => $i18n->get("templateIdViewPoint label"), - hoverHelp => $i18n->get("templateIdViewPoint description"), - }, - workflowIdPoint => { + label => ["templateIdViewPoint label", 'Asset_Map'], + hoverHelp => ["templateIdViewPoint description", 'Asset_Map'], + ); +property workflowIdPoint => ( tab => "security", fieldType => "workflow", - label => $i18n->get("workflowIdPoint label"), - hoverHelp => $i18n->get("workflowIdPoint description"), + label => ["workflowIdPoint label", 'Asset_Map'], + hoverHelp => ["workflowIdPoint description", 'Asset_Map'], type => 'WebGUI::VersionTag', - }, - ); - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'maps.png', - autoGenerateForms => 1, - tableName => 'Map', - className => 'WebGUI::Asset::Wobject::Map', - properties => \%properties - }; - return $class->SUPER::definition( $session, $definition ); -} ## end sub definition + ); #------------------------------------------------------------------- @@ -150,7 +133,7 @@ sub canAddPoint { : $self->session->user ; - return $user->isInGroup( $self->get("groupIdAddPoint") ); + return $user->isInGroup( $self->groupIdAddPoint ); } #---------------------------------------------------------------------------- @@ -185,7 +168,7 @@ sub canEdit { : $self->session->user ; - return $user->isInGroup( $self->get("groupIdEdit") ); + return $user->isInGroup( $self->groupIdEdit ); } } @@ -240,7 +223,7 @@ sub getEditPointTemplate { my $self = shift; if ( !$self->{_editPointTemplate} ) { - my $templateId = $self->get('templateIdEditPoint'); + my $templateId = $self->templateIdEditPoint; my $template = WebGUI::Asset::Template->new( $self->session, $templateId ); $template->prepare; @@ -263,7 +246,7 @@ sub getViewPointTemplate { my $self = shift; if ( !$self->{_viewPointTemplate} ) { - my $templateId = $self->get('templateIdViewPoint'); + my $templateId = $self->templateIdViewPoint; my $template = WebGUI::Asset::Template->new( $self->session, $templateId ); $self->{_viewPointTemplate} = $template; @@ -309,7 +292,7 @@ sub loadMapApiTags { my $style = $self->session->style; my $url = $self->session->url; - $style->setScript("http://www.google.com/jsapi?key=" . $self->get('mapApiKey'),{type=>"text/javascript"}); + $style->setScript("http://www.google.com/jsapi?key=" . $self->mapApiKey,{type=>"text/javascript"}); $style->setRawHeadTags(<<'ENDHTML'); ', - fixed => 'Javascript: ', - comment => "javascript removed", - }, - { - title => 'This is a good Title', - fixed => 'This is a good Title', - comment => "Good titles are passed", - }, - { - title => '', - fixed => '', - comment => "If there is no title left after processing, then it is set to untitled.", - }, - { - title => q|Quotes '"|, - fixed => q|Quotes '"|, - comment => "Quotes are not processed.", - }, - ); -} ##Return an array of hashrefs. Each hashref describes a test ##for the getTitle and getMenuTitle tests. If "assetName" != 0, they diff --git a/t/Asset/AssetClipboard.t b/t/Asset/AssetClipboard.t index 4ef457678..8f03d6ad4 100644 --- a/t/Asset/AssetClipboard.t +++ b/t/Asset/AssetClipboard.t @@ -72,12 +72,13 @@ $versionTag->commit; sleep 2; +note "duplicate"; my $duplicatedSnippet = $snippet->duplicate; -is($duplicatedSnippet->get('title'), 'snippet', 'duplicated snippet has correct title'); -isnt($duplicatedSnippet->getId, $snippetAssetId, 'duplicated snippet does not have same assetId as original'); +is($duplicatedSnippet->title, 'snippet', 'duplicated snippet has correct title'); +isnt($duplicatedSnippet->getId, $snippetAssetId, 'duplicated snippet does not have same assetId as original'); is( - $duplicatedSnippet->get("revisionDate"), + $duplicatedSnippet->revisionDate, $snippetRevisionDate, 'duplicated snippet has the same revision date', ); @@ -96,9 +97,10 @@ WebGUI::Test->tagsToRollback($newVersionTag); # #################################################### -is( $topFolder->cut, 1, 'cut: returns 1 if successful' ); -is($topFolder->get('state'), 'clipboard', '... state set to trash on the trashed asset object'); -is($topFolder->cloneFromDb->get('state'), 'clipboard', '... state set to trash in db on object'); -is($folder1a->cloneFromDb->get('state'), 'clipboard-limbo', '... state set to clipboard-limbo on child #1'); -is($folder1b->cloneFromDb->get('state'), 'clipboard-limbo', '... state set to clipboard-limbo on child #2'); -is($folder1a2->cloneFromDb->get('state'), 'clipboard-limbo', '... state set to clipboard-limbo on grandchild #1-1'); +note "cut"; +is($topFolder->cut, 1, 'returns 1 if successful' ); +is($topFolder->state, 'clipboard', '... state set to trash on the trashed asset object'); +is($topFolder->cloneFromDb->state, 'clipboard', '... state set to trash in db on object'); +is($folder1a->cloneFromDb->state, 'clipboard-limbo', '... state set to clipboard-limbo on child #1'); +is($folder1b->cloneFromDb->state, 'clipboard-limbo', '... state set to clipboard-limbo on child #2'); +is($folder1a2->cloneFromDb->state, 'clipboard-limbo', '... state set to clipboard-limbo on grandchild #1-1'); diff --git a/t/Asset/AssetLineage.t b/t/Asset/AssetLineage.t index 4ea371595..1cb39cd35 100644 --- a/t/Asset/AssetLineage.t +++ b/t/Asset/AssetLineage.t @@ -17,8 +17,9 @@ use WebGUI::Session; use WebGUI::User; use WebGUI::Asset; -use Test::More tests => 90; # increment this value for each test you create +use Test::More tests => 91; # increment this value for each test you create use Test::Deep; +use Data::Dumper; # Test the methods in WebGUI::AssetLineage @@ -83,11 +84,114 @@ my $snippet2 = $folder2->addChild( { }); $versionTag->commit; +my @snipIds; +my $lineageIds; -my @snipIds = map { $_->getId } @snippets; -my $lineageIds = $folder->getLineage(['descendants']); +#################################################### +# +# getLineage +# +#################################################### -cmp_bag(\@snipIds, $lineageIds, 'default order returned by getLineage is lineage order'); +my $ids = $folder->getLineage(['self']); +cmp_deeply( + [$folder->getId], + $ids, + 'getLineage: get self' +); + +@snipIds = map { $_->getId } @snippets; +$lineageIds = $folder->getLineage(['descendants']); + +cmp_deeply($lineageIds, \@snipIds, 'default order returned by getLineage is lineage order'); + +@snipIds = map { $_->getId } @snippets; +$ids = $folder->getLineage(['descendants']); +cmp_bag( + \@snipIds, + $ids, + '... get descendants of folder' +); + +$ids = $folder->getLineage(['self','descendants']); +unshift @snipIds, $folder->getId; +cmp_bag( + \@snipIds, + $ids, + '... get descendants of folder and self' +); + +$ids = $folder->getLineage(['self','children']); +cmp_bag( + \@snipIds, + $ids, + '... descendants == children if there are no grandchildren' +); + +$ids = $topFolder->getLineage(['self','children']); +cmp_bag( + [$topFolder->getId, $folder->getId, $folder2->getId, ], + $ids, + '... children (no descendants) of topFolder', +); + +$ids = $topFolder->getLineage(['self','descendants']); +cmp_bag( + [$topFolder->getId, @snipIds, $folder2->getId, $snippet2->getId], + $ids, + '... descendants of topFolder', +); + +#################################################### +# +# getLineageIterator +# +#################################################### + +sub getListFromIterator { + my $iterator = shift; + my @items; + while (my $item = $iterator->()) { + push @items, $item->getId; + } + return \@items; +} + +@snipIds = map { $_->getId } @snippets; +my $ids = getListFromIterator($folder->getLineageIterator(['descendants'])); +cmp_bag( + \@snipIds, + $ids, + 'getLineageIterator: get descendants of folder' +); + +$ids = getListFromIterator($folder->getLineageIterator(['self','descendants'])); +cmp_bag( + [$folder->getId, @snipIds], + $ids, + 'getLineageIterator: get descendants of folder and self' +); + +$ids = getListFromIterator($folder->getLineageIterator(['self','children'])); +cmp_bag( + [$folder->getId, @snipIds], + $ids, + 'getLineageIterator: descendants == children if there are no grandchildren' +); + +$ids = getListFromIterator($topFolder->getLineageIterator(['self','children'])); +cmp_bag( + [$topFolder->getId, $folder->getId, $folder2->getId, ], + $ids, + 'getLineageIterator: children (no descendants) of topFolder', +); + +$ids = getListFromIterator($topFolder->getLineageIterator(['self','descendants'])); +cmp_bag( + [$topFolder->getId, $folder->getId, @snipIds, $folder2->getId, $snippet2->getId], + $ids, + 'getLineageIterator: descendants of topFolder', +); #################################################### # @@ -184,12 +288,12 @@ is( # #################################################### -#note $snippets[0]->get('lineage'); -#note $snippet2->get('lineage'); +#note $snippets[0]->lineage; +#note $snippet2->lineage; ##Uncomment me to crash the test -#$snippet2->cascadeLineage($snippets[0]->get('lineage')); -#note $snippets[0]->get('lineage'); -#note $snippet2->get('lineage'); +#$snippet2->cascadeLineage($snippets[0]->lineage); +#note $snippets[0]->lineage; +#note $snippet2->lineage; #################################################### # @@ -240,17 +344,19 @@ is($folder2->getNextChildRank, '000002', "getNextChildRank: empty folder"); # #################################################### -is($snippets[0]->swapRank($snippets[1]->get('lineage')), 1, 'swapRank: self and adjacent'); +is($snippets[0]->swapRank($snippets[1]->lineage), 1, 'swapRank: self and adjacent'); + +$folder->cloneFromDb; @snipIds[0,1] = @snipIds[1,0]; $lineageIds = $folder->getLineage(['descendants']); cmp_bag( \@snipIds, $lineageIds, - 'swapRank: swapped first and second snippets' + '... swapped first and second snippets' ); -@snippets[0..1] = map { WebGUI::Asset->newByUrl($session, "snippet$_") } 0..1; +@snippets[0..1] = map { $_->cloneFromDb } @snippets[0..1]; is( $snippets[1]->swapRank($snippets[0]->get('lineage'), $snippets[1]->get('lineage'), ), @@ -274,10 +380,10 @@ is(scalar @snippets, $folder->getChildCount, 'changing lineage does not change is(1 , $folder2->getChildCount, 'changing lineage does not change relationship in folder2'); ##Reinstance the asset object due to db manipulation -$folder = WebGUI::Asset->newByDynamicClass($session, $folder->getId); -$folder2 = WebGUI::Asset->newByDynamicClass($session, $folder2->getId); -@snippets = map { WebGUI::Asset->newByDynamicClass($session, $snippets[$_]->getId) } 0..6; -$snippet2 = WebGUI::Asset->newByDynamicClass($session, $snippet2->getId); +$folder = $folder->cloneFromDb; +$folder2 = $folder2->cloneFromDb; +@snippets = map { $_->cloneFromDb } @snippets; +$snippet2 = $snippet2->cloneFromDb; #################################################### # @@ -399,101 +505,6 @@ delete $cachedLineage->{$snippet4->get('lineage')}->{class}; my $snippet4 = WebGUI::Asset->newByLineage($session, $snippets[4]->get('lineage')); is ($snippet4->getId, $snippets[4]->getId, 'newByLineage: failing class cache forces lookup'); -#################################################### -# -# getLineage -# -#################################################### - -@snipIds = map { $_->getId } @snippets; -my $ids = $folder->getLineage(['descendants']); -cmp_bag( - \@snipIds, - $ids, - 'getLineage: get descendants of folder' -); - -$ids = $folder->getLineage(['self','descendants']); -unshift @snipIds, $folder->getId; -cmp_bag( - \@snipIds, - $ids, - 'getLineage: get descendants of folder and self' -); - -$ids = $folder->getLineage(['self','children']); -cmp_bag( - \@snipIds, - $ids, - 'getLineage: descendants == children if there are no grandchildren' -); - -$ids = $topFolder->getLineage(['self','children']); -cmp_bag( - [$topFolder->getId, $folder->getId, $folder2->getId, ], - $ids, - 'getLineage: children (no descendants) of topFolder', -); - -$ids = $topFolder->getLineage(['self','descendants']); -cmp_bag( - [$topFolder->getId, @snipIds, $folder2->getId, $snippet2->getId], - $ids, - 'getLineage: descendants of topFolder', -); - -#################################################### -# -# getLineageIterator -# -#################################################### - -sub getListFromIterator { - my $iterator = shift; - my @items; - while (my $item = $iterator->()) { - push @items, $item->getId; - } - return \@items; -} - -@snipIds = map { $_->getId } @snippets; -my $ids = getListFromIterator($folder->getLineageIterator(['descendants'])); -cmp_bag( - \@snipIds, - $ids, - 'getLineageIterator: get descendants of folder' -); - -$ids = getListFromIterator($folder->getLineageIterator(['self','descendants'])); -unshift @snipIds, $folder->getId; -cmp_bag( - \@snipIds, - $ids, - 'getLineageIterator: get descendants of folder and self' -); - -$ids = getListFromIterator($folder->getLineageIterator(['self','children'])); -cmp_bag( - \@snipIds, - $ids, - 'getLineageIterator: descendants == children if there are no grandchildren' -); - -$ids = getListFromIterator($topFolder->getLineageIterator(['self','children'])); -cmp_bag( - [$topFolder->getId, $folder->getId, $folder2->getId, ], - $ids, - 'getLineageIterator: children (no descendants) of topFolder', -); - -$ids = getListFromIterator($topFolder->getLineageIterator(['self','descendants'])); -cmp_bag( - [$topFolder->getId, @snipIds, $folder2->getId, $snippet2->getId], - $ids, - 'getLineageIterator: descendants of topFolder', -); - #################################################### # # addChild diff --git a/t/Asset/AssetTrash.t b/t/Asset/AssetTrash.t index ae4e15f3d..2b593ded4 100644 --- a/t/Asset/AssetTrash.t +++ b/t/Asset/AssetTrash.t @@ -57,6 +57,7 @@ my $folder1a2 = $folder1a->addChild({ $versionTag->commit; + #################################################### # # trash @@ -64,11 +65,11 @@ $versionTag->commit; #################################################### is( $topFolder->trash, 1, 'trash: returns 1 if successful' ); -is($topFolder->get('state'), 'trash', '... state set to trash on the trashed asset object'); -is($topFolder->cloneFromDb->get('state'), 'trash', '... state set to trash in db on object'); -is($folder1a->cloneFromDb->get('state'), 'trash-limbo', '... state set to trash-limbo on child #1'); -is($folder1b->cloneFromDb->get('state'), 'trash-limbo', '... state set to trash-limbo on child #2'); -is($folder1a2->cloneFromDb->get('state'), 'trash-limbo', '... state set to trash-limbo on grandchild #1-1'); +is($topFolder->state, 'trash', '... state set to trash on the trashed asset object'); +is($topFolder->cloneFromDb->state, 'trash', '... state set to trash in db on object'); +is($folder1a->cloneFromDb->state, 'trash-limbo', '... state set to trash-limbo on child #1'); +is($folder1b->cloneFromDb->state, 'trash-limbo', '... state set to trash-limbo on child #2'); +is($folder1a2->cloneFromDb->state, 'trash-limbo', '... state set to trash-limbo on grandchild #1-1'); #################################################### # diff --git a/t/Asset/AssetVersion.t b/t/Asset/AssetVersion.t index 64baa28b0..f0d465331 100644 --- a/t/Asset/AssetVersion.t +++ b/t/Asset/AssetVersion.t @@ -18,19 +18,19 @@ use lib "$FindBin::Bin/../lib"; use WebGUI::Test; use WebGUI::Session; use WebGUI::Utility; -use WebGUI::Asset::Template; +use WebGUI::Asset::Snippet; use Test::More; # increment this value for each test you create plan tests => 26; my $session = WebGUI::Test->session; my $propertyHash = { - template => "Hi, I'm a template", + template => "Hi, I'm a snippet", url => '/template/versionTest', - title => 'Version Test Template', - menuTitle => 'Version Test Template', - namespace => 'Article', - className => 'WebGUI::Asset::Template', + title => 'Version Test Snippet', + menuTitle => 'Version Test Snippet', + namespace => 'Snippet', + className => 'WebGUI::Asset::Snippet', }; my $root = WebGUI::Asset->getRoot($session); @@ -44,35 +44,35 @@ my $originalVersionTags = $session->db->quickScalar(q{select count(*) from asset ################################################################ note "purgeRevision tests"; -my $template = $root->addChild($propertyHash); -$template->commit; +my $snippet = $root->addChild($propertyHash); +$snippet->commit; -is (ref $template, "WebGUI::Asset::Template", "Template Asset created"); -checkTableEntries($template->getId, 1,1,1,1); +isa_ok $snippet, "WebGUI::Asset::Snippet"; +checkTableEntries($snippet->getId, 1,1,1,1); sleep 1; -my $templatev2 = $template->addRevision({template => 'Hello, I am a template with formal grammar'}); -$templatev2->commit; +my $snippetv2 = $snippet->addRevision({snippet => 'Hello, I am a snippet with formal grammar'}); +$snippetv2->commit; -is ($templatev2->getId, $template->getId, 'Both versions of the asset have the same assetId'); -checkTableEntries($templatev2->getId, 1,2,2,1); +is ($snippetv2->getId, $snippet->getId, 'Both versions of the asset have the same assetId'); +checkTableEntries($snippetv2->getId, 1,2,2,1); -$templatev2->purgeRevision; +$snippetv2->purgeRevision; -checkTableEntries($templatev2->getId, 1,1,1,1); +checkTableEntries($snippetv2->getId, 1,1,1,1); -undef $templatev2; +undef $snippetv2; -my $templatev2a = $template->addRevision({template => 'Hey, yall! Ima template.'}); -$templatev2a->commit; +my $snippetv2a = $snippet->addRevision({snippet => 'Hey, yall! Ima snippet.'}); +$snippetv2a->commit; -$template->purgeRevision; +$snippet->purgeRevision; -checkTableEntries($template->getId, 1,1,1,1); +checkTableEntries($snippet->getId, 1,1,1,1); -$template->purgeRevision; -checkTableEntries($template->getId, 0,0,0,0); +$snippet->purgeRevision; +checkTableEntries($snippet->getId, 0,0,0,0); my $versionTagCheck; $versionTagCheck = $session->db->quickScalar(q{select count(*) from assetVersionTag}); @@ -84,22 +84,22 @@ is($versionTagCheck, $originalVersionTags, 'version tag cleaned up by deleting l # ################################################################ -$template = $root->addChild($propertyHash); +$snippet = $root->addChild($propertyHash); my $tag1 = WebGUI::VersionTag->getWorking($session); $tag1->commit; WebGUI::Test->tagsToRollback($tag1); sleep 1; -$templatev2 = $template->addRevision({template => 'Vie gates. Ich bin ein templater.'}); +$snippetv2 = $snippet->addRevision({snippet => 'Vie gates. Ich bin ein snippetr.'}); my $tag2 = WebGUI::VersionTag->getWorking($session); $tag2->commit; WebGUI::Test->tagsToRollback($tag2); note "purge"; -checkTableEntries($templatev2->getId, 1,2,2); +checkTableEntries($snippetv2->getId, 1,2,2); $versionTagCheck = $session->db->quickScalar(q{select count(*) from assetVersionTag}); is($versionTagCheck, $originalVersionTags+2, 'created two version tags'); -$template->purge; -checkTableEntries($templatev2->getId, 0,0,0); +$snippet->purge; +checkTableEntries($snippetv2->getId, 0,0,0); $versionTagCheck = $session->db->quickScalar(q{select count(*) from assetVersionTag}); is($versionTagCheck, $originalVersionTags, 'purge deleted both tags'); @@ -110,7 +110,7 @@ is($versionTagCheck, $originalVersionTags, 'purge deleted both tags'); ################################################################ sub checkTableEntries { - my ($assetId, $assetNum, $assetDataNum, $templateNum) = @_; + my ($assetId, $assetNum, $assetDataNum, $snippetNum) = @_; my ($count) = $session->db->quickArray('select COUNT(*) from asset where assetId=?', [$assetId]); is ($count, $assetNum, sprintf 'Expecting %d Assets with that id in asset', $assetNum); @@ -119,7 +119,7 @@ sub checkTableEntries { is ($count, $assetDataNum, sprintf 'Expecting %d Assets with that id in assetData', $assetDataNum); - ($count) = $session->db->quickArray('select COUNT(*) from template where assetId=?', [$assetId]); - is ($count, $templateNum, - sprintf 'Expecting %d Assets with that id in template', $templateNum); + ($count) = $session->db->quickArray('select COUNT(*) from snippet where assetId=?', [$assetId]); + is ($count, $snippetNum, + sprintf 'Expecting %d Assets with that id in snippet', $snippetNum); } diff --git a/t/Asset/Event.t b/t/Asset/Event.t index 87c67b662..fe063b3f8 100644 --- a/t/Asset/Event.t +++ b/t/Asset/Event.t @@ -19,7 +19,7 @@ use WebGUI::Asset::Event; use Test::More; # increment this value for each test you create use Test::Deep; -plan tests => 18; +plan tests => 20; my $session = WebGUI::Test->session; @@ -131,3 +131,22 @@ ok($session->id->valid($event6a->get('storageId')), 'addRevision gives the new r isnt($event6a->get('storageId'), $event6->get('storageId'), '... and it is different from the previous revision'); my $versionTag2 = WebGUI::VersionTag->getWorking($session); WebGUI::Test->tagsToRollback($versionTag2); +$versionTag2->commit; + +my $event7 = $cal->addChild( + { + className => 'WebGUI::Asset::Event', + assetId => 'EventAssetTestStorage6', + url => 'hidden_event', + }, undef, undef, { skipNotifications => 1, skipAutoCommitWorkflows => 1 }, +); + +my $tag = WebGUI::VersionTag->getWorking($session); +$tag->commit; +addToCleanup($tag); + +is $event7->isHidden, 1, 'isHidden set to 1 by default'; + +$event7->isHidden(0); +is $event7->isHidden, 1, 'isHidden cannot be set to 0'; + diff --git a/t/Asset/File.t b/t/Asset/File.t index c167a4a75..3b0cead81 100644 --- a/t/Asset/File.t +++ b/t/Asset/File.t @@ -65,15 +65,15 @@ my $asset = $defaultAsset->addChild($properties, $properties->{id}); ############################################ ok($asset->getStorageLocation, 'File Asset getStorageLocation initialized'); -ok($asset->get('storageId'), 'getStorageLocation updates asset object with storage location'); -is($asset->get('storageId'), $asset->getStorageLocation->getId, 'Asset storageId and cached storageId agree'); +ok($asset->storageId, 'getStorageLocation updates asset object with storage location'); +is($asset->storageId, $asset->getStorageLocation->getId, 'Asset storageId and cached storageId agree'); $asset->update({ storageId => $storage->getId, filename => $filename, }); -is($storage->getId, $asset->get('storageId'), 'Asset updated with correct new storageId'); +is($storage->getId, $asset->storageId, 'Asset updated with correct new storageId'); is($storage->getId, $asset->getStorageLocation->getId, 'Cached Asset storage location updated with correct new storageId'); $versionTag->commit; @@ -86,6 +86,7 @@ $versionTag->commit; my $fileStorage = WebGUI::Storage->create($session); my $guard2 = cleanupGuard($fileStorage); +$mocker->set_always('get', $fileStorage->getId); $mocker->set_always('getValue', $fileStorage->getId); my $fileFormStorage = $asset->getStorageFromPost(); isa_ok($fileFormStorage, 'WebGUI::Storage', 'Asset::File::getStorageFromPost'); diff --git a/t/Asset/File/Image.t b/t/Asset/File/Image.t index 9b2a8bc97..2e82898ea 100644 --- a/t/Asset/File/Image.t +++ b/t/Asset/File/Image.t @@ -30,7 +30,7 @@ use WebGUI::Form::File; use Test::More; # increment this value for each test you create use Test::Deep; -plan tests => 11; +plan tests => 13; my $session = WebGUI::Test->session; @@ -55,54 +55,50 @@ $session->user({userId=>3}); my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"Image Asset test"}); my $properties = { - # '1234567890123456789012' - id => 'ImageAssetTest00000001', - title => 'Image Asset Test', + # '1234567890123456789012' + id => 'ImageAssetTest00000001', + title => 'Image Asset Test', className => 'WebGUI::Asset::File::Image', - url => 'image-asset-test', + url => 'image-asset-test', }; my $defaultAsset = WebGUI::Asset->getDefault($session); my $asset = $defaultAsset->addChild($properties, $properties->{id}); ok($asset->getStorageLocation, 'Image Asset getStorageLocation initialized'); -ok($asset->get('storageId'), 'getStorageLocation updates Image asset object with storage location'); -is($asset->get('storageId'), $asset->getStorageLocation->getId, 'Image Asset storageId and cached storageId agree'); +ok($asset->storageId, 'getStorageLocation updates Image asset object with storage location'); +is($asset->storageId, $asset->getStorageLocation->getId, 'Image Asset storageId and cached storageId agree'); $asset->update({ storageId => $storage->getId, filename => 'blue.png', }); -my $filename = $asset->getStorageLocation->getPath . "/" . $asset->get("filename"); +my $filename = $asset->getStorageLocation->getPath($asset->filename); +ok(-e $filename, 'file exists in the storage location for following tests'); my @stat_before = stat($filename); -$asset->getStorageLocation->rotate($asset->get("filename"), 90); +ok($asset->getStorageLocation->rotate($asset->filename, 90), 'rotate worked'); my @stat_after = stat($filename); is(isnt_array(\@stat_before, \@stat_after), 1, 'Image is different after rotation'); @stat_before = stat($filename); -$asset->getStorageLocation->resize($asset->get("filename"), 200, 300); +$asset->getStorageLocation->resize($asset->filename, 200, 300); my @stat_after = stat($filename); is(isnt_array(\@stat_before, \@stat_after), 1, 'Image is different after resize'); @stat_before = stat($filename); -$asset->getStorageLocation->crop($asset->get("filename"), 100, 125, 10, 25); +$asset->getStorageLocation->crop($asset->filename, 100, 125, 10, 25); my @stat_after = stat($filename); is(isnt_array(\@stat_before, \@stat_after), 1, 'Image is different after crop'); my $sth = $session->db->read('describe ImageAsset annotations'); isnt($sth->hashRef, undef, 'Annotations column is defined'); -is($storage->getId, $asset->get('storageId'), 'Asset updated with correct new storageId'); +is($storage->getId, $asset->storageId, 'Asset updated with correct new storageId'); is($storage->getId, $asset->getStorageLocation->getId, 'Cached Asset storage location updated with correct new storageId'); $versionTag->commit; - -END { - if (defined $versionTag and ref $versionTag eq 'WebGUI::VersionTag') { - $versionTag->rollback; - } -} +addToCleanup($versionTag); sub isnt_array { my ($a, $b) = @_; diff --git a/t/Asset/Shortcut/010-linked-asset.t b/t/Asset/Shortcut/010-linked-asset.t index cb631ab38..5ae832689 100644 --- a/t/Asset/Shortcut/010-linked-asset.t +++ b/t/Asset/Shortcut/010-linked-asset.t @@ -28,6 +28,7 @@ my $session = WebGUI::Test->session; my $node = WebGUI::Asset->getImportNode($session); my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"Shortcut Test"}); +addToCleanup; # Make a snippet to shortcut my $snippet @@ -41,12 +42,6 @@ my $shortcut shortcutToAssetId => $snippet->getId, }); -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} - #---------------------------------------------------------------------------- # Tests @@ -74,7 +69,7 @@ is( #---------------------------------------------------------------------------- # Test trashing snippet trashes shortcut also $snippet->trash; -$shortcut = WebGUI::Asset->newByDynamicClass($session, $shortcut->getId); +$shortcut = WebGUI::Asset->newById($session, $shortcut->getId); ok( defined $shortcut, diff --git a/t/Asset/Sku.t b/t/Asset/Sku.t index e11988107..9d67cddb1 100644 --- a/t/Asset/Sku.t +++ b/t/Asset/Sku.t @@ -30,16 +30,18 @@ my $session = WebGUI::Test->session; #---------------------------------------------------------------------------- # Tests -plan tests => 21; # Increment this number for each test you create +plan tests => 22; # Increment this number for each test you create #---------------------------------------------------------------------------- # put your tests here my $root = WebGUI::Asset->getRoot($session); +warn "Make sku\n"; my $sku = $root->addChild({ className=>"WebGUI::Asset::Sku", title=>"Test Sku", }); isa_ok($sku, "WebGUI::Asset::Sku"); +addToCleanup($sku); $sku->addToCart; @@ -64,13 +66,14 @@ is($sku->isRecurring, 0, "skus are not recurring by default"); is($sku->isShippingRequired, 0, "skus are not shippable by default"); is($sku->getConfiguredTitle, $sku->getTitle, "configured title and title should be the same by default"); is($sku->shipsSeparately, 0, 'shipsSeparately return 0 by default'); +is($sku->isShippingSeparately, 0, 'isShippingSeparately return 0 by default'); -$sku->update({shipsSeparately => 1,}); -is($sku->shipsSeparately, 0, 'shipsSeparately only returns true when isShippingRequired AND shipsSeparately'); +$sku->shipsSeparately(1); +is($sku->isShippingSeparately, 0, 'isShippingSeparately only returns true when isShippingRequired AND shipsSeparately'); { local *WebGUI::Asset::Sku::isShippingRequired = sub { return 1}; - is($sku->shipsSeparately, 1, 'shipsSeparately only returns true when isShippingRequired AND shipsSeparately'); + is($sku->isShippingSeparately, 1, 'isShippingSeparately only returns true when isShippingRequired AND shipsSeparately'); } ok(! $sku->isShippingRequired, 'Making sure that GLOB is no longer in effect'); @@ -82,13 +85,3 @@ $item->cart->delete; my $loadSku = WebGUI::Asset::Sku->newBySku($session, $sku->get("sku")); is($loadSku->getId, $sku->getId, "newBySku() works."); - -#---------------------------------------------------------------------------- -# Cleanup -END { - -$sku->purge; - -} - -1; diff --git a/t/Asset/Sku/Product.t b/t/Asset/Sku/Product.t index 98409d01c..c5fce4584 100644 --- a/t/Asset/Sku/Product.t +++ b/t/Asset/Sku/Product.t @@ -37,7 +37,7 @@ my $session = WebGUI::Test->session; #---------------------------------------------------------------------------- # Tests -plan tests => 13; # Increment this number for each test you create +plan tests => 19; # Increment this number for each test you create #---------------------------------------------------------------------------- # put your tests here @@ -50,6 +50,12 @@ my $product = $node->addChild({ is($product->getThumbnailUrl(), '', 'Product with no image1 property returns the empty string'); +note "Checking automatically generated deleteFileUrl links"; +foreach my $file_property (qw/image1 image2 image3 brochure manual warranty/) { + my $form_properties = $product->getFormProperties($file_property); + like $form_properties->{deleteFileUrl}, qr/file=$file_property/, '...' . $file_property; +} + my $image = WebGUI::Storage->create($session); WebGUI::Test->storagesToDelete($image); $image->addFileFromFilesystem(WebGUI::Test->getTestCollateralPath('lamp.jpg')); @@ -164,7 +170,7 @@ $tag2->commit; WebGUI::Test->tagsToRollback($tag2); ##Fetch a copy from the db, just like a page fetch -$viewProduct = WebGUI::Asset->new($session, $viewProduct->getId, 'WebGUI::Asset::Sku::Product'); +$viewProduct = WebGUI::Asset->newById($session, $viewProduct->getId); $viewProduct->prepareView(); my $json = $viewProduct->view(); diff --git a/t/Asset/Template.t b/t/Asset/Template.t index ad0f3c5bf..e4bc81e23 100644 --- a/t/Asset/Template.t +++ b/t/Asset/Template.t @@ -16,7 +16,7 @@ use WebGUI::Test; use WebGUI::Session; use WebGUI::Asset::Template; use Exception::Class; -use Test::More tests => 43; # increment this value for each test you create +use Test::More tests => 41; # increment this value for each test you create use Test::Deep; use JSON qw{ from_json }; @@ -74,13 +74,9 @@ is($templateCopy->get('isDefault'), 0, 'isDefault set to 0 on copy'); my $template3 = $importNode->addChild({ className => "WebGUI::Asset::Template", title => 'headBlock test', - headBlock => "tag1 tag2 tag3", template => "this is a template", }); -ok(!$template3->get('headBlock'), 'headBlock is empty'); -is($template3->get('extraHeadTags'), 'tag1 tag2 tag3', 'extraHeadTags contains headBlock info'); - my @atts = ( {type => 'headScript', sequence => 1, url => 'bar'}, {type => 'headScript', sequence => 0, url => 'foo'}, diff --git a/t/Asset/Wobject/Article.t b/t/Asset/Wobject/Article.t index 43dd38e6f..cf4d58d4a 100644 --- a/t/Asset/Wobject/Article.t +++ b/t/Asset/Wobject/Article.t @@ -118,12 +118,12 @@ my $output = $article->view; isnt ($output, "", 'view method returns something'); # Lets see if caching works -my $cachedOutput = WebGUI::Cache->new($session, 'view_'.$article->getId)->get; +my $cachedOutput = $session->cache->get('view_'.$article->getId); is ($output, $cachedOutput, 'view method caches output'); # Lets see if the purgeCache method works $article->purgeCache; -$cachedOutput = WebGUI::Cache->new($session, 'view_'.$article->getId)->get; # Check cache post purge +$cachedOutput = $session->cache->get('view_'.$article->getId); # Check cache post purge isnt ($output, $cachedOutput, 'purgeCache method deletes cache'); @@ -136,8 +136,3 @@ TODO: { ok(0, 'Test www_deleteFile method'); ok(0, 'Test www_view method... maybe?'); } - -END { - # Clean up after thy self -} - diff --git a/t/Asset/Wobject/Survey.t b/t/Asset/Wobject/Survey.t index 05a7fdc4f..e5008c588 100644 --- a/t/Asset/Wobject/Survey.t +++ b/t/Asset/Wobject/Survey.t @@ -40,7 +40,7 @@ my $tag = WebGUI::VersionTag->getWorking($session); WebGUI::Test->assetsToPurge($survey); isa_ok($survey, 'WebGUI::Asset::Wobject::Survey'); -my $sJSON = $survey->surveyJSON; +my $sJSON = $survey->getSurveyJSON; # Load bare-bones survey, containing a single section (S0) $sJSON->update([0], { variable => 'S0' }); @@ -209,7 +209,7 @@ cmp_deeply(from_json($surveyEnd), { type => 'forward', url => '/getting_started' # Modify Survey structure, new revision not created $survey->submitObjectEdit({ id => "0", text => "new text"}); - is($survey->surveyJSON->section([0])->{text}, 'new text', 'Survey updated'); + is($survey->getSurveyJSON->section([0])->{text}, 'new text', 'Survey updated'); is($session->db->quickScalar('select revisionDate from Survey where assetId = ?', [$surveyId]), $revisionDate, 'Revision unchanged'); # Push revisionDate into the past because we can't have 2 revision dates with the same epoch (this is very hacky) @@ -220,7 +220,7 @@ cmp_deeply(from_json($surveyEnd), { type => 'forward', url => '/getting_started' $session->db->write('update assetData set revisionDate = ? where assetId = ?', [$revisionDate, $surveyId]); $session->db->write('update wobject set revisionDate = ? where assetId = ?', [$revisionDate, $surveyId]); - $survey = WebGUI::Asset->new($session, $surveyId); + $survey = WebGUI::Asset->newById($session, $surveyId); isa_ok($survey, 'WebGUI::Asset::Wobject::Survey', 'Got back survey after monkeying with revisionDate'); is($session->db->quickScalar('select revisionDate from Survey where assetId = ?', [$surveyId]), $revisionDate, 'Revision date pushed back'); @@ -235,10 +235,10 @@ cmp_deeply(from_json($surveyEnd), { type => 'forward', url => '/getting_started' # Make another change, causing new revision to be automatically created $survey->submitObjectEdit({ id => "0", text => "newer text"}); - my $newerSurvey = WebGUI::Asset->new($session, $surveyId); # retrieve newer revision + my $newerSurvey = WebGUI::Asset->newById($session, $surveyId); # retrieve newer revision isa_ok($newerSurvey, 'WebGUI::Asset::Wobject::Survey', 'After change, re-retrieved Survey instance'); is($newerSurvey->getId, $surveyId, '..which is the same survey'); - is($newerSurvey->surveyJSON->section([0])->{text}, 'newer text', '..with updated text'); + is($newerSurvey->getSurveyJSON->section([0])->{text}, 'newer text', '..with updated text'); ok($newerSurvey->get('revisionDate') > $revisionDate, '..and newer revisionDate'); # Create another response (this one will use the new revision) @@ -261,7 +261,7 @@ SKIP: { skip "Unable to load GraphViz", 1 if $@; -$survey->surveyJSON->remove([1]); +$survey->getSurveyJSON->remove([1]); my ($storage, $filename) = $survey->graph( { format => 'plain', layout => 'dot' } ); like($storage->getFileContentsAsScalar($filename), qr{ ^graph .* # starts with graph diff --git a/t/Asset/permissions.t b/t/Asset/permissions.t new file mode 100644 index 000000000..f81c2967e --- /dev/null +++ b/t/Asset/permissions.t @@ -0,0 +1,902 @@ +#------------------------------------------------------------------- +# WebGUI is Copyright 2001-2009 Plain Black Corporation. +#------------------------------------------------------------------- +# Please read the legal notices (docs/legal.txt) and the license +# (docs/license.txt) that came with this distribution before using +# this software. +#------------------------------------------------------------------- +# http://www.plainblack.com info@plainblack.com +#------------------------------------------------------------------- + +use FindBin; +use strict; +use lib "$FindBin::Bin/../lib"; + +use WebGUI::Test; +use WebGUI::Test::Maker::Permission; +use WebGUI::Session; +use WebGUI::Asset; +use WebGUI::User; +use WebGUI::Asset::Wobject::Navigation; +use WebGUI::Asset::Wobject::Folder; +use WebGUI::Asset::Sku; +use WebGUI::Asset::Sku::Product; +use WebGUI::AssetVersioning; +use WebGUI::VersionTag; + +use Test::More; +use Test::Deep; +use Test::MockObject; +use HTML::TokeParser; +use Data::Dumper; +use Storable qw/dclone/; + +my $session = WebGUI::Test->session; + +my @getTitleTests = getTitleTests($session); + +my $rootAsset = WebGUI::Asset->getRoot($session); + +##Test users. +##All users in here will be deleted at the end of the test. DO NOT PUT +##Visitor or Admin in here! +my %testUsers = (); +##Just a regular user +$testUsers{'regular user'} = WebGUI::User->new($session, 'new'); +$testUsers{'regular user'}->username('regular user'); +##Users in group 12 can add Assets +$testUsers{'canAdd turnOnAdmin'} = WebGUI::User->new($session, 'new'); +$testUsers{'canAdd turnOnAdmin'}->addToGroups(['12']); +$testUsers{'canAdd turnOnAdmin'}->username('Turn On Admin user'); + +##Just a user for owning assets +$testUsers{'owner'} = WebGUI::User->new($session, 'new'); +$testUsers{'owner'}->username('Asset Owner'); + +##Test Groups +##All groups in here will be deleted at the end of the test +my %testGroups = (); +##A group and user for groupIdEdit +$testGroups{'canEdit asset'} = WebGUI::Group->new($session, 'new'); +$testUsers{'canEdit group user'} = WebGUI::User->new($session, 'new'); +$testUsers{'canEdit group user'}->addToGroups([$testGroups{'canEdit asset'}->getId]); +$testUsers{'canEdit group user'}->username('Edit Group User'); +WebGUI::Test->groupsToDelete($testGroups{'canEdit asset'}); + +##A group and user for groupIdEdit +$testGroups{'canAdd asset'} = WebGUI::Group->new($session, 'new'); +$testUsers{'canAdd group user'} = WebGUI::User->new($session, 'new'); +$testUsers{'canAdd group user'}->addToGroups([$testGroups{'canAdd asset'}->getId]); +$testUsers{'canEdit group user'}->username('Can Add Group User'); +WebGUI::Test->groupsToDelete($testGroups{'canAdd asset'}); +WebGUI::Test->usersToDelete(values %testUsers); + +my $canAddMaker = WebGUI::Test::Maker::Permission->new(); +$canAddMaker->prepare({ + 'className' => 'WebGUI::Asset', + 'session' => $session, + 'method' => 'canAdd', + #'pass' => [3, $testUsers{'canAdd turnOnAdmin'}, $testUsers{'canAdd group user'} ], + 'pass' => [3, $testUsers{'canAdd group user'} ], + 'fail' => [1, $testUsers{'regular user'}, ], +}); + +my $canAddMaker2 = WebGUI::Test::Maker::Permission->new(); +$canAddMaker2->prepare({ + 'className' => 'WebGUI::Asset', + 'session' => $session, + 'method' => 'canAdd', + 'fail' => [$testUsers{'canAdd turnOnAdmin'},], +}); + +my $properties; +$properties = { + # '1234567890123456789012' + id => 'canEditAsset0000000010', + title => 'canEdit Asset Test', + url => 'canEditAsset1', + className => 'WebGUI::Asset', + ownerUserId => $testUsers{'owner'}->userId, + groupIdEdit => $testGroups{'canEdit asset'}->getId, + groupIdView => 7, +}; + +my $versionTag2 = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->tagsToRollback($versionTag2); + +my $canEditAsset = $rootAsset->addChild($properties, $properties->{id}); + +$versionTag2->commit; +$properties = {}; ##Clear out the hash so that it doesn't leak later by accident. + +my $canEditMaker = WebGUI::Test::Maker::Permission->new(); +$canEditMaker->prepare({ + 'object' => $canEditAsset, + 'method' => 'canEdit', + 'pass' => [3, $testUsers{'owner'}, $testUsers{'canEdit group user'}, ], + 'fail' => [1, $testUsers{'regular user'}, ], +}); + +my $versionTag3 = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->tagsToRollback($versionTag3); +$properties = { + # '1234567890123456789012' + id => 'canViewAsset0000000010', + title => 'canView Asset Test', + url => 'canViewAsset1', + className => 'WebGUI::Asset', + ownerUserId => $testUsers{'owner'}->userId, + groupIdEdit => $testGroups{'canEdit asset'}->getId, + groupIdView => $testGroups{'canEdit asset'}->getId, +}; + + +my $canViewAsset = $rootAsset->addChild($properties, $properties->{id}); + +$versionTag3->commit; +$properties = {}; ##Clear out the hash so that it doesn't leak later by accident. + +my $canViewMaker = WebGUI::Test::Maker::Permission->new(); +$canViewMaker->prepare( + { + 'object' => $canEditAsset, + 'method' => 'canView', + 'pass' => [1, 3, $testUsers{'owner'}, $testUsers{'canEdit group user'}, $testUsers{'regular user'},], + }, + { + 'object' => $canViewAsset, + 'method' => 'canView', + 'pass' => [3, $testUsers{'owner'}, $testUsers{'canEdit group user'}, ], + 'fail' => [1, $testUsers{'regular user'}, ], + }, +); + +plan tests => 114 + + 2*scalar(@getTitleTests) #same tests used for getTitle and getMenuTitle + + $canAddMaker->plan + + $canAddMaker2->plan + + $canEditMaker->plan + + $canViewMaker->plan + ; + +note "loadModule"; +{ + my $className = eval { WebGUI::Asset->loadModule('Moose::Asset'); }; + my $e = Exception::Class->caught; + isa_ok($e, 'WebGUI::Error::InvalidParam', 'loadModule must get a WebGUI::Asset class'); + cmp_deeply( + $e, + methods( + error => 'Not a WebGUI::Asset class', + param => 'Moose::Asset', + ), + '... checking error message', + ); +} + +# Test the default constructor +my $defaultAsset = WebGUI::Asset->getDefault($session); +is($defaultAsset, 'WebGUI::Asset::Wobject::Layout'); + +# Test the new constructor +my $assetId = "PBnav00000000000000001"; # one of the default nav assets + +# - explicit class +my $asset = WebGUI::Asset->newById($session, $assetId); +isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); +is ($asset->getId, $assetId, 'new constructor explicit - returns correct asset'); + +# - new by hashref properties +$asset = undef; +$asset = WebGUI::Asset->newByPropertyHashRef($session, { + className=>"WebGUI::Asset::Wobject::Navigation", + assetId=>$assetId + }); +isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); +is ($asset->getId, $assetId, 'new constructor newByHashref - returns correct asset'); + +# - implicit class +$asset = undef; +$asset = WebGUI::Asset::Wobject::Navigation->new($session, $assetId); +isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); +is ($asset->getId, $assetId, 'new constructor implicit - returns correct asset'); + +# - die gracefully +# -- no asset id +note "new, constructor fails"; +{ + my $deadAsset = eval { WebGUI::Asset->new($session, ''); }; + my $e = Exception::Class->caught; + isa_ok($e, 'WebGUI::Error::InvalidParam', 'new must get an assetId'); + cmp_deeply( + $e, + methods( + error => 'Asset constructor new() requires an assetId.', + ), + '... checking error message', + ); +} + +# -- no class +my $primevalAsset = WebGUI::Asset->new($session, $assetId); +isa_ok ($primevalAsset, 'WebGUI::Asset'); + +# Test the newById Constructor +$asset = undef; + +note "new"; +use WebGUI::Asset::Wobject::Navigation; +$asset = WebGUI::Asset::Wobject::Navigation->new($session, $assetId); +isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); +is ($asset->getId, $assetId, 'new constructor - returns correct asset when invoked with correct class'); + +note "getClassById"; +{ + my $deadAsset = eval { WebGUI::Asset->getClassById($session, 'RoysNonExistantAssetId'); }; + my $e = Exception::Class->caught; + isa_ok($e, 'WebGUI::Error::InvalidParam', 'getClassById must have a valid assetId'); + cmp_deeply( + $e, + methods( + error => "Couldn't lookup classname", + param => 'RoysNonExistantAssetId', + ), + '... checking error message', + ); +} + +note "newById"; +{ + my $deadAsset = eval { WebGUI::Asset->newById($session); }; + my $e = Exception::Class->caught; + isa_ok($e, 'WebGUI::Error::InvalidParam', "newById won't work without an assetId"); + cmp_deeply( + $e, + methods( + error => "newById must get an assetId", + ), + '... checking error message', + ); +} + +# -- no session +# Root Asset +isa_ok($rootAsset, 'WebGUI::Asset'); +is($rootAsset->getId, 'PBasset000000000000001', 'Root Asset ID check'); + +# getMedia Constructor + +my $mediaFolder = WebGUI::Asset->getMedia($session); +isa_ok($mediaFolder, 'WebGUI::Asset::Wobject::Folder'); +is($mediaFolder->getId, 'PBasset000000000000003', 'Media Folder Asset ID check'); + +# getImportNode Constructor + +my $importNode = WebGUI::Asset->getImportNode($session); +isa_ok($importNode, 'WebGUI::Asset::Wobject::Folder'); +is($importNode->getId, 'PBasset000000000000002', 'Import Node Asset ID check'); +is($importNode->getParent->getId, $rootAsset->getId, 'Import Nodes parent is Root Asset'); + +# tempspace Constructor + +my $tempNode = WebGUI::Asset->getTempspace($session); +isa_ok($tempNode, 'WebGUI::Asset::Wobject::Folder'); +is($tempNode->getId, 'tempspace0000000000000', 'Tempspace Asset ID check'); +is($tempNode->getParent->getId, $rootAsset->getId, 'Tempspace parent is Root Asset'); + +################################################################ +# +# urlExists +# +################################################################ + +##We need an asset with a URL for this one. + +my $importUrl = $importNode->get('url'); +my $importId = $importNode->getId; + +ok( WebGUI::Asset->urlExists($session, $importUrl), 'url for import node exists'); +ok( WebGUI::Asset->urlExists($session, uc($importUrl)), 'url for import node exists, case insensitive'); +ok( !WebGUI::Asset->urlExists($session, '/foo/bar/baz'), 'made up url does not exist'); + +ok( !WebGUI::Asset->urlExists($session, $importUrl, {assetId => $importId}), 'url for import node only exists at specific id'); +ok( !WebGUI::Asset->urlExists($session, '/foo/bar/baz', {assetId => $importId}), 'imaginary url does not exist at specific id'); +ok( WebGUI::Asset->urlExists($session, $importUrl, {assetId => 'notAnWebGUIId'}), 'imaginary url does not exist at wrong id'); + +################################################################ +# +# addEditLabel +# +################################################################ + +my $i18n = WebGUI::International->new($session, 'Asset_Wobject'); +is($importNode->addEditLabel, $i18n->get('edit').' '.$importNode->getName, 'addEditLabel, default mode is edit mode'); + +my $origRequest = $session->{_request}; +my $newRequest = Test::MockObject->new(); +my $func; +$newRequest->set_bound('body', \$func); +$newRequest->set_bound('param', \$func); +$session->{_request} = $newRequest; +$func = 'add'; +is($importNode->addEditLabel, $i18n->get('add').' '.$importNode->getName, 'addEditLabel, use add mode'); +$session->{_request} = $origRequest; + +################################################################ +# +# fixUrl +# +################################################################ + +my $versionTag = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->tagsToRollback($versionTag); +$versionTag->set({name=>"Asset tests"}); + +$properties = { + # '1234567890123456789012' + id => 'fixUrlAsset00000000012', + title => 'fixUrl Asset Test', + className => 'WebGUI::Asset::Wobject::Folder', + url => 'fixUrlFolderURL2', +}; + +my $fixUrlAsset = $defaultAsset->addChild($properties, $properties->{id}); + +# '1234567890123456789012' +$properties->{id} = 'fixUrlAsset00000000013'; +$properties->{url} = 'fixUrlFolderURL9'; + +my $fixUrlAsset2 = $defaultAsset->addChild($properties, $properties->{id}); + +# '1234567890123456789012' +$properties->{id} = 'fixUrlAsset00000000014'; +$properties->{url} = 'fixUrlFolderURL00'; + +my $fixUrlAsset3 = $defaultAsset->addChild($properties, $properties->{id}); + +# '1234567890123456789012' +$properties->{id} = 'fixUrlAsset00000000015'; +$properties->{url} = 'fixUrlFolderURL100'; + +my $fixUrlAsset4 = $defaultAsset->addChild($properties, $properties->{id}); +is($fixUrlAsset4->get('url'), 'fixurlfolderurl100', 'asset setup correctly for 100->101 test'); + +delete $properties->{url}; +# '1234567890123456789012' +$properties->{id} = 'fixUrlAsset00000000016'; +$properties->{menuTitle} = 'fix url folder url autogenerated'; + +my $fixUrlAsset5 = $defaultAsset->addChild($properties, $properties->{id}); + +my $properties2 = { + # '1234567890123456789012' + id => 'fixTitleAsset000000010', + title => '', + className => 'WebGUI::Asset::Snippet', + url => 'fixTitleAsset1', +}; + +my $fixTitleAsset = $defaultAsset->addChild($properties2, $properties2->{id}); +##Commit this asset right away +$fixTitleAsset->commit; + +$properties2 = { + # '1234567890123456789012' + id => 'getTitleAsset000000010', + title => '', + className => 'WebGUI::Asset::Snippet', + url => 'getTitleAsset1', +}; + +my $getTitleAsset = $defaultAsset->addChild($properties2, $properties2->{id}); +$getTitleAsset->commit; + +$versionTag->commit; + +$session->setting->set('urlExtension', undef); + +is($importNode->fixUrl('1234'.'-'x235 . 'abcdefghij'), '1234'.'-'x235 . 'abcdefghij', 'fixUrl leaves long URLs under 250 characters alone'); +is($importNode->fixUrl('1234'.'-'x250 . 'abcdefghij'), '1234'.'-'x216, 'fixUrl truncates long URLs over 250 characters to 220 characters'); + +WebGUI::Test->originalConfig('extrasURL'); +WebGUI::Test->originalConfig('uploadsURL'); +WebGUI::Test->originalConfig('assets'); + +$session->config->set('extrasURL', '/extras'); +$session->config->set('uploadsURL', '/uploads'); + +is($importNode->fixUrl('/extras'), '_extras', 'underscore prepended to URLs that match the extrasURL'); +is($importNode->fixUrl('/uploads'), '_uploads', 'underscore prepended to URLs that match the uploadsURL'); + +#Now that we have verified that extrasURL and uploadsURL both work, just test one. +$session->config->set('extrasURL', '/extras1/'); +is($importNode->fixUrl('/extras1'), '_extras1', 'trailing underscore in extrasURL does not defeat the check'); + +$session->config->set('extrasURL', 'http://mysite.com/extras2'); +is($importNode->fixUrl('/extras2'), '_extras2', 'underscore prepended to URLs that match the extrasURL, even with http://'); + +##Now, check extension removal + +is($importNode->fixUrl('one.html/two.html'), 'one/two.html', 'extensions are not allowed higher up in the path'); +is($importNode->fixUrl('one.html/two.html/three.html'), 'one/two/three.html', 'extensions are not allowed anywhere in the path'); +is($importNode->fixUrl('one.one.html/two.html/three.html'), 'one/two/three.html', 'multiple dot extensions are removed in any path element'); +is($importNode->fixUrl('.startsWithDot'), '.startswithdot', 'leading dots are okay'); + +##Now, check duplicate URLs + +is($importNode->fixUrl('/rootyRootRoot'), 'rootyrootroot', 'URLs are lowercased'); +is($importNode->fixUrl('/root'), 'root2', 'If a node exists, appends a "2" to it'); +my $importNodeURL = $importNode->getUrl; +$importNodeURL =~ s{ ^ / }{}x; +is($importNode->fixUrl($importNodeURL), $importNodeURL, q{fixing an asset's own URL returns it unchanged}); + +is($importNode->fixUrl('fixUrlFolderURL2'), 'fixurlfolderurl3', 'if a URL exists, fix it by incrementing any ending digits 2 -> 3'); +is($importNode->fixUrl('fixUrlFolderURL9'), 'fixurlfolderurl10', 'increments past single digits 9 -> 10'); +is($importNode->fixUrl('fixUrlFolderURL00'), 'fixurlfolderurl1', 'initial zeroes are not preserved 00 -> 1'); +is($importNode->fixUrl('fixUrlFolderURL100'), 'fixurlfolderurl101', '100->101'); + +is($fixUrlAsset5->fixUrl(), 'home/fix-url-folder-url-autogenerated', 'fixUrl will autogenerate a url if not provided one'); + +# Automatic extension adding +$session->setting->set('urlExtension', 'html'); +is($importNode->fixUrl('fixurl'), 'fixurl.html', 'Automatic adding of extensions works'); +is($importNode->fixUrl('fixurl.css'), 'fixurl.css', 'extensions aren\'t automatically added if there is already and extension'); +$session->setting->set('urlExtension', undef); + + +################################################################ +# +# getTitle +# getMenuTitle +# +################################################################ + +my $getTitleAssetName = $getTitleAsset->getName(); + +foreach my $test (@getTitleTests) { + my $expectedTitle = $test->{assetName} ? $getTitleAssetName : $test->{title}; + $getTitleAsset->update({ + title => $test->{title}, + menuTitle => $test->{title}, + }); + is($getTitleAsset->getTitle, $expectedTitle, $test->{comment}); + is($getTitleAsset->getMenuTitle, $expectedTitle, $test->{comment}); +} + +################################################################ +# +# getIcon +# +################################################################ + +like($importNode->getIcon, qr{folder.gif$}, 'getIcon gets correct icon for importNode'); +like($importNode->getIcon(1), qr{small/folder.gif$}, 'getIcon gets small icon for importNode'); + +my $extras = $session->config->get('extrasURL'); + +like($importNode->getIcon(), qr{$extras}, 'getIcon returns an icon from the extras URL'); + +like($defaultAsset->getIcon, qr{layout.gif$}, 'getIcon gets icon for a layout'); +like($fixTitleAsset->getIcon, qr{snippet.gif$}, 'getIcon gets icon for a snippet'); + + +TODO: { + local $TODO = "Coverage test"; + ok(0, "Test the default name for the icon, if not given in the definition sub"); +} + +################################################################ +# +# canAdd +# +################################################################ + +$session->config->set('assets/WebGUI::Asset/addGroup', $testGroups{'canAdd asset'}->getId ); + +$canAddMaker->run; + +#Without proper group setup, Turn On Admin is excluded from adding assets via assetAddPrivilege + +$canAddMaker2->run; + +################################################################ +# +# canEdit +# +################################################################ + +$canEditMaker->run; + +################################################################ +# +# canView +# +################################################################ + +$canViewMaker->run; + +################################################################ +# +# addMissing +# +################################################################ + +$session->user({ userId => 3 }); +$session->var->switchAdminOff; +is($canEditAsset->addMissing('/nowhereMan'), undef, q{addMissing doesn't return anything unless use is in Admin Mode}); + +$session->var->switchAdminOn; +my $addMissing = $canEditAsset->addMissing('/nowhereMan'); +ok($addMissing, 'addMissing returns some output when in Admin Mode'); + +{ + + my $parser = HTML::TokeParser->new(\$addMissing); + my $link = $parser->get_tag('a'); + my $url = $link->[1]{'href'} || '-'; + like($url, qr{func=add;class=WebGUI::Asset::Wobject::Layout;url=/nowhereMan$}, 'addMissing: Link will add a new page asset with correct URL'); + +} + +################################################################ +# +# getContainer +# +################################################################ + +is($rootAsset->getContainer->getId, $rootAsset->getId, 'getContainer: A folder is a container, its container is itself'); +is($fixTitleAsset->getContainer->getId, $defaultAsset->getId, 'getContainer: A snippet is not a container, its container is its parent'); + +################################################################ +# +# getName +# +################################################################ + +is($fixTitleAsset->getName, $i18n->get('assetName', 'Asset_Snippet'), 'getName: Returns the internationalized name of the Asset, Snippet'); +is($importNode->getName, $i18n->get('assetName', 'Asset_Folder'), 'getName: Returns the internationalized name of the Asset, Folder'); +is($canEditAsset->getName, $i18n->get('asset', 'Asset'), 'getName: Returns the internationalized name of the Asset, core Asset'); + +################################################################ +# +# getToolbarState +# toggleToolbar +# +################################################################ + +is($getTitleAsset->getToolbarState, undef, 'getToolbarState: default toolbar state is undef'); +$getTitleAsset->toggleToolbar(); +is($getTitleAsset->getToolbarState, 1, 'getToolbarState: toggleToolbarState toggled the state to 1'); +$getTitleAsset->toggleToolbar(); +is($getTitleAsset->getToolbarState, 0, 'getToolbarState: toggleToolbarState toggled the state to 0'); + +################################################################ +# +# getUiLevel +# +################################################################ + +is($canEditAsset->getUiLevel, 1, 'getUiLevel: WebGUI::Asset uses the default uiLevel of 1'); +is($fixTitleAsset->getUiLevel, 5, 'getUiLevel: Snippet has an uiLevel of 5'); + +my $origAssetUiLevel = $session->config->get('assetUiLevel'); +$session->config->set('assets/WebGUI::Asset/uiLevel', 8); +$session->config->set('assets/WebGUI::Asset::Snippet/uiLevel', 8); + +is($canEditAsset->getUiLevel, 8, 'getUiLevel: WebGUI::Asset has a configured uiLevel of 8'); +is($fixTitleAsset->getUiLevel, 8, 'getUiLevel: Snippet has a configured uiLevel of 8'); + + +################################################################ +# +# isValidRssItem +# +################################################################ + +is($canViewAsset->isValidRssItem, 1, 'isValidRssItem: By default, all Assets are valid RSS items'); + +################################################################ +# +# getEditTabs +# +################################################################ + +my @tabs = $canViewAsset->getEditTabs; +is(scalar(@tabs), 4, 'getEditTabs: 4 tabs by default'); + +################################################################ +# +# getEditForm +# +################################################################ + +$session->style->sent(0); ##Prevent extra output from being generated by session->style + ##At some point, a test will need to tie STDOUT and make sure + ##that the output is correct. +isa_ok($canViewAsset->getEditForm, 'WebGUI::TabForm', 'getEditForm: Returns a tabForm'); + +TODO: { + local $TODO = 'More getEditForm tests'; + ok(0, 'Validate form output'); +} + +################################################################ +# +# newByDynamicClass +# +################################################################ + +my $newFixTitleAsset = WebGUI::Asset->newByDynamicClass($session, $fixTitleAsset->getId); +isnt($newFixTitleAsset, undef, 'newByDynamicClass did not fail'); +isa_ok($newFixTitleAsset, 'WebGUI::Asset', 'newByDynamicClass: able to look up an existing asset by id'); +cmp_deeply($newFixTitleAsset->{_properties}, $fixTitleAsset->{_properties}, 'newByDynamicClass created a duplicate asset'); + +################################################################ +# +# getNotFound +# +################################################################ + +my $origNotFoundPage = $session->setting->get('notFoundPage'); + +$session->setting->set('notFoundPage', WebGUI::Asset->getDefault($session)->getId); + +isa_ok(WebGUI::Asset->getNotFound($session), 'WebGUI::Asset', 'getNotFound: Returns an asset'); +is(WebGUI::Asset->getNotFound($session)->getId, WebGUI::Asset->getDefault($session)->getId, 'getNotFound: Returns the correct asset'); + +$session->setting->set('notFoundPage', $fixTitleAsset->getId); +is(WebGUI::Asset->getNotFound($session)->getId, $fixTitleAsset->getId, 'getNotFound: Returns the correct asset on a different asset'); + +$session->setting->set('notFoundPage', $origNotFoundPage); + +################################################################ +# +# isExportable +# +################################################################ +is($rootAsset->get('isExportable'), 1, 'isExportable exists, defaults to 1'); + +################################################################ +# +# getSeparator +# +################################################################ +is($rootAsset->getSeparator, '~~~PBasset000000000000001~~~', 'getSeparator, known assetId'); +is($rootAsset->getSeparator('!'), '!!!PBasset000000000000001!!!', 'getSeparator, given pad character'); +isnt($rootAsset->getSeparator, $mediaFolder->getSeparator, 'getSeparator: unique string'); + +################################################################ +# +# get +# +################################################################ +my $assetProps = $rootAsset->get(); +my $funkyTitle = q{Miss Annie's Whoopie Emporium and Sasparilla Shop}; +$assetProps->{title} = $funkyTitle; + +isnt( $rootAsset->get('title'), $funkyTitle, 'get returns a safe copy of the Asset properties'); + +################################################################ +# +# getIsa +# +################################################################ +my $node = WebGUI::Asset->getRoot($session); +my $product1 = $node->addChild({ className => 'WebGUI::Asset::Sku::Product'}); +my $product2 = $node->addChild({ className => 'WebGUI::Asset::Sku::Product'}); +my $product3 = $node->addChild({ className => 'WebGUI::Asset::Sku::Product'}); + +my $getAProduct = WebGUI::Asset::Sku::Product->getIsa($session); +isa_ok($getAProduct, 'CODE', 'getIsa returns a sub ref'); +my $counter = 0; +my $productIds = []; +while( my $product = $getAProduct->()) { + ++$counter; + push @{ $productIds }, $product->getId; +} +is($counter, 3, 'getIsa: returned only 3 Products'); +cmp_bag($productIds, [$product1->getId, $product2->getId, $product3->getId], 'getIsa returned the correct 3 products'); + +my $getASku = WebGUI::Asset::Sku->getIsa($session); +$counter = 0; +my $skuIds = []; +while( my $sku = $getASku->()) { + ++$counter; + push @{ $skuIds }, $sku->getId; +} +is($counter, 3, 'getIsa: returned only 3 Products for a parent class'); +cmp_bag($skuIds, [$product1->getId, $product2->getId, $product3->getId], 'getIsa returned the correct 3 products for a parent class'); + +$product1->purge; +$product2->purge; +$product3->purge; + +################################################################ +# +# inheritUrlFromParent +# +################################################################ + +my $versionTag4 = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->tagsToRollback($versionTag4); +$versionTag4->set( { name => 'inheritUrlFromParent tests' } ); + +$properties = { + # '1234567890123456789012' + id => 'inheritUrlFromParent01', + title => 'inheritUrlFromParent01', + className => 'WebGUI::Asset::Wobject::Layout', + url => 'inheriturlfromparent01', +}; + +my $iufpAsset = $defaultAsset->addChild($properties, $properties->{id}); +$iufpAsset->commit; + +$properties2 = { + # '1234567890123456789012' + id => 'inheritUrlFromParent02', + title => 'inheritUrlFromParent02', + className => 'WebGUI::Asset::Wobject::Layout', + url => 'inheriturlfromparent02', +}; + +my $iufpAsset2 = $iufpAsset->addChild($properties2, $properties2->{id}); +$iufpAsset2->update( { inheritUrlFromParent => 1 } ); +$iufpAsset2->commit; +is($iufpAsset2->get('url'), 'inheriturlfromparent01/inheriturlfromparent02', 'inheritUrlFromParent works'); + +my $properties2a = { + # '1234567890123456789012' + id => 'inheritUrlFromParent2a', + title => 'inheritUrlFromParent2a', + className => 'WebGUI::Asset::Wobject::Layout', + url => 'inheriturlfromparent2a', + inheritUrlFromParent => 1, +}; + +my $iufpAsset2a = $iufpAsset->addChild($properties2a, $properties2a->{id}); +$iufpAsset2a->commit; +is($iufpAsset2a->get('url'), 'inheriturlfromparent01/inheriturlfromparent2a', '... works when created with the property'); + +# works for setting, now try disabling. Should not change the URL. +$iufpAsset2->update( { inheritUrlFromParent => 0 } ); +$iufpAsset2->commit; +is($iufpAsset2->get('url'), 'inheriturlfromparent01/inheriturlfromparent02', '... setting inheritUrlFromParent to 0 works'); + +# also make sure that it is actually disabled +is($iufpAsset2->get('inheritUrlFromParent'), 0, "... disabling inheritUrlFromParent actually works"); + +# works for setting and disabling, now ensure it recurses + +my $properties3 = { + # '1234567890123456789012' + id => 'inheritUrlFromParent03', + title => 'inheritUrlFromParent03', + className => 'WebGUI::Asset::Wobject::Layout', + url => 'inheriturlfromparent03', +}; +my $iufpAsset3 = $iufpAsset2->addChild($properties3, $properties3->{id}); +$iufpAsset3->commit; +$iufpAsset2->update( { inheritUrlFromParent => 1 } ); +$iufpAsset2->commit; +$iufpAsset3->update( { inheritUrlFromParent => 1 } ); +$iufpAsset3->commit; +is($iufpAsset3->get('url'), 'inheriturlfromparent01/inheriturlfromparent02/inheriturlfromparent03', '... recurses properly'); + +$iufpAsset2->update({url => 'iufp2'}); +is($iufpAsset2->get('url'), 'inheriturlfromparent01/iufp2', '... update works propertly when iUFP is not passed'); + + +################################################################ +# +# requestAutoCommit to move uncommitted child to uncommitted parent +# +################################################################ + +my $versionTag5 = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->tagsToRollback($versionTag5); +$versionTag5->set( { name => 'move commit of child to uncommitted parent on requestAutoCommit tests vt1' } ); + +$properties = { + # '1234567890123456789012' + id => 'moveVersionToParent_01', + title => 'moveVersionToParent_01', + className => 'WebGUI::Asset::Wobject::Layout', + url => 'moveVersionToParent_01', +}; + +my $parentAsset = $defaultAsset->addChild($properties, $properties->{id}); +my $parentVersionTag = WebGUI::VersionTag->new($session, $parentAsset->get('tagId')); +is($parentVersionTag->get('isCommitted'),0, 'built non-committed parent asset'); + + +my $versionTag6 = WebGUI::VersionTag->create($session, {}); +WebGUI::Test->tagsToRollback($versionTag6); +$versionTag6->set( { name => 'move commit of child to uncommitted parent on requestAutoCommit tests vt2' } ); +$versionTag6->setWorking; + +$properties2 = { + # '1234567890123456789012' + id => 'moveVersionToParent_03', + title => 'moveVersionToParent_03', + className => 'WebGUI::Asset::Wobject::Layout', + url => 'moveVersionToParent_03', +}; + +my $childAsset = $parentAsset->addChild($properties, $properties2->{id}); +my $testAsset = WebGUI::Asset->newPending($session, $childAsset->get('parentId')); +my $testVersionTag = WebGUI::VersionTag->new($session, $testAsset->get('tagId')); + +my $childVersionTag; +$childVersionTag = WebGUI::VersionTag->new($session, $childAsset->get('tagId')); +is($childVersionTag->get('isCommitted'),0, 'built non-committed child asset'); + +isnt($testAsset->get('tagId'),$childAsset->get('tagId'),'parent asset and child asset have different version tags'); +isnt($testVersionTag->getId,$childVersionTag->getId,'parent asset and child asset version tags unmatched'); + +eval { + $childAsset->requestAutoCommit; + $childVersionTag = WebGUI::VersionTag->new($session, $childAsset->get('tagId')); +}; +is($childVersionTag->get('isCommitted'),0, 'confirm non-committed child asset'); + +is($testAsset->get('tagId'),$childAsset->get('tagId'),'parent asset and child asset have same version tags'); + +eval { + $testVersionTag->commit; +}; + +is($testVersionTag->get('isCommitted'),1,'parent asset is now committed'); + +$childVersionTag = WebGUI::VersionTag->new($session, $childAsset->get('tagId')); +is($childVersionTag->get('isCommitted'),1,'child asset is now committed'); + +################################################################ +# +# cloneFromDb +# +################################################################ + +my $assetToCommit = $defaultAsset->addChild({ className => 'WebGUI::Asset::Snippet', title => 'Snippet to commit and clone from db', }); +my $cloneTag = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->tagsToRollback($cloneTag); +$cloneTag->commit; +is($assetToCommit->get('status'), 'pending', 'cloneFromDb: local asset is still pending'); +$assetToCommit = $assetToCommit->cloneFromDb; +is($assetToCommit->get('status'), 'approved', '... returns fresh, commited asset from the db'); + +##Return an array of hashrefs. Each hashref describes a test + +##Return an array of hashrefs. Each hashref describes a test +##for the getTitle and getMenuTitle tests. If "assetName" != 0, they +##will return the Asset's internationalized name. + +sub getTitleTests { + my $session = shift; + return ({ + title => undef, + assetName => 1, + comment => "getTitle: undef returns the Asset's name", + }, + { + title => '', + assetName => 1, + comment => "getTitle: null string returns the Asset's name", + }, + { + title => 'untitled', + assetName => 1, + comment => "getTitle: 'untitled' returns the Asset's name", + }, + { + title => 'UnTiTlEd', + assetName => 1, + comment => "getTitle: 'untitled' in any case returns the Asset's title", + }, + { + title => 'This is a good Title', + assetName => 0, + comment => "getTitle: Good titles are passed", + }, + ); +} diff --git a/t/Definition.t b/t/Definition.t new file mode 100644 index 000000000..b697a1d29 --- /dev/null +++ b/t/Definition.t @@ -0,0 +1,170 @@ +#------------------------------------------------------------------- +# WebGUI is Copyright 2001-2009 Plain Black Corporation. +#------------------------------------------------------------------- +# Please read the legal notices (docs/legal.txt) and the license +# (docs/license.txt) that came with this distribution before using +# this software. +#------------------------------------------------------------------- +# http://www.plainblack.com info@plainblack.com +#------------------------------------------------------------------- + +use FindBin; +use strict; +use warnings; +no warnings qw(uninitialized); +use lib "$FindBin::Bin/lib"; + +use WebGUI::Test; + +use Test::More tests => 15; +use Test::Deep; +use Test::Exception; + +my $session = WebGUI::Test->session; + +my $called_getProperties; +{ + package WGT::Class; + use WebGUI::Definition; + + aspect 'aspect1' => 'aspect1 value'; + property 'property1' => ( + arbitrary_key => 'arbitrary_value', + label => 'property1', + ); + property 'property2' => ( + nother_key => 'nother_value', + label => 'property2', + ); + + # aspects create methods + ::can_ok +__PACKAGE__, 'aspect1'; + + # propeties create methods + ::can_ok +__PACKAGE__, 'property1'; + + # role applied + ::can_ok +__PACKAGE__, 'update'; + ::can_ok +__PACKAGE__, 'get'; + ::can_ok +__PACKAGE__, 'set'; + + ::cmp_deeply( + [ +__PACKAGE__->getProperties ], + [qw/property1 property2/], + 'getProperties works as a class method' + ); + +} + +{ + package WGT::Class2; + use WebGUI::Definition; + + aspect 'aspect1' => 'aspect1 value'; + property 'property3' => ( label => 'label' ); + property 'property1' => ( label => 'label' ); + property 'property2' => ( label => 'label' ); + + my @set_order = (); + + before 'property1' => sub { + my $self = shift; + push @set_order, '1'; + }; + + before 'property2' => sub { + my $self = shift; + push @set_order, '2'; + }; + + before 'property3' => sub { + my $self = shift; + push @set_order, '3'; + }; + + my $object = WGT::Class2->new(); + $object->set(property1 => 1, property2 => 0, property3 => 1); + ::cmp_deeply( [ @set_order ], [3,1,2], 'properties set in insertion order'); + + @set_order = (); + $object->set(property2 => 1, property3 => 0, property1 => 1); + ::cmp_deeply( [ @set_order ], [3,1,2], '... and again'); + + ::cmp_deeply( + $object->getFormProperties('property1'), + { label => 'label' }, + 'getFormProperties works for a simple set of properties' + ); + +} + +{ + package WGT::Class3; + use WebGUI::Definition; + + aspect 'aspect1' => 'aspect1 value'; + property 'property1' => ( + label => ['webgui', 'WebGUI'], + hoverHelp => ['webgui help %s', 'WebGUI', 'extra'], + options => \&property1_options, + named_url => \&named_url, + ); + has session => ( + is => 'ro', + required => 1, + ); + sub property1_options { + return { one => 1, two => 2, three => 3 }; + } + sub named_url { + my ($self, $property, $property_name) = @_; + ::note "Checking arguments passed to subroutine for defining a form property"; + ::isa_ok($self, 'WGT::Class3'); + ::isa_ok($property, 'WebGUI::Definition::Meta::Property'); + ::is($property_name, 'named_url', 'form property name sent'); + return $property->name; + } + + my $object = WGT::Class3->new({session => $session}); + + ::cmp_deeply( + $object->getFormProperties('property1'), + { + label => 'WebGUI', + hoverHelp => 'webgui help extra', + options => { one => 1, two => 2, three => 3 }, + named_url => 'property1', + }, + 'getFormProperties handles i18n and subroutines' + ); + +} + +{ + package WGT::Class4; + use WebGUI::Definition; + extends 'WGT::Class3'; + + aspect 'aspect41' => 'aspect41 value'; + property 'property41' => ( + label => ['webgui', 'WebGUI'], + ); + has something => ( + is => 'rw', + ); + + my $object3 = WGT::Class3->new({session => $session}); + my $object4 = WGT::Class4->new({session => $session}); + + ::cmp_bag ( + [WGT::Class3->meta->get_all_attributes_list], + [qw/ property1 session /], + 'get_all_aspects_list returns all aspects in all metaclasses for the class' + ); + + ::cmp_bag ( + [WGT::Class4->meta->get_all_attributes_list], + [qw/ property41 something property1 session /], + '... checking inherited class' + ); +} diff --git a/t/Definition/Asset.t b/t/Definition/Asset.t new file mode 100644 index 000000000..cbb31fcb9 --- /dev/null +++ b/t/Definition/Asset.t @@ -0,0 +1,258 @@ +#------------------------------------------------------------------- +# WebGUI is Copyright 2001-2009 Plain Black Corporation. +#------------------------------------------------------------------- +# Please read the legal notices (docs/legal.txt) and the license +# (docs/license.txt) that came with this distribution before using +# this software. +#------------------------------------------------------------------- +# http://www.plainblack.com info@plainblack.com +#------------------------------------------------------------------- + +use strict; +use warnings; +no warnings qw(uninitialized); + +use FindBin; +use lib "$FindBin::Bin/../lib"; + +use Test::More 'no_plan'; #tests => 1; +use Test::Deep; +use Test::Exception; +use WebGUI::Test; + +{ + package WGT::Class::Atset; + use WebGUI::Definition::Asset; + + aspect tableName => 'asset'; + ::dies_ok { property 'property1' => (); } 'must have a fieldType'; + ::dies_ok { property 'property1' => (fieldType => 'text'); } 'must pass either a label or noFormPost flag'; + ::lives_ok { property 'property1' => ( + fieldType => 'YUI Super Form', + noFormPost => '1', + ); + } '... pass noFormPost flag'; + ::lives_ok { property 'property1' => ( + fieldType => 'YUI Super Form', + label => 'JSON Powered Uber Widget', + ); + } '... pass label'; + +} + +{ + package WGT::Class::Asset; + use WebGUI::Definition::Asset; + + aspect tableName => 'asset'; + property 'property2' => ( + fieldType => 'text', + label => 'property2', + ); + property 'property1' => ( + fieldType => 'text', + label => 'property1', + ); + + my $filter2 = 0; + around 'property2' => sub { + my $orig = shift; + my $self = shift; + $filter2 = 1; + $self->$orig(@_); + }; + + my $written; + sub write { + $written++; + } + + ::is +__PACKAGE__->meta->get_attribute('property1')->tableName, 'asset', 'tableName copied from attribute into property'; + + ::can_ok +__PACKAGE__, 'update'; + ::can_ok +__PACKAGE__, 'tableName'; + + my $object = __PACKAGE__->new; + $object->set({property1 => 'property value'}); + ::is $object->property1, 'property value', 'checking set, hashref form'; + + $object->set('property1', 'newer property value'); + ::is $object->property1, 'newer property value', '... hash form'; + + # write called + $object->update; + ::is $written, 1, 'update calls write'; + + $object->property2('foo'); + ::is $filter2, 1, 'around modifier called'; + ::is $object->property2(), 'foo', '...and it works for set/get'; + + $object->update(property2 => 'bar', property1 => 'baz'); + ::is $object->property1(), 'baz', 'update set property1'; + ::is $object->property2(), 'bar', 'and ... property1'; + + ::is $object->tableName, 'asset', 'tableName set for object'; + $object->tableName('not asset'); + ::is $object->tableName, 'asset', 'tableName may not be set from the object'; + $object->meta->tableName('not asset'); + ::is $object->tableName, 'not asset', 'object can access meta and change the table'; + $object->meta->tableName('asset'); + + ::cmp_deeply( + [ $object->meta->get_property_list ], + [qw/property2 property1/], + '->meta->get_property_list returns properties as a list in insertion order' + ); + + ::cmp_deeply( + [ $object->meta->get_all_properties ], + ::array_each(::isa('WebGUI::Definition::Meta::Property::Asset')), + '->meta->get_all_properties returns a list of Properties' + ); + + ::cmp_deeply( + [$object->getProperties ], + [qw/property2 property1/], + 'getProperties is an alias for ->meta->get_property_list' + ); + + ::cmp_deeply( + [$object->meta->get_tables ], + [qw/asset/], + 'get_tables returns a list of all tables used by this class' + ); + + my $object2 = __PACKAGE__->new(tableName => 'notAsset'); + ::is $object2->tableName, 'asset', 'tableName ignored in constructor'; + + ::cmp_deeply( + [ __PACKAGE__->meta->get_tables ], + [qw/asset/], + 'get_tables works for a simple asset' + ); + +} + +{ + + package WGT::Class::AlsoAsset; + use WebGUI::Definition::Asset; + + aspect tableName => 'asset'; + property 'property1' => ( + fieldType => 'text', + label => 'property1', + ); + property 'property2' => ( + fieldType => 'text', + label => 'property2', + ); + property 'property3' => ( + fieldType => 'text', + label => 'property3', + ); + + package WGT::Class::Asset::Snippet; + use WebGUI::Definition::Asset; + extends 'WGT::Class::AlsoAsset'; + + aspect tableName => 'snippet'; + property 'property10' => ( + fieldType => 'text', + label => 'property10', + ); + property 'property11' => ( + fieldType => 'text', + label => 'property11', + ); + + package main; + + is +WGT::Class::AlsoAsset->tableName, 'asset', 'tableName set in base class'; + + is +WGT::Class::Asset::Snippet->meta->find_attribute_by_name('property10')->tableName, 'snippet', 'tableName set in subclass'; + is +WGT::Class::Asset::Snippet->meta->find_attribute_by_name('property1')->tableName, 'asset', '... but inherited properties keep their tableName'; + + cmp_bag( + [ map {$_->name} WGT::Class::AlsoAsset->meta->get_attributes ], + [qw/property1 property2 property3/], + 'get_attributes returns attributes for my class' + ); + + cmp_bag( + [ map {$_->name} WGT::Class::Asset::Snippet->meta->get_attributes ], + [qw/property10 property11/], + '...even in a subclass' + ); + + cmp_deeply( + [ WGT::Class::Asset::Snippet->getProperties ], + [qw/property1 property2 property3 property10 property11/], + 'checking inheritance of properties by name, insertion order' + ); + + ::cmp_deeply( + [ WGT::Class::AlsoAsset->meta->get_tables ], + [qw/asset/], + 'get_tables: checking inheritance' + ); + + ::cmp_deeply( + [ WGT::Class::Asset::Snippet->meta->get_tables ], + [qw/asset snippet/], + 'get_tables: checking inheritance on subclass' + ); + +} + +{ + + package WGT::Class::Asset::NotherOne; + use WebGUI::Definition::Asset; + extends 'WGT::Class::AlsoAsset'; + + aspect tableName => 'snippet'; + property 'property10' => ( + fieldType => 'text', + label => 'property10', + ); + property 'property1' => ( + fieldType => 'text', + label => 'property1', + ); + + package main; + + cmp_deeply( + [WGT::Class::Asset::NotherOne->getProperties], + [qw/property1 property2 property3 property10/], + 'checking inheritance of properties by name, insertion order with an overridden property' + ); + +} + +{ + + package WGT::Class::Asset::Tertiary; + use WebGUI::Definition::Asset; + extends 'WGT::Class::AlsoAsset'; + + aspect tableName => 'tertius'; + property 'defaulted' => ( + fieldType => 'text', + label => 'defaulted', + default => 'a sane default', + ); + property 'no_default' => ( + fieldType => 'text', + label => 'noDefault', + ); + + package main; + my $object = WGT::Class::Asset::Tertiary->new; + is $object->defaulted(), 'a sane default', 'setup: checking default'; + is $object->no_default(), undef, '... and one without default'; + + $object->defaulted(undef); + is $object->defaulted(), undef, 'Moose setters accept undef'; +} diff --git a/t/Macro/RootTitle.t b/t/Macro/RootTitle.t index 16a82ca56..65110757f 100644 --- a/t/Macro/RootTitle.t +++ b/t/Macro/RootTitle.t @@ -32,6 +32,7 @@ my $session = WebGUI::Test->session; my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"Adding assets for RootTitle tests"}); +addToCleanup($versionTag); my $root = WebGUI::Asset->getRoot($session); my %properties_A = ( @@ -117,7 +118,7 @@ my $asset_ = $root->addChild(\%properties__, $properties__{id}); $versionTag->commit; -my $origLineage = $asset_->get('lineage'); +my $origLineage = $asset_->lineage; my $newLineage = substr $origLineage, 0, length($origLineage)-1; $session->db->write('update asset set lineage=? where assetId=?',[$newLineage, $asset_->getId]); @@ -160,16 +161,11 @@ my @testSets = ( ); my $numTests = scalar @testSets; -$numTests += 2; +$numTests += 1; plan tests => $numTests; -my $macro = 'WebGUI::Macro::RootTitle'; -my $loaded = use_ok($macro); - -SKIP: { - -skip "Unable to load $macro", $numTests-1 unless $loaded; +use WebGUI::Macro::RootTitle; is( WebGUI::Macro::RootTitle::process($session), @@ -184,11 +180,6 @@ foreach my $testSet (@testSets) { is($output, $testSet->{title}, $testSet->{comment}); } -} - END { ##Clean-up after yourself, always $session->db->write('update asset set lineage=? where assetId=?',[$origLineage, $asset_->getId]); - if (defined $versionTag and ref $versionTag eq 'WebGUI::VersionTag') { - $versionTag->rollback; - } }