Merge branch 'master' into 8-merge

Conflicts:
	docs/gotcha.txt
	lib/WebGUI.pm
	lib/WebGUI/Asset.pm
	lib/WebGUI/Asset/File/GalleryFile/Photo.pm
	lib/WebGUI/Asset/Post.pm
	lib/WebGUI/Asset/Story.pm
	lib/WebGUI/Asset/Template.pm
	lib/WebGUI/Asset/Wobject/Calendar.pm
	lib/WebGUI/Asset/Wobject/GalleryAlbum.pm
	lib/WebGUI/Asset/Wobject/Navigation.pm
	lib/WebGUI/AssetLineage.pm
	lib/WebGUI/AssetTrash.pm
	lib/WebGUI/Config.pm
	lib/WebGUI/Form/Template.pm
	lib/WebGUI/Group.pm
	lib/WebGUI/Inbox.pm
	lib/WebGUI/Workflow/Activity/DeleteExpiredSessions.pm
	lib/WebGUI/Workflow/Activity/TrashExpiredEvents.pm
	sbin/testEnvironment.pl
	t/AdSpace.t
	t/AdSpace/Ad.t
	t/Asset/Asset.t
	t/Asset/AssetExportHtml.t
	t/Asset/AssetLineage.t
	t/Asset/EMSSubmissionForm.t
	t/Asset/Event.t
	t/Asset/File/GalleryFile/Photo/00base.t
	t/Asset/File/GalleryFile/Photo/comment.t
	t/Asset/File/GalleryFile/Photo/download.t
	t/Asset/File/GalleryFile/Photo/edit.t
	t/Asset/File/GalleryFile/Photo/exif.t
	t/Asset/File/GalleryFile/Photo/makeResolutions.t
	t/Asset/File/GalleryFile/Photo/makeShortcut.t
	t/Asset/File/Image/setfile.t
	t/Asset/File/setfile.t
	t/Asset/Post.t
	t/Asset/Post/Thread/getAdjacentThread.t
	t/Asset/Sku.t
	t/Asset/Sku/ProductCollateral.t
	t/Asset/Story.t
	t/Asset/Template.t
	t/Asset/Template/HTMLTemplateExpr.t
	t/Asset/Wobject/Gallery/00base.t
	t/Asset/Wobject/GalleryAlbum/00base.t
	t/Asset/Wobject/GalleryAlbum/ajax.t
	t/Asset/Wobject/GalleryAlbum/delete.t
	t/Asset/Wobject/Matrix.t
	t/Asset/Wobject/StoryArchive.t
	t/Asset/Wobject/Survey/ExpressionEngine.t
	t/Asset/Wobject/Survey/Reports.t
	t/AssetAspect/RssFeed.t
	t/Auth/mech.t
	t/Config.t
	t/Group.t
	t/Help/isa.t
	t/International.t
	t/Mail/Send.t
	t/Operation/AdSpace.t
	t/Operation/Auth.t
	t/Pluggable.t
	t/Session.t
	t/Session/DateTime.t
	t/Session/ErrorHandler.t
	t/Session/Scratch.t
	t/Session/Stow.t
	t/Shop/Cart.t
	t/Shop/Pay.t
	t/Shop/PayDriver/ITransact.t
	t/Shop/PayDriver/PayPalStd.t
	t/Shop/Ship.t
	t/Shop/ShipDriver.t
	t/Shop/TaxDriver/EU.t
	t/Shop/TaxDriver/Generic.t
	t/Shop/Transaction.t
	t/Shop/Vendor.t
	t/VersionTag.t
	t/Workflow/Activity/ArchiveOldStories.t
	t/Workflow/Activity/ExpireIncompleteSurveyResponses.t
	t/lib/WebGUI/Test.pm
This commit is contained in:
Doug Bell 2010-07-09 11:48:30 -05:00
commit babfa74209
238 changed files with 4557 additions and 1287 deletions

View file

@ -1,3 +1,47 @@
7.9.9
- fixed #11693: Shopping cart does not show for visitor user
- fixed: missing per-item template variables for the cart.
7.9.8
- fixed #11651: First Day of Week is a string...
- fixed #11656: Thingy: Select list fields are not sorted properly
- fixed #11662: yahooapis.com sourced links
- fixed #11658: tmpl var message missing in template help for the cart
- fixed: many other template variables for the cart
- fixed #11628: Message Board: Last Post doesn't show up in CS Thread List
- fixed #11646: Post and Thread Last Post
- fixed #11626: Duplicate messages from Collab Systems
- fixed #11667: Shop: unable to remove item from Cart
- fixed #11550: Pending assets in the clipboard or trash are not visible from the approval screen
- fixed #11678: Story Archive leaks version tags
- fixed #11671: Approving version tags takes up 1 to hour to take affect.
- fixed #11663: More detail section of image gallery
- fixed #11681: Gallery album chokes on photo w/ missing properties
- fixed #11612: Thingy: Search on "list" type fields does not work properly
7.9.7
- added #11571: Allow return from photo edit view to gallery edit view
- fixed: Reject form submissions without image selected for upload in edit view of Photo asset
- fixed #11596: Calendar: all day events leaking
- fixed #11604: scheduled workflows getting deleted
- fixed #11613: Thingy: If next action after add is to add more things, previous data remains
- added API method commitAsUser allowing developers to commit version tags as other users
- fixed: The template form plugin would return an empty string when getValueAsHtml was called. ( Martin Kamerbeek / Oqapi )
- fixed #11611: Thingy: The add field pop up box has multiple "Text" field types
- fixed #11610: Bad hover help for CS sortBy field
- fixed #11605: UserList refers to non-existent "publicEmail" user profiling field
- fixed #11595: Orphaned data in inbox_messageState
- fixed AddressBook feedback for missing fields.
- fixed #11606: Syndicated Content feed returns a relative link
- fixed #11614: Forums: Sort Fields
- fixed #11616: No access to /root
- fixed #11619: Trash Expired Events not trashing events
- fixed #11623: Navigation CSS-id
- fixed #11629: WebGUI Collateral Manager = Error
- fixed #11622: Archived CSS entries displayable.
- fixed #11560: Email footer hidden from Outlook users
- fixed #11643: Account/Contributions: does not show archived content
7.9.6
- new checkbox in the asset manager for clearing the package flag on import
- fixed #11597: manageTrash and newlines

File diff suppressed because one or more lines are too long

View file

@ -17,6 +17,12 @@ save you many hours of grief.
- Moose
- CHI
7.9.7
--------------------------------------------------------------------
* Due to a bug introduced in 7.9.3, Scheduler tasks may have been deleted
from your site. The 7.9.7 upgrade will restore all default tasks, and tasks
for handling email from Collaboration Systems, but you should check any Scheduler
tasks that you have created.
7.9.6
--------------------------------------------------------------------

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,241 @@
#!/usr/bin/env perl
#-------------------------------------------------------------------
# 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
#-------------------------------------------------------------------
our ($webguiRoot);
BEGIN {
$webguiRoot = "../..";
unshift (@INC, $webguiRoot."/lib");
}
use strict;
use Getopt::Long;
use WebGUI::Session;
use WebGUI::Storage;
use WebGUI::Asset;
use WebGUI::Asset::Wobject::Collaboration;
use WebGUI::Exception;
use WebGUI::Workflow::Cron;
use WebGUI::Utility qw/isIn/;
my $toVersion = '7.9.7';
my $quiet; # this line required
my $session = start(); # this line required
# upgrade functions go here
restoreDefaultCronJobs($session);
restoreCsCronJobs($session);
cleanup_inbox_messageStateTable($session);
finish($session); # this line required
#----------------------------------------------------------------------------
# Describe what our function does
#sub exampleFunction {
# my $session = shift;
# print "\tWe're doing some stuff here that you should know about... " unless $quiet;
# # and here's our code
# print "DONE!\n" unless $quiet;
#}
#----------------------------------------------------------------------------
# Describe what our function does
sub cleanup_inbox_messageStateTable {
my $session = shift;
print "\tDelete dead entries from the inbox_MessageState table. This may take a long time... " unless $quiet;
# and here's our code
my $source = $session->db->read("select messageId from inbox_messageState s where not exists(select messageId from inbox where messageId = s.messageId)");
my $cleaner = $session->db->prepare("delete from inbox_messageState where messageId=?");
while (my ($messageId) = $source->array) {
$cleaner->execute([$messageId]);
}
$source->finish;
$cleaner->finish;
print "DONE!\n" unless $quiet;
}
#----------------------------------------------------------------------------
# Describe what our function does
sub restoreDefaultCronJobs {
my $session = shift;
# and here's our code
print "\tRestore missing default cron jobs that may have been deleted... " unless $quiet;
my $tasks = WebGUI::Workflow::Cron->getAllTasks($session);
my @taskIds = map { $_->getId } @{ $tasks };
if (! isIn('pbcron0000000000000001', @taskIds)) {
print "\n\t\tRestoring Daily Maintenance Task... " unless $quiet;
WebGUI::Workflow::Cron->create($session, {
title => "Daily Maintenance", dayOfMonth => '*',
enabled => 1, monthOfYear => '*',
runOnce => 0, dayOfWeek => '*',
minuteOfHour => 30, workflowId => 'pbworkflow000000000001',
hourOfDay => 23, priority => 3,
},
'pbcron0000000000000001');
}
if (! isIn('pbcron0000000000000002', @taskIds)) {
print "\n\t\tRestoring Weekly Maintenance Task... " unless $quiet;
WebGUI::Workflow::Cron->create($session, {
title => "Weekly Maintenance", dayOfMonth => '*',
enabled => 1, monthOfYear => '*',
runOnce => 0, dayOfWeek => '0',
minuteOfHour => 30, workflowId => 'pbworkflow000000000002',
hourOfDay => 1, priority => 3,
},
'pbcron0000000000000002');
}
if (! isIn('pbcron0000000000000003', @taskIds)) {
print "\n\t\tRestoring Hourly Maintenance Task... " unless $quiet;
WebGUI::Workflow::Cron->create($session, {
title => "Hourly Maintenance", dayOfMonth => '*',
enabled => 1, monthOfYear => '*',
runOnce => 0, dayOfWeek => '*',
minuteOfHour => 15, workflowId => 'pbworkflow000000000004',
hourOfDay => '*', priority => 3,
},
'pbcron0000000000000003');
}
if (! isIn('pbcron0000000000000004', @taskIds)) {
print "\n\t\tRestoring Email Delivery Task... " unless $quiet;
WebGUI::Workflow::Cron->create($session, {
title => "Send Queued Email Messages Every 5 Minutes",
dayOfMonth => '*',
enabled => 1, monthOfYear => '*',
runOnce => 0, dayOfWeek => '*',
minuteOfHour => '*/5', workflowId => 'pbworkflow000000000007',
hourOfDay => '*', priority => 3,
},
'pbcron0000000000000004');
}
print "DONE!\n" unless $quiet;
}
#----------------------------------------------------------------------------
# Describe what our function does
sub restoreCsCronJobs {
my $session = shift;
print "\tRestore missing Collaboration System cron jobs that may have been deleted... " unless $quiet;
my $i18n = WebGUI::International->new($session, "Asset_Collaboration");
my $getCs = WebGUI::Asset::Wobject::Collaboration->getIsa($session);
CS: while (1) {
my $cs = eval { $getCs->(); };
if (my $e = Exception::Class->caught()) {
$session->log->error($@);
next CS;
}
last CS unless $cs;
##Do something useful with $product
my $cron = undef;
if ($cs->get("getMailCronId")) {
$cron = WebGUI::Workflow::Cron->new($session, $cs->get("getMailCronId"));
}
next CS if $cron;
$cron = WebGUI::Workflow::Cron->create($session, {
title => $cs->getTitle." ".$i18n->get("mail"),
minuteOfHour => "*/".($cs->get("getMailInterval")/60),
className => (ref $cs),
methodName => "new",
parameters => $cs->getId,
workflowId => "csworkflow000000000001"
});
$cs->update({getMailCronId=>$cron->getId});
if ($cs->get("getMail")) {
$cron->set({enabled=>1,title=>$cs->getTitle." ".$i18n->get("mail"), minuteOfHour=>"*/".($cs->get("getMailInterval")/60)});
} else {
$cron->set({enabled=>0,title=>$cs->getTitle." ".$i18n->get("mail"), minuteOfHour=>"*/".($cs->get("getMailInterval")/60)});
}
}
print "DONE!\n" unless $quiet;
}
# -------------- DO NOT EDIT BELOW THIS LINE --------------------------------
#----------------------------------------------------------------------------
# Add a package to the import node
sub addPackage {
my $session = shift;
my $file = shift;
print "\tUpgrading package $file\n" unless $quiet;
# Make a storage location for the package
my $storage = WebGUI::Storage->createTemp( $session );
$storage->addFileFromFilesystem( $file );
# Import the package into the import node
my $package = eval {
my $node = WebGUI::Asset->getImportNode($session);
$node->importPackage( $storage, {
overwriteLatest => 1,
clearPackageFlag => 1,
setDefaultTemplate => 1,
} );
};
if ($package eq 'corrupt') {
die "Corrupt package found in $file. Stopping upgrade.\n";
}
if ($@ || !defined $package) {
die "Error during package import on $file: $@\nStopping upgrade\n.";
}
return;
}
#-------------------------------------------------
sub start {
my $configFile;
$|=1; #disable output buffering
GetOptions(
'configFile=s'=>\$configFile,
'quiet'=>\$quiet
);
my $session = WebGUI::Session->open($webguiRoot,$configFile);
$session->user({userId=>3});
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Upgrade to ".$toVersion});
return $session;
}
#-------------------------------------------------
sub finish {
my $session = shift;
updateTemplates($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->commit;
$session->db->write("insert into webguiVersion values (".$session->db->quote($toVersion).",'upgrade',".time().")");
$session->close();
}
#-------------------------------------------------
sub updateTemplates {
my $session = shift;
return undef unless (-d "packages-".$toVersion);
print "\tUpdating packages.\n" unless ($quiet);
opendir(DIR,"packages-".$toVersion);
my @files = readdir(DIR);
closedir(DIR);
my $newFolder = undef;
foreach my $file (@files) {
next unless ($file =~ /\.wgpkg$/);
# Fix the filename to include a path
$file = "packages-" . $toVersion . "/" . $file;
addPackage( $session, $file );
}
}
#vim:ft=perl

View file

@ -0,0 +1,190 @@
#!/usr/bin/env perl
#-------------------------------------------------------------------
# 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
#-------------------------------------------------------------------
our ($webguiRoot);
BEGIN {
$webguiRoot = "../..";
unshift (@INC, $webguiRoot."/lib");
}
use strict;
use Getopt::Long;
use WebGUI::Session;
use WebGUI::Storage;
use WebGUI::Asset;
use WebGUI::Asset::Wobject::Collaboration;
use WebGUI::Asset::Post::Thread;
use WebGUI::ProfileField;
my $toVersion = '7.9.8';
my $quiet; # this line required
my $session = start(); # this line required
# upgrade functions go here
changeFirstDayOfWeekDefault($session);
updateLastPostCS($session);
updateLastPostThread($session);
addTwitterAuth( $session );
finish($session); # this line required
#----------------------------------------------------------------------------
# Describe what our function does
#sub exampleFunction {
# my $session = shift;
# print "\tWe're doing some stuff here that you should know about... " unless $quiet;
# # and here's our code
# print "DONE!\n" unless $quiet;
#}
#----------------------------------------------------------------------------
# Add twitter auth and macro
sub addTwitterAuth {
my $session = shift;
print "\tAdding twitter auth method... " unless $quiet;
$session->config->addToArray( 'authMethods', 'Twitter' );
$session->config->addToHash( 'macros', "TwitterLogin" => "TwitterLogin" );
$session->setting->set( 'twitterEnabled', 0 );
$session->setting->set( 'twitterTemplateIdChooseUsername', 'mfHGkp6t9gdclmzN33OEnw' );
print "DONE!\n" unless $quiet;
}
#----------------------------------------------------------------------------
# Describe what our function does
sub changeFirstDayOfWeekDefault {
my $session = shift;
print "\tMake the default for firstDayOfWeek a number instead of a string... " unless $quiet;
# and here's our code
my $profileField = WebGUI::ProfileField->new($session, 'firstDayOfWeek');
my $properties = $profileField->get();
$properties->{dataDefault} = 0;
$profileField->set($properties);
print "DONE!\n" unless $quiet;
}
#----------------------------------------------------------------------------
# Describe what our function does
sub updateLastPostCS {
my $session = shift;
print "\tUpdating last post information in every Collaboration System. This could take a very long time... " unless $quiet;
# and here's our code
my $getCs = WebGUI::Asset::Wobject::Collaboration->getIsa($session);
CS: while (my $cs = eval { $getCs->() } ) {
next CS if Exception::Class->caught();
last CS if ! $cs;
next CS unless $cs->get('lastPostId');
my $lastPost = WebGUI::Asset->newByDynamicClass($session, $cs->get('lastPostId'));
next CS unless $lastPost && $lastPost->get('status') eq 'archived';
$lastPost->disqualifyAsLastPost;
}
print "DONE!\n" unless $quiet;
}
#----------------------------------------------------------------------------
# Describe what our function does
sub updateLastPostThread {
my $session = shift;
print "\tUpdating last post information in every Thread. This could also take a very long time... " unless $quiet;
# and here's our code
my $getThread = WebGUI::Asset::Wobject::Collaboration->getIsa($session);
THREAD: while (my $thread = eval { $getThread->() } ) {
next THREAD if Exception::Class->caught();
last THREAD if ! $thread;
next THREAD unless $thread->get('lastPostId');
my $lastPost = WebGUI::Asset->newByDynamicClass($session, $thread->get('lastPostId'));
next THREAD unless $lastPost && $lastPost->get('status') eq 'archived';
$lastPost->disqualifyAsLastPost;
}
print "DONE!\n" unless $quiet;
}
# -------------- DO NOT EDIT BELOW THIS LINE --------------------------------
#----------------------------------------------------------------------------
# Add a package to the import node
sub addPackage {
my $session = shift;
my $file = shift;
print "\tUpgrading package $file\n" unless $quiet;
# Make a storage location for the package
my $storage = WebGUI::Storage->createTemp( $session );
$storage->addFileFromFilesystem( $file );
# Import the package into the import node
my $package = eval {
my $node = WebGUI::Asset->getImportNode($session);
$node->importPackage( $storage, {
overwriteLatest => 1,
clearPackageFlag => 1,
setDefaultTemplate => 1,
} );
};
if ($package eq 'corrupt') {
die "Corrupt package found in $file. Stopping upgrade.\n";
}
if ($@ || !defined $package) {
die "Error during package import on $file: $@\nStopping upgrade\n.";
}
return;
}
#-------------------------------------------------
sub start {
my $configFile;
$|=1; #disable output buffering
GetOptions(
'configFile=s'=>\$configFile,
'quiet'=>\$quiet
);
my $session = WebGUI::Session->open($webguiRoot,$configFile);
$session->user({userId=>3});
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Upgrade to ".$toVersion});
return $session;
}
#-------------------------------------------------
sub finish {
my $session = shift;
updateTemplates($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->commit;
$session->db->write("insert into webguiVersion values (".$session->db->quote($toVersion).",'upgrade',".time().")");
$session->close();
}
#-------------------------------------------------
sub updateTemplates {
my $session = shift;
return undef unless (-d "packages-".$toVersion);
print "\tUpdating packages.\n" unless ($quiet);
opendir(DIR,"packages-".$toVersion);
my @files = readdir(DIR);
closedir(DIR);
my $newFolder = undef;
foreach my $file (@files) {
next unless ($file =~ /\.wgpkg$/);
# Fix the filename to include a path
$file = "packages-" . $toVersion . "/" . $file;
addPackage( $session, $file );
}
}
#vim:ft=perl

View file

@ -0,0 +1,158 @@
#!/usr/bin/env perl
#-------------------------------------------------------------------
# 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
#-------------------------------------------------------------------
our ($webguiRoot);
BEGIN {
$webguiRoot = "../..";
unshift (@INC, $webguiRoot."/lib");
}
use strict;
use Getopt::Long;
use WebGUI::Session;
use WebGUI::Storage;
use WebGUI::Asset;
my $toVersion = '7.9.9';
my $quiet; # this line required
my $session = start(); # this line required
# upgrade functions go here
migrateAttachmentsToJson( $session );
finish($session); # this line required
#----------------------------------------------------------------------------
# Describe what our function does
#sub exampleFunction {
# my $session = shift;
# print "\tWe're doing some stuff here that you should know about... " unless $quiet;
# # and here's our code
# print "DONE!\n" unless $quiet;
#}
#----------------------------------------------------------------------------
# Move Template attachments to JSON collateral
sub migrateAttachmentsToJson {
my $session = shift;
print "\tMoving template attachments to JSON... " unless $quiet;
# and here's our code
$session->db->write(
"ALTER TABLE template ADD attachmentsJson LONGTEXT"
);
my $attach; # hashref (template) of hashrefs (revisionDate)
# of arrayrefs (attachments) of hashrefs (attachment)
my $sth = $session->db->read( "SELECT * FROM template_attachments" );
while ( my $row = $sth->hashRef ) {
push @{ $attach->{ $row->{templateId} }{ $row->{revisionDate} } }, {
url => $row->{url},
type => $row->{type},
};
}
for my $templateId ( keys %{ $attach } ) {
for my $revisionDate ( keys %{ $attach->{$templateId} } ) {
my $data = $attach->{$templateId}{$revisionDate};
my $asset = WebGUI::Asset->newByDynamicClass( $session, $templateId, $revisionDate );
$asset->update({ attachmentsJson => JSON->new->encode( $data ) });
}
}
$session->db->write(
"DROP TABLE template_attachments"
);
print "DONE!\n" unless $quiet;
}
# -------------- DO NOT EDIT BELOW THIS LINE --------------------------------
#----------------------------------------------------------------------------
# Add a package to the import node
sub addPackage {
my $session = shift;
my $file = shift;
print "\tUpgrading package $file\n" unless $quiet;
# Make a storage location for the package
my $storage = WebGUI::Storage->createTemp( $session );
$storage->addFileFromFilesystem( $file );
# Import the package into the import node
my $package = eval {
my $node = WebGUI::Asset->getImportNode($session);
$node->importPackage( $storage, {
overwriteLatest => 1,
clearPackageFlag => 1,
setDefaultTemplate => 1,
} );
};
if ($package eq 'corrupt') {
die "Corrupt package found in $file. Stopping upgrade.\n";
}
if ($@ || !defined $package) {
die "Error during package import on $file: $@\nStopping upgrade\n.";
}
return;
}
#-------------------------------------------------
sub start {
my $configFile;
$|=1; #disable output buffering
GetOptions(
'configFile=s'=>\$configFile,
'quiet'=>\$quiet
);
my $session = WebGUI::Session->open($webguiRoot,$configFile);
$session->user({userId=>3});
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Upgrade to ".$toVersion});
return $session;
}
#-------------------------------------------------
sub finish {
my $session = shift;
updateTemplates($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->commit;
$session->db->write("insert into webguiVersion values (".$session->db->quote($toVersion).",'upgrade',".time().")");
$session->close();
}
#-------------------------------------------------
sub updateTemplates {
my $session = shift;
return undef unless (-d "packages-".$toVersion);
print "\tUpdating packages.\n" unless ($quiet);
opendir(DIR,"packages-".$toVersion);
my @files = readdir(DIR);
closedir(DIR);
my $newFolder = undef;
foreach my $file (@files) {
next unless ($file =~ /\.wgpkg$/);
# Fix the filename to include a path
$file = "packages-" . $toVersion . "/" . $file;
addPackage( $session, $file );
}
}
#vim:ft=perl

View file

@ -180,8 +180,9 @@ sub www_view {
'WebGUI::Asset::WikiPage',
'WebGUI::Asset::Post::Thread',
],
whereClause => "asset.createdBy = '$userId' or assetData.ownerUserId = '$userId'",
orderByClause => "$sortBy $sortDir"
statusToInclude => [ qw/approved archived/ ],
whereClause => "asset.createdBy = '$userId' or assetData.ownerUserId = '$userId'",
orderByClause => "$sortBy $sortDir"
}
);
@ -204,12 +205,6 @@ sub www_view {
}
my $props = $asset->get;
$props->{url} = $asset->getUrl;
if (ref $asset eq "WebGUI::Asset::Post") {
$asset = $asset->getThread;
$props = $asset->get;
$props->{className} = "WebGUI::Asset::Post";
}
push(@contribs,$props);
}
my $contribsCount = $p->getRowCount;

View file

@ -2781,6 +2781,10 @@ sub www_editSave {
$session->asset($object->getParent);
return $session->asset->www_view;
}
elsif ($proceed eq "editParent") {
$session->asset($object->getParent);
return $session->asset->www_edit;
}
elsif ($proceed eq "goBackToPage" && $session->form->process('returnUrl')) {
$session->http->setRedirect($session->form->process("returnUrl"));
return undef;

View file

@ -108,8 +108,7 @@ override applyConstraints => sub {
$storage->resize( $file, undef, undef, $gallery->imageDensity );
$storage->adjustMaxImageSize($file, $maxImageSize);
$self->generateThumbnail;
$self->setSize;
$self->generateThumbnail;
$self->updateExifDataFromFile;
super();
};
@ -229,10 +228,11 @@ sub getEditFormUploadControl {
}
# Control to upload a new file
$html .= WebGUI::Form::file( $session, {
name => 'newFile',
label => $i18n->get('new file'),
hoverHelp => $i18n->get('new file description'),
$html .= WebGUI::Form::image( $session, {
name => 'newFile',
label => $i18n->get('new file'),
hoverHelp => $i18n->get('new file description'),
forceImageOnly => 1,
});
return $html;
@ -378,11 +378,19 @@ contained in.
sub makeResolutions {
my $self = shift;
my $resolutions = shift;
my $session = $self->session;
my $error;
croak "Photo->makeResolutions: resolutions must be an array reference"
if $resolutions && ref $resolutions ne "ARRAY";
# # Return immediately if no image is available
# if ( $self->get("filename") eq '' )
# {
# $session->log->error("makeResolutions skipped since no image available");
# return;
# }
# Get default if necessary
$resolutions ||= $self->getGallery->getImageResolutions;
@ -413,13 +421,20 @@ Make the default title into the file name minus the extention.
override processPropertiesFromFormPost => sub {
my $self = shift;
my $i18n = WebGUI::International->new( $self->session,'Asset_Photo' );
my $form = $self->session->form;
my $errors = super() || [];
# Make sure there is an image file attached to this asset.
if ( !$self->get('filename') ) {
push @{ $errors }, $i18n->get('error no image');
}
# Return if errors
return $errors if @$errors;
### Passes all checks
# If no title was given, make it the file name
if ( !$form->get('title') ) {
my $title = $self->filename;
@ -586,6 +601,7 @@ sub www_edit {
$var->{ form_start }
= WebGUI::Form::formHeader( $session, {
action => $self->getParent->getUrl('func=editSave;assetId=new;class='.__PACKAGE__),
extras => 'name="photoAdd"',
})
. WebGUI::Form::hidden( $session, {
name => 'ownerUserId',
@ -597,6 +613,7 @@ sub www_edit {
$var->{ form_start }
= WebGUI::Form::formHeader( $session, {
action => $self->getUrl('func=editSave'),
extras => 'name="photoEdit"',
})
. WebGUI::Form::hidden( $session, {
name => 'ownerUserId',
@ -607,7 +624,7 @@ sub www_edit {
$var->{ form_start }
.= WebGUI::Form::hidden( $session, {
name => "proceed",
value => "showConfirmation",
value => $form->get('proceed') || "showConfirmation",
});
$var->{ form_end } = WebGUI::Form::formFooter( $session );

View file

@ -118,6 +118,7 @@ sub _fixReplyCount {
my $lastPostId = $asset->getLineage( [ qw{ self descendants } ], {
isa => 'WebGUI::Asset::Post',
orderByClause => 'assetData.revisionDate desc',
limit => 1,
} )->[0];
if (my $lastPost = WebGUI::Asset->newById( $self->session, $lastPostId ) ) {
@ -315,6 +316,53 @@ override cut => sub {
#-------------------------------------------------------------------
=head2 disqualifyAsLastPost ( )
This method should be called whenever something happens to the Post or Thread that would disqualify
it as being the last post in a Thread, or Collaboration System. Good examples are cutting to the
clipboard, trashing, or archiving.
If the Post was the last post, it will find the second to last post for each kind of parent asset,
and update that asset with that Post's information.
=cut
sub disqualifyAsLastPost {
my $self = shift;
my $thread = $self->getThread;
if ($thread->get('lastPostId') eq $self->getId) {
my $secondary_post = $thread->getLineage(['descendants'], {
returnObjects => 1,
includeOnlyClasses => ["WebGUI::Asset::Post", ],
limit => 1,
orderByClause => 'revisionDate,lineage DESC',
})->[0];
if ($secondary_post) { ##Handle edge case for no other
$thread->update({ lastPostId => $secondary_post->getId, lastPostDate => $secondary_post->get('creationDate'), });
}
else {
$thread->update({ lastPostId => '', lastPostDate => '', });
}
}
my $cs = $thread->getParent;
if ($cs->get('lastPostId') eq $self->getId) {
my $secondary_post = $cs->getLineage(['descendants'], {
returnObjects => 1,
includeOnlyClasses => ["WebGUI::Asset::Post","WebGUI::Asset::Post::Thread"],
limit => 1,
orderByClause => 'revisionDate DESC',
})->[0];
if ($secondary_post) { ##Handle edge case for no other
$cs->update({ lastPostId => $secondary_post->getId, lastPostDate => $secondary_post->get('creationDate'), });
}
else {
$cs->update({ lastPostId => '', lastPostDate => '', });
}
}
}
#-------------------------------------------------------------------
=head2 DESTROY
Extend the base method to delete the locally cached thread object.
@ -1102,6 +1150,22 @@ sub postProcess {
#-------------------------------------------------------------------
=head2 publish
Extend the base method to handle updating last post information in the parent Thread
and CS.
=cut
sub publish {
my $self = shift;
$self->next::method(@_);
$self->qualifyAsLastPost;
return 1;
}
#-------------------------------------------------------------------
=head2 purge
Extend the base method to handle cleaning up storage locations.
@ -1149,6 +1213,31 @@ override purgeRevision => sub {
#-------------------------------------------------------------------
=head2 qualifyAsLastPost ( )
This method should be called whenever something happens to the Post or Thread that would qualify
it as being the last post in a Thread, or Collaboration System. Good examples are pasting from
the clipboard, restoring from the trash, or changing the state from archiving.
It checks the parent Thread and CS to see if it is now the last Post, and updates that asset with
its information.
=cut
sub qualifyAsLastPost {
my ($self) = @_;
my $thread = $self->getThread();
if ($self->get('creationDate') > $thread->get('lastPostDate')) {
$thread->update({ lastPostId => $self->getId, lastPostDate => $self->get('creationDate'), });
}
my $cs = $thread->getParent;
if ($self->get('creationDate') > $cs->get('lastPostDate')) {
$cs->update({ lastPostId => $self->getId, lastPostDate => $self->get('creationDate'), });
}
}
#-------------------------------------------------------------------
=head2 rate ( rating )
@ -1253,14 +1342,16 @@ override setParent => sub {
=head2 setStatusArchived ( )
Sets the status of this post to archived.
Sets the status of this post to archived. Updates the parent thread and CS to remove
the lastPost, if this post is the last post.
=cut
sub setStatusArchived {
my ($self) = @_;
$self->update({status=>'archived'});
my ($self) = @_;
$self->update({status=>'archived'});
$self->disqualifyAsLastPost;
}
@ -1269,20 +1360,23 @@ sub setStatusArchived {
=head2 setStatusUnarchived ( )
Sets the status of this post to approved, but does so without any of the normal notifications and other stuff.
Updates the last post information in the parent Thread and CS if applicable.
=cut
sub setStatusUnarchived {
my ($self) = @_;
$self->update({status=>'approved'}) if ($self->status eq "archived");
my ($self) = @_;
$self->update({status=>'approved'}) if ($self->get("status") eq "archived");
$self->qualifyAsLastPost;
}
#-------------------------------------------------------------------
=head2 trash ( )
Moves post to the trash, updates reply counter on thread and recalculates the thread rating.
Moves post to the trash, updates reply counter on thread, recalculates the thread rating,
and updates any lastPost information in the parent Thread, and CS.
=cut
@ -1291,22 +1385,8 @@ override trash => sub {
super();
$self->getThread->sumReplies if ($self->isReply);
$self->getThread->updateThreadRating;
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->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]);
$self->getThread->getParent->update({lastPostId=>$id, lastPostDate=>$date});
}
};
$self->disqualifyAsLastPost;
}
#-------------------------------------------------------------------
@ -1506,6 +1586,7 @@ sub www_edit {
$var{'archive.form'} = WebGUI::Form::yesNo($session, {
name=>"archive"
});
$var{'isSubscribedToCs'} = $self->getThread->getParent->isSubscribed;
$var{'form.header'} .= WebGUI::Form::hidden($session, {
name=>"proceed",
value=>"showConfirmation"

View file

@ -501,12 +501,14 @@ property of the Asset.
=cut
sub getRssData {
my $self = shift;
my $self = shift;
my $session = $self->session;
my $url = $session->url->getSiteURL.$self->getUrl;
my $data = {
title => $self->headline || $self->getTitle,
description => $self->story,
'link' => $self->getUrl,
guid => $self->getUrl,
'link' => $url,
guid => $url,
author => $self->byline,
date => $self->lastModified,
pubDate => $self->session->datetime->epochToMail($self->creationDate),

View file

@ -134,29 +134,77 @@ These methods are available from this class:
#-------------------------------------------------------------------
=head2 addAttachments ( attachments )
=head2 definition ( session, definition )
Adds attachments to this template. Attachments is an arrayref of hashrefs,
where each hashref should have at least url, type, and sequence as keys.
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 addAttachments {
my ($self, $attachments) = @_;
my $db = $self->session->db;
foreach my $a (@$attachments) {
my %params = (
templateId => $self->getId,
revisionDate => $self->revisionDate,
url => $a->{url},
type => $a->{type},
sequence => $a->{sequence},
attachId => 'new',
);
$db->setRow('template_attachments', 'attachId', \%params);
}
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,
},
storageIdExample => {
fieldType => 'image',
},
attachmentsJson => {
fieldType => 'JsonTable',
},
},
};
return $class->SUPER::definition($session,$definition);
}
#-------------------------------------------------------------------
@ -171,7 +219,6 @@ override addRevision => sub {
my ( $self, $properties, @args ) = @_;
my $asset = super();
delete $properties->{templatePacked};
$asset->addAttachments($self->getAttachments);
return $asset;
};
@ -207,7 +254,6 @@ override duplicate => sub {
my $self = shift;
my $newTemplate = super();
$newTemplate->update({isDefault => 0});
$newTemplate->addAttachments($self->getAttachments);
if ( my $storageId = $self->get('storageIdExample') ) {
my $newStorage = WebGUI::Storage->get( $self->session, $storageId )->copy;
$newTemplate->update({ storageIdExample => $newStorage->getId });
@ -225,8 +271,7 @@ Override to add attachments to package data
override exportAssetData => sub {
my ( $self ) = @_;
my $data = super();
$data->{template_attachments} = $self->getAttachments;
my $data = $self->SUPER::exportAssetData;
if ( $self->get('storageIdExample') ) {
push @{$data->{storage}}, $self->get('storageIdExample');
}
@ -249,27 +294,24 @@ If defined, will limit the attachments to this type; e.g., passing
sub getAttachments {
my ( $self, $type ) = @_;
my @params = ($self->getId, $self->revisionDate);
my $typeString;
if ($type) {
$typeString = 'AND type = ?';
push(@params, $type);
}
return [] if !$self->get('attachmentsJson');
my $sql = qq{
SELECT
*
FROM
template_attachments
WHERE
templateId = ?
AND revisionDate = ?
$typeString
ORDER BY
type, sequence ASC
};
return $self->session->db->buildArrayRefOfHashRefs($sql, \@params);
my $attachments = JSON->new->decode( $self->get('attachmentsJson') );
# We want it all and we want it now
if ( !$type ) {
return $attachments;
}
my $output = [];
for my $attach ( @{$attachments} ) {
if ( $attach->{type} eq $type ) {
push @{$output}, $attach;
}
}
return $output;
}
#-------------------------------------------------------------------
@ -344,75 +386,31 @@ override getEditForm => sub {
);
}
### Template attachments
my $session = $self->session;
my @headers = map { '<th>' . $i18n->get("attachment header $_") . '</th>' }
qw(index type url remove);
tie my %attachmentTypeNames, 'Tie::IxHash' => (
stylesheet => $i18n->get('css label'),
headScript => $i18n->get('js head label'),
bodyScript => $i18n->get('js body label'),
$tabform->getTab('properties')->jsonTable(
name => 'attachmentsJson',
value => $self->get('attachmentsJson'),
label => $i18n->get("attachments display label"),
fields => [
{
type => "text",
name => "url",
label => $i18n->get('attachment header url'),
size => '48',
},
{
type => "select",
name => "type",
label => $i18n->get('attachment header type'),
options => [
stylesheet => $i18n->get('css label'),
headScript => $i18n->get('js head label'),
bodyScript => $i18n->get('js body label'),
],
},
],
);
my $table = '<table id="attachmentDisplay">';
$table .= "<thead><tr>@headers</tr></thead><tbody id='addAnchor'>";
foreach my $a ( @{ $self->getAttachments } ) {
my ($seq, $type, $url) = @{$a}{qw(sequence type url)};
# escape macros in the url so they don't get processed
$url =~ s/\^/&#94;/g;
my $del = WebGUI::Form::checkbox(
$session, {
name => 'removeAttachment',
value => $url,
extras => 'class="id"',
}
);
my @data = (
"<td class='index'>$seq</td>",
"<td class='type'>$type</td>",
"<td class='url'>$url</td>",
"<td>$del</td>",
);
$table .= "<tr class='existingAttachment'>@data</tr>";
}
$table .= '</tbody></table>';
my $properties = $tabform->getTab('properties');
my $label = $i18n->get('attachment display label');
$properties->raw("<tr><td>$label</td><td>$table</td></tr>");
my @data = map { "<td>$_</td>" } (
WebGUI::Form::integer(
$session, { size => '2', id => 'addBoxIndex' }
),
WebGUI::Form::selectBox(
$session, { options => \%attachmentTypeNames, id => 'addBoxType' }
),
WebGUI::Form::text($session, { id => 'addBoxUrl', size => 40 }),
WebGUI::Form::button(
$session, {
value => $i18n->get('attachment add button'),
extras => 'onclick="addClick()"'
}
),
);
my ($style, $url) = $self->session->quick(qw(style url));
$style->setScript($url->extras('yui/build/yahoo/yahoo-min.js'));
$style->setScript($url->extras('yui/build/json/json-min.js'));
$style->setScript($url->extras('yui/build/dom/dom-min.js'));
$style->setScript($url->extras('yui/build/event/event-min.js'));
$style->setScript($url->extras('yui/build/connection/connection-min.js'));
$style->setScript($url->extras('yui-webgui/build/i18n/i18n.js'));
pop(@headers);
my $scriptUrl = $url->extras('templateAttachments.js');
$table = "<table id='addBox'><tr>@headers</tr><tr>@data</tr></table>";
$table .= qq(<script type="text/javascript" src="$scriptUrl"></script>);
$label = $i18n->get('attachment add field label');
$properties->raw("<tr><td>$label</td><td>$table</td></tr>");
$properties->image(
$tabform->getTab('properties')->image(
name => 'storageIdExample',
value => $self->getValue('storageIdExample'),
label => $i18n->get('field storageIdExample'),
@ -667,6 +665,7 @@ Extends the master class to handle template parsers, namespaces and template att
override processPropertiesFromFormPost => sub {
my $self = shift;
super();
my $session = $self->session;
# TODO: Perhaps add a way to check template syntax before it blows stuff up?
my %data;
my $needsUpdate = 0;
@ -688,28 +687,7 @@ override processPropertiesFromFormPost => sub {
}
### Template attachments
my $f = $self->session->form;
my $p = $f->paramsHashRef;
my @nums = grep {$_} map { my ($i) = /^attachmentUrl(\d+)$/; $i } keys %$p;
my @add;
# Remove all attachments first, then re-add whatever's left in the form
$self->removeAttachments;
foreach my $n (@nums) {
my ($index, $type, $url) =
map { $f->process('attachment' . $_ . $n) }
qw(Index Type Url);
push(
@add, {
sequence => $index,
url => $url,
type => $type,
}
);
}
$self->addAttachments(\@add);
$self->update({ attachmentsJson => $session->form->process( 'attachmentsJson', 'JsonTable' ), });
return;
};
@ -749,66 +727,25 @@ sub processRaw {
#-------------------------------------------------------------------
=head2 purge ( )
=head2 update
Extend the master to purge attachments in all revisions.
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 purge {
sub update {
my $self = shift;
$self->session->db->write('delete from template_attachments where templateId=?', [$self->getId]);
return $self->SUPER::purge(@_);
}
my $requestedProperties = shift;
my $properties = clone($requestedProperties);
#-------------------------------------------------------------------
=head2 purgeRevision ( )
Extend the master purgeRevision to purge attachments
=cut
override purgeRevision => sub {
my $self = shift;
$self->removeAttachments;
return super();
};
#-------------------------------------------------------------------
=head2 removeAttachments ( urls )
Removes attachments. C<urls> is an arrayref of URLs to remove. If C<urls>
is not defined, will remove all attachments for this revision.
=cut
sub removeAttachments {
my ($self, $urls) = @_;
my $db = $self->session->db;
my $dbh = $db->dbh;
my $rmsql = qq{
DELETE FROM
template_attachments
WHERE
templateId = ?
AND revisionDate = ?
};
if ( $urls && @{$urls} ) {
my $in = join(',', map { $dbh->quote($_) } @{$urls});
$rmsql .= qq{
AND url IN ($in)
};
if (exists $properties->{headBlock}) {
$properties->{extraHeadTags} .= $properties->{headBlock};
delete $properties->{headBlock};
}
my @params = (
$self->getId,
$self->get('revisionDate'),
);
$db->write($rmsql, \@params);
$self->SUPER::update($properties);
}
#-------------------------------------------------------------------

View file

@ -241,12 +241,36 @@ sub _listViewPageInterval_builder {
}
property icalFeeds => (
noFormPost => 1,
fieldType => "textarea",
default => sub { return []; },
traits => ['Array', 'WebGUI::Definition::Meta::Property::Serialize',],
isa => 'WebGUI::Type::JSONArray',
coerce => 1,
fieldType => "JsonTable",
defaultValue => [],
serialize => 1,
tab => "feeds",
fields => [
{
name => 'feedId',
type => 'id',
},
{
name => 'url',
type => 'text',
size => '40',
label => $i18n->get('Feed URL'),
},
{
name => 'status',
type => 'readonly',
label => $i18n->get('434','WebGUI'),
},
{
name => 'lastUpdated',
type => 'readonly',
label => $i18n->get('454', 'WebGUI'),
},
],
);
property icalInterval => (
@ -511,169 +535,17 @@ sub deleteFeed {
#----------------------------------------------------------------------------
=head2 getEditForm
=head2 getEditTabs ( )
Adds an additional tab for feeds.
TODO: Abstract the Javascript enough to export into extras/yui-webgui for use
in other areas.
Add the feeds tab to the edit form
=cut
override getEditForm => sub {
my $self = shift;
my $session = $self->session;
my $form = super();
my $i18n = WebGUI::International->new($session,"Asset_Calendar");
my $tab = $form->addTab("feeds",$i18n->get("feeds"), 6);
$tab->raw("<tr><td>");
$tab->raw(<<'ENDJS');
<script type="text/javascript">
var FeedsManager = new Object();
FeedsManager.addFeed = function (table,rowId,params) {
// TODO: Verify that feed URL is valid
var table = document.getElementById(table);
// If id is "new"
// Add a number on the end.
if (rowId == "new")
rowId = "new" + Math.round(Math.random() * 10000000000000000);
// Create 5 cells
var cells = new Array();
for (var i = 0; i < 5; i++)
cells[i] = document.createElement("td");
/*** [0] - Delete button */
var button = document.createElement("img");
button.setAttribute("src","/extras/wobject/Calendar/images/delete.gif");
button.setAttribute("border","0");
var deleteLink = document.createElement("a");
deleteLink.setAttribute("href","#");
YAHOO.util.Event.addListener(deleteLink, "click", function (e, rowId) {
FeedsManager.deleteFeed('feeds',rowId);
YAHOO.util.Event.preventDefault(e);
}, rowId);
deleteLink.appendChild(button);
cells[0].appendChild(deleteLink);
/*** [1] - Feed link for teh clicking and form element for teh saving */
var feedLink = document.createElement("a");
feedLink.setAttribute("href",params.url);
feedLink.setAttribute("target","_new"); // TODO: Use JS to open window. target="" is deprecated
feedLink.appendChild(document.createTextNode(params.url));
var formElement = document.createElement("input");
formElement.setAttribute("type","hidden");
formElement.setAttribute("name","feeds-"+rowId);
formElement.setAttribute("value",params.url);
cells[1].appendChild(feedLink);
cells[1].appendChild(formElement);
/*** [2] - Result (new) */
if (params.lastResult == undefined)
params.lastResult = "new";
var lastResult = document.createTextNode(params.lastResult);
cells[2].appendChild(lastResult);
/*** [3] - Last updated */
if (params.lastUpdated == undefined)
params.lastUpdated = "never";
var lastUpdated = document.createTextNode(params.lastUpdated);
cells[3].appendChild(lastUpdated);
/*** [4] - Update now! */
/* TODO */
/* Add the row to the table */
var row = document.createElement("tr");
row.setAttribute("id",rowId);
for (var i = 0; i < cells.length; i++)
row.appendChild(cells[i]);
var tbody = table.getElementsByTagName('tbody')[0];
if (tbody)
tbody.appendChild(row);
else
table.appendChild(row);
FeedsManager.updateFeed(table.getAttribute("id"),rowId);
}
FeedsManager.updateFeed = function (table,rowId) {
/* TODO */
}
FeedsManager.deleteFeed = function (table,rowId) {
row = document.getElementById(rowId);
row.parentNode.removeChild(row);
}
FeedsManager.setFeed = function (table,rowId,params) {
}
</script>
ENDJS
my $addFeed = $i18n->get('Add a feed');
my $add = $i18n->get('Add');
my $feedUrl = $i18n->get('Feed URL');
my $status = $i18n->get('434', 'WebGUI');
my $lastUpdated = $i18n->get('454', 'WebGUI');
$tab->raw(<<"ENDHTML");
<label for="addFeed">$addFeed</label>
<input type="text" size="60" id="addFeed" name="addFeed" value="" />
<input type="button" value="$add" onclick="FeedsManager.addFeed('feeds','new',{ 'url' : this.form.addFeed.value }); this.form.addFeed.value=''" />
<table id="feeds" style="width: 100%;">
<thead>
<th style="width: 30px;">&nbsp;</th>
<th style="width: 50%;">$feedUrl</th>
<th>$status</th>
<th>$lastUpdated</th>
<th>&nbsp;</th>
</thead>
</table>
ENDHTML
# Add the existing feeds
my $feeds = $self->getFeeds();
$tab->raw('<script type="text/javascript">'."\n");
for my $feed (@{ $feeds }) {
my $feedId = $feed->{feedId};
$tab->raw("FeedsManager.addFeed('feeds','".$feedId."',".JSON->new->encode( $feed ).");\n");
}
$tab->raw('</script>');
$tab->raw("</td></tr>");
return $form;
};
sub getEditTabs {
my ( $self ) = @_;
my $i18n = WebGUI::International->new($self->session,"Asset_Calendar");
return $self->SUPER::getEditTabs, ["feeds",$i18n->get("feeds"), 6];
}
#----------------------------------------------------------------------------
@ -769,7 +641,7 @@ sub getEventsIn {
&& Event.endTime IS NULL
&&
!(
Event.startDate > '$endDate'
Event.startDate > SUBDATE('$endDate', INTERVAL 1 DAY)
|| Event.endDate < '$startDate'
)
)
@ -794,7 +666,7 @@ sub getEventsIn {
my $orderby = join ',', @order_priority;
my $events
= $self->getLineage(["descendants"], {
= $self->getLineage(["children"], {
returnObjects => 1,
includeOnlyClasses => ['WebGUI::Asset::Event'],
joinClass => 'WebGUI::Asset::Event',
@ -1004,37 +876,6 @@ override processPropertiesFromFormPost => sub {
$self->createSubscriptionGroup();
}
$self->session->errorHandler->info( "DEFAULT VIEW:" . $self->defaultView );
### Get feeds from the form
# Workaround WebGUI::Session::Form->param bug that returns duplicate
# names.
my %feeds;
for my $feedId ( grep /^feeds-/, ($form->param()) ) {
$feedId =~ s/^feeds-//;
$feeds{$feedId}++;
}
my @feedsFromForm = keys %feeds;
# Delete old feeds that are not in @feeds
my @oldFeeds = map { $_->{feedId} } @{ $self->getFeeds };
for my $feedId (@oldFeeds) {
if (!isIn($feedId, @feedsFromForm)) {
$self->deleteFeed($feedId);
}
}
# Create new feeds
for my $feedId (grep /^new(\d+)/, @feedsFromForm) {
$self->addFeed({
url => $form->param("feeds-".$feedId),
feedType => "ical",
lastUpdated => 'never',
lastResult => '',
});
}
return;
};

View file

@ -1176,7 +1176,7 @@ sub getThreadsPaginator {
$sortBy =~ s/^\w+\.//;
# Sort by the thread rating instead of the post rating. other places don't care about threads.
$sortBy = $sortBy eq 'rating' ? 'threadRating' : $sortBy;
if (! WebGUI::Utility::isIn($sortBy, qw/userDefined1 userDefined2 userDefined3 userDefined4 userDefined5 title lineage revisionDate creationDate karmaRank threadRating/)) {
if (! WebGUI::Utility::isIn($sortBy, qw/userDefined1 userDefined2 userDefined3 userDefined4 userDefined5 title lineage revisionDate creationDate karmaRank threadRating views replies lastPostDate/)) {
$sortBy = 'revisionDate';
}
if ($sortBy eq 'assetId' || $sortBy eq 'revisionDate') {

View file

@ -411,7 +411,7 @@ sub view {
$rules{assetToPedigree} = $current if (isIn("pedigree",@includedRelationships));
$rules{ancestorLimit} = $self->ancestorEndPoint;
$rules{orderByClause} = 'rpad(asset.lineage, 255, 9) desc' if ($self->reversePageLoop);
my $assets = $start->getLineage(\@includedRelationships,\%rules);
my $assetIter = $start->getLineageIterator(\@includedRelationships,\%rules);
my $currentLineage = $current->lineage;
my $lineageToSkip = "noskip";
my $absoluteDepthOfLastPage;
@ -419,7 +419,15 @@ sub view {
my %lastChildren;
my $previousPageData = undef;
my $eh = $self->session->errorHandler;
while ( my $asset = $assets->() ) {
while ( 1 ) {
my $asset;
eval { $asset = $assetIter->() };
if ( my $x = WebGUI::Error->caught('WebGUI::Error::ObjectNotFound') ) {
$self->session->log->error($x->full_message);
next;
}
last unless $asset;
# skip pages we shouldn't see
my $pageLineage = $asset->lineage;
next if ($pageLineage =~ m/^$lineageToSkip/);

View file

@ -288,9 +288,14 @@ sub getFolder {
##For a fully automatic commit, save the current tag, create a new one
##with the commit without approval workflow, commit it, then restore
##the original if it exists
my $oldVersionTag = WebGUI::VersionTag->getWorking($session, 'noCreate');
my $newVersionTag = WebGUI::VersionTag->create($session, { workflowId => 'pbworkflow00000000003', });
$newVersionTag->setWorking;
my ($oldVersionTag, $newVersionTag);
$oldVersionTag = WebGUI::VersionTag->getWorking($session, 'noCreate');
if ($self->hasBeenCommitted) {
$newVersionTag = WebGUI::VersionTag->create($session, { workflowId => 'pbworkflow00000000003', });
$newVersionTag->setWorking;
$newVersionTag->set({ name => 'Adding folder '. $folderName. ' to archive '. $self->getUrl});
}
##Call SUPER because my addChild calls getFolder
$folder = $self->addChild({
@ -301,7 +306,7 @@ sub getFolder {
isHidden => 1,
styleTemplateId => $self->styleTemplateId,
});
$newVersionTag->commit();
$newVersionTag->commit() if $newVersionTag;
##Restore the old one, if it exists
$oldVersionTag->setWorking() if $oldVersionTag;

View file

@ -996,20 +996,8 @@ sub getFormPlugin {
eval { WebGUI::Pluggable::load($class) };
if ($class->isa('WebGUI::Form::List')) {
delete $param{size};
my $values = WebGUI::Operation::Shared::secureEval($session,$data->{possibleValues});
if (ref $values eq 'HASH') {
$param{options} = $values;
}
else{
my %options;
tie %options, 'Tie::IxHash';
foreach (split(/\n/x, $data->{possibleValues})) {
s/\s+$//x; # remove trailing spaces
$options{$_} = $_;
}
$param{options} = \%options;
}
$param{options} = $values;
}
if ($data->{fieldType} eq "YesNo") {
@ -2408,6 +2396,8 @@ sub editThingData {
my $thingId = shift || $session->form->process('thingId');
my $thingDataId = shift || $session->form->process('thingDataId') || "new";
my $thingProperties = shift || $self->getThing($thingId);
my $errors = shift;
my $resetForm = shift;
my $i18n = WebGUI::International->new($self->session, "Asset_Thingy");
my $canEditThingData = $self->canEditThingData($thingId, $thingDataId, $thingProperties);
@ -2417,7 +2407,7 @@ sub editThingData {
my (%thingData, $fields,@field_loop,$fieldValue, $privilegedGroup);
my $var = $self->get;
my $url = $self->getUrl;
my $errors = shift;
$var->{error_loop} = $errors if ($errors);
$var->{canEditThings} = $self->canEdit;
@ -2465,14 +2455,17 @@ sub editThingData {
,[$self->getId,$thingId]);
while (my %field = $fields->hash) {
my $fieldName = 'field_'.$field{fieldId};
if ($session->form->process("func") eq "editThingDataSave"){
$fieldValue = $session->form->process($fieldName,$field{fieldType},$field{defaultValue});
$fieldValue = undef;
unless ($resetForm) {
if ($session->form->process("func") eq "editThingDataSave"){
$fieldValue = $session->form->process($fieldName,$field{fieldType},$field{defaultValue});
}
else{
$fieldValue = $thingData{"field_".$field{fieldId}};
}
}
else{
$fieldValue = $thingData{"field_".$field{fieldId}};
}
$field{value} = $fieldValue || $field{defaultValue};
my $formElement .= $self->getFormElement(\%field);
$field{value} = $fieldValue || $field{defaultValue};
my $formElement .= $self->getFormPlugin(\%field,($resetForm eq ""))->toHtml;
my $hidden = ($field{status} eq "hidden" && !$self->session->var->isAdminOn);
my $value = $field{value};
@ -2546,7 +2539,7 @@ sub www_editThingDataSave {
return $self->www_viewThingData($thingId,$newThingDataId);
}
elsif ($thingProperties->{afterSave} eq "addThing") {
return $self->www_editThingData($thingId,"new");
return $self->www_editThingData($thingId,"new",undef,undef,"resetForm");
}
elsif ($thingProperties->{afterSave} =~ m/^searchOther_/x){
$otherThingId = $thingProperties->{afterSave};
@ -2556,7 +2549,7 @@ sub www_editThingDataSave {
elsif ($thingProperties->{afterSave} =~ m/^addOther_/x){
$otherThingId = $thingProperties->{afterSave};
$otherThingId =~ s/^addOther_//x;
return $self->www_editThingData($otherThingId,"new");
return $self->www_editThingData($otherThingId,"new",undef,undef,"resetForm");
}
# if afterSave is thingy default or in any other case return www_view()
else {
@ -3233,7 +3226,7 @@ $self->session->form->process($_) eq "") {
sequenceNumber');
while (my $field = $fields->hashRef) {
if ($field->{searchIn}){
my $searchForm = $self->getFormElement($field);
my $searchForm = $self->getFormPlugin($field, 1);
my $searchTextForm = WebGUI::Form::Text($self->session, {
name=>"field_".$field->{fieldId},
size=>25,
@ -3248,9 +3241,10 @@ sequenceNumber');
push(@searchFields_loop, {
"searchFields_fieldId" => $field->{fieldId},
"searchFields_label" => $field->{label},
"searchFields_form" => $searchForm,
"searchFields_form" => $searchForm->toHtml,
"searchFields_textForm" => $searchTextForm,
"searchFields_is".$fieldType => 1,
"searchFields_listType" => $searchForm->isa('WebGUI::Form::List'),
});
my @searchValue = $session->form->process("field_".$field->{fieldId});

View file

@ -353,7 +353,7 @@ sub view {
my $url = $self->session->url;
my $i18n = WebGUI::International->new($self->session, "Asset_UserList");
my (%var, @users, @profileField_loop, @profileFields);
my ($defaultPublicProfile, $defaultPublicEmail, $user, $sth, $sql, $profileField);
my ($user, $sth, $sql, $profileField);
my $currentUrlWithoutSort = $self->getUrl();
foreach ($form->param) {
@ -505,9 +505,6 @@ sub view {
$sortBy = join '.', map { $self->session->db->quoteIdentifier($_) } split /\./, $sortBy;
$sql .= " order by ".$sortBy." ".$sortOrder;
($defaultPublicProfile) = $self->session->db->quickArray("SELECT dataDefault FROM userProfileField WHERE fieldName='publicProfile'");
($defaultPublicEmail) = $self->session->db->quickArray("SELECT dataDefault FROM userProfileField WHERE fieldName='publicEmail'");
my $paginatePage = $form->param('pn') || 1;
my $currentUrl = $self->getUrl();
foreach ($form->param) {

View file

@ -183,6 +183,7 @@ sub getAssetsInClipboard {
{
statesToInclude => ["clipboard"],
returnObjects => 1,
statusToInclude => [qw/approved pending archived/],
whereClause => $limit,
}
);

View file

@ -420,10 +420,6 @@ An array reference containing a list of asset classes to remove from the result
A boolean indicating that we should return objects rather than asset ids.
=head4 returnSQL
A boolean indicating that we should return the sql statement rather than asset ids.
=head4 invertTree
A boolean indicating whether the resulting asset tree should be returned in reverse order.
@ -446,7 +442,8 @@ A string containing as asset class to join in. There is no real reason to use a
=head4 whereClause
A string containing extra where clause information for the query.
A string containing extra WHERE clause information for the query. The AND conjunction will be added internally, so the clause
should not start with AND.
=head4 orderByClause
@ -595,6 +592,7 @@ An integer describing how many levels of ancestry from the start point that shou
=head4 excludeClasses
An array reference containing a list of asset classes to remove from the result set. The opposite of the includOnlyClasses rule.
Each class is internally appended with a SQL wildcard, so any subclass will also be excluded.
=head4 invertTree
@ -740,7 +738,8 @@ sub getLineageSql {
}
## finish up our where clause
if (!scalar(@whereModifiers)) {
return "";
#Return valid SQL that will never select an asset.
return q|select * from asset where assetId="###---###"|;
}
$where .= ' and ('.join(" or ",@whereModifiers).')';
if (exists $rules->{whereClause} && $rules->{whereClause}) {

View file

@ -57,39 +57,20 @@ sub getAssetsInTrash {
my $self = shift;
my $limitToUser = shift;
my $userId = shift || $self->session->user->userId;
my @assets;
my $limit;
if ($limitToUser) {
$limit = "and asset.stateChangedBy=".$self->session->db->quote($userId);
$limit = "asset.stateChangedBy=".$self->session->db->quote($userId);
}
my $sth = $self->session->db->read("
select
asset.assetId,
assetData.revisionDate
from
asset
left join
assetData on asset.assetId=assetData.assetId
where
asset.state='trash'
and assetData.revisionDate=(SELECT max(revisionDate) from assetData where assetData.assetId=asset.assetId)
$limit
group by
assetData.assetId
order by
assetData.title desc
");
while (my ($id, $date) = $sth->array) {
my $asset = WebGUI::Asset->newById($self->session, $id, $date);
if (!Exception::Class->caught()) {
push(@assets, $asset);
}
else {
$self->session->errorHandler->error("AssetTrash::getAssetsInTrash - failed to instanciate asset with assetId $id and revisionDate $date");
}
}
$sth->finish;
return \@assets;
my $root = WebGUI::Asset->getRoot($self->session);
return $root->getLineage(
["descendants", ],
{
statesToInclude => ["trash"],
statusToInclude => [qw/approved pending archived/],
returnObjects => 1,
whereClause => $limit,
}
);
}
#----------------------------------------------------------------------------

View file

@ -800,7 +800,9 @@ Returns whether or not a method is callable
sub isCallable {
my $self = shift;
return isIn($_[0],@{$self->{callable}})
return 1 if isIn($_[0],@{$self->{callable}});
return 1 if $self->can( 'www_' . $_[0] );
return 0;
}
#-------------------------------------------------------------------

297
lib/WebGUI/Auth/Twitter.pm Normal file
View file

@ -0,0 +1,297 @@
package WebGUI::Auth::Twitter;
=head1 LEGAL
-------------------------------------------------------------------
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
-------------------------------------------------------------------
=cut
use strict;
use base 'WebGUI::Auth';
use Net::Twitter;
=head1 NAME
WebGUI::Auth::Twitter -- Twitter auth for WebGUI
=head1 DESCRIPTION
Allow WebGUI to authenticate to WebGUI
=head1 METHODS
These methods are available from this class:
=cut
#----------------------------------------------------------------------------
=head2 new ( ... )
Create a new object
=cut
sub new {
my $self = shift->SUPER::new(@_);
return bless $self, __PACKAGE__; # Auth requires rebless
}
#----------------------------------------------------------------------------
=head2 createTwitterUser ( twitterUserId, username )
my $user = $self->createTwitterUser( $twitterUserId, $username );
Create a new Auth::Twitter user with the given twitter userId and screen name.
=cut
sub createTwitterUser {
my ( $self, $twitterUserId, $username ) = @_;
my $user = WebGUI::User->create( $self->session );
$user->username( $username );
$self->saveParams( $user->userId, $self->authMethod, {
"twitterUserId" => $twitterUserId,
} );
return $user;
}
#----------------------------------------------------------------------------
=head2 editUserSettingsForm ( )
Return the form to edit the settings of this Auth module
=cut
sub editUserSettingsForm {
my $self = shift;
my $session = $self->session;
my ( $setting ) = $session->quick(qw( setting ));
my $i18n = WebGUI::International->new( $session, 'Auth_Twitter' );
my $keyUrl = 'http://dev.twitter.com/apps/new';
my $f = WebGUI::HTMLForm->new( $session );
$f->yesNo(
name => 'twitterEnabled',
value => $setting->get( 'twitterEnabled' ),
label => $i18n->get('enabled'),
hoverHelp => $i18n->get('enabled help'),
);
$f->text(
name => 'twitterConsumerKey',
value => $setting->get( 'twitterConsumerKey' ),
label => $i18n->get('consumer key'),
hoverHelp => $i18n->get('consumer key help'),
subtext => sprintf( $i18n->get('get key'), ($keyUrl) x 2 ),
);
$f->text(
name => 'twitterConsumerSecret',
value => $setting->get( 'twitterConsumerSecret' ),
label => $i18n->get('consumer secret'),
hoverHelp => $i18n->get('consumer secret help'),
);
$f->template(
name => 'twitterTemplateIdChooseUsername',
value => $setting->get( 'twitterTemplateIdChooseUsername' ),
label => $i18n->get('choose username template'),
hoverHelp => $i18n->get('choose username template help'),
namespace => 'Auth/Twitter/ChooseUsername',
);
return $f->printRowsOnly;
}
#----------------------------------------------------------------------------
=head2 editUserSettingsFormSave ( )
Process the form for this Auth module's settings
=cut
sub editUserSettingsFormSave {
my $self = shift;
my $session = $self->session;
my ( $form, $setting ) = $session->quick(qw( form setting ));
my @fields = qw(
twitterEnabled twitterConsumerKey twitterConsumerSecret
twitterTemplateIdChooseUsername
);
for my $field ( @fields ) {
$setting->set( $field, $form->get( $field ) );
}
return;
}
#----------------------------------------------------------------------------
=head2 getTemplateChooseUsername ( )
Get the template to choose a username
=cut
sub getTemplateChooseUsername {
my ( $self ) = @_;
my $templateId = $self->session->setting->get('twitterTemplateIdChooseUsername');
return WebGUI::Asset::Template->new( $self->session, $templateId );
}
#----------------------------------------------------------------------------
=head2 getTwitter ( )
Get the Net::Twitter object with the appropriate keys
=cut
sub getTwitter {
my ( $self ) = @_;
my $setting = $self->session->setting;
if ( !$self->{_twitter} ) {
my $nt = Net::Twitter->new(
traits => [qw/API::REST OAuth/],
consumer_key => $setting->get( 'twitterConsumerKey' ), # Test: '3hvJpBr73pa4FycNrqw',
consumer_secret => $setting->get( 'twitterConsumerSecret' ), # Test: 'E4M5DJ66RAXiHgNCnJES96yTqglttsUes6OBcw9A',
);
$self->{_twitter} = $nt;
}
return $self->{_twitter};
}
#----------------------------------------------------------------------------
=head2 www_login ( )
Begin the login procedure
=cut
sub www_login {
my ( $self ) = @_;
my $session = $self->session;
my ( $url, $scratch, $setting ) = $session->quick( qw( url scratch setting ) );
my $nt = $self->getTwitter;
my $auth_url = $nt->get_authentication_url(
callback => $url->getSiteURL . $url->page('op=auth&authType=Twitter&method=callback'),
);
$scratch->set( 'AuthTwitterToken', $nt->request_token );
$scratch->set( 'AuthTwitterTokenSecret', $nt->request_token_secret );
$session->http->setRedirect($auth_url);
return "redirect";
}
#----------------------------------------------------------------------------
=head2 www_callback ( )
Callback from the Twitter authentication. Try to log the user in, creating a
new user account if necessary.
If the username is taken, allow the user to choose a new one.
=cut
sub www_callback {
my ( $self ) = @_;
my $session = $self->session;
my ( $form, $scratch, $db, $setting ) = $session->quick(qw( form scratch db setting ));
my $verifier = $form->get('oauth_verifier');
my $nt = $self->getTwitter;
$nt->request_token( $scratch->get('AuthTwitterToken') );
$nt->request_token_secret( $scratch->get('AuthTwitterTokenSecret') );
my ($access_token, $access_token_secret, $twitterUserId, $twitterScreenName )
= $nt->request_access_token(verifier => $verifier);
### Log the user in
# Find their twitter user ID
my $userId = $db->quickScalar(
"SELECT userId FROM authentication WHERE authMethod = ? AND fieldName = ? AND fieldData = ?",
[ "Twitter", "twitterUserId", $twitterUserId ],
);
# Returning user
if ( $userId ) {
my $user = WebGUI::User->new( $session, $userId );
$self->user( $user );
return $self->login;
}
# Otherwise see if their screen name exists and create a user
elsif ( !WebGUI::User->newByUsername( $session, $twitterScreenName ) ) {
my $user = $self->createTwitterUser( $twitterUserId, $twitterScreenName );
$self->user( $user );
return $self->login;
}
# Otherwise ask them for a new username to use
my $i18n = WebGUI::International->new( $session, 'Auth_Twitter' );
$scratch->set( "AuthTwitterUserId", $twitterUserId );
my $tmpl = $self->getTemplateChooseUsername;
my $var = {
message => sprintf( $i18n->get("twitter screen name taken"), $twitterScreenName ),
};
return $tmpl->process( $var );
}
#----------------------------------------------------------------------------
=head2 www_setUsername ( )
Set the username for a twitter user. Only used as part of the initial twitter
registration.
=cut
sub www_setUsername {
my ( $self ) = @_;
my $session = $self->session;
my ( $form, $scratch, $db ) = $session->quick(qw( form scratch db ));
my $i18n = WebGUI::International->new( $session, 'Auth_Twitter' );
# Don't allow just anybody to set a username
return unless $scratch->get('AuthTwitterUserId');
my $username = $form->get('newUsername');
if ( !WebGUI::User->newByUsername( $session, $username ) ) {
my $twitterUserId = $scratch->get( "AuthTwitterUserId" );
my $user = $self->createTwitterUser( $twitterUserId, $username );
$self->user( $user );
return $self->login;
}
# Username is again taken! Noooooo!
my $tmpl = $self->getTemplateChooseUsername;
my $var = {
message => sprintf( $i18n->get("webgui username taken"), $username ),
};
return $tmpl->process( $var );
}
1;

View file

@ -373,9 +373,6 @@ sub www_manage {
$session->style->setScript( $session->url->extras( 'yui-webgui/build/form/form.js' ) );
$session->style->setRawHeadTags( <<ENDHTML );
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.6.0/build/logger/assets/skins/sam/logger.css">
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/logger/logger-min.js"></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady( WebGUI.AssetManager.initManager );
</script>

View file

@ -297,7 +297,7 @@ JS
$output .= '<div class="crumbTrail">'.join(" &gt; ", @crumb)."</div>\n<ul>";
my $useAssetUrls = $session->config->get("richEditorsUseAssetUrls");
my $children = $base->getLineage(["children"]);
my $children = $base->getLineageIterator(["children"]);
while ( my $child = $children->() ) {
next unless $child->canView;
$output .= '<li>';

View file

@ -0,0 +1,215 @@
package WebGUI::Form::JsonTable;
=head1 LEGAL
-------------------------------------------------------------------
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
-------------------------------------------------------------------
=cut
use strict;
use base 'WebGUI::Form::Control';
use WebGUI::International;
use JSON;
=head1 NAME
Package WebGUI::Form::JsonTable
=head1 DESCRIPTION
Creates a table to edit a JSON blob
=head1 SEE ALSO
This is a subclass of WebGUI::Form::Control.
=head1 METHODS
=cut
#-------------------------------------------------------------------
=head2 definition ( [ additionalTerms ] )
See the super class for additional details.
=head3 additionalTerms
The following additional parameters have been added via this sub class.
=head4 fields
An array of hashrefs defining the fields in this JsonTable.
{
type => "text", # One of "text", "select", or "readonly"
name => "name", # The name of the field
label => "Name", # an i18n label
options => [ option => "label", ... ] # Options for select fields
}
=cut
sub definition {
my $class = shift;
my $session = shift;
my $definition = shift || [];
push @{$definition}, {
fields => {
defaultValue => [],
},
};
return $class->SUPER::definition($session, $definition);
}
#-------------------------------------------------------------------
=head2 getName ( session )
Returns the name of the form control.
=cut
sub getName {
my ($class, $session) = @_;
return WebGUI::International->new($session, "Form_JsonTable")->get("topicName");
}
#-------------------------------------------------------------------
=head2 getOriginalValue ( )
Get the original value, encoding to JSON if necessary
=cut
sub getOriginalValue {
my ( $self ) = @_;
my $value = $self->SUPER::getOriginalValue;
if ( ref $value eq "ARRAY" ) {
return JSON->new->encode( $value );
}
return $value;
}
#-------------------------------------------------------------------
=head2 getValue ( value )
Get the value of the field. Substitute id fields with GUIDs.
=cut
sub getValue {
my ( $self, $value ) = @_;
$value ||= $self->SUPER::getValue;
$self->session->log->info( "JsonTable Got $value from form" );
$value = JSON->new->decode( $value );
for my $row ( @{$value} ) {
for my $field ( @{$self->get('fields')} ) {
if ( $field->{type} eq 'id' && $row->{ $field->{name} } eq "new" ) {
$row->{ $field->{name} } = $self->session->id->generate;
}
}
}
return JSON->new->encode( $value );
}
#-------------------------------------------------------------------
=head2 toHtml ( )
Renders an input tag of type text.
=cut
sub toHtml {
my $self = shift;
my $session = $self->session;
my ( $url, $style ) = $session->quick(qw( url style ));
my $value = $self->fixMacros($self->fixQuotes($self->fixSpecialCharacters($self->getOriginalValue)));
my $output = '';
# Table headers
$output .= '<table id="' . $self->get( 'id' ) . '"><thead><tr>';
for my $field ( @{ $self->get('fields') } ) {
$output .= '<th>' . $field->{label} . '</th>';
}
$output .= '<th>&nbsp;</th>'; # Extra column for buttons
# Buttons to add rows in the table footer
my $cols = scalar @{ $self->get('fields') } + 1; # Extra column for buttons
$output .= '</thead><tfoot><tr><td colspan="' . $cols . '">'
. '<button id="' . $self->get('id') . '_add">' . "Add" . '</button>'
. '</td></tr></tfoot>'
;
# Build a hidden row to copy for new rows
$output .= '<tbody><tr class="new_row" style="display: none">';
for my $field ( @{ $self->get('fields') } ) {
my $fieldName = join "_", $self->get('name'), $field->{name};
# Drawing using raw HTML to sanitize field HTML and allow future merging with DataTable
my $fieldHtml;
if ( $field->{type} eq "text" ) {
$fieldHtml = '<input type="text" name="' . $fieldName . '" size="' . $field->{size} . '" />';
}
elsif ( $field->{type} eq "select" ) {
$fieldHtml = '<select name="' . $fieldName . '" size="' . $field->{size} . '">';
my $opts = @{$field->{options}} / 2; # options is arrayref of name => label
for my $i ( 0 .. $opts-1 ) {
my $optValue = $field->{options}[$i*2];
my $optLabel = $field->{options}[$i*2+1];
$fieldHtml .= '<option value="' . $optValue . '">' . $optLabel . '</option>';
}
$fieldHtml .= '</select>';
}
elsif ( $field->{type} eq "id" ) {
$fieldHtml .= '<input type="hidden" class="jsontable_id" name="' . $fieldName . '" value="new" />';
}
else { # Readonly or unknown
$fieldHtml = '&nbsp;';
}
$output .= '<td>' . $fieldHtml . '</td>';
}
$output .= '<td></td>' # Extra cell for buttons
. '</tr></tbody></table>';
# Build the existing rows
$output .= '<input type="hidden" name="' . $self->get('name') . '" value="' . $value . '" />';
# Existing rows are entirely built in javascript from the JSON in the hidden field
$style->setScript(
$url->extras('yui/build/yahoo-dom-event/yahoo-dom-event.js'),
{ type => 'text/javascript' },
);
$style->setScript(
$url->extras('yui/build/json/json-min.js'),
{ type => 'text/javascript' },
);
$output .= sprintf '<script src="%s" type="text/javascript"></script>',
$url->extras('yui-webgui/build/form/jsontable.js');
$output .= '<script type="text/javascript">'
. q{new WebGUI.Form.JsonTable("} . $self->get('name') . q{","} . $self->get( 'id' ) . q{", }
. JSON->new->encode( $self->get('fields') ) . q{ );}
. '</script>';
return $output;
}
1;
#vim:ft=perl

View file

@ -78,23 +78,23 @@ If true, this will limit the list of template to only include templates that are
=cut
sub definition {
my $class = shift;
my $session = shift;
my $definition = shift || [];
my $i18n = WebGUI::International->new($session, 'Asset_Template');
push(@{$definition}, {
label=>{
defaultValue=>$i18n->get("assetName")
},
name=>{
defaultValue=>"templateId"
},
namespace=>{
defaultValue=>undef
},
onlyCommitted=>{
defaultValue=>''
},
my $class = shift;
my $session = shift;
my $definition = shift || [];
my $i18n = WebGUI::International->new($session, 'Asset_Template');
push(@{$definition}, {
label=>{
defaultValue=>$i18n->get("assetName")
},
name=>{
defaultValue=>"templateId"
},
namespace=>{
defaultValue=>undef
},
onlyCommitted=>{
defaultValue=>''
},
});
return $class->SUPER::definition($session, $definition);
}
@ -138,16 +138,39 @@ sub isDynamicCompatible {
#-------------------------------------------------------------------
=head2 toHtml ( )
=head2 getValueAsHtml ( )
Renders a template picker control.
Returns the tempalte name of the selected template.
=cut
sub toHtml {
my $self = shift;
my $onlyCommitted = $self->get('onlyCommitted') ? "assetData.status='approved'" : $self->get('onlyCommitted');
my $templateList = WebGUI::Asset::Template->getList($self->session, $self->get("namespace"), $onlyCommitted);
sub getValueAsHtml {
my $self = shift;
$self->setOptions;
return $self->SUPER::getValueAsHtml;
}
#-------------------------------------------------------------------
=head2 setOptions
Fills the options of the select list with the appropriate templates.
=cut
sub setOptions {
my $self = shift;
my $session = $self->session;
my $userId = $session->user->userId;
my $onlyCommitted = $self->get( 'onlyCommitted' )
? q{assetData.status='approved'}
: $self->get( 'onlyCommitted' )
;
my $templateList = WebGUI::Asset::Template->getList( $session, $self->get( 'namespace' ), $onlyCommitted );
#Remove entries from template list that the user does not have permission to view.
for my $assetId ( keys %{$templateList} ) {
my $asset = WebGUI::Asset::Template->newById($self->session, $assetId);
@ -155,8 +178,26 @@ sub toHtml {
delete $templateList->{$assetId};
}
}
$self->set("options", $templateList);
return $self->SUPER::toHtml();
$self->set( 'options', $templateList );
return;
}
#-------------------------------------------------------------------
=head2 toHtml ( )
Renders a template picker control.
=cut
sub toHtml {
my $self = shift;
$self->setOptions;
return $self->SUPER::toHtml();
}
#-------------------------------------------------------------------

View file

@ -36,6 +36,31 @@ The following methods are specifically available from this class. Check the supe
=cut
#-------------------------------------------------------------------
=head2 getName ( session )
Returns the human readable name of this control.
=cut
sub getName {
my ($self, $session) = @_;
return WebGUI::International->new($session, 'WebGUI')->get('user');
}
#-------------------------------------------------------------------
=head2 isDynamicCompatible ( )
Since this Form field requires a thingId to work it is not dynamic compatible.
=cut
sub isDynamicCompatible {
return 0;
}
#----------------------------------------------------------------------------
=head2 www_getThingFields ($session)

View file

@ -58,6 +58,19 @@ Defaults to the setting textBoxSize or 30 if that's not set. Specifies how big o
#-------------------------------------------------------------------
=head2 getName ( session )
Returns the human readable name of this control.
=cut
sub getName {
my ($self, $session) = @_;
return WebGUI::International->new($session, 'Form_Username')->get('username');
}
#-------------------------------------------------------------------
=head2 getValue ( [ value ] )
Retrieves a value from a form GET or POST and returns it. If the value comes back as undef, this method will return the defaultValue instead. Strip newlines/carriage returns from the value.

View file

@ -283,6 +283,7 @@ sub clearCaches {
$stow->delete("groupObj");
$stow->delete("isInGroup");
$stow->delete("gotGroupsInGroup");
$session->stow->delete("gotGroupsForUser");
}
#-------------------------------------------------------------------

View file

@ -27,6 +27,7 @@ our $HELP = {
{ 'name' => 'reply.synopsis' },
{ 'name' => 'reply.content' },
{ 'name' => 'reply.userDefinedN' },
{ 'name' => 'isSubscribedToCs' },
{ 'name' => 'subscribe.form' },
{ 'name' => 'isNewThread' },
{ 'name' => 'archive.form' },

View file

@ -191,6 +191,7 @@ our $HELP = {
{ 'name' => 'searchFields_textForm' },
{ 'name' => 'searchFields_label' },
{ 'name' => 'searchFields_is__fieldType__' },
{ 'name' => 'searchFields_listType' },
],
},
{ 'name' => 'listOfThings',

View file

@ -72,6 +72,10 @@ our $HELP = {
name => "quantity",
description => "quantity help",
},
{
name => "removeBox",
description => "removeBox help",
},
{
name => "dateAdded",
description => "dateAdded help",
@ -102,32 +106,36 @@ our $HELP = {
description => "price help",
},
{
name => "removeButton",
description => "removeButton help",
required => 1,
},
{
name => "shipToButton",
description => "item shipToButton help",
name => "itemAddressChooser",
description => "itemAddressChooser help",
},
{
name => "shippingAddress",
description => "shippingAddress help",
},
{
name => "isCashier",
name => "taxRate",
description => "item taxRate help",
},
{
name => "posLookupForm",
name => "taxAmount",
description => "item taxAmount help",
},
{
name => "posUsername",
name => "pricePlusTax",
description => "item pricePlusTax help",
},
{
name => "posUserId",
name => "extendedPricePlusTax",
description => "item extendedPricePlusTax help",
},
],
},
{
name => "message",
description => "message help",
required => 1,
},
{
name => "error",
description => "error help",
@ -152,10 +160,26 @@ our $HELP = {
name => "continueShoppingButton",
description => "continueShoppingButton help",
},
{
name => "minimumCartAmount",
description => "minimumCartAmount help",
},
{
name => "subtotalPrice",
description => "subtotalPrice help",
},
{
name => "shippingAddressChooser",
description => "shippingAddressChooser help",
},
{
name => "billingAddressChooser",
description => "billingAddressChooser help",
},
{
name => "sameShippingAsBilling",
description => "sameShippingAsBilling help",
},
{
name => "shippingPrice",
description => "shippingPrice help",
@ -164,19 +188,27 @@ our $HELP = {
name => "tax",
description => "tax help",
},
{
name => "userIsVisitor",
description => "userIsVisitor help",
},
{
name => "shippableItemsInCart",
},
{
name => "hasShippingAddress",
description => "hasShippingAddress help",
},
{
name => "shippingAddress",
description => "shippingAddress help",
},
{
name => "shippingOptions",
description => "shippingOptions help",
required => 1,
},
{
name => "paymentOptions",
description => "paymentOptions help",
required => 1,
},
{
name => "totalPrice",
description => "totalPrice help",
@ -190,6 +222,158 @@ our $HELP = {
name => "inShopCreditDeduction",
description => "inShopCreditDeduction help",
},
{
name => "isCashier",
},
{
name => "posLookupForm",
},
{
name => "posUsername",
},
{
name => "posUserId",
},
{
name => "loginFormHeader",
description => "loginFormHeader help",
required => 1,
},
{
name => "loginFormFooter",
description => "loginFormFooter help",
required => 1,
},
{
name => "loginFormUsername",
description => "loginFormUsername help",
required => 1,
},
{
name => "loginFormPassword",
description => "loginFormPassword help",
required => 1,
},
{
name => "loginFormButton",
description => "loginFormButton help",
required => 1,
},
{
name => "registerLink",
description => "registerLink help",
required => 1,
},
{
name => "billing_address1Field",
description => "address1Field help",
required => 1,
},
{
name => "billing_address2Field",
description => "address2Field help",
required => 1,
},
{
name => "billing_address3Field",
description => "address3Field help",
required => 1,
},
{
name => "billing_labelField",
description => "address labelField help",
required => 1,
},
{
name => "billing_nameField",
description => "address nameField help",
required => 1,
},
{
name => "billing_cityField",
description => "cityField help",
required => 1,
},
{
name => "billing_stateField",
description => "stateField help",
required => 1,
},
{
name => "billing_countryField",
description => "countryField help",
required => 1,
},
{
name => "billing_codeField",
description => "codeField help",
required => 1,
},
{
name => "billing_phoneNumberField",
description => "phoneNumberField help",
required => 1,
},
{
name => "billing_emailField",
description => "emailField help",
required => 1,
},
{
name => "shipping_address1Field",
description => "address1Field help",
required => 1,
},
{
name => "shipping_address2Field",
description => "address2Field help",
required => 1,
},
{
name => "shipping_address3Field",
description => "address3Field help",
required => 1,
},
{
name => "shipping_labelField",
description => "address labelField help",
required => 1,
},
{
name => "shipping_nameField",
description => "address nameField help",
required => 1,
},
{
name => "shipping_cityField",
description => "cityField help",
required => 1,
},
{
name => "shipping_stateField",
description => "stateField help",
required => 1,
},
{
name => "shipping_countryField",
description => "countryField help",
required => 1,
},
{
name => "shipping_codeField",
description => "codeField help",
required => 1,
},
{
name => "shipping_phoneNumberField",
description => "phoneNumberField help",
required => 1,
},
{
name => "shipping_emailField",
description => "emailField help",
required => 1,
},
],
related => [
{
@ -379,6 +563,11 @@ our $HELP = {
description => "phoneNumberField help",
required => 1,
},
{
name => "emailField",
description => "emailField help",
required => 1,
},
],
related => [
{

View file

@ -119,6 +119,29 @@ sub canRead {
#-------------------------------------------------------------------
=head2 deleteMessagesForUser ( $user )
Deletes all messages for a user.
=head3 $user
A WebGUI::User object, representing the user who will have all their messages deleted.
=cut
sub deleteMessagesForUser {
my $self = shift;
my $user = shift;
my $messages = $self->getMessagesForUser($user, 1e10);
my $userId = $user->userId;
foreach my $message (@{ $messages }) {
$message->delete($userId);
}
}
#-------------------------------------------------------------------
=head2 getMessage ( messageId [, userId] )
Returns a WebGUI::Inbox::Message object.
@ -448,7 +471,7 @@ sub getMessageSql {
}
if($whereClause) {
$whereClause = qq{WHERE $whereClause};
$whereClause = qq{AND $whereClause};
}
if($limit) {
@ -473,14 +496,13 @@ SELECT
my $sql = qq{
SELECT
$select
FROM (
( SELECT messageId, subject, sentBy, dateStamp, status FROM inbox WHERE userId = '$userId' order by dateStamp desc limit $limitHalf)
UNION
( SELECT messageId, subject, sentBy, dateStamp, status FROM inbox WHERE groupId IN ( $userGroups ) order by dateStamp desc limit $limitHalf )
) AS ibox
JOIN inbox_messageState on inbox_messageState.messageId=ibox.messageId and inbox_messageState.userId='$userId' and inbox_messageState.deleted=0
LEFT JOIN users on users.userId=ibox.sentBy
LEFT JOIN userProfileData on userProfileData.userId=ibox.sentBy
FROM inbox_messageState
JOIN inbox ibox USING (messageId)
JOIN users on users.userId = ibox.sentBy
JOIN userProfileData on userProfileData.userId = ibox.sentBy
WHERE inbox_messageState.messageId = ibox.messageId
AND inbox_messageState.userId = '$userId'
AND inbox_messageState.deleted = 0
$whereClause
$sortBy
$limit

View file

@ -266,8 +266,7 @@ sub delete {
);
#Delete the message from the database if everyone who was sent the message has deleted it
unless ($isActive) {
$db->write("delete from inbox where messageId=?",[$messageId]);
$db->write("delete from inbox_messageState where messageId=?",[$messageId]);
$self->purge;
}
}
@ -437,6 +436,22 @@ sub new {
#-------------------------------------------------------------------
=head2 purge
Completely deletes a message from the inbox.
=cut
sub purge {
my $self = shift;
my $db = $self->session->db;
my $messageId = $self->getId;
$db->write("delete from inbox where messageId=?",[$messageId]);
$db->write("delete from inbox_messageState where messageId=?",[$messageId]);
}
#-------------------------------------------------------------------
=head2 session
Returns a reference to the current session.

View file

@ -0,0 +1,58 @@
package WebGUI::Macro::TwitterLogin;
#-------------------------------------------------------------------
# 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 List::MoreUtils qw( any );
=head1 NAME
Package WebGUI::Macro::TwitterLogin
=head1 DESCRIPTION
Display a twitter login button
=head2 process( $session )
=over 4
=item *
A session variable
=item *
A URL to an image to log in via Twitter
=back
=cut
#-------------------------------------------------------------------
sub process {
my $session = shift;
return "" unless any { $_ eq 'Twitter' } @{ $session->config->get( 'authMethods' ) };
return "" unless $session->user->isVisitor;
return "" unless $session->setting->get('twitterEnabled'); # Don't allow if twitter login is disabled
my $loginUrl = $session->url->page('op=auth;authType=Twitter;method=login');
my $imgUrl = shift || $session->url->extras( 'twitter_login.png' );
my $output = sprintf '<a href="%s"><img src="%s" border="0" /></a>', $loginUrl, $imgUrl;
return $output;
}
1;
#vim:ft=perl

View file

@ -22,6 +22,7 @@ use Net::SMTP;
use WebGUI::Group;
use WebGUI::Macro;
use WebGUI::User;
use WebGUI::HTML;
use Encode qw(encode);
=head1 NAME
@ -84,15 +85,57 @@ sub addAttachment {
=head2 addFooter ( )
Adds the mail footer as set by the site admin to the end of this message.
Adds the mail footer as set by the site admin to the end of the first
part of this message. If the first part of the message has an HTML MIME-type,
then it will translate the footer to HTML.
If the message is empty, it will create a MIME entity part to hold it.
Macros in the footer will be evaluated.
=cut
sub addFooter {
my $self = shift;
return if $self->{_footerAdded};
my $text = "\n\n".$self->session->setting->get("mailFooter");
WebGUI::Macro::process($self->session, \$text);
$self->addText($text);
$self->{_footerAdded} = 1;
my @parts = $self->getMimeEntity->parts();
##No parts yet, add one with the footer content.
if (! $parts[0]) {
$self->addText($text);
return;
}
##Get the content of the first part, drop it from the set of parts
my $mime_body = $parts[0]->bodyhandle;
my $body_content = join '', $mime_body->as_lines;
my $mime_type;
if ($parts[0]->effective_type eq 'text/plain') {
$body_content .= $text;
my $new_part = MIME::Entity->build(
Charset => "UTF-8",
Encoding => "quoted-printable",
Type => 'text/plain',
Data => encode('utf8', $body_content),
);
shift @parts;
unshift @parts, $new_part;
$self->getMimeEntity->parts(\@parts);
}
elsif ($parts[0]->effective_type eq 'text/html') {
$text = WebGUI::HTML::format($text, 'mixed');
$body_content =~ s{(?=</body>)}{$text};
my $new_part = MIME::Entity->build(
Charset => "UTF-8",
Encoding => "quoted-printable",
Type => 'text/html',
Data => encode('utf8', $body_content),
);
shift @parts;
unshift @parts, $new_part;
$self->getMimeEntity->parts(\@parts);
}
}
#-------------------------------------------------------------------
@ -339,7 +382,13 @@ sub create {
delete $headers->{toGroup};
$message->attach(Data=>"This message was intended for ".$to." but was overridden in the config file.\n\n");
}
bless {_message=>$message, _session=>$session, _toGroup=>$headers->{toGroup}, _isInbox => $isInbox }, $class;
return bless {
_message => $message,
_session => $session,
_toGroup => $headers->{toGroup},
_isInbox => $isInbox,
_footerAdded => 0,
}, $class;
}
#-------------------------------------------------------------------
@ -462,6 +511,9 @@ sub send {
my $smtpServer = $session->setting->get("smtpServer");
my $status = 1;
if ($mail->parts <= 1) {
$mail->make_singlepart;
}
if ($mail->head->get("To")) {
if ($session->config->get("emailToLog")){
my $message = $mail->stringify;

View file

@ -14,6 +14,7 @@ package WebGUI::Operation::Auth;
# logic that defines how Authentication should happen
use strict qw(vars subs);
use List::MoreUtils qw( any );
use URI;
use WebGUI::Operation::Shared;
use WebGUI::Pluggable;
@ -33,9 +34,16 @@ Get the instance of this object or create a new instance if none exists
sub getInstance {
my $session = shift;
#Get Auth Settings
my $authMethod = $session->user->authMethod || $session->setting->get("authMethod");
$authMethod = $session->setting->get("authMethod") if($session->user->isVisitor);
$authMethod = $_[0] if($_[0] && isIn($_[0], @{$session->config->get("authMethods")}));
my $authMethod = $_[0]
|| ( !$session->user->isVisitor && $session->user->authMethod ) # Visitor has no authType
|| $session->form->get('authType')
|| $session->setting->get("authMethod")
;
# Verify is in auth method list
if ( !any { $_ eq $authMethod } @{$session->config->get('authMethods')} ) {
$authMethod = $session->setting->get('authMethod');
}
my $userId = $_[1];
#Create Auth Object
my $auth = eval { WebGUI::Pluggable::instanciate("WebGUI::Auth::".$authMethod, "new", [ $session, $authMethod, $userId ] ) };
@ -68,11 +76,15 @@ sub www_auth {
my $authMethod = getInstance($session,$auth);
my $methodCall = shift || $session->form->process("method") || "init";
if(!$authMethod->isCallable($methodCall)){
$session->errorHandler->security("access uncallable auth method");
$session->errorHandler->security("access uncallable auth method: $methodCall");
my $i18n = WebGUI::International->new($session);
return $i18n->get(1077);
}
my $out = $authMethod->$methodCall;
# Determine if we have a www_ method
my $method = $authMethod->can( 'www_' . $methodCall )
|| $authMethod->can( $methodCall );
my $out = $method->( $authMethod );
if (substr($session->http->getMimeType(),0,9) eq "text/html") {
return $session->style->userStyle($out);
}

View file

@ -308,7 +308,6 @@ sub www_runCronJob {
# Run the instance
my $error = $instance->start( 1 );
if ($error) {
$task->delete(1);
return "error";
}
$task->delete( 1 ) if ( $task->get("runOnce") );

View file

@ -17,6 +17,7 @@ package WebGUI::Paginator;
use strict;
use WebGUI::International;
use WebGUI::Utility;
use List::Util qw/min/;
=head1 NAME
@ -428,10 +429,10 @@ sub getPageData {
}
#Handle setByArrayRef or the old setDataByQuery method
my @pageRows = ();
my $rowsPerPage = $self->{_rpp};
my $rowsPerPage = $self->{_rpp};
my $pageStartRow = ($pageNumber*$rowsPerPage)-$rowsPerPage;
my $pageEndRow = $pageNumber*$rowsPerPage;
my $pageEndRow = min($pageNumber*$rowsPerPage, $#{$allRows}+1);
my @pageRows = ();
for (my $i=$pageStartRow; $i<$pageEndRow; $i++) {
$pageRows[$i-$pageStartRow] = $allRows->[$i] if ($i <= $#{$self->{_rowRef}});
}

View file

@ -87,7 +87,8 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -113,7 +114,8 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -192,7 +194,8 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -218,7 +221,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -269,7 +274,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -295,7 +302,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -321,7 +330,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -347,7 +358,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=head3 disabled
@ -381,7 +394,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -407,7 +422,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -433,7 +450,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -459,7 +478,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=head3 disabled
@ -529,7 +550,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -555,7 +578,9 @@ Any URL parameters that need to be tacked on to the current URL to accomplish wh
=head3 pageURL
The URL to any page. Defaults to the current page.
The URL to any page. Defaults to the current page. If a URL is passed, the gateway URL from the site's config
file will be prepended to it.
=cut
@ -570,6 +595,4 @@ sub view {
}
1;

View file

@ -133,7 +133,7 @@ sub session {
=head2 toHex ( guid )
Returns the hex value of a guid
Returns the hex value of a guid. For all GUIDs generated by the generate method, the return value will be 32 characters long. For some manually created invalid GUIDs, it may be 33 characters long.
=head3 guid
@ -142,11 +142,13 @@ guid to convert to hex value.
=cut
sub toHex {
my $self = shift;
my $self = shift;
my $id = shift;
$id =~ tr{_-}{+/};
my $bin_id = decode_base64("$id==");
my $hex_id = sprintf('%*v02x', '', $bin_id);
$id .= 'AA';
my $bin_id = decode_base64($id);
my $hex_id = unpack("H*", $bin_id);
$hex_id =~ s/0{3,4}$//;
return $hex_id
}

View file

@ -684,7 +684,20 @@ sub www_editAddressSave {
my %addressData = $self->processAddressForm();
my @missingFields = $self->missingFields(\%addressData);
if (@missingFields) {
return $self->www_editAddress(pop @missingFields);
my $i18n = WebGUI::International->new($self->session, "Shop");
my $missingField = pop @missingFields;
my $label = $missingField eq 'label' ? $i18n->get('label')
: $missingField eq 'firstName' ? $i18n->get('firstName')
: $missingField eq 'lastName' ? $i18n->get('lastName')
: $missingField eq 'address1' ? $i18n->get('address')
: $missingField eq 'city' ? $i18n->get('city')
: $missingField eq 'state' ? $i18n->get('state')
: $missingField eq 'country' ? $i18n->get('country')
: $missingField eq 'phoneNumber' ? $i18n->get('phone number')
: '' ;
if ($label) {
return $self->www_editAddress(sprintf($i18n->get('is a required field'), $label));
}
}
if ($form->get('addressId') eq '') {
$self->addAddress(\%addressData);

View file

@ -762,6 +762,15 @@ sub updateFromForm {
$error{id $self} = $i18n->get('mixed items warning');
}
my @cartItemIds = $form->process('remove_item', 'checkList');
foreach my $cartItemId (@cartItemIds) {
my $item = eval { $self->getItem($cartItemId); };
$item->remove if ! Exception::Class->caught();
}
##Visitor cannot have an address book, or set a payment gateway, so skip the rest of this.
return 1 if $session->user->isVisitor;
my $book = $self->getAddressBook;
my $cartProperties = {};
@ -825,12 +834,6 @@ sub updateFromForm {
$cartProperties->{ shipperId } = $form->process( 'shipperId' ) if $form->process( 'shipperId' );
$cartProperties->{ gatewayId } = $form->process( 'gatewayId' ) if $form->process( 'gatewayId' );
$self->update( $cartProperties );
my @cartItemIds = $form->process('remove_item', 'checkList');
foreach my $cartItemId (@cartItemIds) {
my $item = eval { $self->getItem($cartItemId); };
$item->remove if ! Exception::Class->caught();
}
}
#-------------------------------------------------------------------
@ -1096,15 +1099,15 @@ sub www_view {
options => \%specialAddressOptions,
extras => q|class="itemAddressMenu"|,
});
$taxDriver->appendCartItemVars( \%properties, $item );
}
$taxDriver->appendCartItemVars( \%properties, $item );
push(@items, \%properties);
}
$var{items} = \@items;
if ($var{shippableItemsInCart}) {
if (! $var{userIsVisitor} && $var{shippableItemsInCart}) {
my $ship = WebGUI::Shop::Ship->new($self->session);
my $options = $ship->getOptions($self);
my $numberOfOptions = scalar keys %{ $options };

View file

@ -405,8 +405,8 @@ sub delete {
$db->write("DELETE FROM userSession WHERE userId=?",[$userId]);
# remove inbox entries
$db->write("DELETE FROM inbox_messageState WHERE userId=?",[$userId]);
$db->write("DELETE FROM inbox WHERE userId=? AND (groupId IS NULL OR groupId='')",[$userId]);
my $inbox = WebGUI::Inbox->new($session);
$inbox->deleteMessagesForUser($self);
# Shop cleanups
my $sth = $session->db->prepare('select addressBookId from addressBook where userId=?');

View file

@ -186,6 +186,64 @@ sub commit {
return 2;
}
#-------------------------------------------------------------------
=head2 commitAsUser ( userId , options )
Commits the working tab. If userId is passed in, commit will be done as that user
=head3 userId
User to commit tag as
=head3 options
hash ref of options to pass in
=head4 comments
optional comments to set in the version tag
=head4 commitNow
optional boolean which, if set, will perform an immediate.
=cut
sub commitAsUser {
my $self = shift;
my $session = $self->session;
my $config = $session->config;
my $userId = shift;
my $options = shift;
my $commitNow = $options->{commitNow};
my $comments = $options->{comments};
return 0 unless (defined $userId);
#Open a new session
my $new_session = WebGUI::Session->open( $config->getWebguiRoot, $config->getFilename );
#Set the userId in the new session
$new_session->user( { userId => $userId } );
#Clone the tag into a new version tag in the new session
my $new_tag = __PACKAGE__->new( $new_session, $self->getId );
if ( defined $new_tag ) {
$new_tag->set( { comments => $comments } );
if ($commitNow) {
$new_tag->commit;
}
else {
$new_tag->requestCommit;
}
}
#End the new session
$new_session->var->end;
$new_session->close;
return 1;
}
#-------------------------------------------------------------------

View file

@ -17,7 +17,7 @@ package WebGUI::Workflow::Activity::PurgeOldInboxMessages;
use strict;
use base 'WebGUI::Workflow::Activity';
use WebGUI::Asset;
use WebGUI::Inbox::Message;
=head1 NAME
@ -77,45 +77,32 @@ See WebGUI::Workflow::Activity::execute() for details.
=cut
sub execute {
my ($self, $nothing, $instance) = @_;
my ($self, undef, $instance) = @_;
my $session = $self->session;
my $log = $session->errorHandler;
# keep track of how much time it's taking
my $start = time;
my $limit = 2_500;
my $endTime = time() + $self->getTTL;;
my $sth
= $session->db->read(
"SELECT messageId FROM inbox WHERE completedOn IS NOT NULL AND dateStamp < ?",
[ $start - $self->get('purgeAfter') ],
);
while ( ( my $messageId ) = $sth->array ) {
$session->db->write(
"DELETE FROM inbox WHERE messageId = ?",
[ $messageId ],
[ time() - $self->get('purgeAfter') ],
);
MESSAGE: while ( ( my $messageId ) = $sth->array ) {
# give up if we're taking too long
if (time - $start > 120) {
if (time() > $endTime) {
$sth->finish;
return $self->WAITING(1);
}
}
my $message = WebGUI::Inbox::Message->new($session, $messageId);
next MESSAGE unless $message;
$message->purge;
}
# If there are more messages waiting to be purged, return WAITING
if ( $sth->rows >= $limit ) {
return $self->WAITING(1);
}
else {
return $self->COMPLETE;
}
$sth->finish;
return $self->COMPLETE;
}
1;

View file

@ -306,6 +306,7 @@ sub setApproved {
my $self = shift;
my $instance = shift;
$instance->setScratch( "status", "approved" );
$instance->set({}); ##Bump spectre to get it to run right now.
}
#----------------------------------------------------------------------------
@ -325,7 +326,8 @@ sub setDenied {
my $self = shift;
my $instance = shift;
$instance->setScratch( "status", "denied" );
}
$instance->set({}); ##Bump spectre to get it to run right now.
}
#----------------------------------------------------------------------------

View file

@ -75,9 +75,11 @@ See WebGUI::Workflow::Activity::execute() for details.
=cut
sub execute {
my $self = shift;
my $sth = $self->session->db->read( "select assetId from Event where endDate < ?", [ time() - $self->get("trashAfter") ]);
my $self = shift;
my $session = $self->session;
my $finishTime = time() + $self->getTTL;
my $date = WebGUI::DateTime->new($session, time() - $self->get("trashAfter") );
my $sth = $session->db->read( "select Event.assetId, revisionDate from Event join assetData using (assetId, revisionDate) where endDate < ? and revisionDate = (select max(revisionDate) from assetData where assetData.assetId=Event.assetId);", [ $date->toDatabaseDate ]);
EVENT: while ( my ($id) = $sth->array ) {
my $asset = eval { WebGUI::Asset::Event->newById($self->session, $id); };
if (! Exception::Class->caught() && $asset->eventEndDate < time() - $self->trashAfter) {

View file

@ -1191,10 +1191,8 @@ submitted by a user.|,
},
'sort by description' => {
message => q|By default, all posts are displayed in a sorted order. Use this
field to choose by what property they are sorted. Multiple properties
may be selected.|,
lastUpdated => 1119070429,
message => q|By default, all posts are displayed in a sorted order. Use this field to choose by what property they are sorted.|,
lastUpdated => 1275922704,
},
'sort order description' => {

View file

@ -759,6 +759,12 @@ our $I18N = {
lastUpdated => 0,
context => q{Error when user is out of disk space.},
},
'error no image' => {
message => q{You need to select an image to upload.},
lastUpdated => 0,
context => q{Error when user tries to add photo without selecting image.},
},
'template comment add title' => {
message => q{Add comment},

View file

@ -48,6 +48,12 @@ editing an existing Post.|,
lastUpdated => 1149829706,
},
'isSubscribedToCs' => {
message => q|A boolean which will be true if the current user is subscribed to the CS containing this Post.|,
context => q|Template variable description|,
lastUpdated => 1149829706,
},
'subscribe.form' => {
message => q|A yes/no button to allow the user to subscribe to the thread this post belongs to.|,
lastUpdated => 1149829706,

View file

@ -584,14 +584,12 @@ you wish to appear, one per line. <br />
<br />If you want a different label for a value, the possible values list has to be
formatted as follows:
<pre>
&#123;
"key1"=>"value1",
"key2"=>"value2",
"key3"=>"value3"
key1|value1
key2|value2
key3|value3
...
&#125;
</pre>
Braces, quotes and all. You simply replace "key1"/"value1" with your own name/value pairs},
Simply replace "key1"/"value1" with your own name/value pairs},
lastUpdated => 1223372150,
},
@ -972,11 +970,17 @@ search has been done.|,
},
'searchFields_is__fieldType__' => {
message => q|A boolean indicating wether this field is of type __fieldType__. The first letter of __fieldType__ is always uppercase. Example: for a select box the value of &lt;tmpl_var searchFields_isSelectBox&gt; is true.|,
message => q|A boolean indicating whether this field is of type __fieldType__. The first letter of __fieldType__ is always uppercase. Example: for a select box the value of &lt;tmpl_var searchFields_isSelectBox&gt; is true.|,
lastUpdated => 1104630516,
context => q|Description of a tmpl_var for the template help.|,
},
'searchFields_listType' => {
message => q|A boolean indicating whether this field is a List type field.|,
lastUpdated => 1277849256,
context => q|Description of a tmpl_var for the template help.|,
},
'displayInSearchFields_loop' => {
message => q|A loop containing the fields that are displayed in the search results.|,
lastUpdated => 1104630516,

View file

@ -0,0 +1,80 @@
package WebGUI::i18n::English::Auth_Twitter;
use strict;
our $I18N = {
'enabled' => {
message => q{Enabled},
lastUpdated => 0,
context => q{Label for auth setting field},
},
'enabled help' => {
message => q{Enabled Twitter-based login},
lastUpdated => 0,
context => q{Hover help for auth setting field},
},
'get key' => {
message => q{Get a Twitter API key from <a href="%s">%s</a>},
lastUpdated => 0,
context => q{Link to get a twitter API key},
},
'consumer key' => {
message => q{Twitter Consumer Key},
lastUpdated => 0,
context => q{Label for auth setting field},
},
'consumer key help' => {
message => q{The Consumer Key from your application settings},
lastUpdated => 0,
context => q{Hover help for auth setting field},
},
'consumer secret' => {
message => q{Twitter Consumer Secret},
lastUpdated => 0,
context => q{Label for auth setting field},
},
'consumer secret help' => {
message => q{The Consumer Secret from your application settings},
lastUpdated => 0,
context => q{Hover help for auth setting field},
},
'choose username title' => {
message => q{Choose a Username},
lastUpdated => 0,
context => q{Title for screen to choose a username},
},
'twitter screen name taken' => {
message => q{Your twitter screen name "%s" is taken. Please choose a new username.},
lastUpdated => 0,
context => q{An error message for the choose a username screen},
},
'webgui username taken' => {
message => q{That username "%s" is taken. Please choose another.},
lastUpdated => 0,
context => q{An error message for the choose a username screen},
},
'choose username template' => {
message => q{Choose Username Template},
lastUpdated => 0,
context => q{Label for auth setting field},
},
'choose username template help' => {
message => q{The template to choose a username if the user's screen name already exists},
lastUpdated => 0,
context => q{Hover help for auth setting field},
},
};
1;
#vim:ft=perl

View file

@ -0,0 +1,11 @@
package WebGUI::i18n::English::Form_ThingsFieldList;
use strict;
our $I18N = {
'Thingy Fields List' => {
message => q|Thingy Fields List|,
lastUpdated => 1217216725,
},
};
1;

View file

@ -6,6 +6,11 @@ our $I18N = {
message => q|Sorry, that account name is already in use by another member of this site.|,
lastUpdated => 1217216725
},
'username' => {
message => q|Username|,
lastUpdated => 1217216725,
context => q|Name of the form plugin|,
},
};
1;

View file

@ -165,18 +165,6 @@ our $I18N = {
context => q|a help description|,
},
'removeButton help' => {
message => q|Clicking this button will remove the item from the cart.|,
lastUpdated => 0,
context => q|a help description|,
},
'item shipToButton help' => {
message => q|Clicking this button will set an alternate address as the destination of this item.|,
lastUpdated => 0,
context => q|a help description|,
},
'shippingAddress help' => {
message => q|The HTML formatted address to ship to.|,
lastUpdated => 0,
@ -189,6 +177,12 @@ our $I18N = {
context => q|a help description|,
},
'message help' => {
message => q|If the cart is empty, this internationalized message should be displayed to the user.|,
lastUpdated => 0,
context => q|a help description|,
},
'formHeader help' => {
message => q|The top of the form.|,
lastUpdated => 0,
@ -243,6 +237,12 @@ our $I18N = {
context => q|a help description|,
},
'paymentOptions help' => {
message => q|A select list containing all the configured payment options for this order.|,
lastUpdated => 0,
context => q|a help description|,
},
'inShopCreditAvailable help' => {
message => q|The amount of in-shop credit the user has.|,
lastUpdated => 0,
@ -447,6 +447,12 @@ our $I18N = {
context => q|a help description|,
},
'emailField help' => {
message => q|A field to contain the email address for this address.|,
lastUpdated => 0,
context => q|a help description|,
},
'phoneNumber help' => {
message => q|A phone number for this address.|,
lastUpdated => 0,
@ -1782,7 +1788,7 @@ our $I18N = {
'shippableItemsInCart' => {
message => q|A boolean which will be true if any item in the cart requires shipping.|,
lastUpdated => 0,
context => q|form label for the cart. Allows user to choose a payment method. Bart Jol for Minister in 2012!|
context => q|Template variable help.|
},
'no billing address' => {
@ -1905,6 +1911,108 @@ our $I18N = {
context => q|Cart error message|
},
'minimumCartAmount help' => {
message => q|The minimum cart amount, from the settings, formatted to two decimal places.|,
lastUpdated => 0,
context => q|Template variable help|
},
'userIsVisitor help' => {
message => q|A boolean which will be true if the currrent user is Visitor|,
lastUpdated => 0,
context => q|Template variable help|
},
'removeBox help' => {
message => q|A checkbox that will allow this item to be removed from the cart.|,
lastUpdated => 0,
context => q|Template variable help|
},
'itemAddressChooser help' => {
message => q|A dropdown for choosing an address to ship an individual item in the cart to, enabling per-item shipping.|,
lastUpdated => 0,
context => q|Template variable help|
},
'shippingAddressChooser help' => {
message => q|A dropdown for choosing a default shipping address for all items in the cart. Also contains actions for editing and adding new addresses.|,
lastUpdated => 0,
context => q|Template variable help|
},
'billingAddressChooser help' => {
message => q|A dropdown for choosing a default billing address.|,
lastUpdated => 0,
context => q|Template variable help|
},
'sameShippingAsBilling help' => {
message => q|A checkbox to tell the cart that the user wants to use the same shipping address, as their billing address.|,
lastUpdated => 0,
context => q|Template variable help|
},
'loginFormHeader help' => {
message => q|The start of the form to help a user log in. This variable will only be populated if the current user is Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'loginFormFooter help' => {
message => q|The end of the form to help a user log in. This variable will only be populated if the current user is Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'loginFormUsername help' => {
message => q|A text box for the user to enter in their name. This variable will only be populated if the current user is Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'loginFormPassword help' => {
message => q|A text box for the user to enter in their password, obscured. This variable will only be populated if the current user is Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'loginFormButton help' => {
message => q|The end of the form to help a user log in. This variable will only be populated if the current user is Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'registerLink help' => {
message => q|A link for a user to register an account on this site, if they do not already have one. This variable will only be populated if the current user is Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'item taxRate help' => {
message => q|The tax rate for this item. This variable will only be populated if the current user is not Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'item taxAmount help' => {
message => q|The amount of tax for this item. This variable will only be populated if the current user is not Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'item pricePlusTax help' => {
message => q|The amount of tax plus the price for this item. This variable will only be populated if the current user is not Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
'item extendedPricePlusTax help' => {
message => q|The amount of tax plus the price for this item, times the quantity of this item in the cart. This variable will only be populated if the current user is not Visitor.|,
lastUpdated => 0,
context => q|Template variable help|
},
};
1;

View file

@ -149,11 +149,18 @@ checkModule("Business::PayPal::API", "0.62" );
checkModule("Locales", "0.10" );
checkModule("Test::Harness", "3.17" );
checkModule("DateTime::Event::ICal", "0.10" );
<<<<<<< HEAD
checkModule( "CHI", );
checkModule( "Cache::FastMmap", );
checkModule('IO::Socket::SSL', );
checkModule('Package::Stash', );
checkModule('HTTP::Exception', );
=======
checkModule("Cache::FastMmap", "1.35" );
checkModule("CHI", "0.34" );
checkModule('IO::Socket::SSL', );
checkModule('Net::Twitter', "3.13006" );
>>>>>>> master
failAndExit("Required modules are missing, running no more checks.") if $missingModule;

View file

@ -35,200 +35,190 @@ $numTests += 2 * scalar keys %{ $newAdSpaceSettings };
plan tests => $numTests;
my $session = WebGUI::Test->session;
my ($adSpace, $alfred, $alfred2, $bruce, $catWoman, $villianClone, $defaultAdSpace );
my ($adSpace, $alfred, $alfred2, $bruce, $catWoman, );
my ($jokerAd, $penguinAd, $twoFaceAd);
$session->request->env->{REMOTE_ADDR} = '10.0.0.1';
$session->request->env->{HTTP_USER_AGENT} = 'Mozilla/5.0';
$adSpace = WebGUI::AdSpace->create($session, {name=>"Alfred"});
$adSpace = WebGUI::AdSpace->create($session, {name=>"Alfred"});
isa_ok($adSpace, 'WebGUI::AdSpace');
WebGUI::Test->addToCleanup($adSpace);
isa_ok($adSpace, 'WebGUI::AdSpace');
my $data = $session->db->quickHashRef("select adSpaceId, name from adSpace where adSpaceId=?",[$adSpace->getId]);
my $data = $session->db->quickHashRef("select adSpaceId, name from adSpace where adSpaceId=?",[$adSpace->getId]);
ok(exists $data->{adSpaceId}, "create()");
is($data->{name}, $adSpace->get("name"), "get()");
is($data->{adSpaceId}, $adSpace->getId, "getId()");
ok(exists $data->{adSpaceId}, "create()");
is($data->{name}, $adSpace->get("name"), "get()");
is($data->{adSpaceId}, $adSpace->getId, "getId()");
$alfred = WebGUI::AdSpace->newByName($session, 'Alfred');
WebGUI::Test->addToCleanup($alfred);
$alfred = WebGUI::AdSpace->newByName($session, 'Alfred');
cmp_deeply($adSpace, $alfred, 'newByName returns identical object if name exists');
cmp_deeply($adSpace, $alfred, 'newByName returns identical object if name exists');
$bruce = WebGUI::AdSpace->newByName($session, 'Bruce');
is($bruce, undef, 'newByName returns undef if the name does not exist');
$bruce = WebGUI::AdSpace->newByName($session, 'Bruce');
is($bruce, undef, 'newByName returns undef if the name does not exist');
$bruce = WebGUI::AdSpace->new($session, $session->getId);
is($bruce, undef, 'new returns undef if the id does not exist');
$bruce = WebGUI::AdSpace->new($session, $session->getId);
is($bruce, undef, 'new returns undef if the id does not exist');
$alfred2 = WebGUI::AdSpace->create($session);
is($alfred2, undef, 'create returns undef unless you pass it a name');
$alfred2 = WebGUI::AdSpace->create($session);
is($alfred2, undef, 'create returns undef unless you pass it a name');
$alfred2 = WebGUI::AdSpace->create($session, {name => 'Alfred'});
is($alfred2, undef, 'create returns undef if the name already exists');
$alfred2 = WebGUI::AdSpace->create($session, {name => 'Alfred'});
is($alfred2, undef, 'create returns undef if the name already exists');
isa_ok($alfred->session, 'WebGUI::Session');
isa_ok($alfred->session, 'WebGUI::Session');
undef $alfred2;
undef $alfred2;
$alfred->set({title => "Alfred's Ad"});
is($alfred->get('title'), "Alfred's Ad", "get, set work on title");
$alfred->set({title => "Alfred's Ad"});
is($alfred->get('title'), "Alfred's Ad", "get, set work on title");
$bruce = WebGUI::AdSpace->create($session, {name => 'Bruce'});
$bruce->set({title => "Bruce's Ad"});
WebGUI::Test->addToCleanup($bruce);
$bruce = WebGUI::AdSpace->create($session, {name => 'Bruce'});
$bruce->set({title => "Bruce's Ad"});
$catWoman = WebGUI::AdSpace->create($session, {name => 'CatWoman'});
$catWoman->set({title => "CatWoman's Ad"});
WebGUI::Test->addToCleanup($catWoman);
$catWoman = WebGUI::AdSpace->create($session, {name => 'CatWoman'});
$catWoman->set({title => "CatWoman's Ad"});
my $adSpaces = WebGUI::AdSpace->getAdSpaces($session);
my $adSpaces = WebGUI::AdSpace->getAdSpaces($session);
cmp_deeply($adSpaces, [$alfred, $bruce, $catWoman], 'getAdSpaces returns all AdSpaces in alphabetical order by title');
cmp_deeply($adSpaces, [$alfred, $bruce, $catWoman], 'getAdSpaces returns all AdSpaces in alphabetical order by title');
$catWoman->set($newAdSpaceSettings);
foreach my $setting (keys %{ $newAdSpaceSettings } ) {
is($newAdSpaceSettings->{$setting}, $catWoman->get($setting),
sprintf "set and get for %s", $setting);
}
##Bare call to set doesn't change anything
$catWoman->set();
foreach my $setting (keys %{ $newAdSpaceSettings } ) {
is($newAdSpaceSettings->{$setting}, $catWoman->get($setting),
sprintf "empty call to set does not change %s", $setting);
}
$catWoman->set({title => '', name => '', description => '', });
is ($catWoman->get('title'), '', 'set can clear the title');
is ($catWoman->get('description'), '', 'set can clear the title');
is ($catWoman->get('name' ), $newAdSpaceSettings->{'name'}, 'set can not clear the name');
##Create a set of ads for general purpose testing
##The Joker and Penguin Ads go in the bruce adSpace
##The Two Face ad goes in the catWoman adSpace
$jokerAd = WebGUI::AdSpace::Ad->create($session, $bruce->getId,
{
title => 'Joker',
url => '/ha_ha',
type => 'rich',
richMedia => 'Joker',
priority => 2,
isActive => 1,
clicksBought => 0,
impressionsBought => 2,
}
);
$penguinAd = WebGUI::AdSpace::Ad->create($session, $bruce->getId,
{
title => 'Penguin',
url => '/fishy',
type => 'rich',
richMedia => 'Penguin',
priority => 1,
isActive => 1,
clicksBought => 4,
impressionsBought => 0,
}
);
$twoFaceAd = WebGUI::AdSpace::Ad->create($session, $catWoman->getId,
{
title => 'Two Face',
url => '/dent',
type => 'rich',
richMedia => 'Two Face',
priority => 500,
isActive => 1,
clicksBought => 0,
impressionsBought => 0,
}
);
##getAds
my @bruceAdTitles = map { $_->get('title') } @{ $bruce->getAds };
my @catWomanAdTitles = map { $_->get('title') } @{ $catWoman->getAds };
cmp_bag(\@bruceAdTitles, ['Joker', 'Penguin'], 'Got the set of Ads for bruce');
cmp_bag(\@catWomanAdTitles, ['Two Face'], 'Got the set of Ads for catWoman');
##countClicks
my $penguinUrl = WebGUI::AdSpace->countClick($session, $penguinAd->getId);
is($penguinUrl, $penguinAd->get('url'), 'clicking on the penguin ad returns the penguin url');
WebGUI::AdSpace->countClick($session, $penguinAd->getId);
WebGUI::AdSpace->countClick($session, $penguinAd->getId);
my $jokerUrl = WebGUI::AdSpace->countClick($session, $jokerAd->getId);
is($jokerUrl, $jokerAd->get('url'), 'clicking on the joker ad returns the joker url');
my $twoFaceUrl = WebGUI::AdSpace->countClick($session, $twoFaceAd->getId);
is($twoFaceUrl, $twoFaceAd->get('url'), 'clicking on the twoFace ad returns the twoFace url');
my ($penguinClicks) = $session->db->quickArray('select clicks from advertisement where adId=?',[$penguinAd->getId]);
is($penguinClicks, 3, 'counted penguin clicks correctly');
my ($jokerClicks) = $session->db->quickArray('select clicks from advertisement where adId=?',[$jokerAd->getId]);
is($jokerClicks, 1, 'counted joker clicks correctly');
my ($twoFaceClicks) = $session->db->quickArray('select clicks from advertisement where adId=?',[$twoFaceAd->getId]);
is($twoFaceClicks, 1, 'counted twoFace clicks correctly');
##displayImpression
my ($twoFaceImpressions, $twoFacePriority) =
$session->db->quickArray('select impressions,nextInPriority from advertisement where adId=?',[$twoFaceAd->getId]);
is($catWoman->displayImpression(1), $twoFaceAd->get('renderedAd'), 'displayImpression returns the ad');
cmp_bag(
[$twoFaceImpressions, $twoFacePriority],
[$session->db->quickArray('select impressions,nextInPriority from advertisement where adId=?',[$twoFaceAd->getId])],
'displayImpressions: impresssions and nextInPriority are not updated when dontCount=1',
);
$catWoman->displayImpression();
my $twoFaceTime = time();
is(
$session->db->quickArray('select impressions from advertisement where adId=?',[$twoFaceAd->getId]),
1, 'displayImpression added 1 impression'
);
my ($newTwoFacePriority) = $session->db->quickArray('select nextInPriority from advertisement where adId=?',[$twoFaceAd->getId]);
isnt($newTwoFacePriority, $twoFacePriority, 'displayImpression changed the nextInPriority');
cmp_ok(
abs($twoFaceTime + $twoFaceAd->get('priority') - $newTwoFacePriority),
'<=',
'2',
'displayImpression set the nextInPriority correctly'
);
my ($twoFaceIsActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$twoFaceAd->getId]);
is($twoFaceIsActive, 0, 'displayImpression deactivates an ad if enough impressions and clicks are bought');
$session->db->write('update advertisement set nextInPriority=UNIX_TIMESTAMP()+100000 where adId=?',[$jokerAd->getId]);
is($bruce->displayImpression(), $penguinAd->get('renderedAd'), 'displayImpression returns earliest by nextInPriority, penguin has 3 clicks');
WebGUI::AdSpace->countClick($session, $penguinAd->getId); ##4 clicks
is($bruce->displayImpression(), $penguinAd->get('renderedAd'), 'displayImpression returns still returns penguinAd, but deactivates it after 4 clicks');
my ($penguinActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$penguinAd->getId]);
is($penguinActive, 0, 'displayImpression deactiveated penguinAd');
is($bruce->displayImpression(), $jokerAd->get('renderedAd'), 'displayImpression now returns jokerAd');
my ($jokerActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$jokerAd->getId]);
is($jokerActive, 1, 'displayImpression did not deactiveate jokerAd after one impression');
$bruce->displayImpression();
($jokerActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$jokerAd->getId]);
is($jokerActive, 0, 'displayImpression deactivated jokerAd after two impressions');
END {
foreach my $ad_space ($adSpace, $bruce, $alfred, $alfred2, $catWoman, $defaultAdSpace ) {
if (defined $ad_space and ref $ad_space eq 'WebGUI::AdSpace') {
$ad_space->delete;
}
}
foreach my $advert ($jokerAd, $penguinAd, $villianClone, $twoFaceAd) {
if (defined $advert and ref $advert eq 'WebGUI::AdSpace::Ad') {
$advert->delete;
}
}
$catWoman->set($newAdSpaceSettings);
foreach my $setting (keys %{ $newAdSpaceSettings } ) {
is($newAdSpaceSettings->{$setting}, $catWoman->get($setting),
sprintf "set and get for %s", $setting);
}
##Bare call to set doesn't change anything
$catWoman->set();
foreach my $setting (keys %{ $newAdSpaceSettings } ) {
is($newAdSpaceSettings->{$setting}, $catWoman->get($setting),
sprintf "empty call to set does not change %s", $setting);
}
$catWoman->set({title => '', name => '', description => '', });
is ($catWoman->get('title'), '', 'set can clear the title');
is ($catWoman->get('description'), '', 'set can clear the title');
is ($catWoman->get('name' ), $newAdSpaceSettings->{'name'}, 'set can not clear the name');
##Create a set of ads for general purpose testing
##The Joker and Penguin Ads go in the bruce adSpace
##The Two Face ad goes in the catWoman adSpace
$jokerAd = WebGUI::AdSpace::Ad->create($session, $bruce->getId,
{
title => 'Joker',
url => '/ha_ha',
type => 'rich',
richMedia => 'Joker',
priority => 2,
isActive => 1,
clicksBought => 0,
impressionsBought => 2,
}
);
$penguinAd = WebGUI::AdSpace::Ad->create($session, $bruce->getId,
{
title => 'Penguin',
url => '/fishy',
type => 'rich',
richMedia => 'Penguin',
priority => 1,
isActive => 1,
clicksBought => 4,
impressionsBought => 0,
}
);
$twoFaceAd = WebGUI::AdSpace::Ad->create($session, $catWoman->getId,
{
title => 'Two Face',
url => '/dent',
type => 'rich',
richMedia => 'Two Face',
priority => 500,
isActive => 1,
clicksBought => 0,
impressionsBought => 0,
}
);
##getAds
my @bruceAdTitles = map { $_->get('title') } @{ $bruce->getAds };
my @catWomanAdTitles = map { $_->get('title') } @{ $catWoman->getAds };
cmp_bag(\@bruceAdTitles, ['Joker', 'Penguin'], 'Got the set of Ads for bruce');
cmp_bag(\@catWomanAdTitles, ['Two Face'], 'Got the set of Ads for catWoman');
##countClicks
my $penguinUrl = WebGUI::AdSpace->countClick($session, $penguinAd->getId);
is($penguinUrl, $penguinAd->get('url'), 'clicking on the penguin ad returns the penguin url');
WebGUI::AdSpace->countClick($session, $penguinAd->getId);
WebGUI::AdSpace->countClick($session, $penguinAd->getId);
my $jokerUrl = WebGUI::AdSpace->countClick($session, $jokerAd->getId);
is($jokerUrl, $jokerAd->get('url'), 'clicking on the joker ad returns the joker url');
my $twoFaceUrl = WebGUI::AdSpace->countClick($session, $twoFaceAd->getId);
is($twoFaceUrl, $twoFaceAd->get('url'), 'clicking on the twoFace ad returns the twoFace url');
my ($penguinClicks) = $session->db->quickArray('select clicks from advertisement where adId=?',[$penguinAd->getId]);
is($penguinClicks, 3, 'counted penguin clicks correctly');
my ($jokerClicks) = $session->db->quickArray('select clicks from advertisement where adId=?',[$jokerAd->getId]);
is($jokerClicks, 1, 'counted joker clicks correctly');
my ($twoFaceClicks) = $session->db->quickArray('select clicks from advertisement where adId=?',[$twoFaceAd->getId]);
is($twoFaceClicks, 1, 'counted twoFace clicks correctly');
##displayImpression
my ($twoFaceImpressions, $twoFacePriority) =
$session->db->quickArray('select impressions,nextInPriority from advertisement where adId=?',[$twoFaceAd->getId]);
is($catWoman->displayImpression(1), $twoFaceAd->get('renderedAd'), 'displayImpression returns the ad');
cmp_bag(
[$twoFaceImpressions, $twoFacePriority],
[$session->db->quickArray('select impressions,nextInPriority from advertisement where adId=?',[$twoFaceAd->getId])],
'displayImpressions: impresssions and nextInPriority are not updated when dontCount=1',
);
$catWoman->displayImpression();
my $twoFaceTime = time();
is(
$session->db->quickArray('select impressions from advertisement where adId=?',[$twoFaceAd->getId]),
1, 'displayImpression added 1 impression'
);
my ($newTwoFacePriority) = $session->db->quickArray('select nextInPriority from advertisement where adId=?',[$twoFaceAd->getId]);
isnt($newTwoFacePriority, $twoFacePriority, 'displayImpression changed the nextInPriority');
cmp_ok(
abs($twoFaceTime + $twoFaceAd->get('priority') - $newTwoFacePriority),
'<=',
'2',
'displayImpression set the nextInPriority correctly'
);
my ($twoFaceIsActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$twoFaceAd->getId]);
is($twoFaceIsActive, 0, 'displayImpression deactivates an ad if enough impressions and clicks are bought');
$session->db->write('update advertisement set nextInPriority=UNIX_TIMESTAMP()+100000 where adId=?',[$jokerAd->getId]);
is($bruce->displayImpression(), $penguinAd->get('renderedAd'), 'displayImpression returns earliest by nextInPriority, penguin has 3 clicks');
WebGUI::AdSpace->countClick($session, $penguinAd->getId); ##4 clicks
is($bruce->displayImpression(), $penguinAd->get('renderedAd'), 'displayImpression returns still returns penguinAd, but deactivates it after 4 clicks');
my ($penguinActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$penguinAd->getId]);
is($penguinActive, 0, 'displayImpression deactiveated penguinAd');
is($bruce->displayImpression(), $jokerAd->get('renderedAd'), 'displayImpression now returns jokerAd');
my ($jokerActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$jokerAd->getId]);
is($jokerActive, 1, 'displayImpression did not deactiveate jokerAd after one impression');
$bruce->displayImpression();
($jokerActive) = $session->db->quickArray('select isActive from advertisement where adId=?',[$jokerAd->getId]);
is($jokerActive, 0, 'displayImpression deactivated jokerAd after two impressions');
#vim:ft=perl

View file

@ -45,7 +45,6 @@ plan tests => $numTests;
my $session = WebGUI::Test->session;
my $ad;
my ($richAd, $textAd, $imageAd, $nonAd, $setAd);
my $adSpace;
my $imageStorage = WebGUI::Storage->create($session);
WebGUI::Test->addToCleanup($imageStorage);
$imageStorage->addFileFromScalar('foo.bmp', 'This is not really an image');
@ -213,3 +212,132 @@ END {
$adSpace->delete;
}
}
$richAd = WebGUI::AdSpace::Ad->create($session, $adSpace->getId);
$richAd->set({
type => 'rich',
richMedia => 'This is rich, ^@;'
});
my $renderedAd = $richAd->get('renderedAd');
my $userName = $session->user->username;
like($renderedAd, qr/This is rich, $userName/, 'Rich media ads render macros');
##In this series of tests, we'll render a text ad and then pick it apart and make
##sure that all the requisite components are in there.
$adSpace->set({
width => 102,
height => 202
});
$textAd = WebGUI::AdSpace::Ad->create($session, $adSpace->getId);
$textAd->set({
type => 'text',
borderColor => 'black',
backgroundColor => 'white',
textColor => 'blue',
title => 'This is a text ad',
adText => 'Will hack for Gooey dolls.',
});
my $renderedTextAd = $textAd->get('renderedAd');
my $textP = HTML::TokeParser->new(\$renderedTextAd);
##Outer div checks
my $token = $textP->get_tag("div");
my $style = $token->[1]{style};
like($style, qr/height:200/, 'adSpace height rendered correctly');
like($style, qr/width:100/, 'adSpace width rendered correctly');
like($style, qr/border:solid black/, 'ad borderColor rendered correctly');
##Link checks
$token = $textP->get_tag("a");
my $href = $token->[1]{onclick};
like($href, qr/op=clickAd/, 'ad link has correct operation');
my $adId = $textAd->getId;
like($href, qr/id=\Q$adId\E/, 'ad link has correct ad id');
$style = $token->[1]{style};
like($style, qr/background-color:white/, 'ad link background is white');
$token = $textP->get_tag("span");
$style = $token->[1]{style};
like($style, qr/color:blue/, 'ad title text foreground is blue');
$token = $textP->get_tag("span");
$style = $token->[1]{style};
like($style, qr/color:blue/, 'ad title text foreground is blue');
my $adText = $textP->get_trimmed_text('/span');
is($adText, $textAd->get('adText'), 'ad text is correct');
##Ditto for the image ad
$adSpace->set({
width => 250,
height => 250
});
$imageAd = WebGUI::AdSpace::Ad->create($session, $adSpace->getId);
$imageAd->set({
type => 'image',
title => 'This is an image ad',
storageId => $imageStorage->getId,
});
my $renderedImageAd = $imageAd->get('renderedAd');
my $textP = HTML::TokeParser->new(\$renderedImageAd);
##Outer div checks
my $token = $textP->get_tag("div");
my $style = $token->[1]{style};
like($style, qr/height:250/, 'adSpace height rendered correctly, image');
like($style, qr/width:250/, 'adSpace width rendered correctly, image');
##Link checks
$token = $textP->get_tag("a");
my $href = $token->[1]{onclick};
like($href, qr/op=clickAd/, 'ad link has correct operation, image');
$adId = $imageAd->getId;
like($href, qr/id=\Q$adId\E/, 'ad link has correct ad id, image');
$token = $textP->get_tag("img");
$style = $token->[1]{src};
is($style, $imageStorage->getUrl($imageStorage->getFiles->[0]), 'ad image points at correct file');
$style = $token->[1]{alt};
is($style, $imageAd->get('title'), 'ad title matches, image');
my $nonAdProperties = {
type => 'nothing',
title => 'This ad will never render',
};
$nonAd = WebGUI::AdSpace::Ad->create($session, $adSpace->getId, $nonAdProperties);
my $renderedNonAd = $nonAd->get('renderedAd');
is($renderedNonAd, undef, 'undefined ad types are not rendered');
$nonAd->delete;
$nonAd = WebGUI::AdSpace::Ad->new($session, 'nonExistantId');
is($nonAd, undef, 'requesting a non-existant id via new returns undef');
my $setAd = WebGUI::AdSpace::Ad->create($session, $adSpace->getId, {isActive => 1});
is($setAd->get('isActive'), 1, 'set isActive true during instantiation');
$setAd->set({isActive=>0});
is($setAd->get('isActive'), 0, 'set isActive false during instantiation');
$setAd->delete;
my $setAd = WebGUI::AdSpace::Ad->create($session, $adSpace->getId, {priority => 1});
is($setAd->get('priority'), 1, 'set priority=1 during instantiation');
$setAd->set({priority=>0});
is($setAd->get('priority'), 0, 'set priority=0');
$setAd->set({ title => 'myTitle', url => 'http://www.nowhere.com', adText => 'Performing a valuable service for the community'});
is($setAd->get('url'), 'http://www.nowhere.com', 'set: url');
is($setAd->get('adText'), 'Performing a valuable service for the community', 'set: adText');
$setAd->set({ url => '', adText => ''});
is($setAd->get('url'), '', 'set: clearing url');
is($setAd->get('adText'), '', 'set: clearing adText');
#vim:ft=perl

View file

@ -35,7 +35,144 @@ my $session = WebGUI::Test->session;
my @getTitleTests = getTitleTests($session);
plan tests => 121
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');
addToCleanup($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');
addToCleanup($testGroups{'canAdd asset'}, 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);
addToCleanup($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);
addToCleanup($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'}, ],
},
);
#### TestAsset class to test definition / update relationship
BEGIN { $INC{ 'WebGUI/Asset/TestAsset.pm' } = __FILE__ }
package WebGUI::Asset::TestAsset;
our @ISA = ( 'WebGUI::Asset' );
sub definition {
my ( $class, $session, $definition ) = @_;
# Alter assetData fields for testing purposes. Do not do
# this in normal circumstances. Ever.
$definition = $class->SUPER::definition( $session, $definition );
# Make synopsis serialized
$definition->[0]->{properties}->{synopsis}->{serialize} = 1;
return $definition;
}
package main;
plan tests => 132
+ scalar(@fixIdTests)
+ scalar(@fixTitleTests)
+ 2*scalar(@getTitleTests) #same tests used for getTitle and getMenuTitle
;
@ -186,6 +323,40 @@ 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');
################################################################
#
# update
#
################################################################
# Create a new TestAsset instance
my $ta = $importNode->addChild( {
className => 'WebGUI::Asset::TestAsset',
} );
isa_ok( $ta, 'WebGUI::Asset::TestAsset', 'addChild returns correct object' );
ok(
eval { $ta->update({ synopsis => [ "one", "two" ] }); 1; },
'update() succeeds with ref on serialized property',
);
cmp_deeply(
$ta->get('synopsis'),
[ "one", "two" ],
"serialized property returns deserialized ref",
);
ok(
eval { $ta->update({ synopsis => '[ "two", "three" ]', }); 1; },
'update() succeeds with serialized string on serialized property',
);
cmp_deeply(
$ta->get('synopsis'),
[ "two", "three" ],
"serialized property returns deserialized ref",
);
$ta->purge;
################################################################
#
# urlExists
@ -801,3 +972,5 @@ sub getTitleTests {
},
);
}

View file

@ -290,7 +290,7 @@ is($gcAsPath->absolute($exportPath)->stringify, $litmus->absolute($exportPath)->
# now let's get tricky and test different file extensions
my $storage = WebGUI::Storage->create($session);
WebGUI::Test->addToCleanup('WebGUI::Storage' => $storage->getId);
WebGUI::Test->addToCleanup($storage);
my $filename = 'somePerlFile_pl.txt';
$storage->addFileFromScalar($filename, $filename);
$session->user({userId=>3});

View file

@ -17,7 +17,7 @@ use WebGUI::Session;
use WebGUI::User;
use WebGUI::Asset;
use Test::More tests => 94; # increment this value for each test you create
use Test::More tests => 96; # increment this value for each test you create
use Test::Deep;
use Test::Exception;
use Data::Dumper;
@ -509,6 +509,124 @@ is ($snippet4->getId, $snippets[4]->getId, '... failing class cache forces looku
dies_ok { WebGUI::Asset->newByLineage($session, 'notALineage') } '... throws an exception';
ok(!exists $session->stow->get('assetLineage')->{assetLineage}, '... no entry for the bad lineage in stow');
####################################################
#
# 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',
);
$ids = $root->getLineage(['ancestors']);
cmp_deeply(
$ids,
[],
'... getting ancestors of root returns empty array'
);
####################################################
#
# getLineageSql
#
####################################################
note "getLineageSql";
ok $root->getLineageSql(['ancestors']), 'valid SQL returned in an error condition';
####################################################
#
# 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',
);
my $empty = getListFromIterator($root->getLineageIterator(['ancestors']));
cmp_bag(
$empty,
[],
'... getting ancestors of root returns empty array'
);
####################################################
#
# addChild

View file

@ -30,6 +30,7 @@ $session->user({userId => 3});
my $root = WebGUI::Asset->getRoot($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Asset Package test"});
WebGUI::Test->addToCleanup($versionTag);
####################################################
#
@ -55,6 +56,12 @@ my $snippet = $folder->addChild({
$versionTag->commit;
WebGUI::Test->addToCleanup(sub {
foreach my $metaDataFieldId (keys %{ $snippet->getMetaDataFields }) {
$snippet->deleteMetaDataField($metaDataFieldId);
}
});
##Note that there is no MetaData field master class. New fields can be added
##from _ANY_ asset, and be available to all assets.
@ -225,15 +232,4 @@ sub buildNameIndex {
return $nameStruct;
}
END {
foreach my $metaDataFieldId (keys %{ $snippet->getMetaDataFields }) {
$snippet->deleteMetaDataField($metaDataFieldId);
}
foreach my $tag($versionTag) {
if (defined $tag and ref $tag eq 'WebGUI::VersionTag') {
$tag->rollback;
}
}
}
#vim:ft=perl

View file

@ -505,6 +505,4 @@ $sub1->getFormattedComments;
} [], 'no warnings from calling a bunch of functions';
#done_testing();
#print 'press return to complete test' ; <>;
#vim:ft=perl

View file

@ -62,6 +62,7 @@ my $calendar = $node->addChild( {
my $eventUrl;
$versionTags[-1]->commit;
WebGUI::Test->addToCleanup($versionTags[-1]);
#----------------------------------------------------------------------------
# Tests
@ -167,15 +168,6 @@ $properties = {
cmp_deeply( $event->get, superhashof( $properties ), 'Events properties saved correctly' );
#----------------------------------------------------------------------------
# Cleanup
END {
for my $tag ( @versionTags ) {
$tag->rollback;
}
}
#----------------------------------------------------------------------------
# getMechLogin( baseUrl, WebGUI::User, "identifier" )
# Returns a Test::WWW::Mechanize session after logging in the given user using
@ -197,3 +189,5 @@ sub getMechLogin {
return $mech;
}
#vim:ft=perl

View file

@ -31,6 +31,7 @@ $session->user({ userId => 3 });
my @versionTags = ();
push @versionTags, WebGUI::VersionTag->getWorking($session);
$versionTags[-1]->set({name=>"Photo Test, add Gallery, Album and 1 Photo"});
WebGUI::Test->addToCleanup($versionTags[-1]);
my $registeredUser = WebGUI::User->new( $session, "new" );
WebGUI::Test->addToCleanup($registeredUser);
@ -59,6 +60,7 @@ plan tests => 12; # Increment this number for each test you create
# Test permissions of an event added by the Admin
push @versionTags, WebGUI::VersionTag->getWorking($session);
$versionTags[-1]->set({name=>"Photo Test, add Gallery, Album and 1 Photo"});
WebGUI::Test->addToCleanup($versionTags[-1]);
$event = $calendar->addChild({
className => 'WebGUI::Asset::Event',
ownerUserId => 3,
@ -77,10 +79,4 @@ $maker->prepare( {
fail => [ '1', $registeredUser, ],
} )->run;
#----------------------------------------------------------------------------
# Cleanup
END {
for my $tag ( @versionTags ) {
$tag->rollback;
}
}
#vim:ft=perl

View file

@ -93,3 +93,5 @@ my $properties = $photo->get;
$photo->purge;
dies_ok { WebGUI::Asset->newById($session, $properties->{assetId}) } "Photo no longer able to be instanciated";
#vim:ft=perl

View file

@ -30,6 +30,7 @@ my $node = WebGUI::Asset->getImportNode($session);
my @versionTags = ();
push @versionTags, WebGUI::VersionTag->getWorking($session);
WebGUI::Test->addToCleanup($versionTags[-1]);
$versionTags[-1]->set({name=>"Photo Test, add Gallery, Album and 1 Photo"});
WebGUI::Test->addToCleanup($versionTags[-1]);
@ -327,3 +328,5 @@ TODO: {
# TODO
ok( 0, "Visitor has their IP logged in visitorIp field" );
}
#vim:ft=perl

View file

@ -84,3 +84,4 @@ ok(
"getDownloadFileUrl croaks if resolution doesn't exist",
);
#vim:ft=perl

View file

@ -14,18 +14,29 @@
use FindBin;
use strict;
use lib "$FindBin::Bin/../../../../lib";
use Test::More;
use Test::Deep;
use WebGUI::Test; # Must use this before any other WebGUI modules
use WebGUI::Asset;
use WebGUI::Asset::Wobject::Gallery;
use WebGUI::Asset::Wobject::GalleryAlbum;
use WebGUI::Asset::File::GalleryFile::Photo;
use WebGUI::VersionTag;
use WebGUI::Session;
plan skip_all => 'set WEBGUI_LIVE to enable this test' unless $ENV{WEBGUI_LIVE};
#----------------------------------------------------------------------------
# Init
my $session = WebGUI::Test->session;
my $node = WebGUI::Asset->getImportNode( $session );
my @versionTags = ( WebGUI::VersionTag->getWorking( $session ) );
# Create version tag and make sure it gets cleaned up
my $versionTag = WebGUI::VersionTag->getWorking($session);
addToCleanup($versionTag);
# Override some settings to make things easier to test
# userFunctionStyleId
@ -34,36 +45,43 @@ $session->setting->set( 'userFunctionStyleId', 'PBtmpl0000000000000132' );
$session->setting->set( 'specialState', '' );
# Create a user for testing purposes
my $user = WebGUI::User->new( $session, "new" );
my $user = WebGUI::User->new( $session, "new" );
WebGUI::Test->addToCleanup($user);
$user->username( 'dufresne' . time );
my $identifier = 'ritahayworth';
my $auth = WebGUI::Operation::Auth::getInstance( $session, $user->authMethod, $user->userId );
my $identifier = 'ritahayworth';
my $auth = WebGUI::Operation::Auth::getInstance( $session, $user->authMethod, $user->userId );
$auth->saveParams( $user->userId, $user->authMethod, {
'identifier' => Digest::MD5::md5_base64( $identifier ),
});
my ( $mech );
# Get the site's base URL
my $baseUrl = 'http://' . $session->config->get('sitename')->[0];
my @addArgs = ( undef, undef, { skipAutoCommitWorkflows => 1 } );
# Create gallery and a single album
my $gallery
= $node->addChild({
className => "WebGUI::Asset::Wobject::Gallery",
title => "gallery",
groupIdAddFile => 2, # Registered Users
styleTemplateId => "PBtmpl0000000000000132", # Blank Style
styleTemplateId => "PBtmpl0000000000000132", # Blank Style
});
my $album
= $gallery->addChild({
className => "WebGUI::Asset::Wobject::GalleryAlbum",
}, @addArgs );
ownerUserId => $user->getId,
title => "album",
},
undef,
undef,
{
skipAutoCommitWorkflows => 1,
});
$versionTags[-1]->commit;
# Commit assets for testing
$versionTag->commit;
my $photo;
# Get the site's base URL
my $baseUrl = 'http://' . $session->config->get('sitename')->[0];
# Common variables
my ( $mech, $photo );
#----------------------------------------------------------------------------
@ -78,18 +96,93 @@ if ( !$mech->success ) {
plan skip_all => "Cannot load URL '$baseUrl'. Will not test.";
}
plan tests => 5; # Increment this number for each test you create
plan tests => 10; # Increment this number for each test you create
#----------------------------------------------------------------------------
# Test permissions for new photos
$mech = Test::WWW::Mechanize->new;
# Save a new photo
$mech->get( $baseUrl . $album->getUrl("func=add;class=WebGUI::Asset::File::GalleryFile::Photo") );
$mech->content_lacks( 'value="editSave"' );
#----------------------------------------------------------------------------
# Test editing existing photo
# Create single photo inside the album
$photo
= $album->addChild({
className => "WebGUI::Asset::File::GalleryFile::Photo",
ownerUserId => $user->getId,
title => "photo",
synopsis => "synopsis",
keywords => "keywords",
location => "location",
friendsOnly => 0,
},
undef,
time() - 5 # Create photo asset in the past to avoid duplicate revision dates
);
# Attach image file to photo asset
$photo->setFile( WebGUI::Test->getTestCollateralPath("rotation_test.png") );
# New values for photo properties
my %properties = (
title => 'new photo',
synopsis => 'new synopsis',
keywords => 'new keywords',
location => 'new location',
friendsOnly => '1',
);
# Log in
$mech = getMechLogin( $baseUrl, $user, $identifier );
# Request photo edit view
$mech->get_ok( $baseUrl . $photo->getUrl('func=edit'), 'Request Photo edit view' );
# Try to submit edit form
$mech->submit_form_ok({
form_name => 'photoEdit',
fields => \%properties,
},
'Submit Photo edit form' );
# Re-create instance of Photo asset
$photo = WebGUI::Asset->newByDynamicClass($session, $photo->getId);
# Check whether properties were changed correctly
cmp_deeply($photo->get, superhashof(\%properties), 'All changes applied');
#----------------------------------------------------------------------------
# Test redirect to parent's edit view using the "proceed=editParent" parameter
# Create single photo inside the album
$photo
= $album->addChild({
className => "WebGUI::Asset::File::GalleryFile::Photo",
ownerUserId => $user->getId,
},
undef,
time() - 5 # Create photo asset in the past to avoid duplicate revision dates
);
# Attach image file to photo asset
$photo->setFile( WebGUI::Test->getTestCollateralPath("rotation_test.png") );
# Request photo edit view
$mech->get_ok( $baseUrl . $photo->getUrl('func=edit;proceed=editParent'), 'Request Photo edit view with "proceed=editParent"' );
# Submit changes
$mech->submit_form( form_name => 'photoEdit' );
# Currently, a redirect using the proceed parameter will not change the URL
# nor add the proper "func" argument. We have to look at the page content instead.
$mech->content_contains( 'name="galleryAlbumEdit"', "Redirected to parent's edit view" );
#----------------------------------------------------------------------------
# Test creating a new Photo
SKIP: {
skip "File control needs to be fixed to be more 508-compliant before this can be used", 4;
$mech = getMechLogin( $baseUrl, $user, $identifier );
@ -131,14 +224,6 @@ SKIP: {
);
}
#----------------------------------------------------------------------------
# Cleanup
END {
for my $tag ( @versionTags ) {
$tag->rollback;
}
}
#----------------------------------------------------------------------------
# getMechLogin( baseUrl, WebGUI::User, "identifier" )

View file

@ -26,6 +26,7 @@ use Image::ExifTool qw(:Public);
my $session = WebGUI::Test->session;
my $node = WebGUI::Asset->getImportNode($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
WebGUI::Test->addToCleanup($versionTag);
$versionTag->set({name=>"Photo Test"});
WebGUI::Test->addToCleanup($versionTag);
my $gallery
@ -80,3 +81,5 @@ is_deeply(
[ sort map { $_->{tag} } @{ $var->{exifLoop} } ],
"getTemplateVars gets a loop over the tags",
);
#vim:ft=perl

View file

@ -29,6 +29,7 @@ my $node = WebGUI::Asset->getImportNode($session);
my @versionTags = ();
push @versionTags, WebGUI::VersionTag->getWorking($session);
$versionTags[-1]->set({name=>"Photo Test"});
WebGUI::Test->addToCleanup($versionTags[-1]);
my ($gallery, $album, $photo);
$gallery
@ -224,3 +225,5 @@ $photo->update({ filename => 'page_title.jpg' });
"makeResolutions still makes valid resolutions when invalid resolutions given",
);
}
#vim:ft=perl

View file

@ -132,3 +132,5 @@ cmp_deeply(
#----------------------------------------------------------------------------
# www_makeShortcut
#vim:ft=perl

View file

@ -25,6 +25,7 @@ use WebGUI::Asset::File::GalleryFile::Photo;
my $session = WebGUI::Test->session;
my $node = WebGUI::Asset->getImportNode($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
WebGUI::Test->addToCleanup($versionTag);
$versionTag->set({name=>"Photo Test"});
my $gallery
= $node->addChild({
@ -70,10 +71,4 @@ ok(
"Generated resolution file exists on the filesystem",
);
#----------------------------------------------------------------------------
# Cleanup
END {
$versionTag->rollback();
}
#vim:ft=perl

View file

@ -25,6 +25,7 @@ use WebGUI::Asset::File::Image;
my $session = WebGUI::Test->session;
my $node = WebGUI::Asset->getImportNode($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
WebGUI::Test->addToCleanup($versionTag);
$versionTag->set({name=>"Image Test"});
WebGUI::Test->addToCleanup($versionTag);
my $image
@ -55,3 +56,4 @@ ok(
"Thumbnail file exists on the filesystem",
);
#vim:ft=perl

View file

@ -31,6 +31,7 @@ my $file
className => "WebGUI::Asset::File",
});
$versionTag->commit;
WebGUI::Test->addToCleanup($versionTag);
#----------------------------------------------------------------------------
# Tests
@ -54,3 +55,5 @@ is_deeply(
$storage->getFiles, ['WebGUI.pm'],
"Storage location contains only the file we added",
);
#vim:ft=perl

View file

@ -26,6 +26,7 @@ my $node = WebGUI::Asset->getImportNode($session);
my ($matrix, $matrixListing);
my $versionTag = WebGUI::VersionTag->getWorking($session);
WebGUI::Test->addToCleanup($versionTag);
$versionTag->set({name=>"Matrix Listing Test"});
$matrix = $node->addChild({className=>'WebGUI::Asset::Wobject::Matrix'});
@ -34,6 +35,7 @@ $matrixListing = $matrix->addChild({className=>'WebGUI::Asset::MatrixListing'});
# Wikis create and autocommit a version tag when a child is added. Lets get the name so we can roll it back.
my $secondVersionTag = WebGUI::VersionTag->new($session,$matrixListing->get("tagId"));
WebGUI::Test->addToCleanup($secondVersionTag);
# Test for sane object types
isa_ok($matrix, 'WebGUI::Asset::Wobject::Matrix');
@ -53,11 +55,4 @@ isa_ok($matrixListing, 'WebGUI::Asset::MatrixListing');
# local $TODO = "Tests to make later";
# ok(0, 'Lots and lots to do');
#}
END {
# Clean up after thy self
$versionTag->rollback();
$secondVersionTag->rollback();
#$thirdVersionTag->rollback();
}
#vim:ft=perl

119
t/Asset/Post/archiving.t Normal file
View file

@ -0,0 +1,119 @@
#-------------------------------------------------------------------
# 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
#-------------------------------------------------------------------
## Test that archiving a post works, and checking side effects like updating
## lastPost information in the Thread, and CS.
use FindBin;
use strict;
use lib "$FindBin::Bin/../../lib";
use WebGUI::Test;
use WebGUI::Session;
use Test::More tests => 13; # increment this value for each test you create
use WebGUI::Asset::Wobject::Collaboration;
use WebGUI::Asset::Post;
use WebGUI::Asset::Post::Thread;
my $session = WebGUI::Test->session;
# Do our work in the import node
my $node = WebGUI::Asset->getImportNode($session);
# Grab a named version tag
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Collab setup"});
# Need to create a Collaboration system in which the post lives.
my @addArgs = ( undef, undef, { skipAutoCommitWorkflows => 1, skipNotification => 1 } );
my $collab = $node->addChild({className => 'WebGUI::Asset::Wobject::Collaboration'}, @addArgs);
# finally, add posts and threads to the collaboration system
my $first_thread = $collab->addChild(
{ className => 'WebGUI::Asset::Post::Thread', },
undef,
WebGUI::Test->webguiBirthday,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $second_thread = $collab->addChild(
{ className => 'WebGUI::Asset::Post::Thread', },
undef,
WebGUI::Test->webguiBirthday,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
##Thread 1, Post 1 => t1p1
my $t1p1 = $first_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
WebGUI::Test->webguiBirthday,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $t1p2 = $first_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
WebGUI::Test->webguiBirthday + 1,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $past = time()-15;
my $t2p1 = $second_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
$past,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $t2p2 = $second_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
undef,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
$versionTag->commit();
WebGUI::Test->addToCleanup($versionTag);
foreach my $asset ($collab, $t1p1, $t1p2, $t2p1, $t2p2, $first_thread, $second_thread, ) {
$asset = $asset->cloneFromDb;
}
is $collab->getChildCount, 2, 'collab has correct number of children';
is $collab->get('lastPostId'), $t2p2->getId, 'lastPostId set in collab';
is $collab->get('lastPostDate'), $t2p2->get('creationDate'), 'lastPostDate, too';
$t2p2->setStatusArchived;
is $t2p2->get('status'), 'archived', 'setStatusArchived set the post to be archived';
$second_thread = $second_thread->cloneFromDb;
is $second_thread->get('lastPostId'), $t2p1->getId, '.. updated lastPostId in the thread';
is $second_thread->get('lastPostDate'), $t2p1->get('creationDate'), '... lastPostDate, too';
$collab = $collab->cloneFromDb;
is $collab->get('lastPostId'), $t2p1->getId, '.. updated lastPostId in the CS';
is $collab->get('lastPostDate'), $t2p1->get('creationDate'), '... lastPostDate, too';
$t2p2->setStatusUnarchived;
is $t2p2->get('status'), 'approved', 'setStatusUnarchived sets the post back to approved';
$second_thread = $second_thread->cloneFromDb;
is $second_thread->get('lastPostId'), $t2p2->getId, '.. updated lastPostId in the thread';
is $second_thread->get('lastPostDate'), $t2p2->get('creationDate'), '... lastPostDate, too';
$collab = $collab->cloneFromDb;
is $collab->get('lastPostId'), $t2p2->getId, '.. updated lastPostId in the CS';
is $collab->get('lastPostDate'), $t2p2->get('creationDate'), '... lastPostDate, too';
#vim:ft=perl

119
t/Asset/Post/trashing.t Normal file
View file

@ -0,0 +1,119 @@
#-------------------------------------------------------------------
# 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
#-------------------------------------------------------------------
## Test that trashing a post works, and checking side effects like updating
## lastPost information in the Thread, and CS.
use FindBin;
use strict;
use lib "$FindBin::Bin/../../lib";
use WebGUI::Test;
use WebGUI::Session;
use Test::More tests => 13; # increment this value for each test you create
use WebGUI::Asset::Wobject::Collaboration;
use WebGUI::Asset::Post;
use WebGUI::Asset::Post::Thread;
my $session = WebGUI::Test->session;
# Do our work in the import node
my $node = WebGUI::Asset->getImportNode($session);
# Grab a named version tag
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Collab setup"});
# Need to create a Collaboration system in which the post lives.
my @addArgs = ( undef, undef, { skipAutoCommitWorkflows => 1, skipNotification => 1 } );
my $collab = $node->addChild({className => 'WebGUI::Asset::Wobject::Collaboration'}, @addArgs);
# finally, add posts and threads to the collaboration system
my $first_thread = $collab->addChild(
{ className => 'WebGUI::Asset::Post::Thread', },
undef,
WebGUI::Test->webguiBirthday,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $second_thread = $collab->addChild(
{ className => 'WebGUI::Asset::Post::Thread', },
undef,
WebGUI::Test->webguiBirthday,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
##Thread 1, Post 1 => t1p1
my $t1p1 = $first_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
WebGUI::Test->webguiBirthday,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $t1p2 = $first_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
WebGUI::Test->webguiBirthday + 1,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $past = time()-15;
my $t2p1 = $second_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
$past,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
my $t2p2 = $second_thread->addChild(
{ className => 'WebGUI::Asset::Post', },
undef,
undef,
{ skipAutoCommitWorkflows => 1, skipNotification => 1 }
);
$versionTag->commit();
WebGUI::Test->addToCleanup($versionTag);
foreach my $asset ($collab, $t1p1, $t1p2, $t2p1, $t2p2, $first_thread, $second_thread, ) {
$asset = $asset->cloneFromDb;
}
is $collab->getChildCount, 2, 'collab has correct number of children';
is $collab->get('lastPostId'), $t2p2->getId, 'lastPostId set in collab';
is $collab->get('lastPostDate'), $t2p2->get('creationDate'), 'lastPostDate, too';
$t2p2->trash;
is $t2p2->get('state'), 'trash', 'cut set the post to be in the clipboard';
$second_thread = $second_thread->cloneFromDb;
is $second_thread->get('lastPostId'), $t2p1->getId, '.. updated lastPostId in the thread';
is $second_thread->get('lastPostDate'), $t2p1->get('creationDate'), '... lastPostDate, too';
$collab = $collab->cloneFromDb;
is $collab->get('lastPostId'), $t2p1->getId, '.. updated lastPostId in the CS';
is $collab->get('lastPostDate'), $t2p1->get('creationDate'), '... lastPostDate, too';
$t2p2->restore;
is $t2p2->get('state'), 'published', 'publish sets the post normal';
$second_thread = $second_thread->cloneFromDb;
is $second_thread->get('lastPostId'), $t2p2->getId, '.. updated lastPostId in the thread';
is $second_thread->get('lastPostDate'), $t2p2->get('creationDate'), '... lastPostDate, too';
$collab = $collab->cloneFromDb;
is $collab->get('lastPostId'), $t2p2->getId, '.. updated lastPostId in the CS';
is $collab->get('lastPostDate'), $t2p2->get('creationDate'), '... lastPostDate, too';
#vim:ft=perl

View file

@ -63,6 +63,7 @@ my $redirectToAsset
snippet => $testContent,
});
$versionTags[-1]->commit;
WebGUI::Test->addToCleanup($versionTags[-1]);
#----------------------------------------------------------------------------
# Tests
@ -81,6 +82,7 @@ plan tests => 12; # Increment this number for each test you create
#----------------------------------------------------------------------------
# Test operation with a public Redirect
push @versionTags, WebGUI::VersionTag->getWorking( $session );
WebGUI::Test->addToCleanup($versionTags[-1]);
$redirect
= $node->addChild({
className => 'WebGUI::Asset::Redirect',
@ -104,6 +106,7 @@ is(
#----------------------------------------------------------------------------
# Test operation with a private Redirect through a login
push @versionTags, WebGUI::VersionTag->getWorking( $session );
WebGUI::Test->addToCleanup($versionTags[-1]);
$redirect
= $node->addChild({
className => 'WebGUI::Asset::Redirect',
@ -137,6 +140,7 @@ is(
# Test operation with a private Redirect through a login with translate
# query params
push @versionTags, WebGUI::VersionTag->getWorking( $session );
WebGUI::Test->addToCleanup($versionTags[-1]);
$redirect
= $node->addChild({
className => 'WebGUI::Asset::Redirect',
@ -170,12 +174,4 @@ TODO: {
);
};
#----------------------------------------------------------------------------
# Cleanup
END {
for my $tag ( @versionTags ) {
$tag->rollback;
}
}
#vim:ft=perl

View file

@ -25,6 +25,7 @@ my $session = WebGUI::Test->session;
my $node = WebGUI::Asset->getImportNode($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Shortcut Test"});
WebGUI::Test->addToCleanup($versionTag);
# Make a snippet to shortcut
my $snippet
@ -32,12 +33,6 @@ my $snippet
className => "WebGUI::Asset::Snippet",
});
#----------------------------------------------------------------------------
# Cleanup
END {
$versionTag->rollback();
}
#----------------------------------------------------------------------------
# Tests
plan tests => 3;

View file

@ -92,6 +92,7 @@ EOCD
15@500000
EOID
});
WebGUI::Test->addToCleanup($sku);
$sku->applyOptions({
adtitle => 'Sold!',
@ -106,11 +107,4 @@ is($sku->getPrice, '19.00', 'get Price');
# $sku->onCompletePurchase($item); --> not really sure how to test the rest...
# $sku->onRefund
#----------------------------------------------------------------------------
# Cleanup
END {
$sku->purge;
}
1;
#vim:ft=perl

View file

@ -40,6 +40,7 @@ my $sku = $root->addChild({
title=>"Test Donation",
defaultPrice => 50.00,
});
WebGUI::Test->addToCleanup($sku);
isa_ok($sku, "WebGUI::Asset::Sku::Donation");
is($sku->getPrice, 50.00, "Price should be 50.00");

View file

@ -41,6 +41,8 @@ plan tests => 34; # Increment this number for each test you create
#----------------------------------------------------------------------------
# put your tests here
my $root = WebGUI::Asset->getRoot($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
WebGUI::Test->addToCleanup($versionTag);
my $product = $root->addChild({
className => "WebGUI::Asset::Sku::Product",
title => "Rock Hammer",
@ -307,12 +309,4 @@ lives_ok { $product6a->getAllCollateral('variantsJSON', 'vid', $newVid); }, 'Pro
$product6->purge;
#----------------------------------------------------------------------------
# Cleanup
END {
WebGUI::VersionTag->getWorking($session)->rollback;
}
1;
#vim:ft=perl

View file

@ -274,7 +274,7 @@ cmp_deeply(
{
title => 'Story 1',
description => 'WebGUI was originally called Web Done Right.',
'link' => re('story-1$'),
'link' => all(re('^'.$session->url->getSiteURL),re('story-1$')),
guid => re('story-1$'),
author => 'JT Smith',
date => $story->lastModified,
@ -417,10 +417,7 @@ cmp_deeply(
isnt($newPhotoData->[0]->{storageId}, $photoData->[0]->{storageId}, '... and storage 0 is duplicated');
isnt($newPhotoData->[1]->{storageId}, $photoData->[1]->{storageId}, '... and storage 1 is duplicated');
{
my %hash = map { ('WebGUI::Storage' => $_->{storageId}) } @{ $newPhotoData };
WebGUI::Test->addToCleanup(%hash);
}
WebGUI::Test->addToCleanup( map { ( 'WebGUI::Storage' => $_->{storageId} ) } @{ $newPhotoData } );
############################################################
#
@ -440,3 +437,4 @@ cmp_bag(
'...asset package data has the storage locations in it'
);
#vim:ft=perl

View file

@ -18,6 +18,7 @@ use WebGUI::Asset::Template;
use Exception::Class;
use Test::More tests => 42; # increment this value for each test you create
use Test::Deep;
use Data::Dumper;
use JSON qw{ from_json };
my $session = WebGUI::Test->session;
@ -78,13 +79,13 @@ my $template3 = $importNode->addChild({
}, undef, time()-5);
my @atts = (
{type => 'headScript', sequence => 1, url => 'bar'},
{type => 'headScript', sequence => 0, url => 'foo'},
{type => 'stylesheet', sequence => 0, url => 'style'},
{type => 'bodyScript', sequence => 0, url => 'body'},
{type => 'headScript', url => 'foo'},
{type => 'headScript', url => 'bar'},
{type => 'stylesheet', url => 'style'},
{type => 'bodyScript', url => 'body'},
);
$template3->addAttachments(\@atts);
$template3->update({ attachmentsJson => JSON->new->encode( \@atts ) });
my $att3 = $template3->getAttachments('headScript');
is($att3->[0]->{url}, 'foo', 'has foo');
is($att3->[1]->{url}, 'bar', 'has bar');
@ -100,12 +101,12 @@ ok(exists $session->style->{_javascript}->{$_}, "$_ in style") for qw(foo bar bo
#sleep 1;
my $template3dup = $template3->duplicate;
my @atts3dup = map { delete @{ $_ }{qw/attachId templateId revisionDate/}; $_; } @{ $template3dup->getAttachments };
my @atts3dup = @{ $template3dup->getAttachments };
cmp_bag(
[@atts3dup],
[@atts],
'attachments are duplicated'
);
) or diag( Dumper \@atts3dup );
my $template3rev = $template3->addRevision();
my $att4 = $template3rev->getAttachments('headScript');
@ -113,7 +114,9 @@ is($att4->[0]->{url}, 'foo', 'rev has foo');
is($att4->[1]->{url}, 'bar', 'rev has bar');
is(@$att4, 2, 'rev is proper size');
$template3rev->addAttachments([{type => 'headScript', sequence => 2, url => 'baz'}]);
$template3rev->update({
attachmentsJson => JSON->new->encode([ @atts, {type => 'headScript', url => 'baz'} ]),
});
$att4 = $template3rev->getAttachments('headScript');
$att3 = $template3->getAttachments('headScript');
is($att3->[0]->{url}, 'foo', 'original still has foo');
@ -122,13 +125,9 @@ is(@$att3, 2, 'original does not have new thing');
is($att4->[0]->{url}, 'foo', 'rev still has foo');
is($att4->[1]->{url}, 'bar', 'rev still has bar');
is($att4->[2]->{url}, 'baz', 'rev does have new thing');
is($att4->[2]->{url}, 'baz', 'rev does have new thing') or diag( $template3rev->get('attachmentsJson') );
is(@$att4, 3, 'rev is proper size');
##This is a non-test. Duplicate URLs will not cause the test to blow-up with
##an untrappable error.
$template3rev->addAttachments([{ type => 'headScript', sequence => 3, url => 'baz'}]);
$template3rev->purgeRevision();
## Check how templates in the trash and clipboard are handled.

View file

@ -27,26 +27,22 @@ plan tests => 2 + $num_tests;
my $session = WebGUI::Test->session;
# put your tests here
my ($versionTag, $template);
my $originalParsers = $session->config->get('templateParsers');
WebGUI::Test->originalConfig('templateParsers');
my $module = use_ok('HTML::Template::Expr');
my $plugin = use_ok('WebGUI::Asset::Template::HTMLTemplateExpr');
SKIP: {
skip "HTML::Template::Expr or plugin not loaded", $num_tests+1 unless $module;
my $plugin = use_ok('WebGUI::Asset::Template::HTMLTemplateExpr');
SKIP: {
skip "HTML::Template::Expr or plugin not loaded", $num_tests unless $plugin;
$session->config->set('templateParsers', ['WebGUI::Asset::Template::HTMLTemplate', 'WebGUI::Asset::Template::HTMLTemplateExpr',] );
($versionTag, $template) = setup_assets($session);
my $templateOutput = $template->process({ "foo.bar" => "baz", "number.value" => 2 });
my $companyName = $session->config->get('companyName');
like($templateOutput, qr/NAME=$companyName/, "session variable with underscores");
like($templateOutput, qr/FOOBAR=baz/, "explicit variable with dots");
like($templateOutput, qr/EQN=4/, "explicit variable with dots in expr");
}
skip "HTML::Template::Expr or plugin not loaded", $num_tests unless $plugin;
$session->config->set('templateParsers', ['WebGUI::Asset::Template::HTMLTemplate', 'WebGUI::Asset::Template::HTMLTemplateExpr',] );
my ($versionTag, $template) = setup_assets($session);
WebGUI::Test->addToCleanup($versionTag);
my $templateOutput = $template->process({ "foo.bar" => "baz", "number.value" => 2 });
my $companyName = $session->config->get('companyName');
like($templateOutput, qr/NAME=$companyName/, "session variable with underscores");
like($templateOutput, qr/FOOBAR=baz/, "explicit variable with dots");
like($templateOutput, qr/EQN=4/, "explicit variable with dots in expr");
}
sub setup_assets {
@ -67,9 +63,3 @@ sub setup_assets {
$versionTag->commit;
return ($versionTag, $template);
}
END {
if (defined $versionTag and ref $versionTag eq 'WebGUI::VersionTag') {
$versionTag->rollback;
}
}

View file

@ -120,10 +120,12 @@ cmp_deeply(
my $tz = $session->datetime->getTimeZone();
my $bday = WebGUI::DateTime->new($session, WebGUI::Test->webguiBirthday);
$dt = $bday->clone->truncate(to => 'day');
my $startDt = $dt->cloneToUserTimeZone->subtract(days => 1);
my $endDt = $dt->cloneToUserTimeZone->add(days => 1);
##Simulate how windows are built in each view method
my $startDt = $bday->cloneToUserTimeZone->truncate(to => 'day')->subtract(days => 1);
my $windowStart = $startDt->clone;
my $endDt = $startDt->clone->add(days => 2);
my $windowEnd = $endDt->clone->subtract(seconds => 1);
my $inside = $windowCal->addChild({
className => 'WebGUI::Asset::Event',
@ -217,6 +219,38 @@ my $justAfterwt = $windowCal->addChild({
timeZone => $tz,
}, undef, undef, {skipAutoCommitWorkflows => 1});
my $justBefore = $windowCal->addChild({
className => 'WebGUI::Asset::Event',
title => 'Just before the window. Ending date coincident with window start',
startDate => $startDt->clone->add(days => -1)->toDatabaseDate,
endDate => $startDt->clone->add(days => -1)->toDatabaseDate,
timeZone => $tz,
}, undef, undef, {skipAutoCommitWorkflows => 1});
my $justAfter = $windowCal->addChild({
className => 'WebGUI::Asset::Event',
title => 'Just after the window. Start date coincident with window end',
startDate => $endDt->clone->add(days => 1)->toDatabaseDate,
endDate => $endDt->clone->add(days => 1)->toDatabaseDate,
timeZone => $tz,
}, undef, undef, {skipAutoCommitWorkflows => 1});
my $starting = $windowCal->addChild({
className => 'WebGUI::Asset::Event',
title => 'Inside the window, same start date',
startDate => $startDt->toDatabaseDate,
endDate => $startDt->toDatabaseDate,
timeZone => $tz,
}, undef, undef, {skipAutoCommitWorkflows => 1});
my $ending = $windowCal->addChild({
className => 'WebGUI::Asset::Event',
title => 'Inside the window, same end date',
startDate => $endDt->clone->add(days => -1)->toDatabaseDate,
endDate => $endDt->clone->add(days => -1)->toDatabaseDate,
timeZone => $tz,
}, undef, undef, {skipAutoCommitWorkflows => 1});
my $coincident = $windowCal->addChild({
className => 'WebGUI::Asset::Event',
title => 'Coincident with the window start and window end',
@ -241,6 +275,7 @@ my $coincidentHigh = $windowCal->addChild({
timeZone => $tz,
}, undef, undef, {skipAutoCommitWorkflows => 1});
# no suffix = all day event
# wt suffix = with times
# inside
# insidewt
@ -252,7 +287,10 @@ my $coincidentHigh = $windowCal->addChild({
# |----------coincidentLow------------------|
# |--------------------coincidentHigh-------|
# window: |-------------------------------|
# starting--->|
# |<---ending
# justBeforewt justAfterwt
# justBefore justAfter
# outside high
# outside low
#
@ -262,16 +300,19 @@ my $tag2 = WebGUI::VersionTag->getWorking($session);
$tag2->commit;
addToCleanup($tag2);
is(scalar @{ $windowCal->getLineage(['children'])}, 13, 'added events to the window calendar');
is(scalar @{ $windowCal->getLineage(['children'])}, 17, 'added events to the window calendar');
my @window = $windowCal->getEventsIn($startDt->toDatabase, $endDt->toDatabase);
diag "startDate: ". $windowStart->toDatabase;
diag "endDate: ". $windowEnd->toDatabase;
my @window = $windowCal->getEventsIn($windowStart->toDatabase, $windowEnd->toDatabase);
cmp_bag(
[ map { $_->get('title') } @window ],
[ map { $_->get('title') }
($inside, $insidewt,
$straddle, $straddleHighwt, $straddleLowwt, $straddlewt,
$coincident, $coincidentLow, $coincidentHigh, )
$straddle, $straddleHighwt, $straddleLowwt, $straddlewt,
$coincident, $coincidentLow, $coincidentHigh, $starting,
$ending, )
],
'..returns correct set of events'
);
@ -368,7 +409,7 @@ my $monthCal = $node->addChild({
title => 'Calendar for doing event span testing, month',
});
$allDayDt = $bday->cloneToUserTimeZone;
$allDayDt = $bday->cloneToUserTimeZone;
my $nextMonthDt = $bday->cloneToUserTimeZone->add(months => 1)->truncate( to => 'month')->add(days => 29, hours => 19);
$allDay = $monthCal->addChild({

View file

@ -26,6 +26,7 @@ my $node = WebGUI::Asset->getImportNode($session);
my $versionTag = WebGUI::VersionTag->getWorking($session);
$versionTag->set({name=>"Search Test"});
WebGUI::Test->addToCleanup($versionTag);
my $carousel = $node->addChild({className=>'WebGUI::Asset::Wobject::Carousel'});
# Test for a sane object type
@ -41,9 +42,4 @@ foreach my $newSetting (keys %{$newSettings}) {
is ($carousel->get($newSetting), $newSettings->{$newSetting}, "updated $newSetting is ".$newSettings->{$newSetting});
}
END {
# Clean up after thy self
$versionTag->rollback();
}
#vim:ft=perl

View file

@ -25,6 +25,7 @@ use WebGUI::Session;
# Init
my $session = WebGUI::Test->session;
my @versionTags = ( WebGUI::VersionTag->getWorking( $session ) );
WebGUI::Test->addToCleanup($versionTags[-1]);
my @addChildArgs = ( {skipAutoCommitWorkflows=>1} );
my $collab = WebGUI::Asset->getImportNode( $session )->addChild({
className => 'WebGUI::Asset::Wobject::Collaboration',
@ -206,12 +207,6 @@ $session->request->setup_param({});
$session->scratch->delete($collab->getId.'_sortBy');
$session->scratch->delete($collab->getId.'_sortDir');
#----------------------------------------------------------------------------
# Cleanup
END {
$_->rollback for @versionTags;
}
#----------------------------------------------------------------------------
# sortThreads( \&sortSub, @threads )
# Sort threads according to the given subref. Return an arrayref of hashrefs

View file

@ -35,6 +35,7 @@ WebGUI::Test->addToCleanup($user{'2'});
my $versionTag = WebGUI::VersionTag->getWorking( $session );
$versionTag->set( { name => "Collaboration Test" } );
WebGUI::Test->addToCleanup($versionTag);
my @addArgs = ( undef, undef, { skipAutoCommitWorkflows => 1 } );
@ -106,8 +107,4 @@ $maker->prepare( {
fail => [ '1', $user{"2"}, ],
} )->run;
#----------------------------------------------------------------------------
# Cleanup
END {
$versionTag->rollback;
}
#vim:ft=perl

View file

@ -35,6 +35,7 @@ my $df = WebGUI::Asset->getImportNode( $session )
mailData => 0,
fieldConfiguration => '[]',
} );
WebGUI::Test->addToCleanup($df);
# Add three fields to the DataForm
$df->createField( "one", { label => "One" } );
@ -98,10 +99,4 @@ cmp_deeply(
);
#----------------------------------------------------------------------------
# Cleanup
END {
$df->purge;
WebGUI::VersionTag->getWorking( $session )->rollback;
}
#vim:ft=perl

Some files were not shown because too many files have changed in this diff Show more